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

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