storage.py 51 KB

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