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

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

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