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. # 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, (list, tuple, dict)):
  17. ret = []
  18. if isinstance(obj, dict):
  19. targets = ((k, obj[k]) for k in sorted(obj))
  20. else:
  21. targets = ((str(k), v) for k, v in enumerate(obj))
  22. for k, o in targets:
  23. ret.extend(_expand_structure(key + "." + k, o))
  24. return ret
  25. else:
  26. return [(key, obj)]
  27. def _is_parameter(obj):
  28. return isinstance(obj, Parameter)
  29. def _is_buffer(obj):
  30. return isinstance(obj, Buffer)
  31. def _is_module(obj):
  32. return isinstance(obj, Module)
  33. class Module(metaclass=ABCMeta):
  34. """Base Module class.
  35. """
  36. def __init__(self):
  37. self.training = True
  38. @abstractmethod
  39. def forward(self, inputs):
  40. pass
  41. def __call__(self, *inputs, **kwargs):
  42. # ToDo: Convert numpy or scalar
  43. # Maybe ToDo: set training phase
  44. # Maybe ToDo: set computing graph
  45. outputs = self.forward(*inputs, **kwargs)
  46. # Maybe ToDo: set connectivity metadata
  47. return outputs
  48. def _flatten(
  49. self,
  50. *,
  51. recursive: bool = True,
  52. with_key: bool = False,
  53. with_parent: bool = False,
  54. prefix: Optional[str] = None,
  55. predicate: Callable[[Any], bool] = lambda _: True,
  56. seen: Optional[Set[int]] = None
  57. ) -> Union[Iterable[Any], Iterable[Tuple[str, Any]]]:
  58. """Scans the module object and returns an iterable for the attributes that
  59. agree with the ``predicate``. For multiple calls of this function with same
  60. arguments, the order of objects within the returned iterable is guaranteed to be
  61. identical, as long as all the involved module objects' ``__dict__`` does not
  62. change thoughout those calls.
  63. :param recursive: Whether to recursively scan all the submodules.
  64. :param with_key: Whether to yield keys along with yielded objects.
  65. :param with_parent: Whether to yield ``self`` along with yielded objects.
  66. :param prefix: The prefix appended to the yielded keys.
  67. :param predicate: The predicate function applied to scanned objects.
  68. :param seen: A dict that records whether a module has been traversed yet.
  69. """
  70. if seen is None:
  71. seen = set([id(self)])
  72. module_dict = vars(self)
  73. _prefix = "" if prefix is None else prefix + "."
  74. for key in sorted(module_dict):
  75. for expanded_key, leaf in _expand_structure(key, module_dict[key]):
  76. leaf_id = id(leaf)
  77. if leaf_id in seen:
  78. continue
  79. seen.add(leaf_id)
  80. if predicate(leaf):
  81. if with_key and with_parent:
  82. yield _prefix + expanded_key, leaf, self
  83. elif with_key:
  84. yield _prefix + expanded_key, leaf
  85. elif with_parent:
  86. yield leaf, self
  87. else:
  88. yield leaf
  89. if recursive and isinstance(leaf, Module):
  90. yield from leaf._flatten(
  91. recursive=recursive,
  92. with_key=with_key,
  93. with_parent=with_parent,
  94. prefix=_prefix + expanded_key if with_key else None,
  95. predicate=predicate,
  96. seen=seen,
  97. )
  98. def parameters(
  99. self, requires_grad: Optional[bool] = None, recursive: bool = True, **kwargs
  100. ) -> Iterable[Parameter]:
  101. r"""Returns an iterable for the :class:`~.Parameter` of the module.
  102. :param requires_grad: Limitation over the :attr:`~.Parameter.requires_grad`
  103. attribute of returned :class:`.Parameter`. ``None`` for no limitation.
  104. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  105. module, else only returns :class:`~.Parameter` that are direct attributes
  106. of this module.
  107. """
  108. def predicate(obj) -> bool:
  109. return _is_parameter(obj) and (
  110. requires_grad is None or obj.requires_grad == requires_grad
  111. )
  112. yield from self._flatten(
  113. with_key=False, predicate=predicate, recursive=recursive, **kwargs
  114. )
  115. def named_parameters(
  116. self,
  117. requires_grad: Optional[bool] = None,
  118. prefix: Optional[str] = None,
  119. recursive: bool = True,
  120. **kwargs
  121. ) -> Iterable[Tuple[str, Parameter]]:
  122. """Returns an iterable for key :class:`~.Parameter` pairs of the module, where
  123. ``key`` is the dotted path from this module to the :class:`~.Parameter` .
  124. :param requires_grad: Limitation over the :attr:`~.Parameter.requires_grad`
  125. attribute of returned :class:`~.Parameter` . ``None`` for no limitation.
  126. :param prefix: The prefix prepended to the keys.
  127. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  128. module, else only returns :class:`~.Parameter` that are direct attributes
  129. of this module.
  130. """
  131. def predicate(obj) -> bool:
  132. return _is_parameter(obj) and (
  133. requires_grad is None or obj.requires_grad == requires_grad
  134. )
  135. yield from self._flatten(
  136. with_key=True,
  137. prefix=prefix,
  138. predicate=predicate,
  139. recursive=recursive,
  140. **kwargs,
  141. )
  142. def buffers(self, recursive: bool = True, **kwargs) -> Iterable[Buffer]:
  143. """Returns an iterable for the :class:`~.Buffer` of the module.
  144. :param recursive: If ``True``, returns all :class:`~.Buffer` within this
  145. module, else only returns :class:`~.Buffer` that are direct attributes
  146. of this module.
  147. """
  148. yield from self._flatten(
  149. with_key=False, predicate=_is_buffer, recursive=recursive, **kwargs
  150. )
  151. def replace_param(
  152. self, params: dict, start_pos: int, seen: Optional[Set[int]] = None
  153. ):
  154. offset = 0
  155. if seen is None:
  156. seen = set([id(self)])
  157. module_dict = vars(self)
  158. for key in sorted(module_dict):
  159. hash_id = id(module_dict[key])
  160. if hash_id in seen:
  161. continue
  162. seen.add(hash_id)
  163. if isinstance(module_dict[key], Parameter):
  164. if start_pos + offset in params:
  165. assert module_dict[key].shape == params[start_pos + offset].shape
  166. module_dict[key] = params[start_pos + offset]
  167. offset += 1
  168. if isinstance(module_dict[key], Module):
  169. offset += module_dict[key].replace_param(
  170. params, start_pos + offset, seen
  171. )
  172. return offset
  173. def named_buffers(
  174. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  175. ) -> Iterable[Tuple[str, Buffer]]:
  176. """Returns an iterable for key :class:`~.Buffer` pairs of the module, where
  177. ``key`` is the dotted path from this module to the :class:`~.Buffer` .
  178. :param prefix: The prefix prepended to the keys.
  179. :param recursive: If ``True``, returns all :class:`~.Buffer` within this
  180. module, else only returns :class:`~.Buffer` that are direct attributes
  181. of this module.
  182. """
  183. yield from self._flatten(
  184. with_key=True,
  185. prefix=prefix,
  186. predicate=_is_buffer,
  187. recursive=recursive,
  188. **kwargs,
  189. )
  190. def children(self, **kwargs) -> "Iterable[Module]":
  191. """Returns an iterable for all the submodules that are direct attributes of this
  192. module.
  193. """
  194. yield from self._flatten(
  195. with_key=False, predicate=_is_module, recursive=False, **kwargs
  196. )
  197. def named_children(self, **kwargs) -> "Iterable[Tuple[str, Module]]":
  198. """Returns an iterable of key-submodule pairs for all the submodules that are
  199. direct attributes of this module, where 'key' is the attribute name of
  200. submodules.
  201. """
  202. yield from self._flatten(
  203. with_key=True, predicate=_is_module, recursive=False, **kwargs
  204. )
  205. def modules(self, **kwargs) -> "Iterable[Module]":
  206. """Returns an iterable for all the modules within this module, including itself.
  207. """
  208. if "with_parent" in kwargs and kwargs["with_parent"]:
  209. yield self, None
  210. else:
  211. yield self
  212. yield from self._flatten(with_key=False, predicate=_is_module, **kwargs)
  213. def named_modules(
  214. self, prefix: Optional[str] = None, **kwargs
  215. ) -> "Iterable[Tuple[str, Module]]":
  216. """Returns an iterable of key-module pairs for all the modules within this
  217. module, including itself, where 'key' is the dotted path from this module to the
  218. submodules.
  219. :param prefix: The prefix prepended to the path.
  220. """
  221. if "with_parent" in kwargs and kwargs["with_parent"]:
  222. yield ("" if prefix is None else prefix), self, None
  223. else:
  224. yield ("" if prefix is None else prefix), self
  225. yield from self._flatten(
  226. with_key=True, prefix=prefix, predicate=_is_module, **kwargs
  227. )
  228. def apply(self, fn: "Callable[[Module], Any]") -> None:
  229. """Apply function ``fn`` to all the modules within this module, including
  230. itself.
  231. :param fn: The function to be applied on modules.
  232. """
  233. for it in self.modules():
  234. fn(it)
  235. def zero_grad(self) -> None:
  236. """Set all parameters' grads to zero
  237. """
  238. for param in self.parameters():
  239. if param.grad is not None:
  240. param.grad.reset_zero()
  241. def train(self, mode: bool = True) -> None:
  242. """Set training mode of all the modules within this module (including itself) to
  243. ``mode``. This effectively sets the ``training`` attributes of those modules
  244. to ``mode``, but only has effect on certain modules (e.g.
  245. :class:`~.BatchNorm2d`, :class:`~.Dropout`)
  246. :param mode: The training mode to be set on modules.
  247. """
  248. self.training = mode
  249. def fn(x) -> None:
  250. if x is not self:
  251. x.train(mode=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 平台