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

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

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