module.py 82 KB

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