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

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

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