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 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 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. from abc import ABCMeta, abstractmethod
  9. from collections import OrderedDict
  10. from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union
  11. import numpy as np
  12. from ..core.tensor.dtype import is_quantize
  13. from ..logger import get_logger
  14. from ..tensor import Tensor
  15. from ..tensor_nn import Buffer, Parameter
  16. from ..utils.hook import HookHandler
  17. logger = get_logger(__name__)
  18. def _expand_structure(key, obj):
  19. if isinstance(obj, (Tensor, Module)):
  20. return [(key, obj)]
  21. elif isinstance(obj, (list, tuple, dict)):
  22. ret = []
  23. if isinstance(obj, dict):
  24. targets = ((k, obj[k]) for k in sorted(obj))
  25. else:
  26. targets = ((str(k), v) for k, v in enumerate(obj))
  27. for k, o in targets:
  28. sub_ret = _expand_structure(k, o)
  29. if sub_ret and not isinstance(k, str):
  30. raise AssertionError(
  31. "keys for Tensor and Module must be str, error key: {}".format(k)
  32. )
  33. for kt, vt in sub_ret:
  34. ret.extend([(key + "." + kt, vt)])
  35. return ret
  36. else:
  37. return []
  38. def _is_parameter(obj):
  39. return isinstance(obj, Parameter)
  40. def _is_buffer(obj):
  41. return isinstance(obj, Buffer)
  42. def _is_module(obj):
  43. return isinstance(obj, Module)
  44. class Module(metaclass=ABCMeta):
  45. """Base Module class.
  46. """
  47. def __init__(self):
  48. # runtime attributes
  49. self.training = True
  50. self.quantize_disabled = False
  51. # hooks
  52. self._forward_pre_hooks = OrderedDict()
  53. self._forward_hooks = OrderedDict()
  54. @abstractmethod
  55. def forward(self, inputs):
  56. pass
  57. def register_forward_pre_hook(self, hook: Callable) -> HookHandler:
  58. """Register a hook to handle forward inputs. `hook` should be a function
  59. Note that `inputs` keyword inputs
  60. :param hook: a function that receive `module` and `inputs`, then return
  61. a modified `inputs` or `None`.
  62. :return: a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  63. """
  64. return HookHandler(self._forward_pre_hooks, hook)
  65. def register_forward_hook(self, hook: Callable) -> HookHandler:
  66. """Register a hook to handle forward results. `hook` should be a function that
  67. receive `module`, `inputs` and `outputs`, then return a modified `outputs` or `None`.
  68. This method return a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  69. """
  70. return HookHandler(self._forward_hooks, hook)
  71. def __call__(self, *inputs, **kwargs):
  72. for hook in self._forward_pre_hooks.values():
  73. modified_inputs = hook(self, inputs)
  74. if modified_inputs is not None:
  75. if not isinstance(modified_inputs, tuple):
  76. modified_inputs = (modified_inputs,)
  77. inputs = modified_inputs
  78. outputs = self.forward(*inputs, **kwargs)
  79. for hook in self._forward_hooks.values():
  80. modified_outputs = hook(self, inputs, outputs)
  81. if modified_outputs is not None:
  82. outputs = modified_outputs
  83. return outputs
  84. def _flatten(
  85. self,
  86. *,
  87. recursive: bool = True,
  88. with_key: bool = False,
  89. with_parent: bool = False,
  90. prefix: Optional[str] = None,
  91. predicate: Callable[[Any], bool] = lambda _: True,
  92. seen: Optional[Set[int]] = None
  93. ) -> Union[Iterable[Any], Iterable[Tuple[str, Any]]]:
  94. """Scans the module object and returns an iterable for the :class:`~.Tensor`
  95. and :class:`~.Module` attributes that agree with the ``predicate``. For multiple
  96. calls of this function with same arguments, the order of objects within the
  97. returned iterable is guaranteed to be identical, as long as all the involved
  98. module objects' ``__dict__`` does not change thoughout those calls.
  99. :param recursive: Whether to recursively scan all the submodules.
  100. :param with_key: Whether to yield keys along with yielded objects.
  101. :param with_parent: Whether to yield ``self`` along with yielded objects.
  102. :param prefix: The prefix appended to the yielded keys.
  103. :param predicate: The predicate function applied to scanned objects.
  104. :param seen: A dict that records whether a module has been traversed yet.
  105. """
  106. if seen is None:
  107. seen = set([id(self)])
  108. module_dict = vars(self)
  109. _prefix = "" if prefix is None else prefix + "."
  110. for key in sorted(module_dict):
  111. for expanded_key, leaf in _expand_structure(key, module_dict[key]):
  112. leaf_id = id(leaf)
  113. if leaf_id in seen:
  114. continue
  115. seen.add(leaf_id)
  116. if predicate(leaf):
  117. if with_key and with_parent:
  118. yield _prefix + expanded_key, leaf, self
  119. elif with_key:
  120. yield _prefix + expanded_key, leaf
  121. elif with_parent:
  122. yield leaf, self
  123. else:
  124. yield leaf
  125. if recursive and isinstance(leaf, Module):
  126. yield from leaf._flatten(
  127. recursive=recursive,
  128. with_key=with_key,
  129. with_parent=with_parent,
  130. prefix=_prefix + expanded_key if with_key else None,
  131. predicate=predicate,
  132. seen=seen,
  133. )
  134. def parameters(
  135. self, requires_grad: Optional[bool] = None, recursive: bool = True, **kwargs
  136. ) -> Iterable[Parameter]:
  137. r"""Returns an iterable for the :class:`~.Parameter` of the module.
  138. :param requires_grad: Limitation over the :attr:`~.Parameter.requires_grad`
  139. attribute of returned :class:`.Parameter`. ``None`` for no limitation.
  140. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  141. module, else only returns :class:`~.Parameter` that are direct attributes
  142. of this module.
  143. """
  144. def predicate(obj) -> bool:
  145. return _is_parameter(obj) and (
  146. requires_grad is None or obj.requires_grad == requires_grad
  147. )
  148. yield from self._flatten(
  149. with_key=False, predicate=predicate, recursive=recursive, **kwargs
  150. )
  151. def named_parameters(
  152. self,
  153. requires_grad: Optional[bool] = None,
  154. prefix: Optional[str] = None,
  155. recursive: bool = True,
  156. **kwargs
  157. ) -> Iterable[Tuple[str, Parameter]]:
  158. """Returns an iterable for key :class:`~.Parameter` pairs of the module, where
  159. ``key`` is the dotted path from this module to the :class:`~.Parameter` .
  160. :param requires_grad: Limitation over the :attr:`~.Parameter.requires_grad`
  161. attribute of returned :class:`~.Parameter` . ``None`` for no limitation.
  162. :param prefix: The prefix prepended to the keys.
  163. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  164. module, else only returns :class:`~.Parameter` that are direct attributes
  165. of this module.
  166. """
  167. def predicate(obj) -> bool:
  168. return _is_parameter(obj) and (
  169. requires_grad is None or obj.requires_grad == requires_grad
  170. )
  171. yield from self._flatten(
  172. with_key=True,
  173. prefix=prefix,
  174. predicate=predicate,
  175. recursive=recursive,
  176. **kwargs,
  177. )
  178. def buffers(self, recursive: bool = True, **kwargs) -> Iterable[Buffer]:
  179. """Returns an iterable for the :class:`~.Buffer` of the module.
  180. :param recursive: If ``True``, returns all :class:`~.Buffer` within this
  181. module, else only returns :class:`~.Buffer` that are direct attributes
  182. of this module.
  183. """
  184. yield from self._flatten(
  185. with_key=False, predicate=_is_buffer, recursive=recursive, **kwargs
  186. )
  187. def named_buffers(
  188. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  189. ) -> Iterable[Tuple[str, Buffer]]:
  190. """Returns an iterable for key :class:`~.Buffer` pairs of the module, where
  191. ``key`` is the dotted path from this module to the :class:`~.Buffer` .
  192. :param prefix: The prefix prepended to the keys.
  193. :param recursive: If ``True``, returns all :class:`~.Buffer` within this
  194. module, else only returns :class:`~.Buffer` that are direct attributes
  195. of this module.
  196. """
  197. yield from self._flatten(
  198. with_key=True,
  199. prefix=prefix,
  200. predicate=_is_buffer,
  201. recursive=recursive,
  202. **kwargs,
  203. )
  204. def children(self, **kwargs) -> "Iterable[Module]":
  205. """Returns an iterable for all the submodules that are direct attributes of this
  206. module.
  207. """
  208. yield from self._flatten(
  209. with_key=False, predicate=_is_module, recursive=False, **kwargs
  210. )
  211. def named_children(self, **kwargs) -> "Iterable[Tuple[str, Module]]":
  212. """Returns an iterable of key-submodule pairs for all the submodules that are
  213. direct attributes of this module, where 'key' is the attribute name of
  214. submodules.
  215. """
  216. yield from self._flatten(
  217. with_key=True, predicate=_is_module, recursive=False, **kwargs
  218. )
  219. def modules(self, **kwargs) -> "Iterable[Module]":
  220. """Returns an iterable for all the modules within this module, including itself.
  221. """
  222. if "with_parent" in kwargs and kwargs["with_parent"]:
  223. yield self, None
  224. else:
  225. yield self
  226. yield from self._flatten(with_key=False, predicate=_is_module, **kwargs)
  227. def named_modules(
  228. self, prefix: Optional[str] = None, **kwargs
  229. ) -> "Iterable[Tuple[str, Module]]":
  230. """Returns an iterable of key-module pairs for all the modules within this
  231. module, including itself, where 'key' is the dotted path from this module to the
  232. submodules.
  233. :param prefix: The prefix prepended to the path.
  234. """
  235. if "with_parent" in kwargs and kwargs["with_parent"]:
  236. yield ("" if prefix is None else prefix), self, None
  237. else:
  238. yield ("" if prefix is None else prefix), self
  239. yield from self._flatten(
  240. with_key=True, prefix=prefix, predicate=_is_module, **kwargs
  241. )
  242. def apply(self, fn: "Callable[[Module], Any]") -> None:
  243. """Apply function ``fn`` to all the modules within this module, including
  244. itself.
  245. :param fn: The function to be applied on modules.
  246. """
  247. for it in self.modules():
  248. fn(it)
  249. def zero_grad(self) -> None:
  250. """Set all parameters' grads to zero
  251. """
  252. for param in self.parameters():
  253. if param.grad is not None:
  254. param.grad.reset_zero()
  255. def train(self, mode: bool = True, recursive: bool = True) -> None:
  256. """Set training mode of all the modules within this module (including itself) to
  257. ``mode``. This effectively sets the ``training`` attributes of those modules
  258. to ``mode``, but only has effect on certain modules (e.g.
  259. :class:`~.BatchNorm2d`, :class:`~.Dropout`, :class:`~.Observer`)
  260. :param mode: the training mode to be set on modules.
  261. :param recursive: whether to recursively call submodules' ``train()``.
  262. """
  263. if not recursive:
  264. self.training = mode
  265. return
  266. def fn(module: Module) -> None:
  267. module.train(mode, recursive=False)
  268. self.apply(fn)
  269. def eval(self) -> None:
  270. """Set training mode of all the modules within this module (including itself) to
  271. ``False``. See :meth:`~.Module.train` for details.
  272. """
  273. self.train(False)
  274. def disable_quantize(self, value=True):
  275. r"""
  276. Set ``module``'s ``quantize_disabled`` attribute and return ``module``.
  277. Could be used as a decorator.
  278. """
  279. def fn(module: Module) -> None:
  280. module.quantize_disabled = value
  281. self.apply(fn)
  282. def replace_param(
  283. self, params: dict, start_pos: int, seen: Optional[Set[int]] = None
  284. ):
  285. """Replace module's parameters with `params`, used by :class:`~.ParamPack` to
  286. speedup multimachine training.
  287. """
  288. offset = 0
  289. if seen is None:
  290. seen = set([id(self)])
  291. module_dict = vars(self)
  292. for key in sorted(module_dict):
  293. hash_id = id(module_dict[key])
  294. if hash_id in seen:
  295. continue
  296. seen.add(hash_id)
  297. if isinstance(module_dict[key], Parameter):
  298. if start_pos + offset in params:
  299. assert module_dict[key].shape == params[start_pos + offset].shape
  300. module_dict[key] = params[start_pos + offset]
  301. offset += 1
  302. if isinstance(module_dict[key], Module):
  303. offset += module_dict[key].replace_param(
  304. params, start_pos + offset, seen
  305. )
  306. return offset
  307. def state_dict(self, rst=None, prefix="", keep_var=False):
  308. r"""Returns a dictionary containing whole states of the module.
  309. """
  310. def is_state(obj):
  311. return _is_parameter(obj) or _is_buffer(obj)
  312. if rst is None:
  313. rst = OrderedDict()
  314. for k, v in self._flatten(recursive=False, with_key=True, predicate=is_state):
  315. assert prefix + k not in rst, "duplicated state: {}".format(k)
  316. if keep_var:
  317. rst[prefix + k] = v
  318. else:
  319. rst[prefix + k] = v.numpy()
  320. for k, submodule in self._flatten(
  321. recursive=False,
  322. with_key=True,
  323. predicate=lambda obj: isinstance(obj, Module),
  324. ):
  325. submodule.state_dict(rst, prefix + k + ".", keep_var)
  326. return rst
  327. def load_state_dict(
  328. self,
  329. state_dict: Union[dict, Callable[[str, Tensor], Optional[np.ndarray]]],
  330. strict=True,
  331. ):
  332. r"""Load a given dictionary created by :func:`state_dict` into this module.
  333. If ``strict`` is ``True``, the keys of :func:`state_dict` must exactly match the keys
  334. returned by :func:`state_dict`.
  335. Users can also pass a closure: `Function[key: str, var: Tensor] -> Optional[np.ndarray]`
  336. as a `state_dict`, in order to handle complex situations. For example, load everything
  337. except for the final linear classifier:
  338. .. code-block::
  339. state_dict = {...} # Dict[str, np.ndarray]
  340. model.load_state_dict({
  341. k: None if k.startswith('fc') else v
  342. for k, v in state_dict.items()
  343. }, strict=False)
  344. Here returning `None` means skipping parameter `k`.
  345. To prevent shape mismatch (e.g. load PyTorch weights), we can reshape before loading:
  346. .. code-block::
  347. state_dict = {...}
  348. def reshape_accordingly(k, v):
  349. return state_dict[k].reshape(v.shape)
  350. model.load_state_dict(reshape_accordingly)
  351. We can also perform inplace re-initialization or pruning:
  352. .. code-block::
  353. def reinit_and_pruning(k, v):
  354. if 'bias' in k:
  355. M.init.zero_(v)
  356. if 'conv' in k:
  357. return v.numpy() * (np.abs(v.numpy()) > 1e-3).astype("float32)
  358. model.load_state_dict(reinit_and_pruning, strict=False)
  359. """
  360. unused = []
  361. if isinstance(state_dict, dict):
  362. unused = state_dict.keys()
  363. def closure(k, _): # var unused
  364. return state_dict[k] if k in state_dict else None
  365. elif callable(state_dict):
  366. closure = state_dict
  367. else:
  368. raise ValueError(
  369. "`state_dict` must load a dict or callable, got {}".format(
  370. type(state_dict)
  371. )
  372. )
  373. loaded, skipped = self._load_state_dict_with_closure(closure)
  374. unused = set(unused) - loaded
  375. if len(unused) != 0:
  376. if strict:
  377. raise KeyError(
  378. "Unused params violate `strict=True`, unused={}".format(unused)
  379. )
  380. else:
  381. logger.warning(
  382. "Unused params in `strict=False` mode, unused={}".format(unused)
  383. )
  384. if len(skipped) != 0:
  385. if strict:
  386. raise KeyError(
  387. "Missing params violate `strict=True`, missing={}".format(skipped)
  388. )
  389. else:
  390. logger.warning(
  391. "Missing params in `strict=False` mode, missing={}".format(skipped)
  392. )
  393. def _load_state_dict_with_closure(self, closure):
  394. """Advance state_dict load through callable `closure` whose signature is
  395. `closure(key: str, var: Tensor) -> Union[np.ndarry, None]`
  396. """
  397. assert callable(closure), "closure must be a function"
  398. loaded = []
  399. skipped = []
  400. local_state_dict = self.state_dict(keep_var=True)
  401. for k, var in local_state_dict.items():
  402. to_be_load = closure(k, var)
  403. if to_be_load is None:
  404. skipped.append(k)
  405. continue
  406. assert isinstance(
  407. to_be_load, np.ndarray
  408. ), "closure should return a `np.ndarray`, now `{}` get {}".format(
  409. k, to_be_load
  410. )
  411. assert (
  412. var.shape == to_be_load.shape
  413. ), "param `{}` shape mismatch, should be {}, get {}".format(
  414. k, var.shape, to_be_load.shape
  415. )
  416. # For quantized dtype, the initialized dtype
  417. # scale/zero_points maybe invalid, use pretrained dtype instead.
  418. if is_quantize(to_be_load.dtype) and is_quantize(var.dtype):
  419. var = var.astype(to_be_load.dtype)
  420. var.set_value(to_be_load)
  421. loaded.append(k)
  422. return set(loaded), set(skipped)

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