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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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, 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._id = Node.__total_id
  28. Node.__total_id += 1
  29. self._name = name
  30. def __setstate__(self, d):
  31. self.__dict__ = d
  32. Node.__total_id = max(Node.__total_id, self._id) + 1
  33. def __repr__(self):
  34. if self._name is None:
  35. return "%{}".format(self._id)
  36. else:
  37. return "%{}".format(self._name)
  38. class ModuleNode(Node):
  39. """
  40. ``ModuleNode`` represents the Module objects.
  41. Attributes:
  42. module_type: type of the Module correspending to the ModuleNode
  43. graph: the InternalGraph which will be interpreted when call Module's forward method
  44. attr_type_map: record the type of Module's attributes
  45. """
  46. module_type = Module # type: Type[Module]
  47. attr_type_map = None # type: Dict[str, Type[Any]]
  48. argdef_graph_map = None # type: Dict[Treedef, "InternalGraph"]
  49. def __init__(self, expr: "Expr", name: str = None):
  50. super().__init__(expr, name)
  51. self.attr_type_map = {}
  52. self.argdef_graph_map = {}
  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. class TensorNode(Node):
  59. """
  60. ``TensorNode`` represents the Tensor objects.
  61. """
  62. shape = None # type: Tuple[int]
  63. dtype = None # type: numpy.dtype
  64. def __repr__(self):
  65. if self._name is None:
  66. return "%{}(Tensor)".format(self._id)
  67. else:
  68. return "%{}(Tensor)".format(self._name)
  69. class NodeMixin:
  70. __node = None
  71. @classmethod
  72. def wrap(cls, value, node):
  73. if isinstance(value, (NodeMixin, RawTensor)):
  74. if isinstance(node, Node):
  75. if isinstance(value, RawTensor):
  76. node.dtype = value.dtype
  77. node.shape = (
  78. value._tuple_shape if isinstance(value, Tensor) else value.shape
  79. )
  80. setattr(value, "_NodeMixin__node", node)
  81. else:
  82. assert callable(node)
  83. n = node()
  84. if isinstance(value, RawTensor):
  85. n.dtype = value.dtype
  86. n.shape = (
  87. value._tuple_shape if isinstance(value, Tensor) else value.shape
  88. )
  89. setattr(value, "_NodeMixin__node", n)
  90. @classmethod
  91. def wrap_safe(cls, value, node):
  92. assert isinstance(value, (NodeMixin, RawTensor))
  93. if isinstance(value, RawTensor):
  94. node.dtype = value.dtype
  95. node.shape = (
  96. value._tuple_shape if isinstance(value, Tensor) else value.shape
  97. )
  98. setattr(value, "_NodeMixin__node", node)
  99. @classmethod
  100. def get(cls, value, *default):
  101. return getattr(value, "_NodeMixin__node", *default)
  102. @classmethod
  103. def get_wrapped_type(cls, value):
  104. if isinstance(value, RawTensor):
  105. return TensorNode
  106. if isinstance(value, (Module, NodeMixin)):
  107. return ModuleNode
  108. return Node

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