module.py 112 KB

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