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

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

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