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.

node.py 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 abc
  10. import weakref
  11. from typing import Any, Dict, List, Tuple, Type
  12. import numpy
  13. from ...core._imperative_rt.core2 import Tensor as RawTensor
  14. from ...module import Module
  15. from ...tensor import Tensor
  16. class Node:
  17. """
  18. ``Node`` represents the variables (Tensor/Module/other python object) used in Module's forward method. They are inputs/outputs of Expr(the operations on variables).
  19. param expr: the Expr which produces the node
  20. param name: the name of the node
  21. """
  22. expr = None
  23. __total_id = 0
  24. _id = None
  25. _name = None
  26. _top_graph = None # type: weakref.ReferenceType
  27. def __init__(self, expr: "Expr", name: str = None):
  28. self.expr = expr
  29. self.users = [] # List[Expr]
  30. self._id = Node.__total_id
  31. Node.__total_id += 1
  32. self._name = name
  33. def __setstate__(self, d):
  34. self.__dict__ = d
  35. Node.__total_id = max(Node.__total_id, self._id) + 1
  36. def __repr__(self):
  37. if self._name is None:
  38. return "%{}".format(self._id)
  39. else:
  40. return "%{}".format(self._name)
  41. @property
  42. def top_graph(self):
  43. if self._top_graph:
  44. return self._top_graph()
  45. return None
  46. class ModuleNode(Node):
  47. """
  48. ``ModuleNode`` represents the Module objects.
  49. Attributes:
  50. module_type: type of the Module correspending to the ModuleNode
  51. graph: the InternalGraph which will be interpreted when call Module's forward method
  52. attr_type_map: record the type of Module's attributes
  53. """
  54. module_type = Module # type: Type[Module]
  55. _owner = None # type: weakref.ReferenceType
  56. def __init__(self, expr: "Expr", name: str = None):
  57. super().__init__(expr, name)
  58. self.actual_mnode = []
  59. def __repr__(self):
  60. if self._name is None:
  61. return "%{}_({})".format(self._id, self.module_type.__name__)
  62. else:
  63. return "%{}_{}({})".format(self._id, self._name, self.module_type.__name__)
  64. def __getstate__(self):
  65. return {
  66. "expr": self.expr,
  67. "users": self.users,
  68. "_id": self._id,
  69. "_name": self._name,
  70. "module_type": self.module_type,
  71. }
  72. @property
  73. def owner(self):
  74. if self._owner:
  75. return self._owner()
  76. return None
  77. class TensorNode(Node):
  78. """
  79. ``TensorNode`` represents the Tensor objects.
  80. """
  81. shape = None # type: Tuple[int]
  82. dtype = None # type: numpy.dtype
  83. qparam = None
  84. device = None
  85. def __repr__(self):
  86. if self._name is None:
  87. return "%{}_(Tensor)".format(self._id)
  88. else:
  89. return "%{}_{}(Tensor)".format(self._id, self._name)
  90. def __getstate__(self):
  91. return {
  92. "expr": self.expr,
  93. "users": self.users,
  94. "_id": self._id,
  95. "qparam": self.qparam,
  96. "shape": self.shape,
  97. "dtype": self.dtype,
  98. "device": self.device,
  99. }
  100. class NodeMixin(abc.ABC):
  101. __node = None
  102. @abc.abstractmethod
  103. def _record_wrapped_nodes(self, node):
  104. # record the nodes which had been bound to this NodeMixin
  105. pass
  106. @classmethod
  107. def _record_tensornode_property(cls, node, value):
  108. assert isinstance(node, TensorNode)
  109. assert isinstance(value, RawTensor)
  110. if isinstance(value, RawTensor):
  111. node.dtype = value.dtype
  112. node.shape = (
  113. value._tuple_shape if isinstance(value, Tensor) else value.shape
  114. )
  115. node.device = value.device
  116. if hasattr(value, "_qparams") and value._qparams is not None:
  117. node.qparams = value.qparams
  118. @classmethod
  119. def wrap(cls, value, node):
  120. if isinstance(value, (NodeMixin, RawTensor)):
  121. if isinstance(node, Node):
  122. if isinstance(value, RawTensor):
  123. cls._record_tensornode_property(node, value)
  124. if isinstance(value, NodeMixin):
  125. value._record_wrapped_nodes(node)
  126. setattr(value, "_NodeMixin__node", node)
  127. else:
  128. assert callable(node)
  129. n = node()
  130. assert isinstance(n, Node)
  131. if isinstance(value, RawTensor):
  132. cls._record_tensornode_property(n, value)
  133. if isinstance(value, NodeMixin):
  134. value._record_wrapped_nodes(n)
  135. setattr(value, "_NodeMixin__node", n)
  136. @classmethod
  137. def wrap_safe(cls, value, node):
  138. assert isinstance(value, (NodeMixin, RawTensor))
  139. if isinstance(value, RawTensor):
  140. cls._record_tensornode_property(node, value)
  141. setattr(value, "_NodeMixin__node", node)
  142. if isinstance(value, NodeMixin):
  143. value._record_wrapped_nodes(node)
  144. @classmethod
  145. def get(cls, value, *default):
  146. return getattr(value, "_NodeMixin__node", *default)
  147. @classmethod
  148. def get_wrapped_type(cls, value):
  149. if isinstance(value, RawTensor):
  150. return TensorNode
  151. if isinstance(value, (Module, NodeMixin)):
  152. return ModuleNode
  153. return Node

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