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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. import warnings
  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.tensor.utils import make_shape_tuple
  14. from ..logger import get_logger
  15. from ..tensor import Parameter, Tensor
  16. from ..utils.deprecation import deprecated
  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, Tensor) and not isinstance(obj, Parameter)
  43. def _is_module(obj):
  44. return isinstance(obj, Module)
  45. class Module(metaclass=ABCMeta):
  46. """
  47. Base Module class.
  48. """
  49. def __init__(self):
  50. # runtime attributes
  51. self.training = True
  52. self.quantize_disabled = False
  53. # hooks
  54. self._forward_pre_hooks = OrderedDict()
  55. self._forward_hooks = OrderedDict()
  56. self._modules = []
  57. @abstractmethod
  58. def forward(self, inputs):
  59. pass
  60. def register_forward_pre_hook(self, hook: Callable) -> HookHandler:
  61. """
  62. Registers a hook to handle forward inputs. `hook` should be a function.
  63. :param hook: a function that receive `module` and `inputs`, then return
  64. a modified `inputs` or `None`.
  65. :return: a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  66. """
  67. return HookHandler(self._forward_pre_hooks, hook)
  68. def register_forward_hook(self, hook: Callable) -> HookHandler:
  69. """
  70. Registers a hook to handle forward results. `hook` should be a function that
  71. receive `module`, `inputs` and `outputs`, then return a modified `outputs` or `None`.
  72. This method return a handler with :meth:`~.HookHandler.remove` interface to delete the hook.
  73. """
  74. return HookHandler(self._forward_hooks, hook)
  75. def __call__(self, *inputs, **kwargs):
  76. for hook in self._forward_pre_hooks.values():
  77. modified_inputs = hook(self, inputs)
  78. if modified_inputs is not None:
  79. if not isinstance(modified_inputs, tuple):
  80. modified_inputs = (modified_inputs,)
  81. inputs = modified_inputs
  82. outputs = self.forward(*inputs, **kwargs)
  83. for hook in self._forward_hooks.values():
  84. modified_outputs = hook(self, inputs, outputs)
  85. if modified_outputs is not None:
  86. outputs = modified_outputs
  87. return outputs
  88. def _flatten(
  89. self,
  90. *,
  91. recursive: bool = True,
  92. with_key: bool = False,
  93. with_parent: bool = False,
  94. prefix: Optional[str] = None,
  95. predicate: Callable[[Any], bool] = lambda _: True,
  96. seen: Optional[Set[int]] = None
  97. ) -> Union[Iterable[Any], Iterable[Tuple[str, Any]]]:
  98. """
  99. Scans the module object and returns an iterable for the :class:`~.Tensor`
  100. and :class:`~.Module` attributes that agree with the ``predicate``. For multiple
  101. calls of this function with same arguments, the order of objects within the
  102. returned iterable is guaranteed to be identical, as long as all the involved
  103. module objects' ``__dict__`` does not change thoughout those calls.
  104. :param recursive: whether to recursively scan all the submodules.
  105. :param with_key: whether to yield keys along with yielded objects.
  106. :param with_parent: whether to yield ``self`` along with yielded objects.
  107. :param prefix: prefix appended to the yielded keys.
  108. :param predicate: the predication function applied to scanned objects.
  109. :param seen: a dict that records whether a module has been traversed yet.
  110. """
  111. if seen is None:
  112. seen = set([id(self)])
  113. module_dict = vars(self)
  114. _prefix = "" if prefix is None else prefix + "."
  115. for key in sorted(module_dict):
  116. for expanded_key, leaf in _expand_structure(key, module_dict[key]):
  117. leaf_id = id(leaf)
  118. if leaf_id in seen:
  119. continue
  120. seen.add(leaf_id)
  121. if predicate(leaf):
  122. if with_key and with_parent:
  123. yield _prefix + expanded_key, leaf, self
  124. elif with_key:
  125. yield _prefix + expanded_key, leaf
  126. elif with_parent:
  127. yield leaf, self
  128. else:
  129. yield leaf
  130. if recursive and isinstance(leaf, Module):
  131. yield from leaf._flatten(
  132. recursive=recursive,
  133. with_key=with_key,
  134. with_parent=with_parent,
  135. prefix=_prefix + expanded_key if with_key else None,
  136. predicate=predicate,
  137. seen=seen,
  138. )
  139. def parameters(self, recursive: bool = True, **kwargs) -> Iterable[Parameter]:
  140. r"""
  141. Returns an iterable for the :class:`~.Parameter` of the module.
  142. :param recursive: If ``True``, returns all :class:`~.Parameter` within this
  143. module, else only returns :class:`~.Parameter` that are direct attributes
  144. of this module.
  145. """
  146. if "requires_grad" in kwargs:
  147. del kwargs["requires_grad"]
  148. warnings.warn(
  149. "Tensor currently has no requires_grad attribute "
  150. "so requires_grad argument is ignored here",
  151. DeprecationWarning,
  152. )
  153. def predicate(obj) -> bool:
  154. return _is_parameter(obj)
  155. yield from self._flatten(
  156. with_key=False, predicate=predicate, recursive=recursive, **kwargs
  157. )
  158. def named_parameters(
  159. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  160. ) -> Iterable[Tuple[str, Parameter]]:
  161. """
  162. Returns an iterable for key :class:`~.Parameter` pairs of the module, where
  163. ``key`` is the dotted path from this module to the :class:`~.Parameter`.
  164. :param prefix: prefix prepended to the keys.
  165. :param recursive: if ``True``, returns all :class:`~.Parameter` within this
  166. module, else only returns :class:`~.Parameter` that are direct attributes
  167. of this module.
  168. """
  169. if "requires_grad" in kwargs:
  170. del kwargs["requires_grad"]
  171. warnings.warn(
  172. "Tensor currently has no requires_grad attribute "
  173. "so requires_grad argument is ignored here",
  174. DeprecationWarning,
  175. )
  176. def predicate(obj) -> bool:
  177. return _is_parameter(obj)
  178. yield from self._flatten(
  179. with_key=True,
  180. prefix=prefix,
  181. predicate=predicate,
  182. recursive=recursive,
  183. **kwargs,
  184. )
  185. def buffers(self, recursive: bool = True, **kwargs) -> Iterable[Tensor]:
  186. """
  187. Returns an iterable for the buffers of the module.
  188. Buffer is defined to be :class:`~.Tensor` excluding :class:`~.Parameter`.
  189. :param recursive: if ``True``, returns all buffers within this
  190. module, else only returns buffers that are direct attributes
  191. of this module.
  192. """
  193. yield from self._flatten(
  194. with_key=False, predicate=_is_buffer, recursive=recursive, **kwargs
  195. )
  196. def named_buffers(
  197. self, prefix: Optional[str] = None, recursive: bool = True, **kwargs
  198. ) -> Iterable[Tuple[str, Tensor]]:
  199. """
  200. Returns an iterable for key buffer pairs of the module, where
  201. ``key`` is the dotted path from this module to the buffer.
  202. Buffer is defined to be :class:`~.Tensor` excluding :class:`~.Parameter`.
  203. :param prefix: prefix prepended to the keys.
  204. :param recursive: if ``True``, returns all buffers within this
  205. module, else only returns buffers that are direct attributes
  206. of this module.
  207. """
  208. yield from self._flatten(
  209. with_key=True,
  210. prefix=prefix,
  211. predicate=_is_buffer,
  212. recursive=recursive,
  213. **kwargs,
  214. )
  215. def children(self, **kwargs) -> "Iterable[Module]":
  216. """
  217. Returns an iterable for all the submodules that are direct attributes of this
  218. module.
  219. """
  220. yield from self._flatten(
  221. with_key=False, predicate=_is_module, recursive=False, **kwargs
  222. )
  223. def named_children(self, **kwargs) -> "Iterable[Tuple[str, Module]]":
  224. """
  225. Returns an iterable of key-submodule pairs for all the submodules that are
  226. direct attributes of this module, where 'key' is the attribute name of
  227. submodules.
  228. """
  229. yield from self._flatten(
  230. with_key=True, predicate=_is_module, recursive=False, **kwargs
  231. )
  232. def modules(self, **kwargs) -> "Iterable[Module]":
  233. """
  234. Returns an iterable for all the modules within this module, including itself.
  235. """
  236. if "with_parent" in kwargs and kwargs["with_parent"]:
  237. yield self, None
  238. else:
  239. yield self
  240. yield from self._flatten(with_key=False, predicate=_is_module, **kwargs)
  241. def named_modules(
  242. self, prefix: Optional[str] = None, **kwargs
  243. ) -> "Iterable[Tuple[str, Module]]":
  244. """
  245. Returns an iterable of key-module pairs for all the modules within this
  246. module, including itself, where 'key' is the dotted path from this module to the
  247. submodules.
  248. :param prefix: prefix prepended to the path.
  249. """
  250. if "with_parent" in kwargs and kwargs["with_parent"]:
  251. yield ("" if prefix is None else prefix), self, None
  252. else:
  253. yield ("" if prefix is None else prefix), self
  254. yield from self._flatten(
  255. with_key=True, prefix=prefix, predicate=_is_module, **kwargs
  256. )
  257. def apply(self, fn: "Callable[[Module], Any]") -> None:
  258. """
  259. Applies function ``fn`` to all the modules within this module, including
  260. itself.
  261. :param fn: the function to be applied on modules.
  262. """
  263. for it in self.modules():
  264. fn(it)
  265. @deprecated(version="1.0")
  266. def zero_grad(self) -> None:
  267. """
  268. Sets all parameters' grads to zero
  269. """
  270. for param in self.parameters():
  271. if param.grad is not None:
  272. param.grad.reset_zero()
  273. def train(self, mode: bool = True, recursive: bool = True) -> None:
  274. """
  275. Sets training mode of all the modules within this module (including itself) to
  276. ``mode``. This effectively sets the ``training`` attributes of those modules
  277. to ``mode``, but only has effect on certain modules (e.g.
  278. :class:`~.BatchNorm2d`, :class:`~.Dropout`, :class:`~.Observer`)
  279. :param mode: the training mode to be set on modules.
  280. :param recursive: whether to recursively call submodules' ``train()``.
  281. """
  282. if not recursive:
  283. self.training = mode
  284. return
  285. def fn(module: Module) -> None:
  286. module.train(mode, recursive=False)
  287. self.apply(fn)
  288. def eval(self) -> None:
  289. """
  290. Sets training mode of all the modules within this module (including itself) to
  291. ``False``. See :meth:`~.Module.train` for details.
  292. """
  293. self.train(False)
  294. def disable_quantize(self, value=True):
  295. r"""
  296. Sets ``module``'s ``quantize_disabled`` attribute and return ``module``.
  297. Could be used as a decorator.
  298. """
  299. def fn(module: Module) -> None:
  300. module.quantize_disabled = value
  301. self.apply(fn)
  302. @deprecated(version="1.0")
  303. def replace_param(
  304. self, params: dict, start_pos: int, seen: Optional[Set[int]] = None
  305. ):
  306. """
  307. Replaces module's parameters with ``params``, used by :class:`~.ParamPack` to
  308. speedup multimachine training.
  309. """
  310. offset = 0
  311. if seen is None:
  312. seen = set([id(self)])
  313. module_dict = vars(self)
  314. for key in sorted(module_dict):
  315. hash_id = id(module_dict[key])
  316. if hash_id in seen:
  317. continue
  318. seen.add(hash_id)
  319. if isinstance(module_dict[key], Parameter):
  320. if start_pos + offset in params:
  321. assert make_shape_tuple(module_dict[key].shape) == make_shape_tuple(
  322. params[start_pos + offset].shape
  323. )
  324. module_dict[key] = params[start_pos + offset]
  325. offset += 1
  326. if isinstance(module_dict[key], Module):
  327. offset += module_dict[key].replace_param(
  328. params, start_pos + offset, seen
  329. )
  330. return offset
  331. def state_dict(self, rst=None, prefix="", keep_var=False):
  332. r"""
  333. Returns a dictionary containing whole states of the module.
  334. """
  335. def is_state(obj):
  336. return _is_parameter(obj) or _is_buffer(obj)
  337. if rst is None:
  338. rst = OrderedDict()
  339. for k, v in self._flatten(recursive=False, with_key=True, predicate=is_state):
  340. assert prefix + k not in rst, "duplicated state: {}".format(k)
  341. if keep_var:
  342. rst[prefix + k] = v
  343. else:
  344. rst[prefix + k] = v.numpy()
  345. for k, submodule in self._flatten(
  346. recursive=False,
  347. with_key=True,
  348. predicate=lambda obj: isinstance(obj, Module),
  349. ):
  350. submodule.state_dict(rst, prefix + k + ".", keep_var)
  351. return rst
  352. def load_state_dict(
  353. self,
  354. state_dict: Union[dict, Callable[[str, Tensor], Optional[np.ndarray]]],
  355. strict=True,
  356. ):
  357. r"""
  358. Loads a given dictionary created by :func:`state_dict` into this module.
  359. If ``strict`` is ``True``, the keys of :func:`state_dict` must exactly match the keys
  360. returned by :func:`state_dict`.
  361. Users can also pass a closure: ``Function[key: str, var: Tensor] -> Optional[np.ndarray]``
  362. as a `state_dict`, in order to handle complex situations. For example, load everything
  363. except for the final linear classifier:
  364. .. code-block::
  365. state_dict = {...} # Dict[str, np.ndarray]
  366. model.load_state_dict({
  367. k: None if k.startswith('fc') else v
  368. for k, v in state_dict.items()
  369. }, strict=False)
  370. Here returning ``None`` means skipping parameter ``k``.
  371. To prevent shape mismatch (e.g. load PyTorch weights), we can reshape before loading:
  372. .. code-block::
  373. state_dict = {...}
  374. def reshape_accordingly(k, v):
  375. return state_dict[k].reshape(v.shape)
  376. model.load_state_dict(reshape_accordingly)
  377. We can also perform inplace re-initialization or pruning:
  378. .. code-block::
  379. def reinit_and_pruning(k, v):
  380. if 'bias' in k:
  381. M.init.zero_(v)
  382. if 'conv' in k:
  383. return v.numpy() * (np.abs(v.numpy()) > 1e-3).astype("float32)
  384. model.load_state_dict(reinit_and_pruning, strict=False)
  385. """
  386. unused = []
  387. if isinstance(state_dict, dict):
  388. unused = state_dict.keys()
  389. def closure(k, _): # var unused
  390. return state_dict[k] if k in state_dict else None
  391. elif callable(state_dict):
  392. closure = state_dict
  393. else:
  394. raise ValueError(
  395. "`state_dict` must load a dict or callable, got {}".format(
  396. type(state_dict)
  397. )
  398. )
  399. loaded, skipped = self._load_state_dict_with_closure(closure)
  400. unused = set(unused) - loaded
  401. if len(unused) != 0:
  402. if strict:
  403. raise KeyError(
  404. "Unused params violate `strict=True`, unused={}".format(unused)
  405. )
  406. else:
  407. logger.warning(
  408. "Unused params in `strict=False` mode, unused={}".format(unused)
  409. )
  410. if len(skipped) != 0:
  411. if strict:
  412. raise KeyError(
  413. "Missing params violate `strict=True`, missing={}".format(skipped)
  414. )
  415. else:
  416. logger.warning(
  417. "Missing params in `strict=False` mode, missing={}".format(skipped)
  418. )
  419. def _load_state_dict_with_closure(self, closure):
  420. """
  421. Advance state_dict load through callable ``closure`` whose signature is
  422. ``closure(key: str, var: Tensor) -> Union[np.ndarry, None]``
  423. """
  424. assert callable(closure), "closure must be a function"
  425. loaded = []
  426. skipped = []
  427. local_state_dict = self.state_dict(keep_var=True)
  428. for k, var in local_state_dict.items():
  429. to_be_load = closure(k, var)
  430. if to_be_load is None:
  431. skipped.append(k)
  432. continue
  433. assert isinstance(
  434. to_be_load, np.ndarray
  435. ), "closure should return a `np.ndarray`, now `{}` get {}".format(
  436. k, to_be_load
  437. )
  438. assert make_shape_tuple(var.shape) == make_shape_tuple(
  439. to_be_load.shape
  440. ), "param `{}` shape mismatch, should be {}, get {}".format(
  441. k, var.shape, to_be_load.shape
  442. )
  443. var._reset(type(var)(to_be_load, dtype=to_be_load.dtype, device=var.device))
  444. loaded.append(k)
  445. return set(loaded), set(skipped)
  446. def __setattr__(self, name: str, value):
  447. if _is_module(value):
  448. modules = self.__dict__.get("_modules")
  449. if modules is None:
  450. raise AttributeError(
  451. "cannot assign module before Module.__init__() call"
  452. )
  453. if name not in self.__dict__:
  454. modules.append(name)
  455. super().__setattr__(name, value)
  456. def __delattr__(self, name: str):
  457. if name in self.__dict__ and _is_module(self.__dict__[name]):
  458. modules = self.__dict__.get("_modules")
  459. modules.remove(name)
  460. super().__delattr__(name)
  461. def _module_info_string(self) -> str:
  462. r"""
  463. Set the extra representation of the module.
  464. """
  465. return ""
  466. def __repr__(self):
  467. def add_indent(repr_str, num_spaces):
  468. s = repr_str.split("\n")
  469. # don't do anything for single-line stuff
  470. if len(s) == 1:
  471. return repr_str
  472. first = s.pop(0)
  473. s = [(num_spaces * " ") + line for line in s]
  474. s = "\n".join(s)
  475. s = first + "\n" + s
  476. return s
  477. extra_lines = []
  478. extra_repr = self._module_info_string()
  479. if extra_repr:
  480. extra_lines = extra_repr.split("\n")
  481. child_lines = [
  482. "(" + name + "): " + add_indent(repr(self.__dict__[name]), 2)
  483. for name in self._modules
  484. ]
  485. lines = extra_lines + child_lines
  486. main_str = self.__class__.__name__ + "("
  487. if lines:
  488. # simple one-liner info, which most builtin Modules will use
  489. if len(extra_lines) == 1 and not child_lines:
  490. main_str += extra_lines[0]
  491. else:
  492. main_str += "\n " + "\n ".join(lines) + "\n"
  493. main_str += ")"
  494. return main_str

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