You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

module.py 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import warnings
  9. from abc import ABCMeta, abstractmethod
  10. from collections import OrderedDict
  11. from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union
  12. import numpy as np
  13. from ..core.tensor.utils import make_shape_tuple
  14. from ..logger import get_logger
  15. from ..tensor import Parameter, Tensor
  16. from ..utils.deprecation import deprecated
  17. from ..utils.hook import HookHandler
  18. from ..utils.naming import auto_naming
  19. logger = get_logger(__name__)
  20. def _expand_structure(key, obj):
  21. if isinstance(obj, (Tensor, Module)):
  22. return [(key, obj)]
  23. elif isinstance(obj, (list, tuple, dict)):
  24. ret = []
  25. if isinstance(obj, dict):
  26. targets = ((k, obj[k]) for k in sorted(obj))
  27. else:
  28. targets = ((str(k), v) for k, v in enumerate(obj))
  29. for k, o in targets:
  30. sub_ret = _expand_structure(k, o)
  31. if sub_ret and not isinstance(k, str):
  32. raise AssertionError(
  33. "keys for Tensor and Module must be str, error key: {}".format(k)
  34. )
  35. for kt, vt in sub_ret:
  36. ret.extend([(key + "." + kt, vt)])
  37. return ret
  38. else:
  39. return []
  40. def _is_parameter(obj):
  41. return isinstance(obj, Parameter)
  42. def _is_buffer(obj):
  43. return isinstance(obj, Tensor) and not isinstance(obj, Parameter)
  44. def _is_module(obj):
  45. return isinstance(obj, Module)
  46. def _get_XNorm_typeclass():
  47. from .batchnorm import _BatchNorm
  48. from .normalization import GroupNorm, InstanceNorm, LayerNorm
  49. XNorm_types = (_BatchNorm, GroupNorm, LayerNorm, InstanceNorm)
  50. return XNorm_types
  51. class Module(metaclass=ABCMeta):
  52. """
  53. Base Module class.
  54. """
  55. def __init__(self, name=""):
  56. self.name = name
  57. # runtime attributes
  58. self.training = True
  59. self.quantize_disabled = False
  60. # hooks
  61. self._forward_pre_hooks = OrderedDict()
  62. self._forward_hooks = OrderedDict()
  63. self._modules = []
  64. # used for profiler and automatic naming
  65. self._name = "{anonymous}"
  66. @abstractmethod
  67. def forward(self, inputs):
  68. pass
  69. def register_forward_pre_hook(self, hook: Callable) -> HookHandler:
  70. """
  71. Registers a hook to handle forward inputs. `hook` should be a function.
  72. :param hook: a function that receive `module` and `inputs`, then return
  73. a modified `inputs` or `None`.
  74. :return: a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  75. """
  76. return HookHandler(self._forward_pre_hooks, hook)
  77. def register_forward_hook(self, hook: Callable) -> HookHandler:
  78. """
  79. Registers a hook to handle forward results. `hook` should be a function that
  80. receive `module`, `inputs` and `outputs`, then return a modified `outputs` or `None`.
  81. This method return a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  82. """
  83. return HookHandler(self._forward_hooks, hook)
  84. def __call__(self, *inputs, **kwargs):
  85. auto_naming.push_scope(self.name if self.name else self._name)
  86. for hook in self._forward_pre_hooks.values():
  87. modified_inputs = hook(self, inputs)
  88. if modified_inputs is not None:
  89. if not isinstance(modified_inputs, tuple):
  90. modified_inputs = (modified_inputs,)
  91. inputs = modified_inputs
  92. outputs = self.forward(*inputs, **kwargs)
  93. for hook in self._forward_hooks.values():
  94. modified_outputs = hook(self, inputs, outputs)
  95. if modified_outputs is not None:
  96. outputs = modified_outputs
  97. auto_naming.pop_scope()
  98. return outputs
  99. def _flatten(
  100. self,
  101. *,
  102. recursive: bool = True,
  103. with_key: bool = False,
  104. with_parent: bool = False,
  105. prefix: Optional[str] = None,
  106. predicate: Callable[[Any], bool] = lambda _: True,
  107. seen: Optional[Set[int]] = None
  108. ) -> Union[Iterable[Any], Iterable[Tuple[str, Any]]]:
  109. """
  110. Scans the module object and returns an iterable for the :class:`~.Tensor`
  111. and :class:`~.Module` attributes that agree with the ``predicate``. For multiple
  112. calls of this function with same arguments, the order of objects within the
  113. returned iterable is guaranteed to be identical, as long as all the involved
  114. module objects' ``__dict__`` does not change thoughout those calls.
  115. :param recursive: whether to recursively scan all the submodules.
  116. :param with_key: whether to yield keys along with yielded objects.
  117. :param with_parent: whether to yield ``self`` along with yielded objects.
  118. :param prefix: prefix appended to the yielded keys.
  119. :param predicate: the predication function applied to scanned objects.
  120. :param seen: a dict that records whether a module has been traversed yet.
  121. """
  122. if seen is None:
  123. seen = set([id(self)])
  124. module_dict = vars(self)
  125. _prefix = "" if prefix is None else prefix + "."
  126. for key in sorted(module_dict):
  127. for expanded_key, leaf in _expand_structure(key, module_dict[key]):
  128. leaf_id = id(leaf)
  129. if leaf_id in seen:
  130. continue
  131. seen.add(leaf_id)
  132. if predicate(leaf):
  133. if with_key and with_parent:
  134. yield _prefix + expanded_key, leaf, self
  135. elif with_key:
  136. yield _prefix + expanded_key, leaf
  137. elif with_parent:
  138. yield leaf, self
  139. else:
  140. yield leaf
  141. if recursive and isinstance(leaf, Module):
  142. yield from leaf._flatten(
  143. recursive=recursive,
  144. with_key=with_key,
  145. with_parent=with_parent,
  146. prefix=_prefix + expanded_key if with_key else None,
  147. predicate=predicate,
  148. seen=seen,
  149. )
  150. def parameters(self, recursive: bool = True, **kwargs) -> Iterable[Parameter]:
  151. r"""
  152. Returns an iterable for the :class:`~.Parameter` of the module.
  153. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  154. module, else only returns :class:`~.Parameter` that are direct attributes
  155. of this module.
  156. """
  157. if "requires_grad" in kwargs:
  158. del kwargs["requires_grad"]
  159. warnings.warn(
  160. "Tensor currently has no requires_grad attribute "
  161. "so requires_grad argument is ignored here",
  162. DeprecationWarning,
  163. )
  164. def predicate(obj) -> bool:
  165. return _is_parameter(obj)
  166. yield from self._flatten(
  167. with_key=False, predicate=predicate, recursive=recursive, **kwargs
  168. )
  169. def named_parameters(
  170. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  171. ) -> Iterable[Tuple[str, Parameter]]:
  172. """
  173. Returns an iterable for key :class:`~.Parameter` pairs of the module, where
  174. ``key`` is the dotted path from this module to the :class:`~.Parameter`.
  175. :param prefix: prefix prepended to the keys.
  176. :param recursive: if ``True``, returns all :class:`~.Parameter` within this
  177. module, else only returns :class:`~.Parameter` that are direct attributes
  178. of this module.
  179. """
  180. if "requires_grad" in kwargs:
  181. del kwargs["requires_grad"]
  182. warnings.warn(
  183. "Tensor currently has no requires_grad attribute "
  184. "so requires_grad argument is ignored here",
  185. DeprecationWarning,
  186. )
  187. def predicate(obj) -> bool:
  188. return _is_parameter(obj)
  189. yield from self._flatten(
  190. with_key=True,
  191. prefix=prefix,
  192. predicate=predicate,
  193. recursive=recursive,
  194. **kwargs,
  195. )
  196. def buffers(self, recursive: bool = True, **kwargs) -> Iterable[Tensor]:
  197. """
  198. Returns an iterable for the buffers of the module.
  199. Buffer is defined to be :class:`~.Tensor` excluding :class:`~.Parameter`.
  200. :param recursive: if ``True``, returns all buffers within this
  201. module, else only returns buffers that are direct attributes
  202. of this module.
  203. """
  204. yield from self._flatten(
  205. with_key=False, predicate=_is_buffer, recursive=recursive, **kwargs
  206. )
  207. def named_buffers(
  208. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  209. ) -> Iterable[Tuple[str, Tensor]]:
  210. """
  211. Returns an iterable for key buffer pairs of the module, where
  212. ``key`` is the dotted path from this module to the buffer.
  213. Buffer is defined to be :class:`~.Tensor` excluding :class:`~.Parameter`.
  214. :param prefix: prefix prepended to the keys.
  215. :param recursive: if ``True``, returns all buffers within this
  216. module, else only returns buffers that are direct attributes
  217. of this module.
  218. """
  219. yield from self._flatten(
  220. with_key=True,
  221. prefix=prefix,
  222. predicate=_is_buffer,
  223. recursive=recursive,
  224. **kwargs,
  225. )
  226. def children(self, **kwargs) -> "Iterable[Module]":
  227. """
  228. Returns an iterable for all the submodules that are direct attributes of this
  229. module.
  230. """
  231. yield from self._flatten(
  232. with_key=False, predicate=_is_module, recursive=False, **kwargs
  233. )
  234. def named_children(self, **kwargs) -> "Iterable[Tuple[str, Module]]":
  235. """
  236. Returns an iterable of key-submodule pairs for all the submodules that are
  237. direct attributes of this module, where 'key' is the attribute name of
  238. submodules.
  239. """
  240. yield from self._flatten(
  241. with_key=True, predicate=_is_module, recursive=False, **kwargs
  242. )
  243. def modules(self, **kwargs) -> "Iterable[Module]":
  244. """
  245. Returns an iterable for all the modules within this module, including itself.
  246. """
  247. if "with_parent" in kwargs and kwargs["with_parent"]:
  248. yield self, None
  249. else:
  250. yield self
  251. yield from self._flatten(with_key=False, predicate=_is_module, **kwargs)
  252. def named_modules(
  253. self, prefix: Optional[str] = None, **kwargs
  254. ) -> "Iterable[Tuple[str, Module]]":
  255. """
  256. Returns an iterable of key-module pairs for all the modules within this
  257. module, including itself, where 'key' is the dotted path from this module to the
  258. submodules.
  259. :param prefix: prefix prepended to the path.
  260. """
  261. if "with_parent" in kwargs and kwargs["with_parent"]:
  262. yield ("" if prefix is None else prefix), self, None
  263. else:
  264. yield ("" if prefix is None else prefix), self
  265. yield from self._flatten(
  266. with_key=True, prefix=prefix, predicate=_is_module, **kwargs
  267. )
  268. def apply(self, fn: "Callable[[Module], Any]") -> None:
  269. """
  270. Applies function ``fn`` to all the modules within this module, including
  271. itself.
  272. :param fn: the function to be applied on modules.
  273. """
  274. for it in self.modules():
  275. fn(it)
  276. @deprecated(version="1.0")
  277. def zero_grad(self) -> None:
  278. """
  279. Sets all parameters' grads to zero
  280. """
  281. for param in self.parameters():
  282. if param.grad is not None:
  283. param.grad.reset_zero()
  284. def train(self, mode: bool = True, recursive: bool = True) -> None:
  285. """
  286. Sets training mode of all the modules within this module (including itself) to
  287. ``mode``. This effectively sets the ``training`` attributes of those modules
  288. to ``mode``, but only has effect on certain modules (e.g.
  289. :class:`~.BatchNorm2d`, :class:`~.Dropout`, :class:`~.Observer`)
  290. :param mode: the training mode to be set on modules.
  291. :param recursive: whether to recursively call submodules' ``train()``.
  292. """
  293. if not recursive:
  294. self.training = mode
  295. return
  296. def fn(module: Module) -> None:
  297. module.train(mode, recursive=False)
  298. self.apply(fn)
  299. def eval(self) -> None:
  300. """
  301. Sets training mode of all the modules within this module (including itself) to
  302. ``False``. See :meth:`~.Module.train` for details.
  303. """
  304. self.train(False)
  305. def disable_quantize(self, value=True):
  306. r"""
  307. Sets ``module``'s ``quantize_disabled`` attribute and return ``module``.
  308. Could be used as a decorator.
  309. """
  310. def fn(module: Module) -> None:
  311. module.quantize_disabled = value
  312. self.apply(fn)
  313. @deprecated(version="1.0")
  314. def replace_param(
  315. self, params: dict, start_pos: int, seen: Optional[Set[int]] = None
  316. ):
  317. """
  318. Replaces module's parameters with ``params``, used by :class:`~.ParamPack` to
  319. speedup multimachine training.
  320. """
  321. offset = 0
  322. if seen is None:
  323. seen = set([id(self)])
  324. module_dict = vars(self)
  325. for key in sorted(module_dict):
  326. hash_id = id(module_dict[key])
  327. if hash_id in seen:
  328. continue
  329. seen.add(hash_id)
  330. if isinstance(module_dict[key], Parameter):
  331. if start_pos + offset in params:
  332. assert make_shape_tuple(module_dict[key].shape) == make_shape_tuple(
  333. params[start_pos + offset].shape
  334. )
  335. module_dict[key] = params[start_pos + offset]
  336. offset += 1
  337. if isinstance(module_dict[key], Module):
  338. offset += module_dict[key].replace_param(
  339. params, start_pos + offset, seen
  340. )
  341. return offset
  342. def state_dict(self, rst=None, prefix="", keep_var=False):
  343. _rst = self._state_dict(rst=rst, prefix=prefix, keep_var=keep_var)
  344. rst = OrderedDict()
  345. XNorm_typeclass = _get_XNorm_typeclass()
  346. for (module_type, k), v in _rst.items():
  347. # for performance reasons, parameters in XNorm (e.g., BatchNorm2d) are 4-dim tensors,
  348. # however they will be reshaped to 1-dim tensors before returned by `statr_dict()`
  349. if issubclass(module_type, XNorm_typeclass):
  350. v = v.reshape(-1)
  351. rst[k] = v
  352. return rst
  353. def _state_dict(self, rst=None, prefix="", keep_var=False):
  354. r"""
  355. Returns a dictionary containing whole states of the module.
  356. """
  357. def is_state(obj):
  358. return _is_parameter(obj) or _is_buffer(obj)
  359. module_type = self.__class__
  360. if rst is None:
  361. rst = OrderedDict()
  362. for k, v in self._flatten(recursive=False, with_key=True, predicate=is_state):
  363. assert prefix + k not in rst, "duplicated state: {}".format(k)
  364. if keep_var:
  365. rst[(module_type, prefix + k)] = v
  366. else:
  367. rst[(module_type, prefix + k)] = v.numpy()
  368. for k, submodule in self._flatten(
  369. recursive=False,
  370. with_key=True,
  371. predicate=lambda obj: isinstance(obj, Module),
  372. ):
  373. submodule.state_dict(rst, prefix + k + ".", keep_var)
  374. return rst
  375. def load_state_dict(
  376. self,
  377. state_dict: Union[dict, Callable[[str, Tensor], Optional[np.ndarray]]],
  378. strict=True,
  379. ):
  380. r"""
  381. Loads a given dictionary created by :func:`state_dict` into this module.
  382. If ``strict`` is ``True``, the keys of :func:`state_dict` must exactly match the keys
  383. returned by :func:`state_dict`.
  384. Users can also pass a closure: ``Function[key: str, var: Tensor] -> Optional[np.ndarray]``
  385. as a `state_dict`, in order to handle complex situations. For example, load everything
  386. except for the final linear classifier:
  387. .. code-block::
  388. state_dict = {...} # Dict[str, np.ndarray]
  389. model.load_state_dict({
  390. k: None if k.startswith('fc') else v
  391. for k, v in state_dict.items()
  392. }, strict=False)
  393. Here returning ``None`` means skipping parameter ``k``.
  394. To prevent shape mismatch (e.g. load PyTorch weights), we can reshape before loading:
  395. .. code-block::
  396. state_dict = {...}
  397. def reshape_accordingly(k, v):
  398. return state_dict[k].reshape(v.shape)
  399. model.load_state_dict(reshape_accordingly)
  400. We can also perform inplace re-initialization or pruning:
  401. .. code-block::
  402. def reinit_and_pruning(k, v):
  403. if 'bias' in k:
  404. M.init.zero_(v)
  405. if 'conv' in k:
  406. return v.numpy() * (np.abs(v.numpy()) > 1e-3).astype("float32)
  407. model.load_state_dict(reinit_and_pruning, strict=False)
  408. """
  409. unused = []
  410. if isinstance(state_dict, dict):
  411. unused = state_dict.keys()
  412. def closure(k, _): # var unused
  413. return state_dict[k] if k in state_dict else None
  414. elif callable(state_dict):
  415. closure = state_dict
  416. else:
  417. raise ValueError(
  418. "`state_dict` must load a dict or callable, got {}".format(
  419. type(state_dict)
  420. )
  421. )
  422. loaded, skipped = self._load_state_dict_with_closure(closure)
  423. unused = set(unused) - loaded
  424. if len(unused) != 0:
  425. if strict:
  426. raise KeyError(
  427. "Unused params violate `strict=True`, unused={}".format(unused)
  428. )
  429. else:
  430. logger.warning(
  431. "Unused params in `strict=False` mode, unused={}".format(unused)
  432. )
  433. if len(skipped) != 0:
  434. if strict:
  435. raise KeyError(
  436. "Missing params violate `strict=True`, missing={}".format(skipped)
  437. )
  438. else:
  439. logger.warning(
  440. "Missing params in `strict=False` mode, missing={}".format(skipped)
  441. )
  442. def _load_state_dict_with_closure(self, closure):
  443. """
  444. Advance state_dict load through callable ``closure`` whose signature is
  445. ``closure(key: str, var: Tensor) -> Union[np.ndarry, None]``
  446. """
  447. XNorm_typeclass = _get_XNorm_typeclass()
  448. assert callable(closure), "closure must be a function"
  449. loaded = []
  450. skipped = []
  451. local_state_dict = self._state_dict(keep_var=True)
  452. for (module_type, k), var in local_state_dict.items():
  453. to_be_load = closure(k, var)
  454. if to_be_load is None:
  455. skipped.append(k)
  456. continue
  457. assert isinstance(
  458. to_be_load, np.ndarray
  459. ), "closure should return a `np.ndarray`, now `{}` get {}".format(
  460. k, to_be_load
  461. )
  462. var_shape = make_shape_tuple(var.shape)
  463. to_be_load_shape = make_shape_tuple(to_be_load.shape)
  464. if var_shape != to_be_load_shape:
  465. # weight and bias in BatchNorm1d, BatchNorm2d and SyncBatchNorm are 1-dim tensors in v1.0, and
  466. # since v1.1 they are 4-dim tensors. The following special rule for these modules preserves the
  467. # backward compatibility.
  468. if issubclass(module_type, XNorm_typeclass):
  469. if np.prod(var_shape) == np.prod(to_be_load_shape):
  470. to_be_load = to_be_load.reshape(var_shape)
  471. else:
  472. raise ValueError(
  473. "param `{}` size mismatch, should be {}, get {}".format(
  474. k, np.prod(var_shape), np.prod(to_be_load_shape)
  475. )
  476. )
  477. else:
  478. raise ValueError(
  479. "param `{}` shape mismatch, should be {}, get {}".format(
  480. k, var_shape, to_be_load_shape
  481. )
  482. )
  483. var._reset(type(var)(to_be_load, dtype=to_be_load.dtype, device=var.device))
  484. loaded.append(k)
  485. return set(loaded), set(skipped)
  486. def __getattribute__(self, name: str):
  487. value = super().__getattribute__(name)
  488. if name == "_name":
  489. return value
  490. if isinstance(value, (Tensor, Module)):
  491. value._name = name
  492. return value
  493. def __setattr__(self, name: str, value):
  494. if _is_module(value):
  495. modules = self.__dict__.get("_modules")
  496. if modules is None:
  497. raise AttributeError(
  498. "cannot assign module before Module.__init__() call"
  499. )
  500. if name not in self.__dict__:
  501. modules.append(name)
  502. super().__setattr__(name, value)
  503. def __delattr__(self, name: str):
  504. if name in self.__dict__ and _is_module(self.__dict__[name]):
  505. modules = self.__dict__.get("_modules")
  506. modules.remove(name)
  507. super().__delattr__(name)
  508. def _module_info_string(self) -> str:
  509. r"""
  510. Set the extra representation of the module.
  511. """
  512. return ""
  513. def __repr__(self):
  514. def add_indent(repr_str, num_spaces):
  515. s = repr_str.split("\n")
  516. # don't do anything for single-line stuff
  517. if len(s) == 1:
  518. return repr_str
  519. first = s.pop(0)
  520. s = [(num_spaces * " ") + line for line in s]
  521. s = "\n".join(s)
  522. s = first + "\n" + s
  523. return s
  524. extra_lines = []
  525. extra_repr = self._module_info_string()
  526. if extra_repr:
  527. extra_lines = extra_repr.split("\n")
  528. child_lines = [
  529. "(" + name + "): " + add_indent(repr(self.__dict__[name]), 2)
  530. for name in self._modules
  531. ]
  532. lines = extra_lines + child_lines
  533. main_str = self.__class__.__name__ + "("
  534. if lines:
  535. # simple one-liner info, which most builtin Modules will use
  536. if len(extra_lines) == 1 and not child_lines:
  537. main_str += extra_lines[0]
  538. else:
  539. main_str += "\n " + "\n ".join(lines) + "\n"
  540. main_str += ")"
  541. return main_str

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台