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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. logger = get_logger(__name__)
  23. class Tensor(_Tensor, ArrayMethodMixin):
  24. r"""
  25. A tensor object represents a multidimensional, homogeneous array of fixed-size items.
  26. """
  27. grad = None
  28. dmap_callback = None
  29. _qparams = None
  30. def __new__(
  31. cls, data, dtype=None, device=None, is_const=False, no_cache=False, name=None
  32. ):
  33. if device is None:
  34. cn = get_default_device()
  35. elif isinstance(device, str):
  36. if cls.dmap_callback is not None:
  37. cn = CompNode(cls.dmap_callback(device))
  38. else:
  39. cn = CompNode(device)
  40. else:
  41. if isinstance(device, CompNode):
  42. cn = device
  43. else:
  44. cn = device._cn
  45. if isinstance(data, _Tensor):
  46. if dtype is not None:
  47. logger.warning(
  48. "dtype does not work when creating a new Tensor with another Tensor"
  49. )
  50. obj = _Tensor.__new__(cls, data)
  51. else:
  52. if isinstance(data, np.ndarray):
  53. if 0 in data.strides:
  54. data = data.squeeze().reshape(data.shape)
  55. obj = _Tensor.__new__(cls, data, dtype, cn, is_const, no_cache, name)
  56. return obj
  57. @property
  58. def shape(self) -> Union[tuple, "Tensor"]:
  59. r"""
  60. Returns a :class:`tuple` or a :class:`~.Tensor` represents tensor dimensions.
  61. .. note::
  62. The shape of a tensor was usually represented by a :class:`tuple`.
  63. But if a tensor was treated as symbolic placeholder with tracing,
  64. it's shape could also be a :class:`~.Tensor`. See :class:`~.trace` for more details.
  65. The shape property is usually used to get the current shape of a tensor,
  66. but may also be used to reshape the tensor in-place by assigning a tuple of tensor dimensions to it.
  67. As with :func:`~.reshape`, one of the new shape dimensions can be -1,
  68. in which case its value is inferred from the size of the tensor and the remaining dimensions.
  69. """
  70. shape = super().shape
  71. if shape == () or not use_symbolic_shape():
  72. return shape
  73. return apply(GetVarShape(), self)[0]
  74. @property
  75. def _tuple_shape(self):
  76. return super().shape
  77. @property
  78. def device(self) -> CompNode:
  79. r"""
  80. Returns a string represents the device a :class:`~.Tensor` storaged on.
  81. """
  82. return super().device
  83. @property
  84. def dtype(self) -> np.dtype:
  85. r"""
  86. Returns a :class:`numpy.dtype` object represents the data type of a :class:`~.Tensor`.
  87. """
  88. return super().dtype
  89. @property
  90. def qparams(self):
  91. from .quantization.utils import create_qparams # pylint: disable=all
  92. if self._qparams is None:
  93. self._qparams = create_qparams()
  94. return self._qparams
  95. def numpy(self) -> np.ndarray:
  96. r"""
  97. Returns self :class:`~.Tensor` as a :class:`numpy.ndarray`.
  98. """
  99. return super().numpy()
  100. def detach(self):
  101. r"""
  102. Returns a new :class:`~.Tensor`, detached from the current graph.
  103. """
  104. return super().detach()
  105. def _reset(self, other):
  106. super()._reset(other)
  107. def __repr__(self):
  108. piece = "Tensor("
  109. with np.printoptions(precision=4, suppress=True):
  110. piece += "{}".format(str(self.numpy()))
  111. if self.dtype != np.float32:
  112. piece += ", dtype={}".format(np.dtype(self.dtype).name)
  113. piece += ", device={}".format(self.device) + ")"
  114. return piece
  115. @property
  116. def name(self):
  117. return self.c_name
  118. @name.setter
  119. def name(self, name):
  120. self.c_name = name
  121. auto_naming.record_var_name(self._mixin_handle, name)
  122. @deprecated(version="1.0", reason="no need to reuse an existing tensor since 1.0")
  123. def set_value(self, value):
  124. if not isinstance(value, _Tensor):
  125. value = Tensor(value, dtype=self.dtype, device=self.device)
  126. self._reset(value)
  127. @deprecated(version="1.0", reason="use *= 0 instead")
  128. def reset_zero(self):
  129. self *= 0
  130. def to(self, device):
  131. r"""
  132. Copy self :class:`~.Tensor` to specified device. See :func:`~.copy`
  133. """
  134. if isinstance(device, str) and not _valid_device(device):
  135. raise ValueError(
  136. "invalid device name {}. For the correct format of the device name, please refer to the instruction of megengine.device.set_default_device()".format(
  137. device
  138. )
  139. )
  140. cn = as_device(device).to_c()
  141. return apply(Copy(comp_node=cn), self)[0]
  142. @property
  143. def requires_grad(self):
  144. raise AttributeError("requires_grad is reserved for future use")
  145. @requires_grad.setter
  146. def requires_grad(self, value):
  147. raise AttributeError("requires_grad is reserved for future use")
  148. @requires_grad.deleter
  149. def requires_grad(self):
  150. raise AttributeError("requires_grad is reserved for future use")
  151. def __hash__(self):
  152. return id(self)
  153. def __getnewargs__(self):
  154. r""" __getnewargs__ will be called for pickle serialization or deep copy
  155. """
  156. return (self.numpy(), self.dtype, self.device.logical_name)
  157. def __getstate__(self):
  158. r""" __getstate__ will be called for pickle serialization or deep copy
  159. """
  160. state = {
  161. "numpy": self.numpy(),
  162. "dtype": self.dtype,
  163. "device": self.device.logical_name,
  164. }
  165. if self._qparams is not None:
  166. state["qparams"] = self._qparams
  167. return state
  168. def __setstate__(self, state):
  169. from .quantization.utils import create_qparams # pylint: disable=all
  170. if "qdict" in state:
  171. qparams = state.pop("qdict")
  172. logger.warning(
  173. "Tensor's 'qdict' state is depreciated. Use 'qparams' instead"
  174. )
  175. elif "qparams" in state:
  176. qparams = state.pop("qparams")
  177. else:
  178. qparams = None
  179. self._reset(Tensor(state.pop("numpy"), state.pop("dtype"), state.pop("device")))
  180. self._qparams = qparams
  181. tensor = Tensor
  182. class Parameter(Tensor):
  183. r"""
  184. A kind of Tensor that is to be considered a module parameter.
  185. """

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