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

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

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