module.py 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039
  1. # mypy: allow-untyped-defs
  2. import functools
  3. import inspect
  4. import itertools
  5. import warnings
  6. import weakref
  7. from collections import namedtuple, OrderedDict
  8. from collections.abc import Iterator, Mapping
  9. from typing import Any, Callable, Optional, overload, TypeVar, Union
  10. from typing_extensions import Self
  11. import torch
  12. from torch import device, dtype, Tensor
  13. from torch._prims_common import DeviceLikeType
  14. from torch.nn.parameter import Buffer, Parameter
  15. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  16. from torch.utils.hooks import BackwardHook, RemovableHandle
  17. __all__ = [
  18. "register_module_forward_pre_hook",
  19. "register_module_forward_hook",
  20. "register_module_full_backward_pre_hook",
  21. "register_module_backward_hook",
  22. "register_module_full_backward_hook",
  23. "register_module_buffer_registration_hook",
  24. "register_module_module_registration_hook",
  25. "register_module_parameter_registration_hook",
  26. "Module",
  27. ]
  28. _grad_t = Union[tuple[Tensor, ...], Tensor]
  29. # See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use
  30. # of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be
  31. # the type of the subclass, not the looser type of `Module`.
  32. T = TypeVar("T", bound="Module")
  33. class _IncompatibleKeys(
  34. namedtuple("IncompatibleKeys", ["missing_keys", "unexpected_keys"]),
  35. ):
  36. __slots__ = ()
  37. def __repr__(self) -> str:
  38. if not self.missing_keys and not self.unexpected_keys:
  39. return "<All keys matched successfully>"
  40. return super().__repr__()
  41. __str__ = __repr__
  42. def _addindent(s_, numSpaces):
  43. s = s_.split("\n")
  44. # don't do anything for single-line stuff
  45. if len(s) == 1:
  46. return s_
  47. first = s.pop(0)
  48. s = [(numSpaces * " ") + line for line in s]
  49. s = "\n".join(s)
  50. s = first + "\n" + s
  51. return s
  52. r"""This tracks hooks common to all modules that are executed immediately before
  53. .registering the buffer/module/parameter"""
  54. _global_buffer_registration_hooks: dict[int, Callable] = OrderedDict()
  55. _global_module_registration_hooks: dict[int, Callable] = OrderedDict()
  56. _global_parameter_registration_hooks: dict[int, Callable] = OrderedDict()
  57. class _WrappedHook:
  58. def __init__(self, hook: Callable, module: Optional["Module"] = None) -> None:
  59. self.hook: Callable = hook
  60. functools.update_wrapper(self, hook)
  61. self.with_module: bool = False
  62. if module is not None:
  63. self.module: weakref.ReferenceType[Module] = weakref.ref(module)
  64. self.with_module = True
  65. def __call__(self, *args: Any, **kwargs: Any) -> Any:
  66. if self.with_module:
  67. module = self.module()
  68. if module is None:
  69. raise RuntimeError("You are trying to call the hook of a dead Module!")
  70. return self.hook(module, *args, **kwargs)
  71. return self.hook(*args, **kwargs)
  72. def __getstate__(self) -> dict:
  73. result = {"hook": self.hook, "with_module": self.with_module}
  74. if self.with_module:
  75. result["module"] = self.module()
  76. return result
  77. def __setstate__(self, state: dict):
  78. self.hook = state["hook"]
  79. self.with_module = state["with_module"]
  80. if self.with_module:
  81. if state["module"] is None:
  82. raise RuntimeError(
  83. "You are trying to revive the hook of a dead Module!"
  84. )
  85. self.module = weakref.ref(state["module"])
  86. r"""This tracks hooks common to all modules that are executed before/after
  87. calling forward and backward. This is global state used for debugging/profiling
  88. purposes"""
  89. _global_backward_pre_hooks: dict[int, Callable] = OrderedDict()
  90. _global_backward_hooks: dict[int, Callable] = OrderedDict()
  91. _global_is_full_backward_hook: Optional[bool] = None
  92. _global_forward_pre_hooks: dict[int, Callable] = OrderedDict()
  93. _global_forward_hooks: dict[int, Callable] = OrderedDict()
  94. _global_forward_hooks_always_called: dict[int, bool] = OrderedDict()
  95. _global_forward_hooks_with_kwargs: dict[int, bool] = OrderedDict()
  96. def _has_any_global_hook():
  97. return (
  98. _global_backward_pre_hooks
  99. or _global_backward_hooks
  100. or _global_forward_pre_hooks
  101. or _global_forward_hooks
  102. or _global_forward_hooks_always_called
  103. or _global_forward_hooks_with_kwargs
  104. )
  105. _EXTRA_STATE_KEY_SUFFIX = "_extra_state"
  106. def register_module_buffer_registration_hook(
  107. hook: Callable[..., None],
  108. ) -> RemovableHandle:
  109. r"""Register a buffer registration hook common to all modules.
  110. .. warning ::
  111. This adds global state to the `nn.Module` module
  112. The hook will be called every time :func:`register_buffer` is invoked.
  113. It should have the following signature::
  114. hook(module, name, buffer) -> None or new buffer
  115. The hook can modify the input or return a single modified value in the hook.
  116. Returns:
  117. :class:`torch.utils.hooks.RemovableHandle`:
  118. a handle that can be used to remove the added hook by calling
  119. ``handle.remove()``
  120. """
  121. handle = RemovableHandle(_global_buffer_registration_hooks)
  122. _global_buffer_registration_hooks[handle.id] = hook
  123. return handle
  124. def register_module_module_registration_hook(
  125. hook: Callable[..., None],
  126. ) -> RemovableHandle:
  127. r"""Register a module registration hook common to all modules.
  128. .. warning ::
  129. This adds global state to the `nn.Module` module
  130. The hook will be called every time :func:`register_module` is invoked.
  131. It should have the following signature::
  132. hook(module, name, submodule) -> None or new submodule
  133. The hook can modify the input or return a single modified value in the hook.
  134. Returns:
  135. :class:`torch.utils.hooks.RemovableHandle`:
  136. a handle that can be used to remove the added hook by calling
  137. ``handle.remove()``
  138. """
  139. handle = RemovableHandle(_global_module_registration_hooks)
  140. _global_module_registration_hooks[handle.id] = hook
  141. return handle
  142. def register_module_parameter_registration_hook(
  143. hook: Callable[..., None],
  144. ) -> RemovableHandle:
  145. r"""Register a parameter registration hook common to all modules.
  146. .. warning ::
  147. This adds global state to the `nn.Module` module
  148. The hook will be called every time :func:`register_parameter` is invoked.
  149. It should have the following signature::
  150. hook(module, name, param) -> None or new parameter
  151. The hook can modify the input or return a single modified value in the hook.
  152. Returns:
  153. :class:`torch.utils.hooks.RemovableHandle`:
  154. a handle that can be used to remove the added hook by calling
  155. ``handle.remove()``
  156. """
  157. handle = RemovableHandle(_global_parameter_registration_hooks)
  158. _global_parameter_registration_hooks[handle.id] = hook
  159. return handle
  160. def register_module_forward_pre_hook(hook: Callable[..., None]) -> RemovableHandle:
  161. r"""Register a forward pre-hook common to all modules.
  162. .. warning ::
  163. This adds global state to the `nn.module` module
  164. and it is only intended for debugging/profiling purposes.
  165. The hook will be called every time before :func:`forward` is invoked.
  166. It should have the following signature::
  167. hook(module, input) -> None or modified input
  168. The input contains only the positional arguments given to the module.
  169. Keyword arguments won't be passed to the hooks and only to the ``forward``.
  170. The hook can modify the input. User can either return a tuple or a
  171. single modified value in the hook. We will wrap the value into a tuple
  172. if a single value is returned(unless that value is already a tuple).
  173. This hook has precedence over the specific module hooks registered with
  174. ``register_forward_pre_hook``.
  175. Returns:
  176. :class:`torch.utils.hooks.RemovableHandle`:
  177. a handle that can be used to remove the added hook by calling
  178. ``handle.remove()``
  179. """
  180. handle = RemovableHandle(_global_forward_pre_hooks)
  181. _global_forward_pre_hooks[handle.id] = hook
  182. return handle
  183. def register_module_forward_hook(
  184. hook: Callable[..., None],
  185. *,
  186. with_kwargs: bool = False,
  187. always_call: bool = False,
  188. ) -> RemovableHandle:
  189. r"""Register a global forward hook for all the modules.
  190. .. warning ::
  191. This adds global state to the `nn.module` module
  192. and it is only intended for debugging/profiling purposes.
  193. The hook will be called every time after :func:`forward` has computed an output.
  194. It should have the following signature::
  195. hook(module, input, output) -> None or modified output
  196. The input contains only the positional arguments given to the module.
  197. Keyword arguments won't be passed to the hooks and only to the ``forward``.
  198. You can optionally modify the output of the module by returning a new value
  199. that will replace the output from the :func:`forward` function.
  200. Parameters:
  201. hook (Callable): The user defined hook to be registered.
  202. always_call (bool): If ``True`` the ``hook`` will be run regardless of
  203. whether an exception is raised while calling the Module.
  204. Default: ``False``
  205. Returns:
  206. :class:`torch.utils.hooks.RemovableHandle`:
  207. a handle that can be used to remove the added hook by calling
  208. ``handle.remove()``
  209. This hook will be executed before specific module hooks registered with
  210. ``register_forward_hook``.
  211. """
  212. handle = RemovableHandle(
  213. _global_forward_hooks, extra_dict=_global_forward_hooks_always_called
  214. )
  215. _global_forward_hooks[handle.id] = hook
  216. if with_kwargs:
  217. _global_forward_hooks_with_kwargs[handle.id] = True
  218. if always_call:
  219. _global_forward_hooks_always_called[handle.id] = True
  220. return handle
  221. def register_module_backward_hook(
  222. hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]],
  223. ) -> RemovableHandle:
  224. r"""Register a backward hook common to all the modules.
  225. This function is deprecated in favor of
  226. :func:`torch.nn.modules.module.register_module_full_backward_hook`
  227. and the behavior of this function will change in future versions.
  228. Returns:
  229. :class:`torch.utils.hooks.RemovableHandle`:
  230. a handle that can be used to remove the added hook by calling
  231. ``handle.remove()``
  232. """
  233. global _global_is_full_backward_hook
  234. if _global_is_full_backward_hook is True:
  235. raise RuntimeError(
  236. "Cannot use both regular backward hooks and full backward hooks as a "
  237. "global Module hook. Please use only one of them."
  238. )
  239. _global_is_full_backward_hook = False
  240. handle = RemovableHandle(_global_backward_hooks)
  241. _global_backward_hooks[handle.id] = hook
  242. return handle
  243. def register_module_full_backward_pre_hook(
  244. hook: Callable[["Module", _grad_t], Union[None, _grad_t]],
  245. ) -> RemovableHandle:
  246. r"""Register a backward pre-hook common to all the modules.
  247. .. warning ::
  248. This adds global state to the `nn.module` module
  249. and it is only intended for debugging/profiling purposes.
  250. Hooks registered using this function behave in the same way as those
  251. registered by :meth:`torch.nn.Module.register_full_backward_pre_hook`.
  252. Refer to its documentation for more details.
  253. Hooks registered using this function will be called before hooks registered
  254. using :meth:`torch.nn.Module.register_full_backward_pre_hook`.
  255. Returns:
  256. :class:`torch.utils.hooks.RemovableHandle`:
  257. a handle that can be used to remove the added hook by calling
  258. ``handle.remove()``
  259. """
  260. handle = RemovableHandle(_global_backward_pre_hooks)
  261. _global_backward_pre_hooks[handle.id] = hook
  262. return handle
  263. def register_module_full_backward_hook(
  264. hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]],
  265. ) -> RemovableHandle:
  266. r"""Register a backward hook common to all the modules.
  267. .. warning ::
  268. This adds global state to the `nn.module` module
  269. and it is only intended for debugging/profiling purposes.
  270. Hooks registered using this function behave in the same way as those
  271. registered by :meth:`torch.nn.Module.register_full_backward_hook`.
  272. Refer to its documentation for more details.
  273. Hooks registered using this function will be called before hooks registered
  274. using :meth:`torch.nn.Module.register_full_backward_hook`.
  275. Returns:
  276. :class:`torch.utils.hooks.RemovableHandle`:
  277. a handle that can be used to remove the added hook by calling
  278. ``handle.remove()``
  279. """
  280. global _global_is_full_backward_hook
  281. if _global_is_full_backward_hook is False:
  282. raise RuntimeError(
  283. "Cannot use both regular backward hooks and full backward hooks as a "
  284. "global Module hook. Please use only one of them."
  285. )
  286. _global_is_full_backward_hook = True
  287. handle = RemovableHandle(_global_backward_hooks)
  288. _global_backward_hooks[handle.id] = hook
  289. return handle
  290. # Trick mypy into not applying contravariance rules to inputs by defining
  291. # forward as a value, rather than a function. See also
  292. # https://github.com/python/mypy/issues/8795
  293. def _forward_unimplemented(self, *input: Any) -> None:
  294. r"""Define the computation performed at every call.
  295. Should be overridden by all subclasses.
  296. .. note::
  297. Although the recipe for forward pass needs to be defined within
  298. this function, one should call the :class:`Module` instance afterwards
  299. instead of this since the former takes care of running the
  300. registered hooks while the latter silently ignores them.
  301. """
  302. raise NotImplementedError(
  303. f'Module [{type(self).__name__}] is missing the required "forward" function'
  304. )
  305. class Module:
  306. r"""Base class for all neural network modules.
  307. Your models should also subclass this class.
  308. Modules can also contain other Modules, allowing them to be nested in
  309. a tree structure. You can assign the submodules as regular attributes::
  310. import torch.nn as nn
  311. import torch.nn.functional as F
  312. class Model(nn.Module):
  313. def __init__(self) -> None:
  314. super().__init__()
  315. self.conv1 = nn.Conv2d(1, 20, 5)
  316. self.conv2 = nn.Conv2d(20, 20, 5)
  317. def forward(self, x):
  318. x = F.relu(self.conv1(x))
  319. return F.relu(self.conv2(x))
  320. Submodules assigned in this way will be registered, and will also have their
  321. parameters converted when you call :meth:`to`, etc.
  322. .. note::
  323. As per the example above, an ``__init__()`` call to the parent class
  324. must be made before assignment on the child.
  325. :ivar training: Boolean represents whether this module is in training or
  326. evaluation mode.
  327. :vartype training: bool
  328. """
  329. dump_patches: bool = False
  330. _version: int = 1
  331. r"""This allows better BC support for :meth:`load_state_dict`. In
  332. :meth:`state_dict`, the version number will be saved as in the attribute
  333. `_metadata` of the returned state dict, and thus pickled. `_metadata` is a
  334. dictionary with keys that follow the naming convention of state dict. See
  335. ``_load_from_state_dict`` on how to use this information in loading.
  336. If new parameters/buffers are added/removed from a module, this number shall
  337. be bumped, and the module's `_load_from_state_dict` method can compare the
  338. version number and do appropriate changes if the state dict is from before
  339. the change."""
  340. training: bool
  341. _parameters: dict[str, Optional[Parameter]]
  342. _buffers: dict[str, Optional[Tensor]]
  343. _non_persistent_buffers_set: set[str]
  344. _backward_pre_hooks: dict[int, Callable]
  345. _backward_hooks: dict[int, Callable]
  346. _is_full_backward_hook: Optional[bool]
  347. _forward_hooks: dict[int, Callable]
  348. # Marks whether the corresponding _forward_hooks accept kwargs or not.
  349. # As JIT does not support set[int], this dict is used as a set, where all
  350. # hooks represented in this dict accept kwargs.
  351. _forward_hooks_with_kwargs: dict[int, bool]
  352. # forward hooks that should always be called even if an exception is raised
  353. _forward_hooks_always_called: dict[int, bool]
  354. _forward_pre_hooks: dict[int, Callable]
  355. # Marks whether the corresponding _forward_hooks accept kwargs or not.
  356. # As JIT does not support set[int], this dict is used as a set, where all
  357. # hooks represented in this dict accept kwargs.
  358. _forward_pre_hooks_with_kwargs: dict[int, bool]
  359. _state_dict_hooks: dict[int, Callable]
  360. _load_state_dict_pre_hooks: dict[int, Callable]
  361. _state_dict_pre_hooks: dict[int, Callable]
  362. _load_state_dict_post_hooks: dict[int, Callable]
  363. _modules: dict[str, Optional["Module"]]
  364. call_super_init: bool = False
  365. _compiled_call_impl: Optional[Callable] = None
  366. def __init__(self, *args, **kwargs) -> None:
  367. """Initialize internal Module state, shared by both nn.Module and ScriptModule."""
  368. torch._C._log_api_usage_once("python.nn_module")
  369. # Backward compatibility: no args used to be allowed when call_super_init=False
  370. if self.call_super_init is False and bool(kwargs):
  371. raise TypeError(
  372. f"{type(self).__name__}.__init__() got an unexpected keyword argument '{next(iter(kwargs))}'"
  373. ""
  374. )
  375. if self.call_super_init is False and bool(args):
  376. raise TypeError(
  377. f"{type(self).__name__}.__init__() takes 1 positional argument but {len(args) + 1} were"
  378. " given"
  379. )
  380. """
  381. Calls super().__setattr__('a', a) instead of the typical self.a = a
  382. to avoid Module.__setattr__ overhead. Module's __setattr__ has special
  383. handling for parameters, submodules, and buffers but simply calls into
  384. super().__setattr__ for all other attributes.
  385. """
  386. super().__setattr__("training", True)
  387. super().__setattr__("_parameters", {})
  388. super().__setattr__("_buffers", {})
  389. super().__setattr__("_non_persistent_buffers_set", set())
  390. super().__setattr__("_backward_pre_hooks", OrderedDict())
  391. super().__setattr__("_backward_hooks", OrderedDict())
  392. super().__setattr__("_is_full_backward_hook", None)
  393. super().__setattr__("_forward_hooks", OrderedDict())
  394. super().__setattr__("_forward_hooks_with_kwargs", OrderedDict())
  395. super().__setattr__("_forward_hooks_always_called", OrderedDict())
  396. super().__setattr__("_forward_pre_hooks", OrderedDict())
  397. super().__setattr__("_forward_pre_hooks_with_kwargs", OrderedDict())
  398. super().__setattr__("_state_dict_hooks", OrderedDict())
  399. super().__setattr__("_state_dict_pre_hooks", OrderedDict())
  400. super().__setattr__("_load_state_dict_pre_hooks", OrderedDict())
  401. super().__setattr__("_load_state_dict_post_hooks", OrderedDict())
  402. super().__setattr__("_modules", {})
  403. if self.call_super_init:
  404. super().__init__(*args, **kwargs)
  405. forward: Callable[..., Any] = _forward_unimplemented
  406. def register_buffer(
  407. self, name: str, tensor: Optional[Tensor], persistent: bool = True
  408. ) -> None:
  409. r"""Add a buffer to the module.
  410. This is typically used to register a buffer that should not be
  411. considered a model parameter. For example, BatchNorm's ``running_mean``
  412. is not a parameter, but is part of the module's state. Buffers, by
  413. default, are persistent and will be saved alongside parameters. This
  414. behavior can be changed by setting :attr:`persistent` to ``False``. The
  415. only difference between a persistent buffer and a non-persistent buffer
  416. is that the latter will not be a part of this module's
  417. :attr:`state_dict`.
  418. Buffers can be accessed as attributes using given names.
  419. Args:
  420. name (str): name of the buffer. The buffer can be accessed
  421. from this module using the given name
  422. tensor (Tensor or None): buffer to be registered. If ``None``, then operations
  423. that run on buffers, such as :attr:`cuda`, are ignored. If ``None``,
  424. the buffer is **not** included in the module's :attr:`state_dict`.
  425. persistent (bool): whether the buffer is part of this module's
  426. :attr:`state_dict`.
  427. Example::
  428. >>> # xdoctest: +SKIP("undefined vars")
  429. >>> self.register_buffer('running_mean', torch.zeros(num_features))
  430. """
  431. if persistent is False and isinstance(self, torch.jit.ScriptModule):
  432. raise RuntimeError("ScriptModule does not support non-persistent buffers")
  433. if "_buffers" not in self.__dict__:
  434. raise AttributeError("cannot assign buffer before Module.__init__() call")
  435. elif not isinstance(name, str):
  436. raise TypeError(
  437. f"buffer name should be a string. Got {torch.typename(name)}"
  438. )
  439. elif "." in name:
  440. raise KeyError('buffer name can\'t contain "."')
  441. elif name == "":
  442. raise KeyError('buffer name can\'t be empty string ""')
  443. elif hasattr(self, name) and name not in self._buffers:
  444. raise KeyError(f"attribute '{name}' already exists")
  445. elif tensor is not None and not (
  446. isinstance(tensor, torch.Tensor) or hasattr(tensor, "__torch_function__")
  447. ):
  448. raise TypeError(
  449. f"cannot assign '{torch.typename(tensor)}' object to buffer '{name}' "
  450. "(torch Tensor or None required)"
  451. )
  452. else:
  453. for hook in _global_buffer_registration_hooks.values():
  454. output = hook(self, name, tensor)
  455. if output is not None:
  456. tensor = output
  457. self._buffers[name] = tensor
  458. if persistent:
  459. self._non_persistent_buffers_set.discard(name)
  460. else:
  461. self._non_persistent_buffers_set.add(name)
  462. def register_parameter(self, name: str, param: Optional[Parameter]) -> None:
  463. r"""Add a parameter to the module.
  464. The parameter can be accessed as an attribute using given name.
  465. Args:
  466. name (str): name of the parameter. The parameter can be accessed
  467. from this module using the given name
  468. param (Parameter or None): parameter to be added to the module. If
  469. ``None``, then operations that run on parameters, such as :attr:`cuda`,
  470. are ignored. If ``None``, the parameter is **not** included in the
  471. module's :attr:`state_dict`.
  472. """
  473. if "_parameters" not in self.__dict__:
  474. raise AttributeError(
  475. "cannot assign parameter before Module.__init__() call"
  476. )
  477. elif not isinstance(name, str):
  478. raise TypeError(
  479. f"parameter name should be a string. Got {torch.typename(name)}"
  480. )
  481. elif "." in name:
  482. raise KeyError('parameter name can\'t contain "."')
  483. elif name == "":
  484. raise KeyError('parameter name can\'t be empty string ""')
  485. elif hasattr(self, name) and name not in self._parameters:
  486. raise KeyError(f"attribute '{name}' already exists")
  487. if param is None:
  488. self._parameters[name] = None
  489. elif not isinstance(param, Parameter):
  490. raise TypeError(
  491. f"cannot assign '{torch.typename(param)}' object to parameter '{name}' "
  492. "(torch.nn.Parameter or None required)"
  493. )
  494. elif param.grad_fn:
  495. raise ValueError(
  496. f"Cannot assign non-leaf Tensor to parameter '{name}'. Model "
  497. f"parameters must be created explicitly. To express '{name}' "
  498. "as a function of another Tensor, compute the value in "
  499. "the forward() method."
  500. )
  501. else:
  502. for hook in _global_parameter_registration_hooks.values():
  503. output = hook(self, name, param)
  504. if output is not None:
  505. param = output
  506. self._parameters[name] = param
  507. def add_module(self, name: str, module: Optional["Module"]) -> None:
  508. r"""Add a child module to the current module.
  509. The module can be accessed as an attribute using the given name.
  510. Args:
  511. name (str): name of the child module. The child module can be
  512. accessed from this module using the given name
  513. module (Module): child module to be added to the module.
  514. """
  515. if not isinstance(module, Module) and module is not None:
  516. raise TypeError(f"{torch.typename(module)} is not a Module subclass")
  517. elif not isinstance(name, str):
  518. raise TypeError(
  519. f"module name should be a string. Got {torch.typename(name)}"
  520. )
  521. elif hasattr(self, name) and name not in self._modules:
  522. raise KeyError(f"attribute '{name}' already exists")
  523. elif "." in name:
  524. raise KeyError(f'module name can\'t contain ".", got: {name}')
  525. elif name == "":
  526. raise KeyError('module name can\'t be empty string ""')
  527. for hook in _global_module_registration_hooks.values():
  528. output = hook(self, name, module)
  529. if output is not None:
  530. module = output
  531. self._modules[name] = module
  532. def register_module(self, name: str, module: Optional["Module"]) -> None:
  533. r"""Alias for :func:`add_module`."""
  534. self.add_module(name, module)
  535. def get_submodule(self, target: str) -> "Module":
  536. """Return the submodule given by ``target`` if it exists, otherwise throw an error.
  537. For example, let's say you have an ``nn.Module`` ``A`` that
  538. looks like this:
  539. .. code-block:: text
  540. A(
  541. (net_b): Module(
  542. (net_c): Module(
  543. (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
  544. )
  545. (linear): Linear(in_features=100, out_features=200, bias=True)
  546. )
  547. )
  548. (The diagram shows an ``nn.Module`` ``A``. ``A`` which has a nested
  549. submodule ``net_b``, which itself has two submodules ``net_c``
  550. and ``linear``. ``net_c`` then has a submodule ``conv``.)
  551. To check whether or not we have the ``linear`` submodule, we
  552. would call ``get_submodule("net_b.linear")``. To check whether
  553. we have the ``conv`` submodule, we would call
  554. ``get_submodule("net_b.net_c.conv")``.
  555. The runtime of ``get_submodule`` is bounded by the degree
  556. of module nesting in ``target``. A query against
  557. ``named_modules`` achieves the same result, but it is O(N) in
  558. the number of transitive modules. So, for a simple check to see
  559. if some submodule exists, ``get_submodule`` should always be
  560. used.
  561. Args:
  562. target: The fully-qualified string name of the submodule
  563. to look for. (See above example for how to specify a
  564. fully-qualified string.)
  565. Returns:
  566. torch.nn.Module: The submodule referenced by ``target``
  567. Raises:
  568. AttributeError: If at any point along the path resulting from
  569. the target string the (sub)path resolves to a non-existent
  570. attribute name or an object that is not an instance of ``nn.Module``.
  571. """
  572. if target == "":
  573. return self
  574. atoms: list[str] = target.split(".")
  575. mod: torch.nn.Module = self
  576. for item in atoms:
  577. if not hasattr(mod, item):
  578. raise AttributeError(
  579. mod._get_name() + " has no attribute `" + item + "`"
  580. )
  581. mod = getattr(mod, item)
  582. if not isinstance(mod, torch.nn.Module):
  583. raise AttributeError("`" + item + "` is not an nn.Module")
  584. return mod
  585. def set_submodule(
  586. self, target: str, module: "Module", strict: bool = False
  587. ) -> None:
  588. """
  589. Set the submodule given by ``target`` if it exists, otherwise throw an error.
  590. .. note::
  591. If ``strict`` is set to ``False`` (default), the method will replace an existing submodule
  592. or create a new submodule if the parent module exists. If ``strict`` is set to ``True``,
  593. the method will only attempt to replace an existing submodule and throw an error if
  594. the submodule does not exist.
  595. For example, let's say you have an ``nn.Module`` ``A`` that
  596. looks like this:
  597. .. code-block:: text
  598. A(
  599. (net_b): Module(
  600. (net_c): Module(
  601. (conv): Conv2d(3, 3, 3)
  602. )
  603. (linear): Linear(3, 3)
  604. )
  605. )
  606. (The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested
  607. submodule ``net_b``, which itself has two submodules ``net_c``
  608. and ``linear``. ``net_c`` then has a submodule ``conv``.)
  609. To override the ``Conv2d`` with a new submodule ``Linear``, you
  610. could call ``set_submodule("net_b.net_c.conv", nn.Linear(1, 1))``
  611. where ``strict`` could be ``True`` or ``False``
  612. To add a new submodule ``Conv2d`` to the existing ``net_b`` module,
  613. you would call ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1))``.
  614. In the above if you set ``strict=True`` and call
  615. ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True)``, an AttributeError
  616. will be raised because ``net_b`` does not have a submodule named ``conv``.
  617. Args:
  618. target: The fully-qualified string name of the submodule
  619. to look for. (See above example for how to specify a
  620. fully-qualified string.)
  621. module: The module to set the submodule to.
  622. strict: If ``False``, the method will replace an existing submodule
  623. or create a new submodule if the parent module exists. If ``True``,
  624. the method will only attempt to replace an existing submodule and throw an error
  625. if the submodule doesn't already exist.
  626. Raises:
  627. ValueError: If the ``target`` string is empty or if ``module`` is not an instance of ``nn.Module``.
  628. AttributeError: If at any point along the path resulting from
  629. the ``target`` string the (sub)path resolves to a non-existent
  630. attribute name or an object that is not an instance of ``nn.Module``.
  631. """
  632. if target == "":
  633. raise ValueError("Cannot set the submodule without a target name!")
  634. atoms: list[str] = target.split(".")
  635. if not isinstance(module, torch.nn.Module):
  636. raise ValueError(
  637. "`" + "module" + f"` is not an nn.Module, found {type(module)}"
  638. )
  639. if len(atoms) == 1:
  640. parent: torch.nn.Module = self
  641. else:
  642. parent_key = ".".join(atoms[:-1])
  643. parent = self.get_submodule(parent_key)
  644. if strict and not hasattr(parent, atoms[-1]):
  645. raise AttributeError(
  646. parent._get_name() + " has no attribute `" + atoms[-1] + "`"
  647. )
  648. if hasattr(parent, atoms[-1]):
  649. mod = getattr(parent, atoms[-1])
  650. if not isinstance(mod, torch.nn.Module):
  651. raise AttributeError("`" + atoms[-1] + "` is not an nn.Module")
  652. setattr(parent, atoms[-1], module)
  653. def get_parameter(self, target: str) -> "Parameter":
  654. """Return the parameter given by ``target`` if it exists, otherwise throw an error.
  655. See the docstring for ``get_submodule`` for a more detailed
  656. explanation of this method's functionality as well as how to
  657. correctly specify ``target``.
  658. Args:
  659. target: The fully-qualified string name of the Parameter
  660. to look for. (See ``get_submodule`` for how to specify a
  661. fully-qualified string.)
  662. Returns:
  663. torch.nn.Parameter: The Parameter referenced by ``target``
  664. Raises:
  665. AttributeError: If the target string references an invalid
  666. path or resolves to something that is not an
  667. ``nn.Parameter``
  668. """
  669. module_path, _, param_name = target.rpartition(".")
  670. mod: torch.nn.Module = self.get_submodule(module_path)
  671. if not hasattr(mod, param_name):
  672. raise AttributeError(
  673. mod._get_name() + " has no attribute `" + param_name + "`"
  674. )
  675. param: torch.nn.Parameter = getattr(mod, param_name)
  676. if not isinstance(param, torch.nn.Parameter):
  677. raise AttributeError("`" + param_name + "` is not an nn.Parameter")
  678. return param
  679. def get_buffer(self, target: str) -> "Tensor":
  680. """Return the buffer given by ``target`` if it exists, otherwise throw an error.
  681. See the docstring for ``get_submodule`` for a more detailed
  682. explanation of this method's functionality as well as how to
  683. correctly specify ``target``.
  684. Args:
  685. target: The fully-qualified string name of the buffer
  686. to look for. (See ``get_submodule`` for how to specify a
  687. fully-qualified string.)
  688. Returns:
  689. torch.Tensor: The buffer referenced by ``target``
  690. Raises:
  691. AttributeError: If the target string references an invalid
  692. path or resolves to something that is not a
  693. buffer
  694. """
  695. module_path, _, buffer_name = target.rpartition(".")
  696. mod: torch.nn.Module = self.get_submodule(module_path)
  697. if not hasattr(mod, buffer_name):
  698. raise AttributeError(
  699. mod._get_name() + " has no attribute `" + buffer_name + "`"
  700. )
  701. buffer: torch.Tensor = getattr(mod, buffer_name)
  702. if buffer_name not in mod._buffers:
  703. raise AttributeError("`" + buffer_name + "` is not a buffer")
  704. return buffer
  705. def get_extra_state(self) -> Any:
  706. """Return any extra state to include in the module's state_dict.
  707. Implement this and a corresponding :func:`set_extra_state` for your module
  708. if you need to store extra state. This function is called when building the
  709. module's `state_dict()`.
  710. Note that extra state should be picklable to ensure working serialization
  711. of the state_dict. We only provide backwards compatibility guarantees
  712. for serializing Tensors; other objects may break backwards compatibility if
  713. their serialized pickled form changes.
  714. Returns:
  715. object: Any extra state to store in the module's state_dict
  716. """
  717. raise RuntimeError(
  718. "Reached a code path in Module.get_extra_state() that should never be called. "
  719. "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
  720. "to report this bug."
  721. )
  722. def set_extra_state(self, state: Any) -> None:
  723. """Set extra state contained in the loaded `state_dict`.
  724. This function is called from :func:`load_state_dict` to handle any extra state
  725. found within the `state_dict`. Implement this function and a corresponding
  726. :func:`get_extra_state` for your module if you need to store extra state within its
  727. `state_dict`.
  728. Args:
  729. state (dict): Extra state from the `state_dict`
  730. """
  731. raise RuntimeError(
  732. "Reached a code path in Module.set_extra_state() that should never be called. "
  733. "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
  734. "to report this bug."
  735. )
  736. def _apply(self, fn, recurse=True):
  737. if recurse:
  738. for module in self.children():
  739. module._apply(fn)
  740. def compute_should_use_set_data(tensor, tensor_applied) -> bool:
  741. if torch._has_compatible_shallow_copy_type(tensor, tensor_applied):
  742. # If the new tensor has compatible tensor type as the existing tensor,
  743. # the current behavior is to change the tensor in-place using `.data =`,
  744. # and the future behavior is to overwrite the existing tensor. However,
  745. # changing the current behavior is a BC-breaking change, and we want it
  746. # to happen in future releases. So for now we introduce the
  747. # `torch.__future__.get_overwrite_module_params_on_conversion()`
  748. # global flag to let the user control whether they want the future
  749. # behavior of overwriting the existing tensor or not.
  750. return not torch.__future__.get_overwrite_module_params_on_conversion()
  751. else:
  752. return False
  753. should_use_swap_tensors = (
  754. torch.__future__.get_swap_module_params_on_conversion()
  755. )
  756. for key, param in self._parameters.items():
  757. if param is None:
  758. continue
  759. # Tensors stored in modules are graph leaves, and we don't want to
  760. # track autograd history of `param_applied`, so we have to use
  761. # `with torch.no_grad():`
  762. with torch.no_grad():
  763. param_applied = fn(param)
  764. p_should_use_set_data = compute_should_use_set_data(param, param_applied)
  765. from torch._subclasses.fake_tensor import FakeTensor
  766. # subclasses may have multiple child tensors so we need to use swap_tensors
  767. p_should_use_swap_tensors = (
  768. should_use_swap_tensors
  769. or is_traceable_wrapper_subclass(param_applied)
  770. or isinstance(param, FakeTensor)
  771. )
  772. param_grad = param.grad
  773. if p_should_use_swap_tensors:
  774. try:
  775. if param_grad is not None:
  776. # Accessing param.grad makes its at::Tensor's use_count 2, which will prevent swapping.
  777. # Decrement use count of the gradient by setting to None
  778. param.grad = None
  779. param_applied = torch.nn.Parameter(
  780. param_applied, requires_grad=param.requires_grad
  781. )
  782. torch.utils.swap_tensors(param, param_applied)
  783. except Exception as e:
  784. if param_grad is not None:
  785. param.grad = param_grad
  786. raise RuntimeError(
  787. f"_apply(): Couldn't swap {self._get_name()}.{key}"
  788. ) from e
  789. out_param = param
  790. elif p_should_use_set_data:
  791. param.data = param_applied
  792. out_param = param
  793. else:
  794. assert isinstance(param, Parameter)
  795. assert param.is_leaf
  796. out_param = Parameter(param_applied, param.requires_grad)
  797. self._parameters[key] = out_param
  798. if param_grad is not None:
  799. with torch.no_grad():
  800. grad_applied = fn(param_grad)
  801. g_should_use_set_data = compute_should_use_set_data(
  802. param_grad, grad_applied
  803. )
  804. if p_should_use_swap_tensors:
  805. grad_applied.requires_grad_(param_grad.requires_grad)
  806. try:
  807. torch.utils.swap_tensors(param_grad, grad_applied)
  808. except Exception as e:
  809. raise RuntimeError(
  810. f"_apply(): Couldn't swap {self._get_name()}.{key}.grad"
  811. ) from e
  812. out_param.grad = param_grad
  813. elif g_should_use_set_data:
  814. assert out_param.grad is not None
  815. out_param.grad.data = grad_applied
  816. else:
  817. assert param_grad.is_leaf
  818. out_param.grad = grad_applied.requires_grad_(
  819. param_grad.requires_grad
  820. )
  821. for key, buf in self._buffers.items():
  822. if buf is not None:
  823. self._buffers[key] = fn(buf)
  824. return self
  825. def apply(self, fn: Callable[["Module"], None]) -> Self:
  826. r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.
  827. Typical use includes initializing the parameters of a model
  828. (see also :ref:`nn-init-doc`).
  829. Args:
  830. fn (:class:`Module` -> None): function to be applied to each submodule
  831. Returns:
  832. Module: self
  833. Example::
  834. >>> @torch.no_grad()
  835. >>> def init_weights(m):
  836. >>> print(m)
  837. >>> if type(m) == nn.Linear:
  838. >>> m.weight.fill_(1.0)
  839. >>> print(m.weight)
  840. >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
  841. >>> net.apply(init_weights)
  842. Linear(in_features=2, out_features=2, bias=True)
  843. Parameter containing:
  844. tensor([[1., 1.],
  845. [1., 1.]], requires_grad=True)
  846. Linear(in_features=2, out_features=2, bias=True)
  847. Parameter containing:
  848. tensor([[1., 1.],
  849. [1., 1.]], requires_grad=True)
  850. Sequential(
  851. (0): Linear(in_features=2, out_features=2, bias=True)
  852. (1): Linear(in_features=2, out_features=2, bias=True)
  853. )
  854. """
  855. for module in self.children():
  856. module.apply(fn)
  857. fn(self)
  858. return self
  859. def cuda(self, device: Optional[Union[int, device]] = None) -> Self:
  860. r"""Move all model parameters and buffers to the GPU.
  861. This also makes associated parameters and buffers different objects. So
  862. it should be called before constructing the optimizer if the module will
  863. live on GPU while being optimized.
  864. .. note::
  865. This method modifies the module in-place.
  866. Args:
  867. device (int, optional): if specified, all parameters will be
  868. copied to that device
  869. Returns:
  870. Module: self
  871. """
  872. return self._apply(lambda t: t.cuda(device))
  873. def ipu(self, device: Optional[Union[int, device]] = None) -> Self:
  874. r"""Move all model parameters and buffers to the IPU.
  875. This also makes associated parameters and buffers different objects. So
  876. it should be called before constructing the optimizer if the module will
  877. live on IPU while being optimized.
  878. .. note::
  879. This method modifies the module in-place.
  880. Arguments:
  881. device (int, optional): if specified, all parameters will be
  882. copied to that device
  883. Returns:
  884. Module: self
  885. """
  886. return self._apply(lambda t: t.ipu(device))
  887. def xpu(self, device: Optional[Union[int, device]] = None) -> Self:
  888. r"""Move all model parameters and buffers to the XPU.
  889. This also makes associated parameters and buffers different objects. So
  890. it should be called before constructing optimizer if the module will
  891. live on XPU while being optimized.
  892. .. note::
  893. This method modifies the module in-place.
  894. Arguments:
  895. device (int, optional): if specified, all parameters will be
  896. copied to that device
  897. Returns:
  898. Module: self
  899. """
  900. return self._apply(lambda t: t.xpu(device))
  901. def mtia(self, device: Optional[Union[int, device]] = None) -> Self:
  902. r"""Move all model parameters and buffers to the MTIA.
  903. This also makes associated parameters and buffers different objects. So
  904. it should be called before constructing the optimizer if the module will
  905. live on MTIA while being optimized.
  906. .. note::
  907. This method modifies the module in-place.
  908. Arguments:
  909. device (int, optional): if specified, all parameters will be
  910. copied to that device
  911. Returns:
  912. Module: self
  913. """
  914. return self._apply(lambda t: t.mtia(device))
  915. def cpu(self) -> Self:
  916. r"""Move all model parameters and buffers to the CPU.
  917. .. note::
  918. This method modifies the module in-place.
  919. Returns:
  920. Module: self
  921. """
  922. return self._apply(lambda t: t.cpu())
  923. def type(self, dst_type: Union[dtype, str]) -> Self:
  924. r"""Casts all parameters and buffers to :attr:`dst_type`.
  925. .. note::
  926. This method modifies the module in-place.
  927. Args:
  928. dst_type (type or string): the desired type
  929. Returns:
  930. Module: self
  931. """
  932. return self._apply(lambda t: t.type(dst_type))
  933. def float(self) -> Self:
  934. r"""Casts all floating point parameters and buffers to ``float`` datatype.
  935. .. note::
  936. This method modifies the module in-place.
  937. Returns:
  938. Module: self
  939. """
  940. return self._apply(lambda t: t.float() if t.is_floating_point() else t)
  941. def double(self) -> Self:
  942. r"""Casts all floating point parameters and buffers to ``double`` datatype.
  943. .. note::
  944. This method modifies the module in-place.
  945. Returns:
  946. Module: self
  947. """
  948. return self._apply(lambda t: t.double() if t.is_floating_point() else t)
  949. def half(self) -> Self:
  950. r"""Casts all floating point parameters and buffers to ``half`` datatype.
  951. .. note::
  952. This method modifies the module in-place.
  953. Returns:
  954. Module: self
  955. """
  956. return self._apply(lambda t: t.half() if t.is_floating_point() else t)
  957. def bfloat16(self) -> Self:
  958. r"""Casts all floating point parameters and buffers to ``bfloat16`` datatype.
  959. .. note::
  960. This method modifies the module in-place.
  961. Returns:
  962. Module: self
  963. """
  964. return self._apply(lambda t: t.bfloat16() if t.is_floating_point() else t)
  965. def to_empty(
  966. self, *, device: Optional[DeviceLikeType], recurse: bool = True
  967. ) -> Self:
  968. r"""Move the parameters and buffers to the specified device without copying storage.
  969. Args:
  970. device (:class:`torch.device`): The desired device of the parameters
  971. and buffers in this module.
  972. recurse (bool): Whether parameters and buffers of submodules should
  973. be recursively moved to the specified device.
  974. Returns:
  975. Module: self
  976. """
  977. return self._apply(
  978. lambda t: torch.empty_like(t, device=device), recurse=recurse
  979. )
  980. @overload
  981. def to(
  982. self,
  983. device: Optional[DeviceLikeType] = ...,
  984. dtype: Optional[dtype] = ...,
  985. non_blocking: bool = ...,
  986. ) -> Self: ...
  987. @overload
  988. def to(self, dtype: dtype, non_blocking: bool = ...) -> Self: ...
  989. @overload
  990. def to(self, tensor: Tensor, non_blocking: bool = ...) -> Self: ...
  991. def to(self, *args, **kwargs):
  992. r"""Move and/or cast the parameters and buffers.
  993. This can be called as
  994. .. function:: to(device=None, dtype=None, non_blocking=False)
  995. :noindex:
  996. .. function:: to(dtype, non_blocking=False)
  997. :noindex:
  998. .. function:: to(tensor, non_blocking=False)
  999. :noindex:
  1000. .. function:: to(memory_format=torch.channels_last)
  1001. :noindex:
  1002. Its signature is similar to :meth:`torch.Tensor.to`, but only accepts
  1003. floating point or complex :attr:`dtype`\ s. In addition, this method will
  1004. only cast the floating point or complex parameters and buffers to :attr:`dtype`
  1005. (if given). The integral parameters and buffers will be moved
  1006. :attr:`device`, if that is given, but with dtypes unchanged. When
  1007. :attr:`non_blocking` is set, it tries to convert/move asynchronously
  1008. with respect to the host if possible, e.g., moving CPU Tensors with
  1009. pinned memory to CUDA devices.
  1010. See below for examples.
  1011. .. note::
  1012. This method modifies the module in-place.
  1013. Args:
  1014. device (:class:`torch.device`): the desired device of the parameters
  1015. and buffers in this module
  1016. dtype (:class:`torch.dtype`): the desired floating point or complex dtype of
  1017. the parameters and buffers in this module
  1018. tensor (torch.Tensor): Tensor whose dtype and device are the desired
  1019. dtype and device for all parameters and buffers in this module
  1020. memory_format (:class:`torch.memory_format`): the desired memory
  1021. format for 4D parameters and buffers in this module (keyword
  1022. only argument)
  1023. Returns:
  1024. Module: self
  1025. Examples::
  1026. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  1027. >>> linear = nn.Linear(2, 2)
  1028. >>> linear.weight
  1029. Parameter containing:
  1030. tensor([[ 0.1913, -0.3420],
  1031. [-0.5113, -0.2325]])
  1032. >>> linear.to(torch.double)
  1033. Linear(in_features=2, out_features=2, bias=True)
  1034. >>> linear.weight
  1035. Parameter containing:
  1036. tensor([[ 0.1913, -0.3420],
  1037. [-0.5113, -0.2325]], dtype=torch.float64)
  1038. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
  1039. >>> gpu1 = torch.device("cuda:1")
  1040. >>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
  1041. Linear(in_features=2, out_features=2, bias=True)
  1042. >>> linear.weight
  1043. Parameter containing:
  1044. tensor([[ 0.1914, -0.3420],
  1045. [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
  1046. >>> cpu = torch.device("cpu")
  1047. >>> linear.to(cpu)
  1048. Linear(in_features=2, out_features=2, bias=True)
  1049. >>> linear.weight
  1050. Parameter containing:
  1051. tensor([[ 0.1914, -0.3420],
  1052. [-0.5112, -0.2324]], dtype=torch.float16)
  1053. >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
  1054. >>> linear.weight
  1055. Parameter containing:
  1056. tensor([[ 0.3741+0.j, 0.2382+0.j],
  1057. [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
  1058. >>> linear(torch.ones(3, 2, dtype=torch.cdouble))
  1059. tensor([[0.6122+0.j, 0.1150+0.j],
  1060. [0.6122+0.j, 0.1150+0.j],
  1061. [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
  1062. """
  1063. device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(
  1064. *args, **kwargs
  1065. )
  1066. if dtype is not None:
  1067. if not (dtype.is_floating_point or dtype.is_complex):
  1068. raise TypeError(
  1069. "nn.Module.to only accepts floating point or complex "
  1070. f"dtypes, but got desired dtype={dtype}"
  1071. )
  1072. if dtype.is_complex:
  1073. warnings.warn(
  1074. "Complex modules are a new feature under active development whose design may change, "
  1075. "and some modules might not work as expected when using complex tensors as parameters or buffers. "
  1076. "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
  1077. "if a complex module does not work as expected."
  1078. )
  1079. def convert(t):
  1080. try:
  1081. if convert_to_format is not None and t.dim() in (4, 5):
  1082. return t.to(
  1083. device,
  1084. dtype if t.is_floating_point() or t.is_complex() else None,
  1085. non_blocking,
  1086. memory_format=convert_to_format,
  1087. )
  1088. return t.to(
  1089. device,
  1090. dtype if t.is_floating_point() or t.is_complex() else None,
  1091. non_blocking,
  1092. )
  1093. except NotImplementedError as e:
  1094. if str(e) == "Cannot copy out of meta tensor; no data!":
  1095. raise NotImplementedError(
  1096. f"{e} Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() "
  1097. f"when moving module from meta to a different device."
  1098. ) from None
  1099. else:
  1100. raise
  1101. return self._apply(convert)
  1102. def register_full_backward_pre_hook(
  1103. self,
  1104. hook: Callable[["Module", _grad_t], Union[None, _grad_t]],
  1105. prepend: bool = False,
  1106. ) -> RemovableHandle:
  1107. r"""Register a backward pre-hook on the module.
  1108. The hook will be called every time the gradients for the module are computed.
  1109. The hook should have the following signature::
  1110. hook(module, grad_output) -> tuple[Tensor] or None
  1111. The :attr:`grad_output` is a tuple. The hook should
  1112. not modify its arguments, but it can optionally return a new gradient with
  1113. respect to the output that will be used in place of :attr:`grad_output` in
  1114. subsequent computations. Entries in :attr:`grad_output` will be ``None`` for
  1115. all non-Tensor arguments.
  1116. For technical reasons, when this hook is applied to a Module, its forward function will
  1117. receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
  1118. of each Tensor returned by the Module's forward function.
  1119. .. warning ::
  1120. Modifying inputs inplace is not allowed when using backward hooks and
  1121. will raise an error.
  1122. Args:
  1123. hook (Callable): The user-defined hook to be registered.
  1124. prepend (bool): If true, the provided ``hook`` will be fired before
  1125. all existing ``backward_pre`` hooks on this
  1126. :class:`torch.nn.Module`. Otherwise, the provided
  1127. ``hook`` will be fired after all existing ``backward_pre`` hooks
  1128. on this :class:`torch.nn.Module`. Note that global
  1129. ``backward_pre`` hooks registered with
  1130. :func:`register_module_full_backward_pre_hook` will fire before
  1131. all hooks registered by this method.
  1132. Returns:
  1133. :class:`torch.utils.hooks.RemovableHandle`:
  1134. a handle that can be used to remove the added hook by calling
  1135. ``handle.remove()``
  1136. """
  1137. handle = RemovableHandle(self._backward_pre_hooks)
  1138. self._backward_pre_hooks[handle.id] = hook
  1139. if prepend:
  1140. self._backward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
  1141. return handle
  1142. def register_backward_hook(
  1143. self, hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]]
  1144. ) -> RemovableHandle:
  1145. r"""Register a backward hook on the module.
  1146. This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and
  1147. the behavior of this function will change in future versions.
  1148. Returns:
  1149. :class:`torch.utils.hooks.RemovableHandle`:
  1150. a handle that can be used to remove the added hook by calling
  1151. ``handle.remove()``
  1152. """
  1153. if self._is_full_backward_hook is True:
  1154. raise RuntimeError(
  1155. "Cannot use both regular backward hooks and full backward hooks on a "
  1156. "single Module. Please use only one of them."
  1157. )
  1158. self._is_full_backward_hook = False
  1159. handle = RemovableHandle(self._backward_hooks)
  1160. self._backward_hooks[handle.id] = hook
  1161. return handle
  1162. def register_full_backward_hook(
  1163. self,
  1164. hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]],
  1165. prepend: bool = False,
  1166. ) -> RemovableHandle:
  1167. r"""Register a backward hook on the module.
  1168. The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
  1169. 1. Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
  1170. 2. If none of the module inputs require gradients, the hook will fire when the gradients are computed
  1171. with respect to module outputs.
  1172. 3. If none of the module outputs require gradients, then the hooks will not fire.
  1173. The hook should have the following signature::
  1174. hook(module, grad_input, grad_output) -> tuple(Tensor) or None
  1175. The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients
  1176. with respect to the inputs and outputs respectively. The hook should
  1177. not modify its arguments, but it can optionally return a new gradient with
  1178. respect to the input that will be used in place of :attr:`grad_input` in
  1179. subsequent computations. :attr:`grad_input` will only correspond to the inputs given
  1180. as positional arguments and all kwarg arguments are ignored. Entries
  1181. in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor
  1182. arguments.
  1183. For technical reasons, when this hook is applied to a Module, its forward function will
  1184. receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
  1185. of each Tensor returned by the Module's forward function.
  1186. .. warning ::
  1187. Modifying inputs or outputs inplace is not allowed when using backward hooks and
  1188. will raise an error.
  1189. Args:
  1190. hook (Callable): The user-defined hook to be registered.
  1191. prepend (bool): If true, the provided ``hook`` will be fired before
  1192. all existing ``backward`` hooks on this
  1193. :class:`torch.nn.Module`. Otherwise, the provided
  1194. ``hook`` will be fired after all existing ``backward`` hooks on
  1195. this :class:`torch.nn.Module`. Note that global
  1196. ``backward`` hooks registered with
  1197. :func:`register_module_full_backward_hook` will fire before
  1198. all hooks registered by this method.
  1199. Returns:
  1200. :class:`torch.utils.hooks.RemovableHandle`:
  1201. a handle that can be used to remove the added hook by calling
  1202. ``handle.remove()``
  1203. """
  1204. if self._is_full_backward_hook is False:
  1205. raise RuntimeError(
  1206. "Cannot use both regular backward hooks and full backward hooks on a "
  1207. "single Module. Please use only one of them."
  1208. )
  1209. self._is_full_backward_hook = True
  1210. handle = RemovableHandle(self._backward_hooks)
  1211. self._backward_hooks[handle.id] = hook
  1212. if prepend:
  1213. self._backward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
  1214. return handle
  1215. def _get_backward_hooks(self):
  1216. r"""Return the backward hooks for use in the call function.
  1217. It returns two lists, one with the full backward hooks and one with the non-full
  1218. backward hooks.
  1219. """
  1220. full_backward_hooks: list[Callable] = []
  1221. if _global_is_full_backward_hook is True:
  1222. full_backward_hooks += _global_backward_hooks.values()
  1223. if self._is_full_backward_hook is True:
  1224. full_backward_hooks += self._backward_hooks.values()
  1225. non_full_backward_hooks: list[Callable] = []
  1226. if _global_is_full_backward_hook is False:
  1227. non_full_backward_hooks += _global_backward_hooks.values()
  1228. if self._is_full_backward_hook is False:
  1229. non_full_backward_hooks += self._backward_hooks.values()
  1230. return full_backward_hooks, non_full_backward_hooks
  1231. def _get_backward_pre_hooks(self):
  1232. backward_pre_hooks: list[Callable] = []
  1233. backward_pre_hooks += _global_backward_pre_hooks.values()
  1234. backward_pre_hooks += self._backward_pre_hooks.values()
  1235. return backward_pre_hooks
  1236. def _maybe_warn_non_full_backward_hook(self, inputs, result, grad_fn) -> None:
  1237. if not isinstance(result, torch.Tensor):
  1238. if not (
  1239. isinstance(result, tuple)
  1240. and all(isinstance(r, torch.Tensor) for r in result)
  1241. ):
  1242. warnings.warn(
  1243. "Using non-full backward hooks on a Module that does not return a "
  1244. "single Tensor or a tuple of Tensors is deprecated and will be removed "
  1245. "in future versions. This hook will be missing some of the grad_output. "
  1246. "Please use register_full_backward_hook to get the documented behavior.",
  1247. FutureWarning,
  1248. stacklevel=2,
  1249. )
  1250. return
  1251. else:
  1252. result = (result,)
  1253. if not isinstance(inputs, torch.Tensor):
  1254. if not (
  1255. isinstance(inputs, tuple)
  1256. and all(isinstance(i, torch.Tensor) for i in inputs)
  1257. ):
  1258. warnings.warn(
  1259. "Using non-full backward hooks on a Module that does not take as input a "
  1260. "single Tensor or a tuple of Tensors is deprecated and will be removed "
  1261. "in future versions. This hook will be missing some of the grad_input. "
  1262. "Please use register_full_backward_hook to get the documented behavior.",
  1263. FutureWarning,
  1264. stacklevel=2,
  1265. )
  1266. return
  1267. else:
  1268. inputs = (inputs,)
  1269. # At this point we are sure that inputs and result are tuple of Tensors
  1270. out_grad_fn = {r.grad_fn for r in result if r.grad_fn is not None}
  1271. if len(out_grad_fn) == 0 or (
  1272. len(out_grad_fn) == 1 and grad_fn not in out_grad_fn
  1273. ):
  1274. warnings.warn(
  1275. "Using a non-full backward hook when outputs are nested in python data structure "
  1276. "is deprecated and will be removed in future versions. This hook will be missing "
  1277. "some grad_output.",
  1278. FutureWarning,
  1279. stacklevel=2,
  1280. )
  1281. elif len(out_grad_fn) > 1:
  1282. warnings.warn(
  1283. "Using a non-full backward hook when outputs are generated by different autograd Nodes "
  1284. "is deprecated and will be removed in future versions. This hook will be missing "
  1285. "some grad_output. Please use register_full_backward_hook to get the documented behavior.",
  1286. FutureWarning,
  1287. stacklevel=2,
  1288. )
  1289. else:
  1290. # At this point the grad_output part of the hook will most likely be correct
  1291. inputs_grad_fn = {i.grad_fn for i in inputs if i.grad_fn is not None}
  1292. next_functions = {n[0] for n in grad_fn.next_functions}
  1293. if inputs_grad_fn != next_functions:
  1294. warnings.warn(
  1295. "Using a non-full backward hook when the forward contains multiple autograd Nodes "
  1296. "is deprecated and will be removed in future versions. This hook will be missing "
  1297. "some grad_input. Please use register_full_backward_hook to get the documented "
  1298. "behavior.",
  1299. FutureWarning,
  1300. stacklevel=2,
  1301. )
  1302. def register_forward_pre_hook(
  1303. self,
  1304. hook: Union[
  1305. Callable[[T, tuple[Any, ...]], Optional[Any]],
  1306. Callable[
  1307. [T, tuple[Any, ...], dict[str, Any]],
  1308. Optional[tuple[Any, dict[str, Any]]],
  1309. ],
  1310. ],
  1311. *,
  1312. prepend: bool = False,
  1313. with_kwargs: bool = False,
  1314. ) -> RemovableHandle:
  1315. r"""Register a forward pre-hook on the module.
  1316. The hook will be called every time before :func:`forward` is invoked.
  1317. If ``with_kwargs`` is false or not specified, the input contains only
  1318. the positional arguments given to the module. Keyword arguments won't be
  1319. passed to the hooks and only to the ``forward``. The hook can modify the
  1320. input. User can either return a tuple or a single modified value in the
  1321. hook. We will wrap the value into a tuple if a single value is returned
  1322. (unless that value is already a tuple). The hook should have the
  1323. following signature::
  1324. hook(module, args) -> None or modified input
  1325. If ``with_kwargs`` is true, the forward pre-hook will be passed the
  1326. kwargs given to the forward function. And if the hook modifies the
  1327. input, both the args and kwargs should be returned. The hook should have
  1328. the following signature::
  1329. hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
  1330. Args:
  1331. hook (Callable): The user defined hook to be registered.
  1332. prepend (bool): If true, the provided ``hook`` will be fired before
  1333. all existing ``forward_pre`` hooks on this
  1334. :class:`torch.nn.Module`. Otherwise, the provided
  1335. ``hook`` will be fired after all existing ``forward_pre`` hooks
  1336. on this :class:`torch.nn.Module`. Note that global
  1337. ``forward_pre`` hooks registered with
  1338. :func:`register_module_forward_pre_hook` will fire before all
  1339. hooks registered by this method.
  1340. Default: ``False``
  1341. with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
  1342. given to the forward function.
  1343. Default: ``False``
  1344. Returns:
  1345. :class:`torch.utils.hooks.RemovableHandle`:
  1346. a handle that can be used to remove the added hook by calling
  1347. ``handle.remove()``
  1348. """
  1349. handle = RemovableHandle(
  1350. self._forward_pre_hooks, extra_dict=self._forward_pre_hooks_with_kwargs
  1351. )
  1352. self._forward_pre_hooks[handle.id] = hook
  1353. if with_kwargs:
  1354. self._forward_pre_hooks_with_kwargs[handle.id] = True
  1355. if prepend:
  1356. self._forward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
  1357. return handle
  1358. def register_forward_hook(
  1359. self,
  1360. hook: Union[
  1361. Callable[[T, tuple[Any, ...], Any], Optional[Any]],
  1362. Callable[[T, tuple[Any, ...], dict[str, Any], Any], Optional[Any]],
  1363. ],
  1364. *,
  1365. prepend: bool = False,
  1366. with_kwargs: bool = False,
  1367. always_call: bool = False,
  1368. ) -> RemovableHandle:
  1369. r"""Register a forward hook on the module.
  1370. The hook will be called every time after :func:`forward` has computed an output.
  1371. If ``with_kwargs`` is ``False`` or not specified, the input contains only
  1372. the positional arguments given to the module. Keyword arguments won't be
  1373. passed to the hooks and only to the ``forward``. The hook can modify the
  1374. output. It can modify the input inplace but it will not have effect on
  1375. forward since this is called after :func:`forward` is called. The hook
  1376. should have the following signature::
  1377. hook(module, args, output) -> None or modified output
  1378. If ``with_kwargs`` is ``True``, the forward hook will be passed the
  1379. ``kwargs`` given to the forward function and be expected to return the
  1380. output possibly modified. The hook should have the following signature::
  1381. hook(module, args, kwargs, output) -> None or modified output
  1382. Args:
  1383. hook (Callable): The user defined hook to be registered.
  1384. prepend (bool): If ``True``, the provided ``hook`` will be fired
  1385. before all existing ``forward`` hooks on this
  1386. :class:`torch.nn.Module`. Otherwise, the provided
  1387. ``hook`` will be fired after all existing ``forward`` hooks on
  1388. this :class:`torch.nn.Module`. Note that global
  1389. ``forward`` hooks registered with
  1390. :func:`register_module_forward_hook` will fire before all hooks
  1391. registered by this method.
  1392. Default: ``False``
  1393. with_kwargs (bool): If ``True``, the ``hook`` will be passed the
  1394. kwargs given to the forward function.
  1395. Default: ``False``
  1396. always_call (bool): If ``True`` the ``hook`` will be run regardless of
  1397. whether an exception is raised while calling the Module.
  1398. Default: ``False``
  1399. Returns:
  1400. :class:`torch.utils.hooks.RemovableHandle`:
  1401. a handle that can be used to remove the added hook by calling
  1402. ``handle.remove()``
  1403. """
  1404. handle = RemovableHandle(
  1405. self._forward_hooks,
  1406. extra_dict=[
  1407. self._forward_hooks_with_kwargs,
  1408. self._forward_hooks_always_called,
  1409. ],
  1410. )
  1411. self._forward_hooks[handle.id] = hook
  1412. if with_kwargs:
  1413. self._forward_hooks_with_kwargs[handle.id] = True
  1414. if always_call:
  1415. self._forward_hooks_always_called[handle.id] = True
  1416. if prepend:
  1417. self._forward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
  1418. return handle
  1419. def _slow_forward(self, *input, **kwargs):
  1420. tracing_state = torch._C._get_tracing_state()
  1421. if not tracing_state or isinstance(self.forward, torch._C.ScriptMethod):
  1422. return self.forward(*input, **kwargs)
  1423. recording_scopes = torch.jit._trace._trace_module_map is not None
  1424. if recording_scopes:
  1425. # type ignore was added because at this point one knows that
  1426. # torch.jit._trace._trace_module_map is not Optional and has type Dict[Any, Any]
  1427. name = (
  1428. torch.jit._trace._trace_module_map[self] # type: ignore[index]
  1429. if self in torch.jit._trace._trace_module_map # type: ignore[operator]
  1430. else None
  1431. ) # noqa: B950
  1432. if name:
  1433. tracing_state.push_scope(name)
  1434. else:
  1435. recording_scopes = False
  1436. try:
  1437. result = self.forward(*input, **kwargs)
  1438. finally:
  1439. if recording_scopes:
  1440. tracing_state.pop_scope()
  1441. return result
  1442. def _wrapped_call_impl(self, *args, **kwargs):
  1443. if self._compiled_call_impl is not None:
  1444. return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
  1445. else:
  1446. return self._call_impl(*args, **kwargs)
  1447. # torchrec tests the code consistency with the following code
  1448. # fmt: off
  1449. def _call_impl(self, *args, **kwargs):
  1450. forward_call = (self._slow_forward if torch._C._get_tracing_state() else self.forward)
  1451. # If we don't have any hooks, we want to skip the rest of the logic in
  1452. # this function, and just call forward.
  1453. if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
  1454. or _global_backward_pre_hooks or _global_backward_hooks
  1455. or _global_forward_hooks or _global_forward_pre_hooks):
  1456. return forward_call(*args, **kwargs)
  1457. result = None
  1458. called_always_called_hooks = set()
  1459. def inner():
  1460. nonlocal result, args, kwargs
  1461. full_backward_hooks, non_full_backward_hooks = [], []
  1462. backward_pre_hooks = []
  1463. if self._backward_pre_hooks or _global_backward_pre_hooks:
  1464. backward_pre_hooks = self._get_backward_pre_hooks()
  1465. if self._backward_hooks or _global_backward_hooks:
  1466. full_backward_hooks, non_full_backward_hooks = self._get_backward_hooks()
  1467. if _global_forward_pre_hooks or self._forward_pre_hooks:
  1468. for hook_id, hook in (
  1469. *_global_forward_pre_hooks.items(),
  1470. *self._forward_pre_hooks.items(),
  1471. ):
  1472. if hook_id in self._forward_pre_hooks_with_kwargs:
  1473. args_kwargs_result = hook(self, args, kwargs) # type: ignore[misc]
  1474. if args_kwargs_result is not None:
  1475. if isinstance(args_kwargs_result, tuple) and len(args_kwargs_result) == 2:
  1476. args, kwargs = args_kwargs_result
  1477. else:
  1478. raise RuntimeError(
  1479. "forward pre-hook must return None or a tuple "
  1480. f"of (new_args, new_kwargs), but got {args_kwargs_result}."
  1481. )
  1482. else:
  1483. args_result = hook(self, args)
  1484. if args_result is not None:
  1485. if not isinstance(args_result, tuple):
  1486. args_result = (args_result,)
  1487. args = args_result
  1488. bw_hook = None
  1489. if full_backward_hooks or backward_pre_hooks:
  1490. bw_hook = BackwardHook(self, full_backward_hooks, backward_pre_hooks)
  1491. args = bw_hook.setup_input_hook(args)
  1492. result = forward_call(*args, **kwargs)
  1493. if _global_forward_hooks or self._forward_hooks:
  1494. for hook_id, hook in (
  1495. *_global_forward_hooks.items(),
  1496. *self._forward_hooks.items(),
  1497. ):
  1498. # mark that always called hook is run
  1499. if hook_id in self._forward_hooks_always_called or hook_id in _global_forward_hooks_always_called:
  1500. called_always_called_hooks.add(hook_id)
  1501. if hook_id in self._forward_hooks_with_kwargs or hook_id in _global_forward_hooks_with_kwargs:
  1502. hook_result = hook(self, args, kwargs, result)
  1503. else:
  1504. hook_result = hook(self, args, result)
  1505. if hook_result is not None:
  1506. result = hook_result
  1507. if bw_hook:
  1508. if not isinstance(result, (torch.Tensor, tuple)):
  1509. warnings.warn("For backward hooks to be called,"
  1510. " module output should be a Tensor or a tuple of Tensors"
  1511. f" but received {type(result)}")
  1512. result = bw_hook.setup_output_hook(result)
  1513. # Handle the non-full backward hooks
  1514. if non_full_backward_hooks:
  1515. var = result
  1516. while not isinstance(var, torch.Tensor):
  1517. if isinstance(var, dict):
  1518. var = next(v for v in var.values() if isinstance(v, torch.Tensor))
  1519. else:
  1520. var = var[0]
  1521. grad_fn = var.grad_fn
  1522. if grad_fn is not None:
  1523. for hook in non_full_backward_hooks:
  1524. grad_fn.register_hook(_WrappedHook(hook, self))
  1525. self._maybe_warn_non_full_backward_hook(args, result, grad_fn)
  1526. return result
  1527. # This is technically not behavior equivalent when compiling, but it's
  1528. # incredibly unlikely we will ever support throwing an exception in NN
  1529. # module, and then catching it here, and then reraising it, and then
  1530. # catching it again, and expecting the resulting frame to be compiled.
  1531. # The reraise here just gunks up our exception handling for no good
  1532. # reason. Don't try to run the always called hooks in event of
  1533. # exception.
  1534. if torch.compiler.is_compiling():
  1535. return inner()
  1536. try:
  1537. return inner()
  1538. except Exception:
  1539. # run always called hooks if they have not already been run
  1540. # For now only forward hooks have the always_call option but perhaps
  1541. # this functionality should be added to full backward hooks as well.
  1542. for hook_id, hook in _global_forward_hooks.items():
  1543. if hook_id in _global_forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined]
  1544. try:
  1545. hook_result = hook(self, args, result) # type: ignore[possibly-undefined]
  1546. if hook_result is not None:
  1547. result = hook_result
  1548. except Exception as e:
  1549. warnings.warn("global module forward hook with ``always_call=True`` raised an exception "
  1550. f"that was silenced as another error was raised in forward: {str(e)}")
  1551. continue
  1552. for hook_id, hook in self._forward_hooks.items():
  1553. if hook_id in self._forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined]
  1554. try:
  1555. if hook_id in self._forward_hooks_with_kwargs:
  1556. hook_result = hook(self, args, kwargs, result) # type: ignore[possibly-undefined]
  1557. else:
  1558. hook_result = hook(self, args, result) # type: ignore[possibly-undefined]
  1559. if hook_result is not None:
  1560. result = hook_result
  1561. except Exception as e:
  1562. warnings.warn("module forward hook with ``always_call=True`` raised an exception "
  1563. f"that was silenced as another error was raised in forward: {str(e)}")
  1564. continue
  1565. # raise exception raised in try block
  1566. raise
  1567. # fmt: on
  1568. __call__: Callable[..., Any] = _wrapped_call_impl
  1569. def __getstate__(self):
  1570. state = self.__dict__.copy()
  1571. state.pop("_compiled_call_impl", None)
  1572. return state
  1573. def __setstate__(self, state):
  1574. self.__dict__.update(state)
  1575. # Support loading old checkpoints that don't have the following attrs:
  1576. if "_forward_pre_hooks" not in self.__dict__:
  1577. self._forward_pre_hooks = OrderedDict()
  1578. if "_forward_pre_hooks_with_kwargs" not in self.__dict__:
  1579. self._forward_pre_hooks_with_kwargs = OrderedDict()
  1580. if "_forward_hooks_with_kwargs" not in self.__dict__:
  1581. self._forward_hooks_with_kwargs = OrderedDict()
  1582. if "_forward_hooks_always_called" not in self.__dict__:
  1583. self._forward_hooks_always_called = OrderedDict()
  1584. if "_state_dict_hooks" not in self.__dict__:
  1585. self._state_dict_hooks = OrderedDict()
  1586. if "_state_dict_pre_hooks" not in self.__dict__:
  1587. self._state_dict_pre_hooks = OrderedDict()
  1588. if "_load_state_dict_pre_hooks" not in self.__dict__:
  1589. self._load_state_dict_pre_hooks = OrderedDict()
  1590. if "_load_state_dict_post_hooks" not in self.__dict__:
  1591. self._load_state_dict_post_hooks = OrderedDict()
  1592. if "_non_persistent_buffers_set" not in self.__dict__:
  1593. self._non_persistent_buffers_set = set()
  1594. if "_is_full_backward_hook" not in self.__dict__:
  1595. self._is_full_backward_hook = None
  1596. if "_backward_pre_hooks" not in self.__dict__:
  1597. self._backward_pre_hooks = OrderedDict()
  1598. # It is crucial that the return type is not annotated as `Any`, otherwise type checking
  1599. # on `torch.nn.Module` and all its subclasses is largely disabled as a result. See:
  1600. # https://github.com/pytorch/pytorch/pull/115074
  1601. def __getattr__(self, name: str) -> Union[Tensor, "Module"]:
  1602. if "_parameters" in self.__dict__:
  1603. _parameters = self.__dict__["_parameters"]
  1604. if name in _parameters:
  1605. return _parameters[name]
  1606. if "_buffers" in self.__dict__:
  1607. _buffers = self.__dict__["_buffers"]
  1608. if name in _buffers:
  1609. return _buffers[name]
  1610. if "_modules" in self.__dict__:
  1611. modules = self.__dict__["_modules"]
  1612. if name in modules:
  1613. return modules[name]
  1614. raise AttributeError(
  1615. f"'{type(self).__name__}' object has no attribute '{name}'"
  1616. )
  1617. def __setattr__(self, name: str, value: Union[Tensor, "Module"]) -> None:
  1618. def remove_from(*dicts_or_sets) -> None:
  1619. for d in dicts_or_sets:
  1620. if name in d:
  1621. if isinstance(d, dict):
  1622. del d[name]
  1623. else:
  1624. d.discard(name)
  1625. params = self.__dict__.get("_parameters")
  1626. if isinstance(value, Parameter):
  1627. if params is None:
  1628. raise AttributeError(
  1629. "cannot assign parameters before Module.__init__() call"
  1630. )
  1631. remove_from(
  1632. self.__dict__,
  1633. self._buffers,
  1634. self._modules,
  1635. self._non_persistent_buffers_set,
  1636. )
  1637. self.register_parameter(name, value)
  1638. elif params is not None and name in params:
  1639. if value is not None:
  1640. raise TypeError(
  1641. f"cannot assign '{torch.typename(value)}' as parameter '{name}' "
  1642. "(torch.nn.Parameter or None expected)"
  1643. )
  1644. self.register_parameter(name, value)
  1645. else:
  1646. modules = self.__dict__.get("_modules")
  1647. if isinstance(value, Module):
  1648. if modules is None:
  1649. raise AttributeError(
  1650. "cannot assign module before Module.__init__() call"
  1651. )
  1652. remove_from(
  1653. self.__dict__,
  1654. self._parameters,
  1655. self._buffers,
  1656. self._non_persistent_buffers_set,
  1657. )
  1658. for hook in _global_module_registration_hooks.values():
  1659. output = hook(self, name, value)
  1660. if output is not None:
  1661. value = output
  1662. modules[name] = value
  1663. elif modules is not None and name in modules:
  1664. if value is not None:
  1665. raise TypeError(
  1666. f"cannot assign '{torch.typename(value)}' as child module '{name}' "
  1667. "(torch.nn.Module or None expected)"
  1668. )
  1669. for hook in _global_module_registration_hooks.values():
  1670. output = hook(self, name, value)
  1671. if output is not None:
  1672. value = output
  1673. modules[name] = value
  1674. else:
  1675. buffers = self.__dict__.get("_buffers")
  1676. if isinstance(value, Buffer) or buffers is not None and name in buffers:
  1677. if value is not None and not (
  1678. isinstance(value, torch.Tensor)
  1679. or hasattr(value, "__torch_function__")
  1680. ):
  1681. raise TypeError(
  1682. f"cannot assign '{torch.typename(value)}' as buffer '{name}' "
  1683. "(torch.nn.Buffer, torch.Tensor or None expected)"
  1684. )
  1685. if isinstance(value, Buffer):
  1686. persistent = value.persistent
  1687. else:
  1688. persistent = name not in self._non_persistent_buffers_set
  1689. # === HACK ===
  1690. # This whole block below should just be:
  1691. # self.register_buffer(name, value, persistent)
  1692. # But to support subclasses of nn.Module that (wrongfully) implement a
  1693. # register_buffer() method that doesn't have the "persistent"
  1694. # argument. Only pass it in if it is accepted otherwise assume
  1695. # it is always true
  1696. if (
  1697. getattr(self.register_buffer, "__func__", None)
  1698. is torch.nn.Module.register_buffer
  1699. ):
  1700. self.register_buffer(name, value, persistent)
  1701. else:
  1702. sign = inspect.signature(self.register_buffer)
  1703. if "persistent" in sign.parameters:
  1704. self.register_buffer(name, value, persistent)
  1705. else:
  1706. if not persistent:
  1707. raise RuntimeError(
  1708. "Registering a non-persistent buffer "
  1709. "on a Module subclass that implements "
  1710. "register_buffer() without the persistent "
  1711. "argument is not allowed."
  1712. )
  1713. # Assume that the implementation without the argument has the
  1714. # behavior from before the argument was added: persistent=True
  1715. self.register_buffer(name, value)
  1716. # === HACK END ===
  1717. else:
  1718. super().__setattr__(name, value)
  1719. def __delattr__(self, name) -> None:
  1720. if name in self._parameters:
  1721. del self._parameters[name]
  1722. elif name in self._buffers:
  1723. del self._buffers[name]
  1724. self._non_persistent_buffers_set.discard(name)
  1725. elif name in self._modules:
  1726. del self._modules[name]
  1727. else:
  1728. super().__delattr__(name)
  1729. def _register_state_dict_hook(self, hook):
  1730. r"""Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method.
  1731. It should have the following signature::
  1732. hook(module, state_dict, prefix, local_metadata) -> None or state_dict
  1733. The registered hooks can modify the ``state_dict`` inplace or return a new one.
  1734. If a new ``state_dict`` is returned, it will only be respected if it is the root
  1735. module that :meth:`~nn.Module.state_dict` is called from.
  1736. """
  1737. if getattr(hook, "_from_public_api", False):
  1738. raise RuntimeError(
  1739. "Cannot register the same function as the state dict post hook that was "
  1740. "previously registered via register_state_dict_post_hook"
  1741. )
  1742. handle = RemovableHandle(self._state_dict_hooks)
  1743. self._state_dict_hooks[handle.id] = hook
  1744. return handle
  1745. def register_state_dict_post_hook(self, hook):
  1746. r"""Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method.
  1747. It should have the following signature::
  1748. hook(module, state_dict, prefix, local_metadata) -> None
  1749. The registered hooks can modify the ``state_dict`` inplace.
  1750. """
  1751. # In _register_state_dict_hook there was a bug described in
  1752. # https://github.com/pytorch/pytorch/issues/117437 where the return value
  1753. # was only respected for the root module but not child submodules.
  1754. # We fix this in this public version by only allowing inplace modifications on
  1755. # the state_dict by the hook. However, since hooks registered via both these
  1756. # APIs will be added to `_state_dict_hooks` and the type of `_state_dict_hooks`
  1757. # cannot be changed due to many dependencies on it, we mark a hook
  1758. # as being registered via the public API by setting `_from_public_api` on it.
  1759. # In the implementation of `state_dict`, if the callable does not have this
  1760. # flag, the old behavior of respecting the return value will be preserved
  1761. # for the root module, otherwise, we ensure that the hook returns None.
  1762. hook._from_public_api = True
  1763. handle = RemovableHandle(self._state_dict_hooks)
  1764. self._state_dict_hooks[handle.id] = hook
  1765. return handle
  1766. def register_state_dict_pre_hook(self, hook):
  1767. r"""Register a pre-hook for the :meth:`~torch.nn.Module.state_dict` method.
  1768. It should have the following signature::
  1769. hook(module, prefix, keep_vars) -> None
  1770. The registered hooks can be used to perform pre-processing before the ``state_dict``
  1771. call is made.
  1772. """
  1773. handle = RemovableHandle(self._state_dict_pre_hooks)
  1774. self._state_dict_pre_hooks[handle.id] = hook
  1775. return handle
  1776. def _save_to_state_dict(self, destination, prefix, keep_vars) -> None:
  1777. r"""Save module state to the `destination` dictionary.
  1778. The `destination` dictionary will contain the state
  1779. of the module, but not its descendants. This is called on every
  1780. submodule in :meth:`~torch.nn.Module.state_dict`.
  1781. In rare cases, subclasses can achieve class-specific behavior by
  1782. overriding this method with custom logic.
  1783. Args:
  1784. destination (dict): a dict where state will be stored
  1785. prefix (str): the prefix for parameters and buffers used in this
  1786. module
  1787. """
  1788. for name, param in self._parameters.items():
  1789. if param is not None:
  1790. destination[prefix + name] = param if keep_vars else param.detach()
  1791. for name, buf in self._buffers.items():
  1792. if buf is not None and name not in self._non_persistent_buffers_set:
  1793. destination[prefix + name] = buf if keep_vars else buf.detach()
  1794. extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX
  1795. if (
  1796. getattr(self.__class__, "get_extra_state", Module.get_extra_state)
  1797. is not Module.get_extra_state
  1798. ):
  1799. destination[extra_state_key] = self.get_extra_state()
  1800. # The user can pass an optional arbitrary mappable object to `state_dict`, in which case `state_dict` returns
  1801. # back that same object. But if they pass nothing, an `OrderedDict` is created and returned.
  1802. T_destination = TypeVar("T_destination", bound=dict[str, Any])
  1803. @overload
  1804. def state_dict(
  1805. self,
  1806. *,
  1807. destination: T_destination,
  1808. prefix: str = ...,
  1809. keep_vars: bool = ...,
  1810. ) -> T_destination: ...
  1811. @overload
  1812. def state_dict(
  1813. self,
  1814. *,
  1815. prefix: str = ...,
  1816. keep_vars: bool = ...,
  1817. ) -> dict[str, Any]: ...
  1818. # TODO: Change `*args` to `*` and remove the corresponding warning in docs when BC allows.
  1819. # Also remove the logic for arg parsing together.
  1820. def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
  1821. r"""Return a dictionary containing references to the whole state of the module.
  1822. Both parameters and persistent buffers (e.g. running averages) are
  1823. included. Keys are corresponding parameter and buffer names.
  1824. Parameters and buffers set to ``None`` are not included.
  1825. .. note::
  1826. The returned object is a shallow copy. It contains references
  1827. to the module's parameters and buffers.
  1828. .. warning::
  1829. Currently ``state_dict()`` also accepts positional arguments for
  1830. ``destination``, ``prefix`` and ``keep_vars`` in order. However,
  1831. this is being deprecated and keyword arguments will be enforced in
  1832. future releases.
  1833. .. warning::
  1834. Please avoid the use of argument ``destination`` as it is not
  1835. designed for end-users.
  1836. Args:
  1837. destination (dict, optional): If provided, the state of module will
  1838. be updated into the dict and the same object is returned.
  1839. Otherwise, an ``OrderedDict`` will be created and returned.
  1840. Default: ``None``.
  1841. prefix (str, optional): a prefix added to parameter and buffer
  1842. names to compose the keys in state_dict. Default: ``''``.
  1843. keep_vars (bool, optional): by default the :class:`~torch.Tensor` s
  1844. returned in the state dict are detached from autograd. If it's
  1845. set to ``True``, detaching will not be performed.
  1846. Default: ``False``.
  1847. Returns:
  1848. dict:
  1849. a dictionary containing a whole state of the module
  1850. Example::
  1851. >>> # xdoctest: +SKIP("undefined vars")
  1852. >>> module.state_dict().keys()
  1853. ['bias', 'weight']
  1854. """
  1855. # TODO: Remove `args` and the parsing logic when BC allows.
  1856. if len(args) > 0:
  1857. # DeprecationWarning is ignored by default
  1858. warnings.warn(
  1859. "Positional args are being deprecated, use kwargs instead. Refer to "
  1860. "https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.state_dict"
  1861. " for details.",
  1862. FutureWarning,
  1863. stacklevel=2,
  1864. )
  1865. if destination is None:
  1866. destination = args[0]
  1867. if len(args) > 1 and prefix == "":
  1868. prefix = args[1]
  1869. if len(args) > 2 and keep_vars is False:
  1870. keep_vars = args[2]
  1871. if destination is None:
  1872. destination = OrderedDict()
  1873. destination._metadata = OrderedDict()
  1874. local_metadata = dict(version=self._version)
  1875. if hasattr(destination, "_metadata"):
  1876. destination._metadata[prefix[:-1]] = local_metadata
  1877. for hook in self._state_dict_pre_hooks.values():
  1878. hook(self, prefix, keep_vars)
  1879. self._save_to_state_dict(destination, prefix, keep_vars)
  1880. for name, module in self._modules.items():
  1881. if module is not None:
  1882. module.state_dict(
  1883. destination=destination,
  1884. prefix=prefix + name + ".",
  1885. keep_vars=keep_vars,
  1886. )
  1887. for hook in self._state_dict_hooks.values():
  1888. hook_result = hook(self, destination, prefix, local_metadata)
  1889. if not getattr(hook, "_from_public_api", False):
  1890. if hook_result is not None:
  1891. destination = hook_result
  1892. else:
  1893. if hook_result is not None:
  1894. raise RuntimeError("state_dict post-hook must return None")
  1895. return destination
  1896. def _register_load_state_dict_pre_hook(self, hook, with_module=False):
  1897. r"""See :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` for details.
  1898. A subtle difference is that if ``with_module`` is set to ``False``, then the
  1899. hook will not take the ``module`` as the first argument whereas
  1900. :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` always takes the
  1901. ``module`` as the first argument.
  1902. Arguments:
  1903. hook (Callable): Callable hook that will be invoked before
  1904. loading the state dict.
  1905. with_module (bool, optional): Whether or not to pass the module
  1906. instance to the hook as the first parameter.
  1907. """
  1908. handle = RemovableHandle(self._load_state_dict_pre_hooks)
  1909. self._load_state_dict_pre_hooks[handle.id] = _WrappedHook(
  1910. hook, self if with_module else None
  1911. )
  1912. return handle
  1913. def register_load_state_dict_pre_hook(self, hook):
  1914. r"""Register a pre-hook to be run before module's :meth:`~nn.Module.load_state_dict` is called.
  1915. It should have the following signature::
  1916. hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
  1917. Arguments:
  1918. hook (Callable): Callable hook that will be invoked before
  1919. loading the state dict.
  1920. """
  1921. return self._register_load_state_dict_pre_hook(hook, with_module=True)
  1922. def register_load_state_dict_post_hook(self, hook):
  1923. r"""Register a post-hook to be run after module's :meth:`~nn.Module.load_state_dict` is called.
  1924. It should have the following signature::
  1925. hook(module, incompatible_keys) -> None
  1926. The ``module`` argument is the current module that this hook is registered
  1927. on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting
  1928. of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys``
  1929. is a ``list`` of ``str`` containing the missing keys and
  1930. ``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys.
  1931. The given incompatible_keys can be modified inplace if needed.
  1932. Note that the checks performed when calling :func:`load_state_dict` with
  1933. ``strict=True`` are affected by modifications the hook makes to
  1934. ``missing_keys`` or ``unexpected_keys``, as expected. Additions to either
  1935. set of keys will result in an error being thrown when ``strict=True``, and
  1936. clearing out both missing and unexpected keys will avoid an error.
  1937. Returns:
  1938. :class:`torch.utils.hooks.RemovableHandle`:
  1939. a handle that can be used to remove the added hook by calling
  1940. ``handle.remove()``
  1941. """
  1942. handle = RemovableHandle(self._load_state_dict_post_hooks)
  1943. self._load_state_dict_post_hooks[handle.id] = hook
  1944. return handle
  1945. def _load_from_state_dict(
  1946. self,
  1947. state_dict,
  1948. prefix,
  1949. local_metadata,
  1950. strict,
  1951. missing_keys,
  1952. unexpected_keys,
  1953. error_msgs,
  1954. ) -> None:
  1955. r"""Copy parameters and buffers from :attr:`state_dict` into only this module, but not its descendants.
  1956. This is called on every submodule
  1957. in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this
  1958. module in input :attr:`state_dict` is provided as :attr:`local_metadata`.
  1959. For state dicts without metadata, :attr:`local_metadata` is empty.
  1960. Subclasses can achieve class-specific backward compatible loading using
  1961. the version number at `local_metadata.get("version", None)`.
  1962. Additionally, :attr:`local_metadata` can also contain the key
  1963. `assign_to_params_buffers` that indicates whether keys should be
  1964. assigned their corresponding tensor in the state_dict.
  1965. .. note::
  1966. :attr:`state_dict` is not the same object as the input
  1967. :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So
  1968. it can be modified.
  1969. Args:
  1970. state_dict (dict): a dict containing parameters and
  1971. persistent buffers.
  1972. prefix (str): the prefix for parameters and buffers used in this
  1973. module
  1974. local_metadata (dict): a dict containing the metadata for this module.
  1975. See
  1976. strict (bool): whether to strictly enforce that the keys in
  1977. :attr:`state_dict` with :attr:`prefix` match the names of
  1978. parameters and buffers in this module
  1979. missing_keys (list of str): if ``strict=True``, add missing keys to
  1980. this list
  1981. unexpected_keys (list of str): if ``strict=True``, add unexpected
  1982. keys to this list
  1983. error_msgs (list of str): error messages should be added to this
  1984. list, and will be reported together in
  1985. :meth:`~torch.nn.Module.load_state_dict`
  1986. """
  1987. for hook in self._load_state_dict_pre_hooks.values():
  1988. hook(
  1989. state_dict,
  1990. prefix,
  1991. local_metadata,
  1992. strict,
  1993. missing_keys,
  1994. unexpected_keys,
  1995. error_msgs,
  1996. )
  1997. persistent_buffers = {
  1998. k: v
  1999. for k, v in self._buffers.items()
  2000. if k not in self._non_persistent_buffers_set
  2001. }
  2002. local_name_params = itertools.chain(
  2003. self._parameters.items(), persistent_buffers.items()
  2004. )
  2005. local_state = {k: v for k, v in local_name_params if v is not None}
  2006. assign_to_params_buffers = local_metadata.get("assign_to_params_buffers", False)
  2007. use_swap_tensors = torch.__future__.get_swap_module_params_on_conversion()
  2008. for name, param in local_state.items():
  2009. key = prefix + name
  2010. if key in state_dict:
  2011. input_param = state_dict[key]
  2012. if not torch.overrides.is_tensor_like(input_param):
  2013. error_msgs.append(
  2014. f'While copying the parameter named "{key}", '
  2015. "expected torch.Tensor or Tensor-like object from checkpoint but "
  2016. f"received {type(input_param)}"
  2017. )
  2018. continue
  2019. # This is used to avoid copying uninitialized parameters into
  2020. # non-lazy modules, since they dont have the hook to do the checks
  2021. # in such case, it will error when accessing the .shape attribute.
  2022. is_param_lazy = torch.nn.parameter.is_lazy(param)
  2023. # Backward compatibility: loading 1-dim tensor from 0.3.* to version 0.4+
  2024. if (
  2025. not is_param_lazy
  2026. and len(param.shape) == 0
  2027. and len(input_param.shape) == 1
  2028. ):
  2029. input_param = input_param[0]
  2030. if not is_param_lazy and input_param.shape != param.shape:
  2031. # local shape should match the one in checkpoint
  2032. error_msgs.append(
  2033. f"size mismatch for {key}: copying a param with shape {input_param.shape} from checkpoint, "
  2034. f"the shape in current model is {param.shape}."
  2035. )
  2036. continue
  2037. if (
  2038. param.is_meta
  2039. and not input_param.is_meta
  2040. and not assign_to_params_buffers
  2041. ):
  2042. warnings.warn(
  2043. f"for {key}: copying from a non-meta parameter in the checkpoint to a meta "
  2044. "parameter in the current model, which is a no-op. (Did you mean to "
  2045. "pass `assign=True` to assign items in the state dictionary to their "
  2046. "corresponding key in the module instead of copying them in place?)"
  2047. )
  2048. try:
  2049. with torch.no_grad():
  2050. if use_swap_tensors:
  2051. new_input_param = param.module_load(
  2052. input_param, assign=assign_to_params_buffers
  2053. )
  2054. if id(new_input_param) == id(input_param) or id(
  2055. new_input_param
  2056. ) == id(param):
  2057. raise RuntimeError(
  2058. "module_load returned one of self or other, please .detach() "
  2059. "the result if returning one of the inputs in module_load"
  2060. )
  2061. if isinstance(param, torch.nn.Parameter):
  2062. if not isinstance(new_input_param, torch.nn.Parameter):
  2063. new_input_param = torch.nn.Parameter(
  2064. new_input_param,
  2065. requires_grad=param.requires_grad,
  2066. )
  2067. else:
  2068. new_input_param.requires_grad_(param.requires_grad)
  2069. torch.utils.swap_tensors(param, new_input_param)
  2070. del new_input_param
  2071. elif assign_to_params_buffers:
  2072. # Shape checks are already done above
  2073. if isinstance(param, torch.nn.Parameter):
  2074. if not isinstance(input_param, torch.nn.Parameter):
  2075. input_param = torch.nn.Parameter(
  2076. input_param, requires_grad=param.requires_grad
  2077. )
  2078. else:
  2079. input_param.requires_grad_(param.requires_grad)
  2080. setattr(self, name, input_param)
  2081. else:
  2082. param.copy_(input_param)
  2083. except Exception as ex:
  2084. action = "swapping" if use_swap_tensors else "copying"
  2085. error_msgs.append(
  2086. f'While {action} the parameter named "{key}", '
  2087. f"whose dimensions in the model are {param.size()} and "
  2088. f"whose dimensions in the checkpoint are {input_param.size()}, "
  2089. f"an exception occurred : {ex.args}."
  2090. )
  2091. elif strict:
  2092. missing_keys.append(key)
  2093. extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX
  2094. if (
  2095. getattr(self.__class__, "set_extra_state", Module.set_extra_state)
  2096. is not Module.set_extra_state
  2097. ):
  2098. if extra_state_key in state_dict:
  2099. self.set_extra_state(state_dict[extra_state_key])
  2100. elif strict:
  2101. missing_keys.append(extra_state_key)
  2102. elif strict and (extra_state_key in state_dict):
  2103. unexpected_keys.append(extra_state_key)
  2104. if strict:
  2105. for key in state_dict.keys():
  2106. if key.startswith(prefix) and key != extra_state_key:
  2107. input_name = key[len(prefix) :].split(".", 1)
  2108. # Must be Module if it have attributes
  2109. if len(input_name) > 1:
  2110. if input_name[0] not in self._modules:
  2111. unexpected_keys.append(key)
  2112. elif input_name[0] not in local_state:
  2113. unexpected_keys.append(key)
  2114. def load_state_dict(
  2115. self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False
  2116. ):
  2117. r"""Copy parameters and buffers from :attr:`state_dict` into this module and its descendants.
  2118. If :attr:`strict` is ``True``, then
  2119. the keys of :attr:`state_dict` must exactly match the keys returned
  2120. by this module's :meth:`~torch.nn.Module.state_dict` function.
  2121. .. warning::
  2122. If :attr:`assign` is ``True`` the optimizer must be created after
  2123. the call to :attr:`load_state_dict` unless
  2124. :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.
  2125. Args:
  2126. state_dict (dict): a dict containing parameters and
  2127. persistent buffers.
  2128. strict (bool, optional): whether to strictly enforce that the keys
  2129. in :attr:`state_dict` match the keys returned by this module's
  2130. :meth:`~torch.nn.Module.state_dict` function. Default: ``True``
  2131. assign (bool, optional): When set to ``False``, the properties of the tensors
  2132. in the current module are preserved whereas setting it to ``True`` preserves
  2133. properties of the Tensors in the state dict. The only
  2134. exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`
  2135. for which the value from the module is preserved. Default: ``False``
  2136. Returns:
  2137. ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
  2138. * ``missing_keys`` is a list of str containing any keys that are expected
  2139. by this module but missing from the provided ``state_dict``.
  2140. * ``unexpected_keys`` is a list of str containing the keys that are not
  2141. expected by this module but present in the provided ``state_dict``.
  2142. Note:
  2143. If a parameter or buffer is registered as ``None`` and its corresponding key
  2144. exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a
  2145. ``RuntimeError``.
  2146. """
  2147. if not isinstance(state_dict, Mapping):
  2148. raise TypeError(
  2149. f"Expected state_dict to be dict-like, got {type(state_dict)}."
  2150. )
  2151. missing_keys: list[str] = []
  2152. unexpected_keys: list[str] = []
  2153. error_msgs: list[str] = []
  2154. # copy state_dict so _load_from_state_dict can modify it
  2155. metadata = getattr(state_dict, "_metadata", None)
  2156. state_dict = OrderedDict(state_dict)
  2157. if metadata is not None:
  2158. # mypy isn't aware that "_metadata" exists in state_dict
  2159. state_dict._metadata = metadata # type: ignore[attr-defined]
  2160. def load(module, local_state_dict, prefix="") -> None:
  2161. local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
  2162. if assign:
  2163. local_metadata["assign_to_params_buffers"] = assign
  2164. module._load_from_state_dict(
  2165. local_state_dict,
  2166. prefix,
  2167. local_metadata,
  2168. True,
  2169. missing_keys,
  2170. unexpected_keys,
  2171. error_msgs,
  2172. )
  2173. for name, child in module._modules.items():
  2174. if child is not None:
  2175. child_prefix = prefix + name + "."
  2176. child_state_dict = {
  2177. k: v
  2178. for k, v in local_state_dict.items()
  2179. if k.startswith(child_prefix)
  2180. }
  2181. load(child, child_state_dict, child_prefix) # noqa: F821
  2182. # Note that the hook can modify missing_keys and unexpected_keys.
  2183. incompatible_keys = _IncompatibleKeys(missing_keys, unexpected_keys)
  2184. for hook in module._load_state_dict_post_hooks.values():
  2185. out = hook(module, incompatible_keys)
  2186. assert out is None, (
  2187. "Hooks registered with ``register_load_state_dict_post_hook`` are not"
  2188. "expected to return new values, if incompatible_keys need to be modified,"
  2189. "it should be done inplace."
  2190. )
  2191. load(self, state_dict)
  2192. del load
  2193. if strict:
  2194. if len(unexpected_keys) > 0:
  2195. error_msgs.insert(
  2196. 0,
  2197. "Unexpected key(s) in state_dict: {}. ".format(
  2198. ", ".join(f'"{k}"' for k in unexpected_keys)
  2199. ),
  2200. )
  2201. if len(missing_keys) > 0:
  2202. error_msgs.insert(
  2203. 0,
  2204. "Missing key(s) in state_dict: {}. ".format(
  2205. ", ".join(f'"{k}"' for k in missing_keys)
  2206. ),
  2207. )
  2208. if len(error_msgs) > 0:
  2209. raise RuntimeError(
  2210. "Error(s) in loading state_dict for {}:\n\t{}".format(
  2211. self.__class__.__name__, "\n\t".join(error_msgs)
  2212. )
  2213. )
  2214. return _IncompatibleKeys(missing_keys, unexpected_keys)
  2215. def _named_members(
  2216. self, get_members_fn, prefix="", recurse=True, remove_duplicate: bool = True
  2217. ):
  2218. r"""Help yield various names + members of modules."""
  2219. memo = set()
  2220. modules = (
  2221. self.named_modules(prefix=prefix, remove_duplicate=remove_duplicate)
  2222. if recurse
  2223. else [(prefix, self)]
  2224. )
  2225. for module_prefix, module in modules:
  2226. members = get_members_fn(module)
  2227. for k, v in members:
  2228. if v is None or v in memo:
  2229. continue
  2230. if remove_duplicate:
  2231. memo.add(v)
  2232. name = module_prefix + ("." if module_prefix else "") + k
  2233. yield name, v
  2234. def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
  2235. r"""Return an iterator over module parameters.
  2236. This is typically passed to an optimizer.
  2237. Args:
  2238. recurse (bool): if True, then yields parameters of this module
  2239. and all submodules. Otherwise, yields only parameters that
  2240. are direct members of this module.
  2241. Yields:
  2242. Parameter: module parameter
  2243. Example::
  2244. >>> # xdoctest: +SKIP("undefined vars")
  2245. >>> for param in model.parameters():
  2246. >>> print(type(param), param.size())
  2247. <class 'torch.Tensor'> (20L,)
  2248. <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
  2249. """
  2250. for _name, param in self.named_parameters(recurse=recurse):
  2251. yield param
  2252. def named_parameters(
  2253. self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
  2254. ) -> Iterator[tuple[str, Parameter]]:
  2255. r"""Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
  2256. Args:
  2257. prefix (str): prefix to prepend to all parameter names.
  2258. recurse (bool): if True, then yields parameters of this module
  2259. and all submodules. Otherwise, yields only parameters that
  2260. are direct members of this module.
  2261. remove_duplicate (bool, optional): whether to remove the duplicated
  2262. parameters in the result. Defaults to True.
  2263. Yields:
  2264. (str, Parameter): Tuple containing the name and parameter
  2265. Example::
  2266. >>> # xdoctest: +SKIP("undefined vars")
  2267. >>> for name, param in self.named_parameters():
  2268. >>> if name in ['bias']:
  2269. >>> print(param.size())
  2270. """
  2271. gen = self._named_members(
  2272. lambda module: module._parameters.items(),
  2273. prefix=prefix,
  2274. recurse=recurse,
  2275. remove_duplicate=remove_duplicate,
  2276. )
  2277. yield from gen
  2278. def buffers(self, recurse: bool = True) -> Iterator[Tensor]:
  2279. r"""Return an iterator over module buffers.
  2280. Args:
  2281. recurse (bool): if True, then yields buffers of this module
  2282. and all submodules. Otherwise, yields only buffers that
  2283. are direct members of this module.
  2284. Yields:
  2285. torch.Tensor: module buffer
  2286. Example::
  2287. >>> # xdoctest: +SKIP("undefined vars")
  2288. >>> for buf in model.buffers():
  2289. >>> print(type(buf), buf.size())
  2290. <class 'torch.Tensor'> (20L,)
  2291. <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
  2292. """
  2293. for _, buf in self.named_buffers(recurse=recurse):
  2294. yield buf
  2295. def named_buffers(
  2296. self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
  2297. ) -> Iterator[tuple[str, Tensor]]:
  2298. r"""Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
  2299. Args:
  2300. prefix (str): prefix to prepend to all buffer names.
  2301. recurse (bool, optional): if True, then yields buffers of this module
  2302. and all submodules. Otherwise, yields only buffers that
  2303. are direct members of this module. Defaults to True.
  2304. remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.
  2305. Yields:
  2306. (str, torch.Tensor): Tuple containing the name and buffer
  2307. Example::
  2308. >>> # xdoctest: +SKIP("undefined vars")
  2309. >>> for name, buf in self.named_buffers():
  2310. >>> if name in ['running_var']:
  2311. >>> print(buf.size())
  2312. """
  2313. gen = self._named_members(
  2314. lambda module: module._buffers.items(),
  2315. prefix=prefix,
  2316. recurse=recurse,
  2317. remove_duplicate=remove_duplicate,
  2318. )
  2319. yield from gen
  2320. def children(self) -> Iterator["Module"]:
  2321. r"""Return an iterator over immediate children modules.
  2322. Yields:
  2323. Module: a child module
  2324. """
  2325. for _name, module in self.named_children():
  2326. yield module
  2327. def named_children(self) -> Iterator[tuple[str, "Module"]]:
  2328. r"""Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
  2329. Yields:
  2330. (str, Module): Tuple containing a name and child module
  2331. Example::
  2332. >>> # xdoctest: +SKIP("undefined vars")
  2333. >>> for name, module in model.named_children():
  2334. >>> if name in ['conv4', 'conv5']:
  2335. >>> print(module)
  2336. """
  2337. memo = set()
  2338. for name, module in self._modules.items():
  2339. if module is not None and module not in memo:
  2340. memo.add(module)
  2341. yield name, module
  2342. def modules(self) -> Iterator["Module"]:
  2343. r"""Return an iterator over all modules in the network.
  2344. Yields:
  2345. Module: a module in the network
  2346. Note:
  2347. Duplicate modules are returned only once. In the following
  2348. example, ``l`` will be returned only once.
  2349. Example::
  2350. >>> l = nn.Linear(2, 2)
  2351. >>> net = nn.Sequential(l, l)
  2352. >>> for idx, m in enumerate(net.modules()):
  2353. ... print(idx, '->', m)
  2354. 0 -> Sequential(
  2355. (0): Linear(in_features=2, out_features=2, bias=True)
  2356. (1): Linear(in_features=2, out_features=2, bias=True)
  2357. )
  2358. 1 -> Linear(in_features=2, out_features=2, bias=True)
  2359. """
  2360. for _, module in self.named_modules():
  2361. yield module
  2362. def named_modules(
  2363. self,
  2364. memo: Optional[set["Module"]] = None,
  2365. prefix: str = "",
  2366. remove_duplicate: bool = True,
  2367. ):
  2368. r"""Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
  2369. Args:
  2370. memo: a memo to store the set of modules already added to the result
  2371. prefix: a prefix that will be added to the name of the module
  2372. remove_duplicate: whether to remove the duplicated module instances in the result
  2373. or not
  2374. Yields:
  2375. (str, Module): Tuple of name and module
  2376. Note:
  2377. Duplicate modules are returned only once. In the following
  2378. example, ``l`` will be returned only once.
  2379. Example::
  2380. >>> l = nn.Linear(2, 2)
  2381. >>> net = nn.Sequential(l, l)
  2382. >>> for idx, m in enumerate(net.named_modules()):
  2383. ... print(idx, '->', m)
  2384. 0 -> ('', Sequential(
  2385. (0): Linear(in_features=2, out_features=2, bias=True)
  2386. (1): Linear(in_features=2, out_features=2, bias=True)
  2387. ))
  2388. 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
  2389. """
  2390. if memo is None:
  2391. memo = set()
  2392. if self not in memo:
  2393. if remove_duplicate:
  2394. memo.add(self)
  2395. yield prefix, self
  2396. for name, module in self._modules.items():
  2397. if module is None:
  2398. continue
  2399. submodule_prefix = prefix + ("." if prefix else "") + name
  2400. yield from module.named_modules(
  2401. memo, submodule_prefix, remove_duplicate
  2402. )
  2403. def train(self, mode: bool = True) -> Self:
  2404. r"""Set the module in training mode.
  2405. This has an effect only on certain modules. See the documentation of
  2406. particular modules for details of their behaviors in training/evaluation
  2407. mode, i.e., whether they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
  2408. etc.
  2409. Args:
  2410. mode (bool): whether to set training mode (``True``) or evaluation
  2411. mode (``False``). Default: ``True``.
  2412. Returns:
  2413. Module: self
  2414. """
  2415. if not isinstance(mode, bool):
  2416. raise ValueError("training mode is expected to be boolean")
  2417. self.training = mode
  2418. for module in self.children():
  2419. module.train(mode)
  2420. return self
  2421. def eval(self) -> Self:
  2422. r"""Set the module in evaluation mode.
  2423. This has an effect only on certain modules. See the documentation of
  2424. particular modules for details of their behaviors in training/evaluation
  2425. mode, i.e. whether they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
  2426. etc.
  2427. This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.
  2428. See :ref:`locally-disable-grad-doc` for a comparison between
  2429. `.eval()` and several similar mechanisms that may be confused with it.
  2430. Returns:
  2431. Module: self
  2432. """
  2433. return self.train(False)
  2434. def requires_grad_(self, requires_grad: bool = True) -> Self:
  2435. r"""Change if autograd should record operations on parameters in this module.
  2436. This method sets the parameters' :attr:`requires_grad` attributes
  2437. in-place.
  2438. This method is helpful for freezing part of the module for finetuning
  2439. or training parts of a model individually (e.g., GAN training).
  2440. See :ref:`locally-disable-grad-doc` for a comparison between
  2441. `.requires_grad_()` and several similar mechanisms that may be confused with it.
  2442. Args:
  2443. requires_grad (bool): whether autograd should record operations on
  2444. parameters in this module. Default: ``True``.
  2445. Returns:
  2446. Module: self
  2447. """
  2448. for p in self.parameters():
  2449. p.requires_grad_(requires_grad)
  2450. return self
  2451. def zero_grad(self, set_to_none: bool = True) -> None:
  2452. r"""Reset gradients of all model parameters.
  2453. See similar function under :class:`torch.optim.Optimizer` for more context.
  2454. Args:
  2455. set_to_none (bool): instead of setting to zero, set the grads to None.
  2456. See :meth:`torch.optim.Optimizer.zero_grad` for details.
  2457. """
  2458. if getattr(self, "_is_replica", False):
  2459. warnings.warn(
  2460. "Calling .zero_grad() from a module created with nn.DataParallel() has no effect. "
  2461. "The parameters are copied (in a differentiable manner) from the original module. "
  2462. "This means they are not leaf nodes in autograd and so don't accumulate gradients. "
  2463. "If you need gradients in your forward method, consider using autograd.grad instead."
  2464. )
  2465. for p in self.parameters():
  2466. if p.grad is not None:
  2467. if set_to_none:
  2468. p.grad = None
  2469. else:
  2470. if p.grad.grad_fn is not None:
  2471. p.grad.detach_()
  2472. else:
  2473. p.grad.requires_grad_(False)
  2474. p.grad.zero_()
  2475. def share_memory(self) -> Self:
  2476. r"""See :meth:`torch.Tensor.share_memory_`."""
  2477. return self._apply(lambda t: t.share_memory_())
  2478. def _get_name(self):
  2479. return self.__class__.__name__
  2480. def extra_repr(self) -> str:
  2481. r"""Return the extra representation of the module.
  2482. To print customized extra information, you should re-implement
  2483. this method in your own modules. Both single-line and multi-line
  2484. strings are acceptable.
  2485. """
  2486. return ""
  2487. def __repr__(self) -> str:
  2488. # We treat the extra repr like the sub-module, one item per line
  2489. extra_lines = []
  2490. extra_repr = self.extra_repr()
  2491. # empty string will be split into list ['']
  2492. if extra_repr:
  2493. extra_lines = extra_repr.split("\n")
  2494. child_lines = []
  2495. for key, module in self._modules.items():
  2496. mod_str = repr(module)
  2497. mod_str = _addindent(mod_str, 2)
  2498. child_lines.append("(" + key + "): " + mod_str)
  2499. lines = extra_lines + child_lines
  2500. main_str = self._get_name() + "("
  2501. if lines:
  2502. # simple one-liner info, which most builtin Modules will use
  2503. if len(extra_lines) == 1 and not child_lines:
  2504. main_str += extra_lines[0]
  2505. else:
  2506. main_str += "\n " + "\n ".join(lines) + "\n"
  2507. main_str += ")"
  2508. return main_str
  2509. def __dir__(self):
  2510. module_attrs = dir(self.__class__)
  2511. attrs = list(self.__dict__.keys())
  2512. parameters = list(self._parameters.keys())
  2513. modules = list(self._modules.keys())
  2514. buffers = list(self._buffers.keys())
  2515. keys = module_attrs + attrs + parameters + modules + buffers
  2516. # Eliminate attrs that are not legal Python variable names
  2517. keys = [key for key in keys if not key[0].isdigit()]
  2518. return sorted(keys)
  2519. def _replicate_for_data_parallel(self):
  2520. replica = self.__new__(type(self))
  2521. replica.__dict__ = self.__dict__.copy()
  2522. # replicas do not have parameters themselves, the replicas reference the original
  2523. # module.
  2524. replica._parameters = {}
  2525. replica._buffers = replica._buffers.copy()
  2526. replica._modules = replica._modules.copy()
  2527. replica._is_replica = True # type: ignore[assignment]
  2528. return replica
  2529. def compile(self, *args, **kwargs):
  2530. """
  2531. Compile this Module's forward using :func:`torch.compile`.
  2532. This Module's `__call__` method is compiled and all arguments are passed as-is
  2533. to :func:`torch.compile`.
  2534. See :func:`torch.compile` for details on the arguments for this function.
  2535. """
  2536. self._compiled_call_impl = torch.compile(self._call_impl, *args, **kwargs)