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

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

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