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.

utils.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 collections
  9. import copy
  10. import inspect
  11. from collections.abc import MutableMapping, MutableSequence
  12. from inspect import FullArgSpec
  13. from typing import Callable, Dict, Iterable, List, Optional, Sequence, Type, Union
  14. from .. import get_logger
  15. from ..module import Module
  16. logger = get_logger(__name__)
  17. def replace_container_with_module_container(container):
  18. has_module = False
  19. module_container = None
  20. if isinstance(container, Dict):
  21. m_dic = copy.copy(container)
  22. for key, value in container.items():
  23. if isinstance(value, Module):
  24. has_module = True
  25. elif isinstance(value, (List, Dict)):
  26. (
  27. _has_module,
  28. _module_container,
  29. ) = replace_container_with_module_container(value)
  30. m_dic[key] = _module_container
  31. if _has_module:
  32. has_module = True
  33. if not all(isinstance(v, Module) for v in m_dic.values()):
  34. return has_module, None
  35. else:
  36. return has_module, _ModuleDict(m_dic)
  37. elif isinstance(container, List):
  38. m_list = copy.copy(container)
  39. for ind, value in enumerate(container):
  40. if isinstance(value, Module):
  41. has_module = True
  42. elif isinstance(value, (List, Dict)):
  43. (
  44. _has_module,
  45. _module_container,
  46. ) = replace_container_with_module_container(value)
  47. m_list[ind] = _module_container
  48. if _has_module:
  49. has_module = True
  50. if not all(isinstance(v, Module) for v in m_list):
  51. return has_module, None
  52. else:
  53. return has_module, _ModuleList(m_list)
  54. return has_module, module_container
  55. def _convert_kwargs_to_args(
  56. argspecs: Union[Callable, FullArgSpec], args, kwargs, is_bounded=False
  57. ):
  58. # is_bounded = True when func is a method and provided args don't include 'self'
  59. arg_specs = (
  60. inspect.getfullargspec(argspecs) if isinstance(argspecs, Callable) else argspecs
  61. )
  62. assert isinstance(arg_specs, FullArgSpec)
  63. arg_specs_args = arg_specs.args
  64. if is_bounded:
  65. arg_specs_args = arg_specs.args[1:]
  66. new_args = []
  67. new_kwargs = {}
  68. new_args.extend(args)
  69. if set(arg_specs_args[0 : len(new_args)]) & set(kwargs.keys()):
  70. repeated_arg_name = set(arg_specs_args[0 : len(new_args)]) & set(kwargs.keys())
  71. raise TypeError(
  72. "{} got multiple values for argument {}".format(
  73. func.__qualname__, ", ".join(repeated_arg_name)
  74. )
  75. )
  76. if len(new_args) < len(arg_specs.args):
  77. for ind in range(len(new_args), len(arg_specs_args)):
  78. arg_name = arg_specs_args[ind]
  79. if arg_name in kwargs:
  80. new_args.append(kwargs[arg_name])
  81. else:
  82. index = ind - len(arg_specs_args) + len(arg_specs.defaults)
  83. assert index < len(arg_specs.defaults) and index >= 0
  84. new_args.append(arg_specs.defaults[index])
  85. for kwarg_name in arg_specs.kwonlyargs:
  86. if kwarg_name in kwargs:
  87. new_kwargs[kwarg_name] = kwargs[kwarg_name]
  88. else:
  89. assert kwarg_name in arg_specs.kwonlydefaults
  90. new_kwargs[kwarg_name] = arg_specs.kwonlydefaults[kwarg_name]
  91. for k, v in kwargs.items():
  92. if k not in arg_specs.args and k not in arg_specs.kwonlyargs:
  93. if arg_specs.varkw is None:
  94. raise TypeError(
  95. "{} got an unexpected keyword argument {}".format(
  96. func.__qualname__, k
  97. )
  98. )
  99. new_kwargs[k] = v
  100. return tuple(new_args), new_kwargs
  101. def _check_obj_attr(obj):
  102. # check if all the attributes of a obj is serializable
  103. from .pytree import tree_flatten
  104. from .pytree import SUPPORTED_LEAF_CLS, SUPPORTED_LEAF_TYPE, TreeDef
  105. from .expr import Expr
  106. from .traced_module import TracedModule, InternalGraph, NameSpace
  107. def _check_leaf_type(leaf):
  108. leaf_type = leaf if isinstance(leaf, type) else type(leaf)
  109. traced_module_types = [Expr, TreeDef, TracedModule, InternalGraph, NameSpace]
  110. return (
  111. issubclass(leaf_type, tuple(SUPPORTED_LEAF_CLS + traced_module_types))
  112. or leaf_type in SUPPORTED_LEAF_TYPE
  113. )
  114. for _, v in obj.items():
  115. leafs, _ = tree_flatten(v, is_leaf=lambda _: True)
  116. for leaf in leafs:
  117. assert _check_leaf_type(
  118. leaf
  119. ), "Type {} is not supported by traced module".format(
  120. leaf if isinstance(leaf, type) else type(leaf)
  121. )
  122. def _check_builtin_module_attr(mod):
  123. from .pytree import _is_leaf as _check_leaf_type
  124. from .pytree import tree_flatten
  125. # check if all the attributes of a builtin module is serializable
  126. is_non_serializable_module = lambda m: isinstance(
  127. m, Module
  128. ) and not _check_builtin_module_attr(m)
  129. for k, v in mod.__dict__.items():
  130. if k == "_m_dump_modulestate":
  131. continue
  132. if is_non_serializable_module(v):
  133. return False
  134. elif not isinstance(v, Module):
  135. leafs, _ = tree_flatten(v, is_leaf=lambda _: True)
  136. for leaf in leafs:
  137. if not _check_leaf_type(leaf) or is_non_serializable_module(leaf):
  138. logger.warn(
  139. "Type {} is not supported by traced module".format(
  140. leaf if isinstance(leaf, type) else type(leaf)
  141. )
  142. )
  143. return False
  144. return True
  145. class _ModuleList(Module, MutableSequence):
  146. r"""A List-like container.
  147. Using a ``ModuleList``, one can visit, add, delete and modify submodules
  148. just like an ordinary python list.
  149. """
  150. def __init__(self, modules: Optional[Iterable[Module]] = None):
  151. super().__init__()
  152. self._size = 0
  153. if modules is None:
  154. return
  155. for mod in modules:
  156. self.append(mod)
  157. @classmethod
  158. def _ikey(cls, idx):
  159. return "{}".format(idx)
  160. def _check_idx(self, idx):
  161. L = len(self)
  162. if idx < 0:
  163. idx = L + idx
  164. if idx < 0 or idx >= L:
  165. raise IndexError("list index out of range")
  166. return idx
  167. def __getitem__(self, idx: int):
  168. if isinstance(idx, slice):
  169. idx = range(self._size)[idx]
  170. if not isinstance(idx, Sequence):
  171. idx = [
  172. idx,
  173. ]
  174. rst = []
  175. for i in idx:
  176. i = self._check_idx(i)
  177. key = self._ikey(i)
  178. try:
  179. rst.append(getattr(self, key))
  180. except AttributeError:
  181. raise IndexError("list index out of range")
  182. return rst if len(rst) > 1 else rst[0]
  183. def __setattr__(self, key, value):
  184. # clear mod name to avoid warning in Module's setattr
  185. if isinstance(value, Module):
  186. value._name = None
  187. super().__setattr__(key, value)
  188. def __setitem__(self, idx: int, mod: Module):
  189. if not isinstance(mod, Module):
  190. raise ValueError("invalid sub-module")
  191. idx = self._check_idx(idx)
  192. setattr(self, self._ikey(idx), mod)
  193. def __delitem__(self, idx):
  194. idx = self._check_idx(idx)
  195. L = len(self)
  196. for orig_idx in range(idx + 1, L):
  197. new_idx = orig_idx - 1
  198. self[new_idx] = self[orig_idx]
  199. delattr(self, self._ikey(L - 1))
  200. self._size -= 1
  201. def __len__(self):
  202. return self._size
  203. def insert(self, idx, mod: Module):
  204. assert isinstance(mod, Module)
  205. L = len(self)
  206. if idx < 0:
  207. idx = L - idx
  208. # clip idx to (0, L)
  209. if idx > L:
  210. idx = L
  211. elif idx < 0:
  212. idx = 0
  213. for new_idx in range(L, idx, -1):
  214. orig_idx = new_idx - 1
  215. key = self._ikey(new_idx)
  216. setattr(self, key, self[orig_idx])
  217. key = self._ikey(idx)
  218. setattr(self, key, mod)
  219. self._size += 1
  220. def forward(self):
  221. raise RuntimeError("ModuleList is not callable")
  222. class _ModuleDict(Module, MutableMapping):
  223. r"""A Dict-like container.
  224. Using a ``ModuleDict``, one can visit, add, delete and modify submodules
  225. just like an ordinary python dict.
  226. """
  227. def __init__(self, modules: Optional[Dict[str, Module]] = None):
  228. super().__init__()
  229. self._module_keys = []
  230. if modules is not None:
  231. self.update(modules)
  232. def __delitem__(self, key):
  233. delattr(self, key)
  234. assert key in self._module_keys
  235. self._module_keys.remove(key)
  236. def __getitem__(self, key):
  237. return getattr(self, key)
  238. def __setattr__(self, key, value):
  239. # clear mod name to avoid warning in Module's setattr
  240. if isinstance(value, Module):
  241. value._name = None
  242. super().__setattr__(key, value)
  243. def __setitem__(self, key, value):
  244. if not isinstance(value, Module):
  245. raise ValueError("invalid sub-module")
  246. setattr(self, key, value)
  247. if key not in self._module_keys:
  248. self._module_keys.append(key)
  249. def __iter__(self):
  250. return iter(self.keys())
  251. def __len__(self):
  252. return len(self._module_keys)
  253. def items(self):
  254. return [(key, getattr(self, key)) for key in self._module_keys]
  255. def values(self):
  256. return [getattr(self, key) for key in self._module_keys]
  257. def keys(self):
  258. return self._module_keys
  259. def forward(self):
  260. raise RuntimeError("ModuleList is not callable")

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