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

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

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