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

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

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