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

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

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