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 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-2020 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. import collections
  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.ops.builtin import Copy, GetVarShape
  16. from .core.tensor.raw_tensor import as_device
  17. from .core.tensor.tensor_wrapper import ArrayMethodMixin
  18. from .device import _valid_device, get_default_device
  19. from .utils.deprecation import deprecated
  20. class Tensor(_Tensor, ArrayMethodMixin):
  21. grad = None
  22. dmap_callback = None
  23. q_dict = {"mode": None, "scale": None, "zero_point": None}
  24. def __new__(cls, data, dtype=None, device=None):
  25. if device is None:
  26. cn = get_default_device()
  27. elif isinstance(device, str):
  28. if cls.dmap_callback is not None:
  29. cn = CompNode(cls.dmap_callback(device))
  30. else:
  31. cn = CompNode(device)
  32. else:
  33. assert isinstance(device, CompNode)
  34. cn = device
  35. if isinstance(data, _Tensor):
  36. obj = _Tensor.__new__(cls, data)
  37. else:
  38. obj = _Tensor.__new__(cls, data, dtype, cn)
  39. return obj
  40. @property
  41. def shape(self):
  42. shape = super().shape
  43. if shape == () or not use_symbolic_shape():
  44. return shape
  45. return apply(GetVarShape(), self)[0]
  46. @property
  47. def _tuple_shape(self):
  48. return super().shape
  49. def __repr__(self):
  50. piece = "Tensor("
  51. with np.printoptions(precision=4, suppress=True):
  52. piece += "{}".format(str(self.numpy()))
  53. if self.dtype != np.float32:
  54. piece += ", dtype={}".format(np.dtype(self.dtype).name)
  55. piece += ", device={}".format(self.device) + ")"
  56. return piece
  57. @deprecated(version="1.0", reason="no need to reuse an existing tensor since 1.0")
  58. def set_value(self, value):
  59. if not isinstance(value, _Tensor):
  60. value = Tensor(value, dtype=self.dtype, device=self.device)
  61. self._reset(value)
  62. @deprecated(version="1.0", reason="use *= 0 instead")
  63. def reset_zero(self):
  64. self *= 0
  65. def to(self, device):
  66. if isinstance(device, str) and not _valid_device(device):
  67. raise ValueError(
  68. "invalid device name {}. For the correct format of the device name, please refer to the instruction of megengine.device.set_default_device()".format(
  69. device
  70. )
  71. )
  72. cn = as_device(device).to_c()
  73. return apply(Copy(comp_node=cn), self)[0]
  74. @property
  75. def requires_grad(self):
  76. raise AttributeError("requires_grad is reserved for future use")
  77. @requires_grad.setter
  78. def requires_grad(self, value):
  79. raise AttributeError("requires_grad is reserved for future use")
  80. @requires_grad.deleter
  81. def requires_grad(self):
  82. raise AttributeError("requires_grad is reserved for future use")
  83. def __hash__(self):
  84. return id(self)
  85. def __getnewargs__(self):
  86. r""" __getnewargs__ will be called for pickle serialization or deep copy
  87. """
  88. return (self.numpy(), self.dtype, self.device.logical_name)
  89. def __getstate__(self):
  90. r""" __getstate__ will be called for pickle serialization or deep copy
  91. """
  92. state = {
  93. "qdict": self.q_dict,
  94. }
  95. return state
  96. def __setstate__(self, state):
  97. self.q_dict = state.pop("qdict")
  98. tensor = Tensor
  99. class Parameter(Tensor):
  100. r"""
  101. A kind of Tensor that is to be considered a module parameter.
  102. """

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