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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. from .core import Tensor as _Tensor
  11. from .core.ops.builtin import Copy
  12. from .core.tensor.core import apply
  13. from .device import get_default_device
  14. class Tensor(_Tensor):
  15. requires_grad = False
  16. dmap_callback = None
  17. def __init__(self, data, dtype=None, device=None):
  18. if device is None:
  19. device = get_default_device()
  20. self.q_dict = {"mode": None, "scale": None, "zero_point": None}
  21. super().__init__(data, dtype=dtype, device=device)
  22. def set_value(self, value):
  23. self._reset(value)
  24. def reset_zero(self):
  25. self *= 0
  26. def to(self, cn):
  27. return apply(Copy(comp_node=cn), self)[0]
  28. def __getstate__(self):
  29. r""" __getstate__ will be called for pickle serialization or deep copy
  30. """
  31. state = {
  32. "data": self.numpy(),
  33. "device": str(self.device),
  34. "dtype": self.dtype,
  35. "qdict": self.q_dict,
  36. }
  37. return state
  38. def __setstate__(self, state):
  39. data = state.pop("data")
  40. device = state.pop("device")
  41. if self.dmap_callback is not None:
  42. assert isinstance(device, str)
  43. device = self.dmap_callback(device)
  44. dtype = state.pop("dtype")
  45. self.q_dict = state.pop("qdict")
  46. super().__init__(data, dtype=dtype, device=device)
  47. def detach(self):
  48. r"""
  49. Returns a new tensor which is treated as constant during backward gradient calcuation,
  50. i.e. its gradient is zero.
  51. :param inp: input tensor
  52. """
  53. Wrapper = type(self)
  54. Tensor = type(self.__wrapped__)
  55. return Wrapper(Tensor(self.__wrapped__._data))
  56. tensor = Tensor
  57. class Dict(collections.MutableMapping):
  58. def __init__(self, *args, key=None, **kwargs):
  59. self.data = {}
  60. if key:
  61. self.keyfn = key
  62. for i in args:
  63. self.update(i)
  64. self.update(**kwargs)
  65. @staticmethod
  66. def keyfn(key): # pylint: disable=method-hidden
  67. return key
  68. def __getitem__(self, key):
  69. _, v = self.data[self.keyfn(key)]
  70. return v
  71. def __setitem__(self, key, value):
  72. self.data[self.keyfn(key)] = key, value
  73. def __delitem__(self, key):
  74. del self.data[self.keyfn(key)]
  75. def __iter__(self):
  76. for _, (k, _) in self.data.items():
  77. yield k
  78. def __len__(self):
  79. return len(self.data)
  80. class TensorDict(Dict): # pylint: disable=too-many-ancestors
  81. class keyfn:
  82. def __new__(cls, x: Tensor):
  83. if not isinstance(x, Tensor):
  84. return x
  85. return super().__new__(cls)
  86. def __init__(self, x: Tensor):
  87. self._data = x # do not save id directly to make pickle work
  88. def __hash__(self):
  89. return id(self._data)
  90. def __eq__(self, other):
  91. # pylint: disable=undefined-variable
  92. return isinstance(other, __class__) and id(self._data) == id(other._data)
  93. def __init__(self, *args):
  94. super().__init__(*args)

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