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.

pytree.py 8.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. from collections import OrderedDict, defaultdict
  10. from functools import partial
  11. from inspect import FullArgSpec
  12. from typing import Callable, NamedTuple
  13. import numpy as np
  14. from ..core._imperative_rt import OpDef
  15. from ..core._imperative_rt.common import CompNode
  16. from ..core._imperative_rt.core2 import Tensor as RawTensor
  17. from ..core._wrap import Device
  18. from ..core.tensor.dtype import QuantDtypeMeta
  19. from ..distributed import Group
  20. from ..module import Module
  21. from ..quantization.utils import LSQParams, QParams, QuantMode
  22. from ..tensor import Parameter, Tensor
  23. from .node import ModuleNode, Node, NodeMixin, TensorNode
  24. class ArgsIndex:
  25. def __init__(self, index=0, name="") -> None:
  26. self.index = index
  27. self.name = name
  28. def __repr__(self) -> str:
  29. return self.name
  30. SUPPORTED_TYPE = {}
  31. # if type(object) or obj in SUPPORTED_LEAF_TYPE, the object could be treated as leaf node of pytree
  32. SUPPORTED_LEAF_TYPE = {
  33. RawTensor,
  34. Tensor,
  35. Parameter,
  36. str,
  37. int,
  38. float,
  39. bool,
  40. QuantDtypeMeta,
  41. CompNode,
  42. Device,
  43. type(None),
  44. type(Ellipsis),
  45. QuantMode,
  46. ArgsIndex,
  47. Group,
  48. FullArgSpec,
  49. }
  50. USER_REGISTERED_LEAF_TYPE = []
  51. USER_REGISTERED_CONTAINER_TYPE = []
  52. # if isinstance(object, SUPPORTED_LEAF_CLS) or issubclass(obj, SUPPORTED_LEAF_CLS) is True, the object could be threated as leaf node of pytree
  53. SUPPORTED_LEAF_CLS = [
  54. Module,
  55. Node,
  56. NodeMixin,
  57. np.dtype,
  58. np.ndarray,
  59. np.number,
  60. np.bool_,
  61. OpDef,
  62. ]
  63. NodeType = NamedTuple("NodeType", [("flatten", Callable), ("unflatten", Callable)])
  64. def register_supported_type(type, flatten=None, unflatten=None):
  65. tp_info = (type.__module__, type.__qualname__)
  66. if flatten and unflatten:
  67. USER_REGISTERED_CONTAINER_TYPE.append(tp_info)
  68. else:
  69. USER_REGISTERED_LEAF_TYPE.append(tp_info)
  70. _register_supported_type(type, flatten, unflatten)
  71. def _register_supported_type(type, flatten=None, unflatten=None):
  72. if flatten and unflatten:
  73. SUPPORTED_TYPE[type] = NodeType(flatten, unflatten)
  74. else:
  75. SUPPORTED_LEAF_CLS.append(type)
  76. def _dict_flatten(ordered, inp):
  77. aux_data = []
  78. results = []
  79. dict_items = inp.items() if ordered else sorted(inp.items())
  80. for key, value in dict_items:
  81. results.append(value)
  82. aux_data.append(key)
  83. return results, tuple(aux_data)
  84. def _dict_unflatten(dict_type, inps, aux_data):
  85. return dict_type(zip(aux_data, inps))
  86. def qparams_flatten(inp):
  87. aux_data = []
  88. results = []
  89. for key in inp.__slots__:
  90. aux_data.append(key)
  91. results.append(getattr(inp, key, None))
  92. return results, tuple(aux_data)
  93. def qparams_unflatten(qparam_type, inp, aux_data):
  94. obj = qparam_type.__new__(qparam_type)
  95. for k, v in zip(aux_data, inp):
  96. setattr(obj, k, v)
  97. return obj
  98. _register_supported_type(list, lambda x: (x, None), lambda x, aux_data: list(x))
  99. _register_supported_type(tuple, lambda x: (x, None), lambda x, aux_data: tuple(x))
  100. _register_supported_type(
  101. dict, partial(_dict_flatten, False), partial(_dict_unflatten, dict)
  102. )
  103. _register_supported_type(
  104. defaultdict, partial(_dict_flatten, False), partial(_dict_unflatten, defaultdict)
  105. )
  106. _register_supported_type(
  107. OrderedDict, partial(_dict_flatten, True), partial(_dict_unflatten, OrderedDict)
  108. )
  109. _register_supported_type(
  110. slice,
  111. lambda x: ([x.start, x.stop, x.step], None),
  112. lambda x, aux_data: slice(x[0], x[1], x[2]),
  113. )
  114. _register_supported_type(QParams, qparams_flatten, partial(qparams_unflatten, QParams))
  115. _register_supported_type(
  116. LSQParams, qparams_flatten, partial(qparams_unflatten, LSQParams)
  117. )
  118. def _is_leaf(obj):
  119. obj_type = obj if isinstance(obj, type) else type(obj)
  120. return (
  121. issubclass(obj_type, tuple(SUPPORTED_LEAF_CLS))
  122. or obj_type in SUPPORTED_LEAF_TYPE
  123. )
  124. def _leaf_type(node):
  125. if isinstance(node, (RawTensor, TensorNode)):
  126. return (Tensor, TensorNode, ArgsIndex)
  127. elif isinstance(node, (NodeMixin, Module, ModuleNode)):
  128. return (Module, ModuleNode, NodeMixin, ArgsIndex)
  129. else:
  130. return (type(node), ArgsIndex)
  131. def _is_const_leaf(node):
  132. if isinstance(node, (RawTensor, NodeMixin, Module)):
  133. return False
  134. return True
  135. def tree_flatten(
  136. values,
  137. leaf_type: Callable = _leaf_type,
  138. is_leaf: Callable = _is_leaf,
  139. is_const_leaf: Callable = _is_const_leaf,
  140. ):
  141. r"""Flattens a pytree into a list of values and a :class:`TreeDef` that can be used
  142. to reconstruct the pytree.
  143. """
  144. if type(values) not in SUPPORTED_TYPE:
  145. assert is_leaf(values), values
  146. node = LeafDef(leaf_type(values))
  147. if is_const_leaf(values):
  148. node.const_val = values
  149. return [values,], node
  150. rst = []
  151. children_defs = []
  152. children_values, aux_data = SUPPORTED_TYPE[type(values)].flatten(values)
  153. for v in children_values:
  154. v_list, treedef = tree_flatten(v, leaf_type, is_leaf, is_const_leaf)
  155. rst.extend(v_list)
  156. children_defs.append(treedef)
  157. return rst, TreeDef(type(values), aux_data, children_defs)
  158. class TreeDef:
  159. r"""A ``TreeDef`` represents the structure of a pytree.
  160. Args:
  161. type: the type of root Node of the pytree.
  162. aux_data: some const data that is useful in unflattening the pytree.
  163. children_defs: ``TreeDef`` for each child of the root Node.
  164. num_leaves: the number of leaves.
  165. """
  166. def __init__(self, type, aux_data, children_defs):
  167. self.type = type
  168. self.aux_data = aux_data
  169. self.children_defs = children_defs
  170. self.num_leaves = sum(ch.num_leaves for ch in children_defs)
  171. def unflatten(self, leaves):
  172. r"""Given a list of values and a ``TreeDef``, builds a pytree.
  173. This is the inverse operation of ``tree_flatten``.
  174. """
  175. assert len(leaves) == self.num_leaves
  176. start = 0
  177. children = []
  178. for ch in self.children_defs:
  179. children.append(ch.unflatten(leaves[start : start + ch.num_leaves]))
  180. start += ch.num_leaves
  181. return SUPPORTED_TYPE[self.type].unflatten(children, self.aux_data)
  182. def __hash__(self):
  183. return hash(
  184. tuple(
  185. [
  186. self.type,
  187. self.aux_data,
  188. self.num_leaves,
  189. tuple([hash(x) for x in self.children_defs]),
  190. ]
  191. )
  192. )
  193. def __ne__(self, other) -> bool:
  194. return not self.__eq__(other)
  195. def __eq__(self, other) -> bool:
  196. return (
  197. self.type == other.type
  198. and self.aux_data == other.aux_data
  199. and self.num_leaves == other.num_leaves
  200. and self.children_defs == other.children_defs
  201. )
  202. def __repr__(self):
  203. return "{}[{}]".format(self.type.__name__, self.children_defs)
  204. class LeafDef(TreeDef):
  205. def __init__(self, type):
  206. if not isinstance(type, collections.abc.Sequence):
  207. type = (type,)
  208. super().__init__(type, None, [])
  209. self.num_leaves = 1
  210. self.const_val = None
  211. def unflatten(self, leaves):
  212. assert len(leaves) == 1
  213. assert isinstance(leaves[0], self.type), self.type
  214. return leaves[0]
  215. def __ne__(self, other) -> bool:
  216. return not self.__eq__(other)
  217. def __eq__(self, other):
  218. if isinstance(self.const_val, np.ndarray):
  219. return self.type == other.type and (self.const_val == other.const_val).all()
  220. return self.type == other.type and self.const_val == other.const_val
  221. def __hash__(self):
  222. if isinstance(self.const_val, np.ndarray):
  223. return hash(tuple([self.type, str(self.const_val)]))
  224. return hash(tuple([self.type, self.const_val]))
  225. def __repr__(self):
  226. return "Leaf({}[{}])".format(
  227. ", ".join(t.__name__ for t in self.type), self.const_val
  228. )

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