storage.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. # mypy: allow-untyped-defs
  2. import io
  3. import torch
  4. from ._utils import _type, _to
  5. from torch.types import Storage
  6. from typing import cast, Any, Dict as _Dict, Optional as _Optional, TypeVar, Type, Union
  7. import copy
  8. import collections
  9. from functools import lru_cache
  10. import warnings
  11. import threading
  12. import functools
  13. try:
  14. import numpy as np
  15. HAS_NUMPY = True
  16. except ModuleNotFoundError:
  17. np = None # type: ignore[assignment]
  18. _share_memory_lock = threading.Lock()
  19. _share_memory_map: _Dict[int, threading.RLock] = {}
  20. T = TypeVar('T', bound='Union[_StorageBase, TypedStorage]')
  21. class _StorageBase:
  22. _cdata: Any
  23. is_sparse: bool = False
  24. is_sparse_csr: bool = False
  25. device: torch.device
  26. def __init__(self, *args, **kwargs): ... # noqa: E704
  27. def __len__(self) -> int: ... # type: ignore[empty-body] # noqa: E704
  28. def __getitem__(self, idx): ... # noqa: E704
  29. def __setitem__(self, *args, **kwargs): ... # noqa: E704
  30. def copy_(self, source: T, non_blocking: _Optional[bool] = None) -> T: ... # type: ignore[empty-body] # noqa: E704
  31. def new(self) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  32. def nbytes(self) -> int: ... # type: ignore[empty-body] # noqa: E704
  33. def size(self) -> int:
  34. return self.nbytes()
  35. def type(self, dtype: _Optional[str] = None, non_blocking: bool = False) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  36. def cuda(self, device=None, non_blocking=False) -> T: # type: ignore[type-var, misc] # noqa: E704
  37. """Returns a copy of this object in CUDA memory.
  38. If this object is already in CUDA memory and on the correct device, then
  39. no copy is performed and the original object is returned.
  40. Args:
  41. device (int): The destination GPU id. Defaults to the current device.
  42. non_blocking (bool): If ``True`` and the source is in pinned memory,
  43. the copy will be asynchronous with respect to the host. Otherwise,
  44. the argument has no effect.
  45. """
  46. device2 = torch.device('cuda', device) if device else torch.device('cuda')
  47. return self.to(device=device2, non_blocking=non_blocking)
  48. def hpu(self, device=None, non_blocking=False) -> T: # type: ignore[type-var, misc] # noqa: E704
  49. """Returns a copy of this object in HPU memory.
  50. If this object is already in HPU memory and on the correct device, then
  51. no copy is performed and the original object is returned.
  52. Args:
  53. device (int): The destination HPU id. Defaults to the current device.
  54. non_blocking (bool): If ``True`` and the source is in pinned memory,
  55. the copy will be asynchronous with respect to the host. Otherwise,
  56. the argument has no effect.
  57. """
  58. device2 = torch.device('hpu', device) if device else torch.device('hpu')
  59. return self.to(device=device2, non_blocking=non_blocking)
  60. def element_size(self) -> int: ... # type: ignore[empty-body, type-var] # noqa: E704
  61. def get_device(self) -> int:
  62. return self.device.index
  63. def data_ptr(self) -> int: ... # type: ignore[empty-body] # noqa: E704
  64. def resizable(self) -> bool: ... # type: ignore[empty-body] # noqa: E704
  65. # Defined in torch/csrc/generic/StorageSharing.cpp
  66. def _share_filename_cpu_(self, *args, **kwargs): ... # noqa: E704
  67. def _share_fd_cpu_(self, *args, **kwargs): ... # noqa: E704
  68. @classmethod
  69. def _new_using_filename_cpu(cls: Type[T], size: int) -> T: ... # type: ignore[empty-body] # noqa: E704
  70. @classmethod
  71. def _new_using_fd_cpu(cls: Type[T], size: int) -> T: ... # type: ignore[empty-body] # noqa: E704
  72. @classmethod
  73. def from_buffer(cls: Type[T], *args, **kwargs) -> T: ... # type: ignore[empty-body] # noqa: E704
  74. @classmethod
  75. def _new_shared_filename_cpu(cls: Type[T], manager, obj, size, *, device=None, dtype=None) -> T: ... # type: ignore[empty-body] # noqa: E704
  76. @classmethod
  77. def _release_ipc_counter_cuda(cls: Type[T], *args, **kwargs) -> T: ... # type: ignore[empty-body] # noqa: E704
  78. @classmethod
  79. def _new_with_weak_ptr(cls: Type[T], *args, **kwargs) -> T: ... # type: ignore[empty-body] # noqa: E704
  80. def _shared_decref(self) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  81. def _write_file(self, *args, **kwargs): ... # noqa: E704
  82. def resize_(self, size: int): ... # noqa: E704
  83. def _weak_ref(self, *args, **kwargs) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  84. def _set_from_file(self, *args, **kwargs): ... # noqa: E704
  85. def _set_cdata(self, *args, **kwargs): ... # noqa: E704
  86. def _share_cuda_(self, *args, **kwargs): ... # noqa: E704
  87. def is_shared(self) -> bool: ... # type: ignore[empty-body] # noqa: E704
  88. @classmethod
  89. def _new_shared_cuda(cls: Type[T], *args, **kwargs) -> T: ... # type: ignore[empty-body] # noqa: E704
  90. def _shared_incref(self, *args, **kwargs): ... # noqa: E704
  91. @classmethod
  92. def _free_weak_ref(cls, *args, **kwargs): ... # noqa: E704
  93. @property
  94. def is_cuda(self): ... # noqa: E704
  95. @property
  96. def is_hpu(self): ... # noqa: E704
  97. @classmethod
  98. def from_file(cls, filename, shared, nbytes) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  99. @classmethod
  100. def _expired(cls, *args, **kwargs) -> T: ... # type: ignore[empty-body, misc, type-var] # noqa: E704
  101. def _byteswap(self, *args, **kwargs): ... # noqa: E704
  102. def _get_filename(self, *args, **kwargs) -> _Optional[str]: ... # type: ignore[empty-body, misc] # noqa: E704
  103. def __str__(self):
  104. info_str = (
  105. f'[{torch.typename(self)}(device={self.device}) '
  106. f'of size {len(self)}]')
  107. if self.device.type == 'meta':
  108. return '...\n' + info_str
  109. else:
  110. data_str = ' ' + '\n '.join(str(self[i]) for i in range(self.size()))
  111. return data_str + '\n' + info_str
  112. def __repr__(self):
  113. return str(self)
  114. def __iter__(self):
  115. return iter(self[i] for i in range(self.size()))
  116. def __copy__(self):
  117. return self.clone()
  118. def __deepcopy__(self, memo):
  119. memo = memo.setdefault('torch', {})
  120. if self._cdata in memo:
  121. return memo[self._cdata]
  122. new_storage = self.clone()
  123. memo[self._cdata] = new_storage
  124. return new_storage
  125. def __reduce__(self):
  126. b = io.BytesIO()
  127. torch.save(self, b, _use_new_zipfile_serialization=False)
  128. return (_load_from_bytes, (b.getvalue(),))
  129. def __sizeof__(self):
  130. return super().__sizeof__() + self.size()
  131. def clone(self):
  132. """Return a copy of this storage."""
  133. return type(self)(self.nbytes(), device=self.device).copy_(self)
  134. def tolist(self):
  135. """Return a list containing the elements of this storage."""
  136. return list(self)
  137. def cpu(self):
  138. """Return a CPU copy of this storage if it's not already on the CPU."""
  139. if self.device.type != 'cpu':
  140. return torch.UntypedStorage(self.size()).copy_(self, False)
  141. else:
  142. return self
  143. def mps(self):
  144. """Return a MPS copy of this storage if it's not already on the MPS."""
  145. if self.device.type != 'mps':
  146. return torch.UntypedStorage(self.size(), device="mps").copy_(self, False)
  147. else:
  148. return self
  149. def _to(self, dtype):
  150. if not isinstance(dtype, torch.dtype):
  151. raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}")
  152. storage = torch.tensor([], dtype=torch.uint8, device=self.device).set_(cast(Storage, self)).to(dtype)._typed_storage()
  153. if storage.data_ptr() == self.data_ptr():
  154. storage = storage.clone()
  155. return storage
  156. def to(self, *, device: torch.device, non_blocking: bool = False) -> T: # type: ignore[type-var, misc] # noqa: E704
  157. return _to(self, device, non_blocking)
  158. def double(self):
  159. """Casts this storage to double type."""
  160. return self._to(torch.double)
  161. def float(self):
  162. """Casts this storage to float type."""
  163. return self._to(torch.float)
  164. def half(self):
  165. """Casts this storage to half type."""
  166. return self._to(torch.half)
  167. def long(self):
  168. """Casts this storage to long type."""
  169. return self._to(torch.long)
  170. def int(self):
  171. """Casts this storage to int type."""
  172. return self._to(torch.int)
  173. def short(self):
  174. """Casts this storage to short type."""
  175. return self._to(torch.short)
  176. def char(self):
  177. """Casts this storage to char type."""
  178. return self._to(torch.int8)
  179. def byte(self):
  180. """Casts this storage to byte type."""
  181. return self._to(torch.uint8)
  182. def bool(self):
  183. """Casts this storage to bool type."""
  184. return self._to(torch.bool)
  185. def bfloat16(self):
  186. """Casts this storage to bfloat16 type."""
  187. return self._to(torch.bfloat16)
  188. def complex_double(self):
  189. """Casts this storage to complex double type."""
  190. return self._to(torch.cdouble)
  191. def complex_float(self):
  192. """Casts this storage to complex float type."""
  193. return self._to(torch.cfloat)
  194. def float8_e5m2(self):
  195. """Casts this storage to float8_e5m2 type"""
  196. return self._to(torch.float8_e5m2)
  197. def float8_e4m3fn(self):
  198. """Casts this storage to float8_e4m3fn type"""
  199. return self._to(torch.float8_e4m3fn)
  200. def float8_e5m2fnuz(self):
  201. """Casts this storage to float8_e5m2fnuz type"""
  202. return self._to(torch.float8_e5m2fnuz)
  203. def float8_e4m3fnuz(self):
  204. """Casts this storage to float8_e4m3fnuz type"""
  205. return self._to(torch.float8_e4m3fnuz)
  206. def is_pinned(self, device: Union[str, torch.device] = 'cuda'):
  207. r"""Determine whether the CPU storage is already pinned on device.
  208. Args:
  209. device (str or torch.device): The device to pin memory on. Default: ``'cuda'``.
  210. Returns:
  211. A boolean variable.
  212. """
  213. return torch.tensor([], dtype=torch.uint8, device=self.device).set_(
  214. cast(Storage, self)).is_pinned(device)
  215. def pin_memory(self, device: Union[str, torch.device] = 'cuda'):
  216. r"""Copy the CPU storage to pinned memory, if it's not already pinned.
  217. Args:
  218. device (str or torch.device): The device to pin memory on. Default: ``'cuda'``.
  219. Returns:
  220. A pinned CPU storage.
  221. """
  222. if self.device.type != 'cpu':
  223. raise TypeError(f"cannot pin '{self.type()}' only CPU memory can be pinned")
  224. pinned_tensor = torch.tensor([], dtype=torch.uint8, device=self.device).set_(
  225. cast(Storage, self)).pin_memory(device)
  226. return pinned_tensor.untyped_storage()
  227. def share_memory_(self):
  228. """See :meth:`torch.UntypedStorage.share_memory_`"""
  229. from torch.multiprocessing import get_sharing_strategy
  230. if self.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]:
  231. pass # CUDA or PrivateUse1 doesn't use POSIX shared memory
  232. elif get_sharing_strategy() == 'file_system':
  233. self._share_filename_cpu_()
  234. else:
  235. self._share_fd_cpu_()
  236. return self
  237. @classmethod
  238. def _new_shared(cls, size, *, device='cpu'):
  239. """Create a new storage in shared memory with the same data type."""
  240. from torch.multiprocessing import get_sharing_strategy
  241. device = torch.device(device)
  242. if device.type in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]:
  243. return cls(size, device=device)
  244. elif get_sharing_strategy() == 'file_system':
  245. return cls._new_using_filename_cpu(size)
  246. else:
  247. return cls._new_using_fd_cpu(size)
  248. def untyped(self):
  249. return self
  250. def byteswap(self, dtype):
  251. """Swap bytes in underlying data."""
  252. elem_size = torch._utils._element_size(dtype)
  253. # for complex types, don't swap first and second numbers
  254. if dtype.is_complex:
  255. elem_size = max(int(elem_size / 2), 1)
  256. self._byteswap(elem_size)
  257. def _share_memory_lock_protected(fn):
  258. @functools.wraps(fn)
  259. def wrapper(self, *args, **kwargs):
  260. to_free = None
  261. to_wait = None
  262. with _share_memory_lock:
  263. key = self._cdata
  264. if key in _share_memory_map:
  265. to_wait = _share_memory_map[key]
  266. else:
  267. _share_memory_map[key] = threading.RLock()
  268. _share_memory_map[key].acquire()
  269. to_free = key
  270. # If we're already in the process of sharing the storage, wait
  271. # for it to be done.
  272. if to_wait is not None:
  273. with to_wait:
  274. pass
  275. try:
  276. return fn(self, *args, **kwargs)
  277. finally:
  278. # If we acquired the storage lock here and we're done working on it
  279. # we can now release it and free the entry.
  280. if to_free is not None:
  281. # Ensure that the cdata from the storage didn't change and only
  282. # the data_ptr did.
  283. assert self._cdata == to_free
  284. with _share_memory_lock:
  285. _share_memory_map[to_free].release()
  286. del _share_memory_map[to_free]
  287. return wrapper
  288. class UntypedStorage(torch._C.StorageBase, _StorageBase):
  289. def __getitem__(self, *args, **kwargs):
  290. if self.device.type == 'meta':
  291. raise NotImplementedError("Not available for 'meta' device type")
  292. return super().__getitem__(*args, **kwargs)
  293. @property
  294. def is_cuda(self):
  295. return self.device.type == 'cuda'
  296. @property
  297. def is_hpu(self):
  298. return self.device.type == 'hpu'
  299. @property
  300. def filename(self) -> _Optional[str]:
  301. """Returns the file name associated with this storage if the storage was memory mapped from a file.
  302. or ``None`` if the storage was not created by memory mapping a file."""
  303. return self._get_filename()
  304. @_share_memory_lock_protected
  305. def share_memory_(self, *args, **kwargs):
  306. """
  307. Moves the storage to shared memory.
  308. This is a no-op for storages already in shared memory and for CUDA
  309. storages, which do not need to be moved for sharing across processes.
  310. Storages in shared memory cannot be resized.
  311. Note that to mitigate issues like `this <https://github.com/pytorch/pytorch/issues/95606>`_
  312. it is thread safe to call this function from multiple threads on the same object.
  313. It is NOT thread safe though to call any other function on self without proper
  314. synchronization. Please see :doc:`/notes/multiprocessing` for more details.
  315. .. note::
  316. When all references to a storage in shared memory are deleted, the associated shared memory
  317. object will also be deleted. PyTorch has a special cleanup process to ensure that this happens
  318. even if the current process exits unexpectedly.
  319. It is worth noting the difference between :meth:`share_memory_` and :meth:`from_file` with ``shared = True``
  320. #. ``share_memory_`` uses `shm_open(3) <https://man7.org/linux/man-pages/man3/shm_open.3.html>`_ to create a
  321. POSIX shared memory object while :meth:`from_file` uses
  322. `open(2) <https://man7.org/linux/man-pages/man2/open.2.html>`_ to open the filename passed by the user.
  323. #. Both use an `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_ with ``MAP_SHARED``
  324. to map the file/object into the current virtual address space
  325. #. ``share_memory_`` will call ``shm_unlink(3)`` on the object after mapping it to make sure the shared memory
  326. object is freed when no process has the object open. ``torch.from_file(shared=True)`` does not unlink the
  327. file. This file is persistent and will remain until it is deleted by the user.
  328. Returns:
  329. ``self``
  330. """
  331. return super().share_memory_(*args, **kwargs)
  332. @_share_memory_lock_protected
  333. def _share_fd_cpu_(self, *args, **kwargs):
  334. return super()._share_fd_cpu_(*args, **kwargs)
  335. @_share_memory_lock_protected
  336. def _share_filename_cpu_(self, *args, **kwargs):
  337. return super()._share_filename_cpu_(*args, **kwargs)
  338. def _load_from_bytes(b):
  339. return torch.load(io.BytesIO(b), weights_only=False)
  340. _StorageBase.type = _type # type: ignore[assignment]
  341. @lru_cache(maxsize=None)
  342. def _new_dtypes():
  343. # These are dtypes serialized as UntypedStorage unlike those in
  344. # _dtype_to_storage_type_map
  345. return {
  346. torch.float8_e5m2,
  347. torch.float8_e4m3fn,
  348. torch.float8_e5m2fnuz,
  349. torch.float8_e4m3fnuz,
  350. torch.bits8,
  351. torch.bits16,
  352. torch.bits1x8,
  353. torch.bits2x4,
  354. torch.bits4x2,
  355. torch.complex32,
  356. }
  357. @lru_cache(maxsize=None)
  358. def _dtype_to_storage_type_map():
  359. # NOTE: We should no longer add dtypes to this map. This map
  360. # is only used for BC/FC with older PyTorch versions. Going forward,
  361. # new dtypes of TypedStorage should not translate to a legacy
  362. # <type>Storage class. Instead, new dtypes of TypedStorage should
  363. # be serialized as an UntypedStorage paired with a torch.dtype
  364. return {
  365. torch.double: 'DoubleStorage',
  366. torch.float: 'FloatStorage',
  367. torch.half: 'HalfStorage',
  368. torch.long: 'LongStorage',
  369. torch.int: 'IntStorage',
  370. torch.int16: 'ShortStorage',
  371. torch.int8: 'CharStorage',
  372. torch.uint8: 'ByteStorage',
  373. torch.bool: 'BoolStorage',
  374. torch.bfloat16: 'BFloat16Storage',
  375. torch.cdouble: 'ComplexDoubleStorage',
  376. torch.cfloat: 'ComplexFloatStorage',
  377. torch.qint8: 'QInt8Storage',
  378. torch.qint32: 'QInt32Storage',
  379. torch.quint8: 'QUInt8Storage',
  380. torch.quint4x2: 'QUInt4x2Storage',
  381. torch.quint2x4: 'QUInt2x4Storage',
  382. }
  383. @lru_cache(maxsize=None)
  384. def _storage_type_to_dtype_map():
  385. dtype_map = {
  386. val: key for key, val in _dtype_to_storage_type_map().items()}
  387. return dtype_map
  388. def _get_storage_from_sequence(sequence, dtype, device):
  389. if dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  390. interpret_dtypes = {
  391. torch.quint8: torch.uint8,
  392. torch.quint4x2: torch.uint8,
  393. torch.quint2x4: torch.uint8,
  394. torch.qint32: torch.int32,
  395. torch.qint8: torch.int8
  396. }
  397. tmp_tensor = torch.tensor(
  398. sequence,
  399. dtype=interpret_dtypes[dtype],
  400. device=device)
  401. else:
  402. tmp_tensor = torch.tensor(
  403. sequence,
  404. dtype=dtype,
  405. device=device)
  406. return tmp_tensor._typed_storage()._untyped_storage
  407. def _isint(x):
  408. if HAS_NUMPY:
  409. return isinstance(x, (int, np.integer))
  410. else:
  411. return isinstance(x, int)
  412. _always_warn_typed_storage_removal = False
  413. def _get_always_warn_typed_storage_removal():
  414. return _always_warn_typed_storage_removal
  415. def _set_always_warn_typed_storage_removal(always_warn):
  416. global _always_warn_typed_storage_removal
  417. assert isinstance(always_warn, bool)
  418. _always_warn_typed_storage_removal = always_warn
  419. def _warn_typed_storage_removal(stacklevel=2):
  420. global _always_warn_typed_storage_removal
  421. def is_first_time():
  422. if not hasattr(_warn_typed_storage_removal, 'has_warned'):
  423. return True
  424. else:
  425. return not _warn_typed_storage_removal.__dict__['has_warned']
  426. if _get_always_warn_typed_storage_removal() or is_first_time():
  427. message = (
  428. "TypedStorage is deprecated. It will be removed in the future and "
  429. "UntypedStorage will be the only storage class. This should only matter "
  430. "to you if you are using storages directly. To access UntypedStorage "
  431. "directly, use tensor.untyped_storage() instead of tensor.storage()"
  432. )
  433. warnings.warn(message, UserWarning, stacklevel=stacklevel + 1)
  434. _warn_typed_storage_removal.__dict__['has_warned'] = True
  435. def _reset_warn_typed_storage_removal():
  436. _warn_typed_storage_removal.__dict__['has_warned'] = False
  437. def _get_device_from_module(module: str):
  438. last_part = module.rsplit(".", 1)[-1]
  439. if last_part in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]:
  440. return last_part
  441. else:
  442. return "cpu"
  443. class TypedStorage:
  444. is_sparse = False
  445. dtype: torch.dtype
  446. @property
  447. def _dtype(self):
  448. return self.dtype
  449. @property
  450. def filename(self) -> _Optional[str]:
  451. """Returns the file name associated with this storage if the storage was memory mapped from a file.
  452. or ``None`` if the storage was not created by memory mapping a file."""
  453. return self._untyped_storage.filename
  454. def fill_(self, value):
  455. _warn_typed_storage_removal()
  456. self._setitem(slice(0, self._size()), value)
  457. return self
  458. def __new__(cls, *args, wrap_storage=None, dtype=None, device=None, _internal=False):
  459. if not _internal:
  460. _warn_typed_storage_removal()
  461. if cls == torch.storage._LegacyStorage:
  462. raise RuntimeError("Only child classes of _LegacyStorage can be instantiated")
  463. if cls == TypedStorage:
  464. return super().__new__(cls)
  465. else:
  466. arg_error_msg = (
  467. f'{cls}.__new__ received an invalid combination '
  468. f'of arguments. Expected one of:\n'
  469. ' * no arguments\n'
  470. ' * (int size)\n'
  471. ' * (Sequence data)\n'
  472. ' * (*, UntypedStorage wrap_storage)')
  473. if device is not None:
  474. raise RuntimeError(
  475. arg_error_msg +
  476. "\nKeyword argument 'device' cannot be specified")
  477. if dtype is not None:
  478. raise RuntimeError(
  479. arg_error_msg +
  480. "\nKeyword argument 'dtype' cannot be specified")
  481. if wrap_storage is None:
  482. if len(args) > 1:
  483. raise RuntimeError(
  484. arg_error_msg +
  485. "\nToo many positional arguments")
  486. if len(args) == 1 and not _isint(args[0]) and not isinstance(args[0], collections.abc.Sequence):
  487. raise TypeError(
  488. arg_error_msg +
  489. f"\nArgument type not recognized: {type(args[0])}")
  490. return TypedStorage(
  491. *args,
  492. dtype=cls._dtype,
  493. device=_get_device_from_module(cls.__module__),
  494. _internal=True)
  495. else:
  496. if len(args) != 0:
  497. raise RuntimeError(
  498. arg_error_msg +
  499. "\nNo positional arguments should be given when using "
  500. "'wrap_storage'")
  501. if not isinstance(wrap_storage, torch.UntypedStorage):
  502. raise TypeError(
  503. arg_error_msg +
  504. f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}")
  505. cls_device = _get_device_from_module(cls.__module__)
  506. if wrap_storage.device.type != cls_device:
  507. raise RuntimeError(
  508. arg_error_msg +
  509. f"\nDevice of 'wrap_storage' must be {cls_device}"
  510. f", but got {wrap_storage.device.type}")
  511. return TypedStorage(
  512. *args,
  513. wrap_storage=wrap_storage,
  514. dtype=cls.dtype,
  515. _internal=True)
  516. def __init__(self, *args, device=None, dtype=None, wrap_storage=None, _internal=False):
  517. if not _internal:
  518. _warn_typed_storage_removal()
  519. arg_error_msg = (
  520. 'TypedStorage.__init__ received an invalid combination '
  521. 'of arguments. Expected one of:\n'
  522. ' * (*, torch.device device, torch.dtype dtype)\n'
  523. ' * (int size, *, torch.device device, torch.dtype dtype)\n'
  524. ' * (Sequence data, *, torch.device device, torch.dtype dtype)\n'
  525. ' * (*, UntypedStorage wrap_storage, torch.dtype dtype)')
  526. if wrap_storage is not None:
  527. if len(args) != 0:
  528. raise RuntimeError(
  529. arg_error_msg +
  530. "\nNo positional arguments should be given when using "
  531. "'wrap_storage'")
  532. if dtype is None:
  533. raise RuntimeError(
  534. arg_error_msg +
  535. "\nArgument 'dtype' must be specified")
  536. if not isinstance(dtype, torch.dtype):
  537. raise TypeError(
  538. arg_error_msg +
  539. f"\nArgument 'dtype' must be torch.dtype, not {type(dtype)}")
  540. if device is not None:
  541. raise RuntimeError(
  542. arg_error_msg +
  543. "\nArgument 'device' should not be specified when 'wrap_storage' is given")
  544. self.dtype = dtype
  545. if not isinstance(wrap_storage, torch.UntypedStorage):
  546. raise TypeError(
  547. arg_error_msg +
  548. f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}")
  549. self._untyped_storage = wrap_storage
  550. else:
  551. self.dtype = torch.get_default_dtype() if dtype is None else dtype
  552. device = torch.device('cpu' if device is None else device)
  553. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  554. if device.type == 'cuda':
  555. raise RuntimeError("Cannot create CUDA storage with quantized dtype")
  556. if len(args) == 0:
  557. self._untyped_storage = torch.UntypedStorage(device=device)
  558. elif len(args) == 1:
  559. if _isint(args[0]):
  560. self._untyped_storage = torch.UntypedStorage(int(args[0]) * self._element_size(), device=device)
  561. elif isinstance(args[0], collections.abc.Sequence):
  562. self._untyped_storage = _get_storage_from_sequence(args[0], self.dtype, device)
  563. else:
  564. raise TypeError(
  565. arg_error_msg +
  566. f"\nArgument type not recognized: {type(args[0])}")
  567. else:
  568. raise RuntimeError(
  569. arg_error_msg +
  570. "\nToo many positional arguments")
  571. @property
  572. def is_cuda(self):
  573. _warn_typed_storage_removal()
  574. return self._untyped_storage.device.type == 'cuda'
  575. @property
  576. def is_hpu(self):
  577. _warn_typed_storage_removal()
  578. return self._untyped_storage.device.type == 'hpu'
  579. def untyped(self):
  580. """Return the internal :class:`torch.UntypedStorage`."""
  581. _warn_typed_storage_removal()
  582. return self._untyped_storage
  583. def _new_wrapped_storage(self, untyped_storage):
  584. assert type(untyped_storage) == torch.UntypedStorage
  585. if type(self) == TypedStorage:
  586. return TypedStorage(
  587. wrap_storage=untyped_storage,
  588. dtype=self.dtype,
  589. _internal=True)
  590. else:
  591. return type(self)(wrap_storage=untyped_storage)
  592. def __len__(self):
  593. _warn_typed_storage_removal()
  594. return self._size()
  595. def _maybe_wrap_index(self, idx, is_stop=False):
  596. if idx is None:
  597. if is_stop:
  598. return self._size()
  599. else:
  600. return 0
  601. else:
  602. if type(idx) != int:
  603. raise TypeError(
  604. f"can't index a {type(self)} with {type(idx)}")
  605. if is_stop:
  606. if (idx > self._size()) or (idx < -self._size()):
  607. raise IndexError(
  608. f'index {idx} out of range for storage of size {self.size()}')
  609. if idx > 0:
  610. return idx
  611. else:
  612. return idx % self._size()
  613. else:
  614. if (idx >= self._size()) or (idx < -self._size()):
  615. raise IndexError(
  616. f'index {idx} out of range for storage of size {self.size()}')
  617. return idx % self._size()
  618. def __setitem__(self, idx, value):
  619. _warn_typed_storage_removal()
  620. return self._setitem(idx, value)
  621. def _setitem(self, idx, value):
  622. if not isinstance(idx, (int, slice)):
  623. raise RuntimeError(f"can't index a {type(self)} with {type(idx)}")
  624. if torch.is_storage(value):
  625. raise RuntimeError(f'cannot set item with value type {type(value)}')
  626. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  627. interpret_dtypes = {
  628. torch.quint8: torch.uint8,
  629. torch.quint4x2: torch.uint8,
  630. torch.quint2x4: torch.uint8,
  631. torch.qint32: torch.int32,
  632. torch.qint8: torch.int8
  633. }
  634. tmp_dtype = interpret_dtypes[self.dtype]
  635. tmp_tensor = torch.tensor([], dtype=tmp_dtype, device=self._untyped_storage.device)
  636. tmp_tensor.set_(TypedStorage(
  637. wrap_storage=self._untyped_storage,
  638. dtype=tmp_dtype,
  639. _internal=True))
  640. else:
  641. tmp_tensor = torch.tensor([], dtype=self.dtype, device=self._untyped_storage.device).set_(self)
  642. tmp_tensor[idx] = value
  643. def __getitem__(self, idx):
  644. _warn_typed_storage_removal()
  645. return self._getitem(idx)
  646. def _getitem(self, idx):
  647. if self._untyped_storage.device.type == 'meta':
  648. raise NotImplementedError("Not available for 'meta' device type")
  649. # NOTE: Before TypedStorage existed, indexing with a slice used to be
  650. # possible for <type>Storage objects. However, it would return
  651. # a storage view, which would be a hassle to implement in TypedStorage,
  652. # so it was disabled
  653. if isinstance(idx, slice):
  654. raise RuntimeError('slices are only supported in UntypedStorage.__getitem__')
  655. elif not isinstance(idx, int):
  656. raise RuntimeError(f"can't index a {type(self)} with {type(idx)}")
  657. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  658. interpret_dtypes = {
  659. torch.quint8: torch.uint8,
  660. torch.quint4x2: torch.uint8,
  661. torch.quint2x4: torch.uint8,
  662. torch.qint32: torch.int32,
  663. torch.qint8: torch.int8
  664. }
  665. return TypedStorage(
  666. wrap_storage=self._untyped_storage,
  667. dtype=interpret_dtypes[self.dtype],
  668. _internal=True)._getitem(idx)
  669. idx_wrapped = self._maybe_wrap_index(idx)
  670. from torch._subclasses.fake_tensor import unset_fake_temporarily
  671. with unset_fake_temporarily():
  672. tmp_tensor = torch.tensor([], dtype=self.dtype, device=self._untyped_storage.device).set_(self)
  673. return tmp_tensor[idx_wrapped].item()
  674. def copy_(self, source: T, non_blocking: _Optional[bool] = None):
  675. _warn_typed_storage_removal()
  676. if isinstance(source, TypedStorage):
  677. self._untyped_storage.copy_(source._untyped_storage, non_blocking) # type: ignore[arg-type]
  678. else:
  679. self._untyped_storage.copy_(source, non_blocking) # type: ignore[arg-type]
  680. return self
  681. def nbytes(self):
  682. _warn_typed_storage_removal()
  683. return self._nbytes()
  684. # For internal use only, to avoid deprecation warning
  685. def _nbytes(self):
  686. return self._untyped_storage.nbytes()
  687. def type(self, dtype: _Optional[str] = None, non_blocking: bool = False) -> Union[T, str]:
  688. _warn_typed_storage_removal()
  689. if dtype is None:
  690. legacy_class = self._get_legacy_storage_class()
  691. if legacy_class is not None:
  692. return legacy_class.__module__ + '.' + legacy_class.__name__
  693. return '.'.join([self.__module__, type(self).__name__])
  694. else:
  695. return self._untyped_storage.type(dtype, non_blocking)
  696. def cuda(self, device=None, non_blocking=False) -> T: # type: ignore[misc, type-var]
  697. _warn_typed_storage_removal()
  698. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  699. raise RuntimeError("Cannot create CUDA storage with quantized dtype")
  700. cuda_storage: torch.UntypedStorage = self._untyped_storage.cuda(device, non_blocking)
  701. return self._new_wrapped_storage(cuda_storage)
  702. def hpu(self, device=None, non_blocking=False) -> T: # type: ignore[misc, type-var]
  703. _warn_typed_storage_removal()
  704. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  705. raise RuntimeError("Cannot create HPU storage with quantized dtype")
  706. hpu_storage: torch.UntypedStorage = self._untyped_storage.hpu(device, non_blocking)
  707. return self._new_wrapped_storage(hpu_storage)
  708. def to(self, *, device: torch.device, non_blocking: bool = False) -> T: # type: ignore[type-var, misc]
  709. _warn_typed_storage_removal()
  710. if self.dtype in [torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8]:
  711. raise RuntimeError(f"Cannot create {device.type.upper()} storage with quantized dtype")
  712. to_storage: torch.UntypedStorage = self._untyped_storage.to(device=device, non_blocking=non_blocking)
  713. return self._new_wrapped_storage(to_storage)
  714. def element_size(self):
  715. _warn_typed_storage_removal()
  716. return self._element_size()
  717. # For internal use only, to avoid deprecation warning
  718. def _element_size(self):
  719. return torch._utils._element_size(self.dtype)
  720. def get_device(self) -> int:
  721. _warn_typed_storage_removal()
  722. return self._untyped_storage.get_device()
  723. def __str__(self):
  724. _warn_typed_storage_removal()
  725. info_str = (
  726. f'[{torch.typename(self)}(dtype={self.dtype}, '
  727. f'device={self.device}) of size {len(self)}]')
  728. if self.device.type == 'meta':
  729. return '...\n' + info_str
  730. else:
  731. data_str = ' ' + '\n '.join(str(self[i]) for i in range(self.size()))
  732. return data_str + '\n' + info_str
  733. def __repr__(self):
  734. _warn_typed_storage_removal()
  735. return str(self)
  736. def __iter__(self):
  737. _warn_typed_storage_removal()
  738. return iter(self[i] for i in range(self.size()))
  739. def __copy__(self):
  740. _warn_typed_storage_removal()
  741. return self._new_wrapped_storage(copy.copy(self._untyped_storage))
  742. def __deepcopy__(self, memo):
  743. _warn_typed_storage_removal()
  744. return self._deepcopy(memo)
  745. # For internal use only, to avoid deprecation warning
  746. def _deepcopy(self, memo):
  747. return self._new_wrapped_storage(copy.deepcopy(self._untyped_storage, memo))
  748. def __sizeof__(self):
  749. _warn_typed_storage_removal()
  750. return super().__sizeof__() + self.nbytes()
  751. def clone(self):
  752. """Return a copy of this storage."""
  753. _warn_typed_storage_removal()
  754. return self._new_wrapped_storage(self._untyped_storage.clone())
  755. def tolist(self):
  756. """Return a list containing the elements of this storage."""
  757. _warn_typed_storage_removal()
  758. return list(self)
  759. def cpu(self):
  760. """Return a CPU copy of this storage if it's not already on the CPU."""
  761. _warn_typed_storage_removal()
  762. return self._new_wrapped_storage(self._untyped_storage.cpu())
  763. def is_pinned(self, device: Union[str, torch.device] = 'cuda'):
  764. r"""Determine whether the CPU TypedStorage is already pinned on device.
  765. Args:
  766. device (str or torch.device): The device to pin memory on. Default: ``'cuda'``
  767. Returns:
  768. A boolean variable.
  769. """
  770. _warn_typed_storage_removal()
  771. return self._untyped_storage.is_pinned(device)
  772. def pin_memory(self, device: Union[str, torch.device] = 'cuda'):
  773. r"""Copy the CPU TypedStorage to pinned memory, if it's not already pinned.
  774. Args:
  775. device (str or torch.device): The device to pin memory on. Default: ``'cuda'``.
  776. Returns:
  777. A pinned CPU storage.
  778. """
  779. _warn_typed_storage_removal()
  780. return self._new_wrapped_storage(self._untyped_storage.pin_memory(device=device))
  781. def share_memory_(self):
  782. """See :meth:`torch.UntypedStorage.share_memory_`"""
  783. _warn_typed_storage_removal()
  784. return self._share_memory_()
  785. # For internal use only, to avoid deprecation warning
  786. def _share_memory_(self):
  787. self._untyped_storage.share_memory_()
  788. return self
  789. def _new_shared(self, size, *, device=None):
  790. """Create a new storage in shared memory with the same data type."""
  791. if device is None:
  792. device = 'cpu'
  793. device = torch.device(device)
  794. untyped_storage = torch.UntypedStorage._new_shared(size * self._element_size(), device=device)
  795. return TypedStorage(
  796. wrap_storage=untyped_storage,
  797. dtype=self.dtype,
  798. _internal=True)
  799. @property
  800. def _cdata(self):
  801. return self._untyped_storage._cdata
  802. @property
  803. def device(self):
  804. _warn_typed_storage_removal()
  805. return self._untyped_storage.device
  806. def size(self):
  807. _warn_typed_storage_removal()
  808. return self._size()
  809. # For internal use only, to avoid deprecation warning
  810. def _size(self):
  811. # NB: don't indirect through __len__, as that requires
  812. # an int to be returned
  813. return self._untyped_storage.nbytes() // self._element_size()
  814. def pickle_storage_type(self):
  815. _warn_typed_storage_removal()
  816. return self._pickle_storage_type()
  817. # For internal use only, to avoid deprecation warning
  818. def _pickle_storage_type(self):
  819. try:
  820. return _dtype_to_storage_type_map()[self.dtype]
  821. except KeyError as e:
  822. raise KeyError(f'dtype {self.dtype} is not recognized') from e
  823. def __reduce__(self):
  824. b = io.BytesIO()
  825. torch.save(self, b, _use_new_zipfile_serialization=False)
  826. return (_load_from_bytes, (b.getvalue(),))
  827. def data_ptr(self):
  828. _warn_typed_storage_removal()
  829. return self._data_ptr()
  830. # For internal use only, to avoid deprecation warning
  831. def _data_ptr(self):
  832. return self._untyped_storage.data_ptr()
  833. def resizable(self):
  834. _warn_typed_storage_removal()
  835. return self._untyped_storage.resizable()
  836. def resize_(self, size):
  837. _warn_typed_storage_removal()
  838. self._resize_(size)
  839. # For internal use only, to avoid deprecation warning
  840. def _resize_(self, size):
  841. self._untyped_storage.resize_(size * self._element_size())
  842. @classmethod
  843. def _free_weak_ref(cls, *args, **kwargs):
  844. return UntypedStorage._free_weak_ref(*args, **kwargs)
  845. def _weak_ref(self, *args, **kwargs):
  846. return self._untyped_storage._weak_ref(*args, **kwargs)
  847. @classmethod
  848. def from_buffer(cls, *args, **kwargs):
  849. _warn_typed_storage_removal()
  850. return cls._from_buffer(*args, **kwargs)
  851. @classmethod
  852. def _from_buffer(cls, *args, dtype=None, device=None, **kwargs):
  853. if cls == TypedStorage:
  854. dtype = torch.get_default_dtype() if dtype is None else dtype
  855. device = torch.device('cpu' if device is None else device)
  856. if device.type != 'cpu':
  857. raise RuntimeError(f'TypedStorage.from_buffer: Not available for device {device.type}')
  858. untyped_storage: torch.UntypedStorage = torch.UntypedStorage.from_buffer(*args, dtype=dtype, **kwargs)
  859. else:
  860. if dtype is not None or len(args) == 5:
  861. raise RuntimeError(
  862. "from_buffer: 'dtype' can only be specified in "
  863. "UntypedStorage.from_buffer and TypedStorage.from_buffer")
  864. if device is not None:
  865. raise RuntimeError(
  866. "from_buffer: 'device' can only be specified in "
  867. "UntypedStorage.from_buffer and TypedStorage.from_buffer")
  868. dtype = cls._dtype
  869. untyped_storage = torch.UntypedStorage.from_buffer(*args, dtype=dtype, **kwargs)
  870. return TypedStorage(
  871. wrap_storage=untyped_storage,
  872. dtype=dtype,
  873. _internal=True)
  874. def _to(self, dtype):
  875. if not isinstance(dtype, torch.dtype):
  876. raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}")
  877. storage = torch.tensor([], dtype=self.dtype, device=self.device).set_(self).to(dtype)._typed_storage()
  878. if storage.data_ptr() == self.data_ptr():
  879. storage = storage.clone()
  880. return storage
  881. def double(self):
  882. """Casts this storage to double type."""
  883. _warn_typed_storage_removal()
  884. return self._to(torch.double)
  885. def float(self):
  886. """Casts this storage to float type."""
  887. _warn_typed_storage_removal()
  888. return self._to(torch.float)
  889. def half(self):
  890. """Casts this storage to half type."""
  891. _warn_typed_storage_removal()
  892. return self._to(torch.half)
  893. def long(self):
  894. """Casts this storage to long type."""
  895. _warn_typed_storage_removal()
  896. return self._to(torch.long)
  897. def int(self):
  898. """Casts this storage to int type."""
  899. _warn_typed_storage_removal()
  900. return self._to(torch.int)
  901. def short(self):
  902. """Casts this storage to short type."""
  903. _warn_typed_storage_removal()
  904. return self._to(torch.short)
  905. def char(self):
  906. """Casts this storage to char type."""
  907. _warn_typed_storage_removal()
  908. return self._to(torch.int8)
  909. def byte(self):
  910. """Casts this storage to byte type."""
  911. _warn_typed_storage_removal()
  912. return self._to(torch.uint8)
  913. def bool(self):
  914. """Casts this storage to bool type."""
  915. _warn_typed_storage_removal()
  916. return self._to(torch.bool)
  917. def bfloat16(self):
  918. """Casts this storage to bfloat16 type."""
  919. _warn_typed_storage_removal()
  920. return self._to(torch.bfloat16)
  921. def complex_double(self):
  922. """Casts this storage to complex double type."""
  923. _warn_typed_storage_removal()
  924. return self._to(torch.cdouble)
  925. def complex_float(self):
  926. """Casts this storage to complex float type."""
  927. _warn_typed_storage_removal()
  928. return self._to(torch.cfloat)
  929. def float8_e5m2(self):
  930. """Casts this storage to float8_e5m2 type"""
  931. _warn_typed_storage_removal()
  932. return self._to(torch.float8_e5m2)
  933. def float8_e4m3fn(self):
  934. """Casts this storage to float8_e4m3fn type"""
  935. _warn_typed_storage_removal()
  936. return self._to(torch.float8_e4m3fn)
  937. def float8_e5m2fnuz(self):
  938. """Casts this storage to float8_e5m2fnuz type"""
  939. _warn_typed_storage_removal()
  940. return self._to(torch.float8_e5m2fnuz)
  941. def float8_e4m3fnuz(self):
  942. """Casts this storage to float8_e4m3fnuz type"""
  943. _warn_typed_storage_removal()
  944. return self._to(torch.float8_e4m3fnuz)
  945. @classmethod
  946. def from_file(cls, filename, shared, size):
  947. """from_file(filename, shared=False, size=0) -> Storage
  948. Creates a CPU storage backed by a memory-mapped file.
  949. If ``shared`` is ``True``, then memory is shared between all processes.
  950. All changes are written to the file. If ``shared`` is ``False``, then the changes on
  951. the storage do not affect the file.
  952. ``size`` is the number of elements in the storage. If ``shared`` is ``False``,
  953. then the file must contain at least ``size * sizeof(Type)`` bytes
  954. (``Type`` is the type of storage). If ``shared`` is ``True`` the file will be created if needed.
  955. Args:
  956. filename (str): file name to map
  957. shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the
  958. underlying `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_)
  959. size (int): number of elements in the storage
  960. """
  961. _warn_typed_storage_removal()
  962. if cls == TypedStorage:
  963. raise RuntimeError('from_file can only be called on derived classes')
  964. untyped_storage: UntypedStorage = UntypedStorage.from_file(
  965. filename,
  966. shared,
  967. size * torch._utils._element_size(cls.dtype))
  968. storage = cls(wrap_storage=untyped_storage)
  969. return storage
  970. @classmethod
  971. def _expired(cls, *args, **kwargs):
  972. return UntypedStorage._expired(*args, **kwargs)
  973. def _write_file(self, *args, **kwargs):
  974. return self._untyped_storage._write_file(*args, **kwargs)
  975. def _set_from_file(self, *args, **kwargs):
  976. return self._untyped_storage._set_from_file(*args, **kwargs)
  977. def _set_cdata(self, *args, **kwargs):
  978. return self._untyped_storage._set_cdata(*args, **kwargs)
  979. def _share_cuda_(self, *args, **kwargs):
  980. return self._untyped_storage._share_cuda_(*args, **kwargs)
  981. def is_shared(self):
  982. _warn_typed_storage_removal()
  983. return self._is_shared()
  984. # For internal use only, to avoid deprecation warning
  985. def _is_shared(self):
  986. return self._untyped_storage.is_shared()
  987. @classmethod
  988. def _new_shared_cuda(cls, *args, **kwargs):
  989. return torch.UntypedStorage._new_shared_cuda(*args, **kwargs)
  990. def _share_filename_cpu_(self, *args, **kwargs):
  991. manager_handle, storage_handle, size = self._untyped_storage._share_filename_cpu_(*args, **kwargs)
  992. return manager_handle, storage_handle, size // self._element_size()
  993. def _shared_decref(self):
  994. self._untyped_storage._shared_decref()
  995. return self
  996. @classmethod
  997. def _release_ipc_counter(cls, *args, device=None, **kwargs):
  998. return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
  999. def _shared_incref(self, *args, **kwargs):
  1000. return self._untyped_storage._shared_incref(*args, **kwargs)
  1001. def _share_fd_cpu_(self, *args, **kwargs):
  1002. fd, size = self._untyped_storage._share_fd_cpu_(*args, **kwargs)
  1003. return fd, size // self._element_size()
  1004. def _get_legacy_storage_class(self):
  1005. if self.dtype not in _dtype_to_storage_type_map():
  1006. return None
  1007. storage_name = _dtype_to_storage_type_map()[self.dtype]
  1008. if self.device.type not in ['cpu', 'cuda', "hpu", torch._C._get_privateuse1_backend_name()]:
  1009. return None
  1010. module = torch if self.device.type == 'cpu' else getattr(torch, self.device.type)
  1011. try:
  1012. return getattr(module, storage_name)
  1013. except AttributeError:
  1014. return None
  1015. TypedStorage.type.__doc__ = _type.__doc__
  1016. TypedStorage.cuda.__doc__ = _StorageBase.cuda.__doc__
  1017. TypedStorage.hpu.__doc__ = _StorageBase.hpu.__doc__
  1018. TypedStorage.to.__doc__ = _to.__doc__
  1019. class _LegacyStorageMeta(type):
  1020. dtype: torch.dtype
  1021. def __instancecheck__(cls, instance):
  1022. if type(instance) == TypedStorage:
  1023. cls_device = _get_device_from_module(cls.__module__)
  1024. return (cls_device == instance.device.type) and (cls.dtype == instance.dtype)
  1025. return False
  1026. class _LegacyStorage(TypedStorage, metaclass=_LegacyStorageMeta):
  1027. @classmethod
  1028. def _new_shared(cls, size):
  1029. """Create a new storage in shared memory with the same data type."""
  1030. untyped_storage = torch.UntypedStorage._new_shared(size * cls()._element_size())
  1031. return cls(wrap_storage=untyped_storage)
  1032. @classmethod
  1033. def _release_ipc_counter(cls, *args, **kwargs):
  1034. return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
  1035. @classmethod
  1036. def _new_shared_filename(cls, manager, obj, size):
  1037. bytes_size = size * torch._utils._element_size(cls.dtype)
  1038. return cls(wrap_storage=torch.UntypedStorage._new_shared_filename_cpu(manager, obj, bytes_size))
  1039. def _get_dtype_from_pickle_storage_type(pickle_storage_type: str):
  1040. try:
  1041. return _storage_type_to_dtype_map()[pickle_storage_type]
  1042. except KeyError as e:
  1043. raise KeyError(
  1044. f'pickle storage type "{pickle_storage_type}" is not recognized') from e