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

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

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