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.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. from typing import Any, Dict, List, Tuple, Type
  10. import numpy
  11. from ...core._imperative_rt.core2 import Tensor as RawTensor
  12. from ...module import Module
  13. from ...tensor import Tensor
  14. from .pytree import TreeDef
  15. class Node:
  16. """
  17. ``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).
  18. param expr: the Expr which produces the node
  19. param name: the name of the node
  20. """
  21. expr = None
  22. __total_id = 0
  23. _id = None
  24. _name = None
  25. def __init__(self, expr: "Expr", name: str = None):
  26. self.expr = expr
  27. self.users = [] # List[Expr]
  28. self._id = Node.__total_id
  29. Node.__total_id += 1
  30. self._name = name
  31. def __setstate__(self, d):
  32. self.__dict__ = d
  33. Node.__total_id = max(Node.__total_id, self._id) + 1
  34. def __repr__(self):
  35. if self._name is None:
  36. return "%{}".format(self._id)
  37. else:
  38. return "%{}".format(self._name)
  39. class ModuleNode(Node):
  40. """
  41. ``ModuleNode`` represents the Module objects.
  42. Attributes:
  43. module_type: type of the Module correspending to the ModuleNode
  44. graph: the InternalGraph which will be interpreted when call Module's forward method
  45. attr_type_map: record the type of Module's attributes
  46. """
  47. module_type = Module # type: Type[Module]
  48. attr_type_map = None # type: Dict[str, Type[Any]]
  49. argdef_graph_map = None # type: Dict[Treedef, "InternalGraph"]
  50. argdef_outdef_map = None # type: Dict[Treedef, Treedef]
  51. def __init__(self, expr: "Expr", name: str = None):
  52. super().__init__(expr, name)
  53. self.attr_type_map = {}
  54. self.argdef_graph_map = {}
  55. self.argdef_outdef_map = {}
  56. def __repr__(self):
  57. if self._name is None:
  58. return "%{}({})".format(self._id, self.module_type.__name__)
  59. else:
  60. return "%{}({})".format(self._name, self.module_type.__name__)
  61. class TensorNode(Node):
  62. """
  63. ``TensorNode`` represents the Tensor objects.
  64. """
  65. shape = None # type: Tuple[int]
  66. dtype = None # type: numpy.dtype
  67. def __repr__(self):
  68. if self._name is None:
  69. return "%{}(Tensor)".format(self._id)
  70. else:
  71. return "%{}(Tensor)".format(self._name)
  72. class NodeMixin:
  73. __node = None
  74. @classmethod
  75. def wrap(cls, value, node):
  76. if isinstance(value, (NodeMixin, RawTensor)):
  77. if isinstance(node, Node):
  78. if isinstance(value, RawTensor):
  79. node.dtype = value.dtype
  80. node.shape = (
  81. value._tuple_shape if isinstance(value, Tensor) else value.shape
  82. )
  83. setattr(value, "_NodeMixin__node", node)
  84. else:
  85. assert callable(node)
  86. n = node()
  87. if isinstance(value, RawTensor):
  88. n.dtype = value.dtype
  89. n.shape = (
  90. value._tuple_shape if isinstance(value, Tensor) else value.shape
  91. )
  92. setattr(value, "_NodeMixin__node", n)
  93. @classmethod
  94. def wrap_safe(cls, value, node):
  95. assert isinstance(value, (NodeMixin, RawTensor))
  96. if isinstance(value, RawTensor):
  97. node.dtype = value.dtype
  98. node.shape = (
  99. value._tuple_shape if isinstance(value, Tensor) else value.shape
  100. )
  101. setattr(value, "_NodeMixin__node", node)
  102. @classmethod
  103. def get(cls, value, *default):
  104. return getattr(value, "_NodeMixin__node", *default)
  105. @classmethod
  106. def get_wrapped_type(cls, value):
  107. if isinstance(value, RawTensor):
  108. return TensorNode
  109. if isinstance(value, (Module, NodeMixin)):
  110. return ModuleNode
  111. return Node

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