module.py 102 KB

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