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

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

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