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

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

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