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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. SUPPORTED_TYPE = {}
  14. NodeType = NamedTuple("NodeType", [("flatten", Callable), ("unflatten", Callable)])
  15. def register_supported_type(type, flatten, unflatten):
  16. SUPPORTED_TYPE[type] = NodeType(flatten, unflatten)
  17. def _dict_flatten(inp):
  18. aux_data = []
  19. results = []
  20. for key, value in sorted(inp.items()):
  21. results.append(value)
  22. aux_data.append(key)
  23. return results, tuple(aux_data)
  24. def _dict_unflatten(inps, aux_data):
  25. return dict(zip(aux_data, inps))
  26. def _ordereddict_flatten(inp):
  27. aux_data = []
  28. results = []
  29. for key, value in inp.items():
  30. results.append(value)
  31. aux_data.append(key)
  32. return results, tuple(aux_data)
  33. def _ordereddict_unflatten(inps, aux_data):
  34. return OrderedDict(zip(aux_data, inps))
  35. register_supported_type(list, lambda x: (x, None), lambda x, aux_data: list(x))
  36. register_supported_type(tuple, lambda x: (x, None), lambda x, aux_data: tuple(x))
  37. register_supported_type(dict, _dict_flatten, _dict_unflatten)
  38. register_supported_type(
  39. collections.OrderedDict, _ordereddict_flatten, _ordereddict_unflatten
  40. )
  41. register_supported_type(
  42. slice,
  43. lambda x: ([x.start, x.stop, x.step], None),
  44. lambda x, aux_data: slice(x[0], x[1], x[2]),
  45. )
  46. def tree_flatten(
  47. values,
  48. leaf_type: Callable = lambda x: type(x),
  49. is_leaf: Callable = lambda _: True,
  50. is_const_leaf: Callable = lambda _: False,
  51. ):
  52. if type(values) not in SUPPORTED_TYPE:
  53. assert is_leaf(values)
  54. node = LeafDef(leaf_type(values))
  55. if is_const_leaf(values):
  56. if isinstance(values, np.ndarray):
  57. node.const_val = str(values)
  58. else:
  59. node.const_val = values
  60. return [values,], node
  61. rst = []
  62. children_defs = []
  63. children_values, aux_data = SUPPORTED_TYPE[type(values)].flatten(values)
  64. for v in children_values:
  65. v_list, treedef = tree_flatten(v, leaf_type, is_leaf, is_const_leaf)
  66. rst.extend(v_list)
  67. children_defs.append(treedef)
  68. return rst, TreeDef(type(values), aux_data, children_defs)
  69. class TreeDef:
  70. def __init__(self, type, aux_data, children_defs):
  71. self.type = type
  72. self.aux_data = aux_data
  73. self.children_defs = children_defs
  74. self.num_leaves = sum(ch.num_leaves for ch in children_defs)
  75. def unflatten(self, leaves):
  76. assert len(leaves) == self.num_leaves
  77. start = 0
  78. children = []
  79. for ch in self.children_defs:
  80. children.append(ch.unflatten(leaves[start : start + ch.num_leaves]))
  81. start += ch.num_leaves
  82. return SUPPORTED_TYPE[self.type].unflatten(children, self.aux_data)
  83. def __hash__(self):
  84. return hash(
  85. tuple(
  86. [
  87. self.type,
  88. self.aux_data,
  89. self.num_leaves,
  90. tuple([hash(x) for x in self.children_defs]),
  91. ]
  92. )
  93. )
  94. def __lt__(self, other):
  95. return self.__hash__() < other.__hash__()
  96. def __gt__(self, other):
  97. return self.__hash__() > other.__hash__()
  98. def __eq__(self, other):
  99. return (
  100. self.type == other.type
  101. and self.aux_data == other.aux_data
  102. and self.num_leaves == other.num_leaves
  103. and self.children_defs == other.children_defs
  104. )
  105. def __repr__(self):
  106. return "{}[{}]".format(self.type.__name__, self.children_defs)
  107. class LeafDef(TreeDef):
  108. def __init__(self, type):
  109. if not isinstance(type, collections.abc.Sequence):
  110. type = (type,)
  111. super().__init__(type, None, [])
  112. self.num_leaves = 1
  113. self.const_val = None
  114. def unflatten(self, leaves):
  115. assert len(leaves) == 1
  116. assert isinstance(leaves[0], self.type), self.type
  117. return leaves[0]
  118. def __eq__(self, other):
  119. return self.type == other.type and self.const_val == other.const_val
  120. def __hash__(self):
  121. return hash(tuple([self.type, self.const_val]))
  122. def __repr__(self):
  123. return "Leaf({}[{}])".format(
  124. ", ".join(t.__name__ for t in self.type), self.const_val
  125. )

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