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.

tensor.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 Union
  10. import numpy as np
  11. from .core._imperative_rt import CompNode
  12. from .core._imperative_rt.core2 import Tensor as _Tensor
  13. from .core._imperative_rt.core2 import apply
  14. from .core._trace_option import use_symbolic_shape
  15. from .core._wrap import device as as_device
  16. from .core.ops.builtin import Copy, GetVarShape
  17. from .core.tensor.array_method import ArrayMethodMixin
  18. from .device import _valid_device, get_default_device
  19. from .logger import get_logger
  20. from .utils.deprecation import deprecated
  21. from .utils.naming import auto_naming
  22. class Tensor(_Tensor, ArrayMethodMixin):
  23. grad = None
  24. dmap_callback = None
  25. _q_dict = None
  26. def __new__(
  27. cls, data, dtype=None, device=None, is_const=False, no_cache=False, name=""
  28. ):
  29. if device is None:
  30. cn = get_default_device()
  31. elif isinstance(device, str):
  32. if cls.dmap_callback is not None:
  33. cn = CompNode(cls.dmap_callback(device))
  34. else:
  35. cn = CompNode(device)
  36. else:
  37. if isinstance(device, CompNode):
  38. cn = device
  39. else:
  40. cn = device._cn
  41. if isinstance(data, _Tensor):
  42. if dtype is not None:
  43. get_logger().warning(
  44. "dtype does not work when creating a new Tensor with another Tensor"
  45. )
  46. obj = _Tensor.__new__(cls, data)
  47. else:
  48. if isinstance(data, np.ndarray):
  49. if 0 in data.strides:
  50. data = data.squeeze().reshape(data.shape)
  51. obj = _Tensor.__new__(cls, data, dtype, cn, is_const, no_cache, name)
  52. return obj
  53. @property
  54. def shape(self) -> Union[tuple, "Tensor"]:
  55. shape = super().shape
  56. if shape == () or not use_symbolic_shape():
  57. return shape
  58. return apply(GetVarShape(), self)[0]
  59. @property
  60. def _tuple_shape(self):
  61. return super().shape
  62. @property
  63. def dtype(self) -> np.dtype:
  64. return super().dtype
  65. @property
  66. def q_dict(self):
  67. if self._q_dict is None:
  68. self._q_dict = {"mode": None, "scale": None, "zero_point": None}
  69. return self._q_dict
  70. def numpy(self) -> np.ndarray:
  71. return super().numpy()
  72. def _reset(self, other):
  73. super()._reset(other)
  74. def __repr__(self):
  75. piece = "Tensor("
  76. with np.printoptions(precision=4, suppress=True):
  77. piece += "{}".format(str(self.numpy()))
  78. if self.dtype != np.float32:
  79. piece += ", dtype={}".format(np.dtype(self.dtype).name)
  80. piece += ", device={}".format(self.device) + ")"
  81. return piece
  82. @property
  83. def name(self):
  84. return self.c_name
  85. @name.setter
  86. def name(self, name):
  87. self.c_name = name
  88. auto_naming.record_var_name(self._mixin_handle, name)
  89. @deprecated(version="1.0", reason="no need to reuse an existing tensor since 1.0")
  90. def set_value(self, value):
  91. if not isinstance(value, _Tensor):
  92. value = Tensor(value, dtype=self.dtype, device=self.device)
  93. self._reset(value)
  94. @deprecated(version="1.0", reason="use *= 0 instead")
  95. def reset_zero(self):
  96. self *= 0
  97. def to(self, device):
  98. if isinstance(device, str) and not _valid_device(device):
  99. raise ValueError(
  100. "invalid device name {}. For the correct format of the device name, please refer to the instruction of megengine.device.set_default_device()".format(
  101. device
  102. )
  103. )
  104. cn = as_device(device).to_c()
  105. return apply(Copy(comp_node=cn), self)[0]
  106. @property
  107. def requires_grad(self):
  108. raise AttributeError("requires_grad is reserved for future use")
  109. @requires_grad.setter
  110. def requires_grad(self, value):
  111. raise AttributeError("requires_grad is reserved for future use")
  112. @requires_grad.deleter
  113. def requires_grad(self):
  114. raise AttributeError("requires_grad is reserved for future use")
  115. def __hash__(self):
  116. return id(self)
  117. def __getnewargs__(self):
  118. r""" __getnewargs__ will be called for pickle serialization or deep copy
  119. """
  120. return (self.numpy(), self.dtype, self.device.logical_name)
  121. def __getstate__(self):
  122. r""" __getstate__ will be called for pickle serialization or deep copy
  123. """
  124. state = {
  125. "qdict": self.q_dict,
  126. }
  127. return state
  128. def __setstate__(self, state):
  129. self._q_dict = state.pop("qdict")
  130. tensor = Tensor
  131. class Parameter(Tensor):
  132. r"""
  133. A kind of Tensor that is to be considered a module parameter.
  134. """

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