module.py 125 KB

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