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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import collections
  10. from collections import OrderedDict
  11. from typing import Callable, NamedTuple
  12. import numpy as np
  13. from ...core._imperative_rt.common import CompNode
  14. from ...core._imperative_rt.core2 import Tensor as RawTensor
  15. from ...core._wrap import Device
  16. from ...core.tensor.dtype import QuantDtypeMeta
  17. from ...module import Module
  18. from ...quantization.utils import LSQParams, QParams, QuantMode
  19. from ...tensor import Parameter, Tensor
  20. from .node import ModuleNode, Node, NodeMixin, TensorNode
  21. SUPPORTED_TYPE = {}
  22. # if type(object) or obj in SUPPORTED_LEAF_TYPE, the object could be treated as leaf node of pytree
  23. SUPPORTED_LEAF_TYPE = {
  24. RawTensor,
  25. Tensor,
  26. Parameter,
  27. str,
  28. int,
  29. float,
  30. bool,
  31. QuantDtypeMeta,
  32. CompNode,
  33. Device,
  34. type(None),
  35. type(Ellipsis),
  36. QuantMode,
  37. }
  38. # if isinstance(object, SUPPORTED_LEAF_CLS) or issubclass(obj, SUPPORTED_LEAF_CLS) is True, the object could be threated as leaf node of pytree
  39. SUPPORTED_LEAF_CLS = [Module, Node, NodeMixin, np.dtype, np.ndarray, np.number]
  40. NodeType = NamedTuple("NodeType", [("flatten", Callable), ("unflatten", Callable)])
  41. def register_supported_type(type, flatten=None, unflatten=None):
  42. if flatten and unflatten:
  43. SUPPORTED_TYPE[type] = NodeType(flatten, unflatten)
  44. else:
  45. SUPPORTED_LEAF_CLS.append(type)
  46. def _dict_flatten(inp):
  47. aux_data = []
  48. results = []
  49. for key, value in sorted(inp.items()):
  50. results.append(value)
  51. aux_data.append(key)
  52. return results, tuple(aux_data)
  53. def _dict_unflatten(inps, aux_data):
  54. return dict(zip(aux_data, inps))
  55. def _ordereddict_flatten(inp):
  56. aux_data = []
  57. results = []
  58. for key, value in inp.items():
  59. results.append(value)
  60. aux_data.append(key)
  61. return results, tuple(aux_data)
  62. def _ordereddict_unflatten(inps, aux_data):
  63. return OrderedDict(zip(aux_data, inps))
  64. def qparams_flatten(inp):
  65. aux_data = []
  66. results = []
  67. for key in inp.__slots__:
  68. aux_data.append(key)
  69. results.append(getattr(inp, key, None))
  70. return results, tuple(aux_data)
  71. def qparams_unflatten(inp, aux_data):
  72. obj = QParams.__new__(QParams)
  73. for k, v in zip(aux_data, inp):
  74. setattr(obj, k, v)
  75. return obj
  76. register_supported_type(list, lambda x: (x, None), lambda x, aux_data: list(x))
  77. register_supported_type(tuple, lambda x: (x, None), lambda x, aux_data: tuple(x))
  78. register_supported_type(dict, _dict_flatten, _dict_unflatten)
  79. register_supported_type(
  80. collections.OrderedDict, _ordereddict_flatten, _ordereddict_unflatten
  81. )
  82. register_supported_type(
  83. slice,
  84. lambda x: ([x.start, x.stop, x.step], None),
  85. lambda x, aux_data: slice(x[0], x[1], x[2]),
  86. )
  87. register_supported_type(QParams, qparams_flatten, qparams_unflatten)
  88. def _is_leaf(obj):
  89. if isinstance(obj, type):
  90. return issubclass(obj, tuple(SUPPORTED_LEAF_CLS)) or obj in SUPPORTED_LEAF_TYPE
  91. return (
  92. isinstance(obj, tuple(SUPPORTED_LEAF_CLS)) or type(obj) in SUPPORTED_LEAF_TYPE
  93. )
  94. def _leaf_type(node):
  95. if isinstance(node, (RawTensor, TensorNode)):
  96. return (Tensor, TensorNode)
  97. elif isinstance(node, (NodeMixin, Module)):
  98. return (Module, ModuleNode, NodeMixin)
  99. else:
  100. return type(node)
  101. def _is_const_leaf(node):
  102. if isinstance(node, (RawTensor, NodeMixin, Module)):
  103. return False
  104. return True
  105. def tree_flatten(
  106. values,
  107. leaf_type: Callable = _leaf_type,
  108. is_leaf: Callable = _is_leaf,
  109. is_const_leaf: Callable = _is_const_leaf,
  110. ):
  111. if type(values) not in SUPPORTED_TYPE:
  112. assert is_leaf(values), values
  113. node = LeafDef(leaf_type(values))
  114. if is_const_leaf(values):
  115. if isinstance(values, np.ndarray):
  116. node.const_val = str(values)
  117. else:
  118. node.const_val = values
  119. return [values,], node
  120. rst = []
  121. children_defs = []
  122. children_values, aux_data = SUPPORTED_TYPE[type(values)].flatten(values)
  123. for v in children_values:
  124. v_list, treedef = tree_flatten(v, leaf_type, is_leaf, is_const_leaf)
  125. rst.extend(v_list)
  126. children_defs.append(treedef)
  127. return rst, TreeDef(type(values), aux_data, children_defs)
  128. class TreeDef:
  129. def __init__(self, type, aux_data, children_defs):
  130. self.type = type
  131. self.aux_data = aux_data
  132. self.children_defs = children_defs
  133. self.num_leaves = sum(ch.num_leaves for ch in children_defs)
  134. def unflatten(self, leaves):
  135. assert len(leaves) == self.num_leaves
  136. start = 0
  137. children = []
  138. for ch in self.children_defs:
  139. children.append(ch.unflatten(leaves[start : start + ch.num_leaves]))
  140. start += ch.num_leaves
  141. return SUPPORTED_TYPE[self.type].unflatten(children, self.aux_data)
  142. def __hash__(self):
  143. return hash(
  144. tuple(
  145. [
  146. self.type,
  147. self.aux_data,
  148. self.num_leaves,
  149. tuple([hash(x) for x in self.children_defs]),
  150. ]
  151. )
  152. )
  153. def __lt__(self, other):
  154. return self.__hash__() < other.__hash__()
  155. def __gt__(self, other):
  156. return self.__hash__() > other.__hash__()
  157. def __eq__(self, other):
  158. return (
  159. self.type == other.type
  160. and self.aux_data == other.aux_data
  161. and self.num_leaves == other.num_leaves
  162. and self.children_defs == other.children_defs
  163. )
  164. def __repr__(self):
  165. return "{}[{}]".format(self.type.__name__, self.children_defs)
  166. class LeafDef(TreeDef):
  167. def __init__(self, type):
  168. if not isinstance(type, collections.abc.Sequence):
  169. type = (type,)
  170. super().__init__(type, None, [])
  171. self.num_leaves = 1
  172. self.const_val = None
  173. def unflatten(self, leaves):
  174. assert len(leaves) == 1
  175. assert isinstance(leaves[0], self.type), self.type
  176. return leaves[0]
  177. def __eq__(self, other):
  178. return self.type == other.type and self.const_val == other.const_val
  179. def __hash__(self):
  180. return hash(tuple([self.type, self.const_val]))
  181. def __repr__(self):
  182. return "Leaf({}[{}])".format(
  183. ", ".join(t.__name__ for t in self.type), self.const_val
  184. )

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