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

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

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