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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. graph = None
  48. attr_type_map = None # type: Dict[str, Type[Any]]
  49. arg_def = None # type: TreeDef
  50. def __repr__(self):
  51. if self._name is None:
  52. return "%{}({})".format(self._id, self.module_type.__name__)
  53. else:
  54. return "%{}({})".format(self._name, self.module_type.__name__)
  55. class TensorNode(Node):
  56. """
  57. ``TensorNode`` represents the Tensor objects.
  58. """
  59. shape = None # type: Tuple[int]
  60. dtype = None # type: numpy.dtype
  61. def __repr__(self):
  62. if self._name is None:
  63. return "%{}(Tensor)".format(self._id)
  64. else:
  65. return "%{}(Tensor)".format(self._name)
  66. class NodeMixin:
  67. __node = None
  68. @classmethod
  69. def wrap(cls, value, node):
  70. if isinstance(value, (NodeMixin, RawTensor)):
  71. if isinstance(node, Node):
  72. if isinstance(value, RawTensor):
  73. node.dtype = value.dtype
  74. node.shape = (
  75. value._tuple_shape if isinstance(value, Tensor) else value.shape
  76. )
  77. setattr(value, "_NodeMixin__node", node)
  78. else:
  79. assert callable(node)
  80. n = node()
  81. if isinstance(value, RawTensor):
  82. n.dtype = value.dtype
  83. n.shape = (
  84. value._tuple_shape if isinstance(value, Tensor) else value.shape
  85. )
  86. setattr(value, "_NodeMixin__node", n)
  87. @classmethod
  88. def wrap_safe(cls, value, node):
  89. assert isinstance(value, (NodeMixin, RawTensor))
  90. if isinstance(value, RawTensor):
  91. node.dtype = value.dtype
  92. node.shape = (
  93. value._tuple_shape if isinstance(value, Tensor) else value.shape
  94. )
  95. setattr(value, "_NodeMixin__node", node)
  96. @classmethod
  97. def get(cls, value, *default):
  98. return getattr(value, "_NodeMixin__node", *default)
  99. @classmethod
  100. def get_wrapped_type(cls, value):
  101. if isinstance(value, RawTensor):
  102. return TensorNode
  103. if isinstance(value, (Module, NodeMixin)):
  104. return ModuleNode
  105. return Node

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