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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. from .pytree import TreeDef
  17. class Node:
  18. """
  19. ``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).
  20. param expr: the Expr which produces the node
  21. param name: the name of the node
  22. """
  23. expr = None
  24. __total_id = 0
  25. _id = None
  26. _name = None
  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. class ModuleNode(Node):
  42. """
  43. ``ModuleNode`` represents the Module objects.
  44. Attributes:
  45. module_type: type of the Module correspending to the ModuleNode
  46. graph: the InternalGraph which will be interpreted when call Module's forward method
  47. attr_type_map: record the type of Module's attributes
  48. """
  49. module_type = Module # type: Type[Module]
  50. _owner = None # type: weakref.ReferenceType
  51. def __init__(self, expr: "Expr", name: str = None):
  52. super().__init__(expr, name)
  53. def __repr__(self):
  54. if self._name is None:
  55. return "%{}({})".format(self._id, self.module_type.__name__)
  56. else:
  57. return "%{}({})".format(self._name, self.module_type.__name__)
  58. def __getstate__(self):
  59. d = self.__dict__
  60. d.pop("_owner", None)
  61. return d
  62. @property
  63. def owner(self):
  64. return self._owner()
  65. class TensorNode(Node):
  66. """
  67. ``TensorNode`` represents the Tensor objects.
  68. """
  69. shape = None # type: Tuple[int]
  70. dtype = None # type: numpy.dtype
  71. def __repr__(self):
  72. if self._name is None:
  73. return "%{}(Tensor)".format(self._id)
  74. else:
  75. return "%{}(Tensor)".format(self._name)
  76. class NodeMixin(abc.ABC):
  77. __node = None
  78. @abc.abstractmethod
  79. def _record_wrapped_nodes(self, node):
  80. # record the nodes which had been bound to this NodeMixin
  81. pass
  82. @classmethod
  83. def wrap(cls, value, node):
  84. if isinstance(value, (NodeMixin, RawTensor)):
  85. if isinstance(node, Node):
  86. if isinstance(value, RawTensor):
  87. node.dtype = value.dtype
  88. node.shape = (
  89. value._tuple_shape if isinstance(value, Tensor) else value.shape
  90. )
  91. if isinstance(value, NodeMixin):
  92. value._record_wrapped_nodes(node)
  93. setattr(value, "_NodeMixin__node", node)
  94. else:
  95. assert callable(node)
  96. n = node()
  97. assert isinstance(n, Node)
  98. if isinstance(value, RawTensor):
  99. n.dtype = value.dtype
  100. n.shape = (
  101. value._tuple_shape if isinstance(value, Tensor) else value.shape
  102. )
  103. if isinstance(value, NodeMixin):
  104. value._record_wrapped_nodes(n)
  105. setattr(value, "_NodeMixin__node", n)
  106. @classmethod
  107. def wrap_safe(cls, value, node):
  108. assert isinstance(value, (NodeMixin, RawTensor))
  109. if isinstance(value, RawTensor):
  110. node.dtype = value.dtype
  111. node.shape = (
  112. value._tuple_shape if isinstance(value, Tensor) else value.shape
  113. )
  114. setattr(value, "_NodeMixin__node", node)
  115. if isinstance(value, NodeMixin):
  116. value._record_wrapped_nodes(node)
  117. @classmethod
  118. def get(cls, value, *default):
  119. return getattr(value, "_NodeMixin__node", *default)
  120. @classmethod
  121. def get_wrapped_type(cls, value):
  122. if isinstance(value, RawTensor):
  123. return TensorNode
  124. if isinstance(value, (Module, NodeMixin)):
  125. return ModuleNode
  126. return Node

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