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

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

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