storage.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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. assert self._cdata == to_free
  352. with _share_memory_lock:
  353. _share_memory_map[to_free].release()
  354. del _share_memory_map[to_free]
  355. return wrapper
  356. class UntypedStorage(torch._C.StorageBase, _StorageBase):
  357. def __getitem__(self, *args, **kwargs):
  358. if self.device.type == "meta":
  359. raise NotImplementedError("Not available for 'meta' device type")
  360. return super().__getitem__(*args, **kwargs)
  361. @property
  362. def is_cuda(self):
  363. return self.device.type == "cuda"
  364. @property
  365. def is_hpu(self):
  366. return self.device.type == "hpu"
  367. @property
  368. def filename(self) -> str | None:
  369. """Returns the file name associated with this storage.
  370. The file name will be a string if the storage is on CPU and was created via
  371. :meth:`~torch.from_file()` with ``shared`` as ``True``. This attribute is ``None`` otherwise.
  372. """
  373. return self._get_filename()
  374. @_share_memory_lock_protected
  375. def share_memory_(self, *args, **kwargs):
  376. """
  377. Moves the storage to shared memory.
  378. This is a no-op for storages already in shared memory and for CUDA
  379. storages, which do not need to be moved for sharing across processes.
  380. Storages in shared memory cannot be resized.
  381. Note that to mitigate issues like `this <https://github.com/pytorch/pytorch/issues/95606>`_
  382. it is thread safe to call this function from multiple threads on the same object.
  383. It is NOT thread safe though to call any other function on self without proper
  384. synchronization. Please see :doc:`/notes/multiprocessing` for more details.
  385. .. note::
  386. When all references to a storage in shared memory are deleted, the associated shared memory
  387. object will also be deleted. PyTorch has a special cleanup process to ensure that this happens
  388. even if the current process exits unexpectedly.
  389. It is worth noting the difference between :meth:`share_memory_` and :meth:`from_file` with ``shared = True``
  390. #. ``share_memory_`` uses `shm_open(3) <https://man7.org/linux/man-pages/man3/shm_open.3.html>`_ to create a
  391. POSIX shared memory object while :meth:`from_file` uses
  392. `open(2) <https://man7.org/linux/man-pages/man2/open.2.html>`_ to open the filename passed by the user.
  393. #. Both use an `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_ with ``MAP_SHARED``
  394. to map the file/object into the current virtual address space
  395. #. ``share_memory_`` will call ``shm_unlink(3)`` on the object after mapping it to make sure the shared memory
  396. object is freed when no process has the object open. ``torch.from_file(shared=True)`` does not unlink the
  397. file. This file is persistent and will remain until it is deleted by the user.
  398. Returns:
  399. ``self``
  400. """
  401. return super().share_memory_(*args, **kwargs)
  402. @_share_memory_lock_protected
  403. def _share_fd_cpu_(self, *args, **kwargs):
  404. return super()._share_fd_cpu_(*args, **kwargs)
  405. @_share_memory_lock_protected
  406. def _share_filename_cpu_(self, *args, **kwargs):
  407. return super()._share_filename_cpu_(*args, **kwargs)
  408. def _load_from_bytes(b):
  409. return torch.load(io.BytesIO(b), weights_only=False)
  410. @functools.cache
  411. def _new_dtypes():
  412. # These are dtypes serialized as UntypedStorage unlike those in
  413. # _dtype_to_storage_type_map
  414. return {
  415. torch.float8_e5m2,
  416. torch.float8_e4m3fn,
  417. torch.float8_e5m2fnuz,
  418. torch.float8_e4m3fnuz,
  419. torch.float8_e8m0fnu,
  420. torch.float4_e2m1fn_x2,
  421. torch.bits8,
  422. torch.bits16,
  423. torch.bits1x8,
  424. torch.bits2x4,
  425. torch.bits4x2,
  426. torch.complex32,
  427. torch.uint16,
  428. torch.uint32,
  429. torch.uint64,
  430. }
  431. @functools.cache
  432. def _dtype_to_storage_type_map():
  433. # NOTE: We should no longer add dtypes to this map. This map
  434. # is only used for BC/FC with older PyTorch versions. Going forward,
  435. # new dtypes of TypedStorage should not translate to a legacy
  436. # <type>Storage class. Instead, new dtypes of TypedStorage should
  437. # be serialized as an UntypedStorage paired with a torch.dtype
  438. return {
  439. torch.double: "DoubleStorage",
  440. torch.float: "FloatStorage",
  441. torch.half: "HalfStorage",
  442. torch.long: "LongStorage",
  443. torch.int: "IntStorage",
  444. torch.int16: "ShortStorage",
  445. torch.int8: "CharStorage",
  446. torch.uint8: "ByteStorage",
  447. torch.bool: "BoolStorage",
  448. torch.bfloat16: "BFloat16Storage",
  449. torch.cdouble: "ComplexDoubleStorage",
  450. torch.cfloat: "ComplexFloatStorage",
  451. torch.qint8: "QInt8Storage",
  452. torch.qint32: "QInt32Storage",
  453. torch.quint8: "QUInt8Storage",
  454. torch.quint4x2: "QUInt4x2Storage",
  455. torch.quint2x4: "QUInt2x4Storage",
  456. }
  457. @functools.cache
  458. def _storage_type_to_dtype_map():
  459. dtype_map = {val: key for key, val in _dtype_to_storage_type_map().items()}
  460. return dtype_map
  461. def _get_storage_from_sequence(sequence, dtype, device):
  462. if dtype in [
  463. torch.quint8,
  464. torch.quint4x2,
  465. torch.quint2x4,
  466. torch.qint32,
  467. torch.qint8,
  468. ]:
  469. interpret_dtypes = {
  470. torch.quint8: torch.uint8,
  471. torch.quint4x2: torch.uint8,
  472. torch.quint2x4: torch.uint8,
  473. torch.qint32: torch.int32,
  474. torch.qint8: torch.int8,
  475. }
  476. tmp_tensor = torch.tensor(
  477. sequence, dtype=interpret_dtypes[dtype], device=device
  478. )
  479. else:
  480. tmp_tensor = torch.tensor(sequence, dtype=dtype, device=device)
  481. return tmp_tensor._typed_storage()._untyped_storage
  482. def _isint(x):
  483. if HAS_NUMPY:
  484. return isinstance(x, (int, np.integer)) # pyrefly: ignore [missing-attribute]
  485. else:
  486. return isinstance(x, int)
  487. _always_warn_typed_storage_removal = False
  488. def _get_always_warn_typed_storage_removal():
  489. return _always_warn_typed_storage_removal
  490. def _set_always_warn_typed_storage_removal(always_warn):
  491. global _always_warn_typed_storage_removal
  492. assert isinstance(always_warn, bool)
  493. _always_warn_typed_storage_removal = always_warn
  494. def _warn_typed_storage_removal(stacklevel=2):
  495. global _always_warn_typed_storage_removal
  496. def is_first_time():
  497. if not hasattr(_warn_typed_storage_removal, "has_warned"):
  498. return True
  499. else:
  500. return not _warn_typed_storage_removal.__dict__["has_warned"]
  501. if _get_always_warn_typed_storage_removal() or is_first_time():
  502. message = (
  503. "TypedStorage is deprecated. It will be removed in the future and "
  504. "UntypedStorage will be the only storage class. This should only matter "
  505. "to you if you are using storages directly. To access UntypedStorage "
  506. "directly, use tensor.untyped_storage() instead of tensor.storage()"
  507. )
  508. warnings.warn(message, UserWarning, stacklevel=stacklevel + 1)
  509. _warn_typed_storage_removal.__dict__["has_warned"] = True
  510. def _reset_warn_typed_storage_removal():
  511. _warn_typed_storage_removal.__dict__["has_warned"] = False
  512. def _get_device_from_module(module: str):
  513. last_part = module.rsplit(".", 1)[-1]
  514. if last_part in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]:
  515. return last_part
  516. else:
  517. return "cpu"
  518. class TypedStorage:
  519. is_sparse: _bool = False
  520. # Used when stashing FakeTensor device onto storage in torch.save(metadata_only=True)
  521. _fake_device: torch.device | None = None
  522. dtype: torch.dtype
  523. @property
  524. def _dtype(self):
  525. return self.dtype
  526. @property
  527. def filename(self) -> str | None:
  528. """Returns the file name associated with this storage if the storage was memory mapped from a file.
  529. or ``None`` if the storage was not created by memory mapping a file."""
  530. return self._untyped_storage.filename
  531. def fill_(self, value):
  532. _warn_typed_storage_removal()
  533. self._setitem(slice(0, self._size()), value)
  534. return self
  535. def __new__(
  536. cls,
  537. *args,
  538. wrap_storage=None,
  539. dtype=None,
  540. device=None,
  541. _internal=False,
  542. ):
  543. if not _internal:
  544. _warn_typed_storage_removal()
  545. if cls == torch.storage._LegacyStorage:
  546. raise RuntimeError(
  547. "Only child classes of _LegacyStorage can be instantiated"
  548. )
  549. if cls == TypedStorage:
  550. return super().__new__(cls)
  551. else:
  552. arg_error_msg = (
  553. f"{cls}.__new__ received an invalid combination "
  554. f"of arguments. Expected one of:\n"
  555. " * no arguments\n"
  556. " * (int size)\n"
  557. " * (Sequence data)\n"
  558. " * (*, UntypedStorage wrap_storage)"
  559. )
  560. if device is not None:
  561. raise RuntimeError(
  562. arg_error_msg + "\nKeyword argument 'device' cannot be specified"
  563. )
  564. if dtype is not None:
  565. raise RuntimeError(
  566. arg_error_msg + "\nKeyword argument 'dtype' cannot be specified"
  567. )
  568. if wrap_storage is None:
  569. if len(args) > 1:
  570. raise RuntimeError(
  571. arg_error_msg + "\nToo many positional arguments"
  572. )
  573. if (
  574. len(args) == 1
  575. and not _isint(args[0])
  576. and not isinstance(args[0], collections.abc.Sequence)
  577. ):
  578. raise TypeError(
  579. arg_error_msg
  580. + f"\nArgument type not recognized: {type(args[0])}"
  581. )
  582. return TypedStorage(
  583. *args,
  584. dtype=cls._dtype,
  585. device=_get_device_from_module(cls.__module__),
  586. _internal=True,
  587. )
  588. else:
  589. if len(args) != 0:
  590. raise RuntimeError(
  591. arg_error_msg
  592. + "\nNo positional arguments should be given when using "
  593. "'wrap_storage'"
  594. )
  595. if not isinstance(wrap_storage, torch.UntypedStorage):
  596. raise TypeError(
  597. arg_error_msg
  598. + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}"
  599. )
  600. cls_device = _get_device_from_module(cls.__module__)
  601. if wrap_storage.device.type != cls_device:
  602. raise RuntimeError(
  603. arg_error_msg
  604. + f"\nDevice of 'wrap_storage' must be {cls_device}"
  605. f", but got {wrap_storage.device.type}"
  606. )
  607. return TypedStorage(
  608. *args,
  609. wrap_storage=wrap_storage,
  610. dtype=cls.dtype,
  611. _internal=True,
  612. )
  613. def __init__(
  614. self,
  615. *args,
  616. device=None,
  617. dtype=None,
  618. wrap_storage=None,
  619. _internal=False,
  620. ):
  621. if not _internal:
  622. _warn_typed_storage_removal()
  623. arg_error_msg = (
  624. "TypedStorage.__init__ received an invalid combination "
  625. "of arguments. Expected one of:\n"
  626. " * (*, torch.device device, torch.dtype dtype)\n"
  627. " * (int size, *, torch.device device, torch.dtype dtype)\n"
  628. " * (Sequence data, *, torch.device device, torch.dtype dtype)\n"
  629. " * (*, UntypedStorage wrap_storage, torch.dtype dtype)"
  630. )
  631. if wrap_storage is not None:
  632. if len(args) != 0:
  633. raise RuntimeError(
  634. arg_error_msg
  635. + "\nNo positional arguments should be given when using "
  636. "'wrap_storage'"
  637. )
  638. if dtype is None:
  639. raise RuntimeError(
  640. arg_error_msg + "\nArgument 'dtype' must be specified"
  641. )
  642. if not isinstance(dtype, torch.dtype):
  643. raise TypeError(
  644. arg_error_msg
  645. + f"\nArgument 'dtype' must be torch.dtype, not {type(dtype)}"
  646. )
  647. if device is not None:
  648. raise RuntimeError(
  649. arg_error_msg
  650. + "\nArgument 'device' should not be specified when 'wrap_storage' is given"
  651. )
  652. self.dtype = dtype
  653. if not isinstance(wrap_storage, torch.UntypedStorage):
  654. raise TypeError(
  655. arg_error_msg
  656. + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}"
  657. )
  658. self._untyped_storage = wrap_storage
  659. else:
  660. self.dtype = torch.get_default_dtype() if dtype is None else dtype
  661. device = torch.device("cpu" if device is None else device)
  662. if self.dtype in [
  663. torch.quint8,
  664. torch.quint4x2,
  665. torch.quint2x4,
  666. torch.qint32,
  667. torch.qint8,
  668. ]:
  669. if device.type == "cuda":
  670. raise RuntimeError(
  671. "Cannot create CUDA storage with quantized dtype"
  672. )
  673. if len(args) == 0:
  674. self._untyped_storage = torch.UntypedStorage(device=device)
  675. elif len(args) == 1:
  676. if _isint(args[0]):
  677. self._untyped_storage = torch.UntypedStorage(
  678. int(args[0]) * self._element_size(), device=device
  679. )
  680. elif isinstance(args[0], collections.abc.Sequence):
  681. self._untyped_storage = _get_storage_from_sequence(
  682. args[0], self.dtype, device
  683. )
  684. else:
  685. raise TypeError(
  686. arg_error_msg
  687. + f"\nArgument type not recognized: {type(args[0])}"
  688. )
  689. else:
  690. raise RuntimeError(arg_error_msg + "\nToo many positional arguments")
  691. @property
  692. def is_cuda(self):
  693. _warn_typed_storage_removal()
  694. return self._untyped_storage.device.type == "cuda"
  695. @property
  696. def is_hpu(self):
  697. _warn_typed_storage_removal()
  698. return self._untyped_storage.device.type == "hpu"
  699. def untyped(self):
  700. """Return the internal :class:`torch.UntypedStorage`."""
  701. _warn_typed_storage_removal()
  702. return self._untyped_storage
  703. def _new_wrapped_storage(self, untyped_storage) -> Self:
  704. assert type(untyped_storage) is torch.UntypedStorage
  705. if type(self) is TypedStorage:
  706. return cast(
  707. Self,
  708. TypedStorage(
  709. wrap_storage=untyped_storage, dtype=self.dtype, _internal=True
  710. ),
  711. )
  712. else:
  713. return type(self)(wrap_storage=untyped_storage)
  714. def __len__(self):
  715. _warn_typed_storage_removal()
  716. return self._size()
  717. def _maybe_wrap_index(self, idx, is_stop=False):
  718. if idx is None:
  719. if is_stop:
  720. return self._size()
  721. else:
  722. return 0
  723. else:
  724. if type(idx) is not int:
  725. raise TypeError(f"can't index a {type(self)} with {type(idx)}")
  726. if is_stop:
  727. if (idx > self._size()) or (idx < -self._size()):
  728. raise IndexError(
  729. f"index {idx} out of range for storage of size {self.size()}"
  730. )
  731. if idx > 0:
  732. return idx
  733. else:
  734. return idx % self._size()
  735. else:
  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. return idx % self._size()
  741. def __setitem__(self, idx, value):
  742. _warn_typed_storage_removal()
  743. return self._setitem(idx, value)
  744. def _setitem(self, idx, value):
  745. if not isinstance(idx, (int, slice)):
  746. raise RuntimeError(f"can't index a {type(self)} with {type(idx)}")
  747. if torch.is_storage(value):
  748. raise RuntimeError(f"cannot set item with value type {type(value)}")
  749. if self.dtype in [
  750. torch.quint8,
  751. torch.quint4x2,
  752. torch.quint2x4,
  753. torch.qint32,
  754. torch.qint8,
  755. ]:
  756. interpret_dtypes = {
  757. torch.quint8: torch.uint8,
  758. torch.quint4x2: torch.uint8,
  759. torch.quint2x4: torch.uint8,
  760. torch.qint32: torch.int32,
  761. torch.qint8: torch.int8,
  762. }
  763. tmp_dtype = interpret_dtypes[self.dtype]
  764. tmp_tensor = torch.tensor(
  765. [], dtype=tmp_dtype, device=self._untyped_storage.device
  766. )
  767. tmp_tensor.set_(
  768. TypedStorage(
  769. wrap_storage=self._untyped_storage, dtype=tmp_dtype, _internal=True
  770. )
  771. )
  772. else:
  773. tmp_tensor = torch.tensor(
  774. [], dtype=self.dtype, device=self._untyped_storage.device
  775. ).set_(self)
  776. tmp_tensor[idx] = value
  777. def __getitem__(self, idx):
  778. _warn_typed_storage_removal()
  779. return self._getitem(idx)
  780. def _getitem(self, idx):
  781. if self._untyped_storage.device.type == "meta":
  782. raise NotImplementedError("Not available for 'meta' device type")
  783. # NOTE: Before TypedStorage existed, indexing with a slice used to be
  784. # possible for <type>Storage objects. However, it would return
  785. # a storage view, which would be a hassle to implement in TypedStorage,
  786. # so it was disabled
  787. if isinstance(idx, slice):
  788. raise RuntimeError(
  789. "slices are only supported in UntypedStorage.__getitem__"
  790. )
  791. elif not isinstance(idx, int):
  792. raise RuntimeError(f"can't index a {type(self)} with {type(idx)}")
  793. if self.dtype in [
  794. torch.quint8,
  795. torch.quint4x2,
  796. torch.quint2x4,
  797. torch.qint32,
  798. torch.qint8,
  799. ]:
  800. interpret_dtypes = {
  801. torch.quint8: torch.uint8,
  802. torch.quint4x2: torch.uint8,
  803. torch.quint2x4: torch.uint8,
  804. torch.qint32: torch.int32,
  805. torch.qint8: torch.int8,
  806. }
  807. return TypedStorage(
  808. wrap_storage=self._untyped_storage,
  809. dtype=interpret_dtypes[self.dtype],
  810. _internal=True,
  811. )._getitem(idx)
  812. idx_wrapped = self._maybe_wrap_index(idx)
  813. from torch._subclasses.fake_tensor import unset_fake_temporarily
  814. with unset_fake_temporarily():
  815. tmp_tensor = torch.tensor(
  816. [], dtype=self.dtype, device=self._untyped_storage.device
  817. ).set_(self)
  818. return tmp_tensor[idx_wrapped].item()
  819. def copy_(self, source: T, non_blocking: bool | None = None):
  820. _warn_typed_storage_removal()
  821. if isinstance(source, TypedStorage):
  822. self._untyped_storage.copy_(source._untyped_storage, non_blocking)
  823. else:
  824. self._untyped_storage.copy_(source, non_blocking)
  825. return self
  826. def nbytes(self):
  827. _warn_typed_storage_removal()
  828. return self._nbytes()
  829. # For internal use only, to avoid deprecation warning
  830. def _nbytes(self):
  831. return self._untyped_storage.nbytes()
  832. def type(
  833. self,
  834. dtype: str | None = None,
  835. non_blocking: bool = False,
  836. ) -> _StorageBase | TypedStorage | str:
  837. _warn_typed_storage_removal()
  838. if dtype is None:
  839. legacy_class = self._get_legacy_storage_class()
  840. if legacy_class is not None:
  841. return legacy_class.__module__ + "." + legacy_class.__name__
  842. return ".".join([self.__module__, type(self).__name__])
  843. else:
  844. return self._untyped_storage.type(dtype, non_blocking)
  845. def cuda(self, device=None, non_blocking=False) -> Self:
  846. _warn_typed_storage_removal()
  847. if self.dtype in [
  848. torch.quint8,
  849. torch.quint4x2,
  850. torch.quint2x4,
  851. torch.qint32,
  852. torch.qint8,
  853. ]:
  854. raise RuntimeError("Cannot create CUDA storage with quantized dtype")
  855. cuda_storage = self._untyped_storage.cuda(device, non_blocking)
  856. return self._new_wrapped_storage(cuda_storage)
  857. def hpu(self, device=None, non_blocking=False) -> Self:
  858. _warn_typed_storage_removal()
  859. if self.dtype in [
  860. torch.quint8,
  861. torch.quint4x2,
  862. torch.quint2x4,
  863. torch.qint32,
  864. torch.qint8,
  865. ]:
  866. raise RuntimeError("Cannot create HPU storage with quantized dtype")
  867. hpu_storage = self._untyped_storage.hpu(device, non_blocking)
  868. return self._new_wrapped_storage(hpu_storage)
  869. def to(self, *, device: DeviceLikeType, non_blocking: bool = False) -> Self:
  870. _warn_typed_storage_removal()
  871. if not isinstance(device, torch.device):
  872. device = torch.device(device)
  873. if self.dtype in [
  874. torch.quint8,
  875. torch.quint4x2,
  876. torch.quint2x4,
  877. torch.qint32,
  878. torch.qint8,
  879. ]:
  880. raise RuntimeError(
  881. f"Cannot create {device.type.upper()} storage with quantized dtype"
  882. )
  883. to_storage = self._untyped_storage.to(device=device, non_blocking=non_blocking)
  884. return self._new_wrapped_storage(to_storage)
  885. def element_size(self):
  886. _warn_typed_storage_removal()
  887. return self._element_size()
  888. # For internal use only, to avoid deprecation warning
  889. def _element_size(self):
  890. return torch._utils._element_size(self.dtype)
  891. def get_device(self) -> _int:
  892. _warn_typed_storage_removal()
  893. return self._untyped_storage.get_device()
  894. def __str__(self):
  895. _warn_typed_storage_removal()
  896. info_str = (
  897. f"[{torch.typename(self)}(dtype={self.dtype}, "
  898. f"device={self.device}) of size {len(self)}]"
  899. )
  900. if self.device.type == "meta":
  901. return "...\n" + info_str
  902. else:
  903. data_str = " " + "\n ".join(str(self[i]) for i in range(self.size()))
  904. return data_str + "\n" + info_str
  905. def __repr__(self):
  906. _warn_typed_storage_removal()
  907. return str(self)
  908. def __iter__(self):
  909. _warn_typed_storage_removal()
  910. return iter(self[i] for i in range(self.size()))
  911. def __copy__(self):
  912. _warn_typed_storage_removal()
  913. return self._new_wrapped_storage(copy.copy(self._untyped_storage))
  914. def __deepcopy__(self, memo):
  915. _warn_typed_storage_removal()
  916. return self._deepcopy(memo)
  917. # For internal use only, to avoid deprecation warning
  918. def _deepcopy(self, memo):
  919. return self._new_wrapped_storage(copy.deepcopy(self._untyped_storage, memo))
  920. def __sizeof__(self):
  921. _warn_typed_storage_removal()
  922. return super().__sizeof__() + self.nbytes()
  923. def clone(self):
  924. """Return a copy of this storage."""
  925. _warn_typed_storage_removal()
  926. return self._new_wrapped_storage(self._untyped_storage.clone())
  927. def tolist(self):
  928. """Return a list containing the elements of this storage."""
  929. _warn_typed_storage_removal()
  930. return list(self)
  931. def cpu(self):
  932. """Return a CPU copy of this storage if it's not already on the CPU."""
  933. _warn_typed_storage_removal()
  934. return self._new_wrapped_storage(self._untyped_storage.cpu())
  935. def is_pinned(self, device: str | torch.device = "cuda"):
  936. r"""Determine whether the CPU TypedStorage is already pinned on device.
  937. Args:
  938. device (str or torch.device): The device to pin memory on (default: ``'cuda'``).
  939. This argument is discouraged and subject to deprecated.
  940. Returns:
  941. A boolean variable.
  942. """
  943. _warn_typed_storage_removal()
  944. return self._untyped_storage.is_pinned(device)
  945. def pin_memory(self, device: str | torch.device = "cuda"):
  946. r"""Copy the CPU TypedStorage to pinned memory, if it's not already pinned.
  947. Args:
  948. device (str or torch.device): The device to pin memory on (default: ``'cuda'``).
  949. This argument is discouraged and subject to deprecated.
  950. Returns:
  951. A pinned CPU storage.
  952. """
  953. _warn_typed_storage_removal()
  954. return self._new_wrapped_storage(
  955. self._untyped_storage.pin_memory(device=device)
  956. )
  957. def share_memory_(self):
  958. """See :meth:`torch.UntypedStorage.share_memory_`"""
  959. _warn_typed_storage_removal()
  960. return self._share_memory_()
  961. # For internal use only, to avoid deprecation warning
  962. def _share_memory_(self):
  963. self._untyped_storage.share_memory_()
  964. return self
  965. def _new_shared(self, size, *, device=None):
  966. """Create a new storage in shared memory with the same data type."""
  967. if device is None:
  968. device = "cpu"
  969. device = torch.device(device)
  970. untyped_storage = torch.UntypedStorage._new_shared(
  971. size * self._element_size(), device=device
  972. )
  973. return TypedStorage(
  974. wrap_storage=untyped_storage, dtype=self.dtype, _internal=True
  975. )
  976. @property
  977. def _cdata(self):
  978. return self._untyped_storage._cdata
  979. @property
  980. def device(self):
  981. _warn_typed_storage_removal()
  982. return self._untyped_storage.device
  983. def size(self):
  984. _warn_typed_storage_removal()
  985. return self._size()
  986. # For internal use only, to avoid deprecation warning
  987. def _size(self):
  988. # NB: don't indirect through __len__, as that requires
  989. # an int to be returned
  990. return self._untyped_storage.nbytes() // self._element_size()
  991. def pickle_storage_type(self):
  992. _warn_typed_storage_removal()
  993. return self._pickle_storage_type()
  994. # For internal use only, to avoid deprecation warning
  995. def _pickle_storage_type(self):
  996. try:
  997. return _dtype_to_storage_type_map()[self.dtype]
  998. except KeyError as e:
  999. raise KeyError(f"dtype {self.dtype} is not recognized") from e
  1000. def __reduce__(self):
  1001. b = io.BytesIO()
  1002. torch.save(self, b, _use_new_zipfile_serialization=False)
  1003. return (_load_from_bytes, (b.getvalue(),))
  1004. def data_ptr(self):
  1005. _warn_typed_storage_removal()
  1006. return self._data_ptr()
  1007. # For internal use only, to avoid deprecation warning
  1008. def _data_ptr(self):
  1009. return self._untyped_storage.data_ptr()
  1010. def resizable(self):
  1011. _warn_typed_storage_removal()
  1012. return self._untyped_storage.resizable()
  1013. def resize_(self, size):
  1014. _warn_typed_storage_removal()
  1015. self._resize_(size)
  1016. # For internal use only, to avoid deprecation warning
  1017. def _resize_(self, size):
  1018. self._untyped_storage.resize_(size * self._element_size())
  1019. @classmethod
  1020. def _free_weak_ref(cls, *args, **kwargs):
  1021. return UntypedStorage._free_weak_ref(*args, **kwargs)
  1022. def _weak_ref(self, *args, **kwargs):
  1023. return self._untyped_storage._weak_ref(*args, **kwargs)
  1024. @classmethod
  1025. def from_buffer(cls, *args, **kwargs):
  1026. _warn_typed_storage_removal()
  1027. return cls._from_buffer(*args, **kwargs)
  1028. @classmethod
  1029. def _from_buffer(cls, *args, dtype=None, device=None, **kwargs):
  1030. if cls == TypedStorage:
  1031. dtype = torch.get_default_dtype() if dtype is None else dtype
  1032. device = torch.device("cpu" if device is None else device)
  1033. if device.type != "cpu":
  1034. raise RuntimeError(
  1035. f"TypedStorage.from_buffer: Not available for device {device.type}"
  1036. )
  1037. untyped_storage: torch.UntypedStorage = torch.UntypedStorage.from_buffer(
  1038. *args, dtype=dtype, **kwargs
  1039. )
  1040. else:
  1041. if dtype is not None or len(args) == 5:
  1042. raise RuntimeError(
  1043. "from_buffer: 'dtype' can only be specified in "
  1044. "UntypedStorage.from_buffer and TypedStorage.from_buffer"
  1045. )
  1046. if device is not None:
  1047. raise RuntimeError(
  1048. "from_buffer: 'device' can only be specified in "
  1049. "UntypedStorage.from_buffer and TypedStorage.from_buffer"
  1050. )
  1051. dtype = cls._dtype
  1052. untyped_storage = torch.UntypedStorage.from_buffer(
  1053. *args, dtype=dtype, **kwargs
  1054. )
  1055. return TypedStorage(wrap_storage=untyped_storage, dtype=dtype, _internal=True)
  1056. def _to(self, dtype):
  1057. if not isinstance(dtype, torch.dtype):
  1058. raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}")
  1059. storage = (
  1060. torch.tensor([], dtype=self.dtype, device=self.device)
  1061. .set_(self)
  1062. .to(dtype)
  1063. ._typed_storage()
  1064. )
  1065. if storage.data_ptr() == self.data_ptr():
  1066. storage = storage.clone()
  1067. return storage
  1068. def double(self):
  1069. """Casts this storage to double type."""
  1070. _warn_typed_storage_removal()
  1071. return self._to(torch.double)
  1072. def float(self):
  1073. """Casts this storage to float type."""
  1074. _warn_typed_storage_removal()
  1075. return self._to(torch.float)
  1076. def half(self):
  1077. """Casts this storage to half type."""
  1078. _warn_typed_storage_removal()
  1079. return self._to(torch.half)
  1080. def long(self):
  1081. """Casts this storage to long type."""
  1082. _warn_typed_storage_removal()
  1083. return self._to(torch.long)
  1084. def int(self):
  1085. """Casts this storage to int type."""
  1086. _warn_typed_storage_removal()
  1087. return self._to(torch.int)
  1088. def short(self):
  1089. """Casts this storage to short type."""
  1090. _warn_typed_storage_removal()
  1091. return self._to(torch.short)
  1092. def char(self):
  1093. """Casts this storage to char type."""
  1094. _warn_typed_storage_removal()
  1095. return self._to(torch.int8)
  1096. def byte(self):
  1097. """Casts this storage to byte type."""
  1098. _warn_typed_storage_removal()
  1099. return self._to(torch.uint8)
  1100. def bool(self):
  1101. """Casts this storage to bool type."""
  1102. _warn_typed_storage_removal()
  1103. return self._to(torch.bool)
  1104. def bfloat16(self):
  1105. """Casts this storage to bfloat16 type."""
  1106. _warn_typed_storage_removal()
  1107. return self._to(torch.bfloat16)
  1108. def complex_double(self):
  1109. """Casts this storage to complex double type."""
  1110. _warn_typed_storage_removal()
  1111. return self._to(torch.cdouble)
  1112. def complex_float(self):
  1113. """Casts this storage to complex float type."""
  1114. _warn_typed_storage_removal()
  1115. return self._to(torch.cfloat)
  1116. def float8_e5m2(self):
  1117. """Casts this storage to float8_e5m2 type"""
  1118. _warn_typed_storage_removal()
  1119. return self._to(torch.float8_e5m2)
  1120. def float8_e4m3fn(self):
  1121. """Casts this storage to float8_e4m3fn type"""
  1122. _warn_typed_storage_removal()
  1123. return self._to(torch.float8_e4m3fn)
  1124. def float8_e5m2fnuz(self):
  1125. """Casts this storage to float8_e5m2fnuz type"""
  1126. _warn_typed_storage_removal()
  1127. return self._to(torch.float8_e5m2fnuz)
  1128. def float8_e4m3fnuz(self):
  1129. """Casts this storage to float8_e4m3fnuz type"""
  1130. _warn_typed_storage_removal()
  1131. return self._to(torch.float8_e4m3fnuz)
  1132. @classmethod
  1133. def from_file(cls, filename, shared, size):
  1134. """from_file(filename, shared=False, size=0) -> Storage
  1135. Creates a CPU storage backed by a memory-mapped file.
  1136. If ``shared`` is ``True``, then memory is shared between all processes.
  1137. All changes are written to the file. If ``shared`` is ``False``, then the changes on
  1138. the storage do not affect the file.
  1139. ``size`` is the number of elements in the storage. If ``shared`` is ``False``,
  1140. then the file must contain at least ``size * sizeof(Type)`` bytes
  1141. (``Type`` is the type of storage). If ``shared`` is ``True`` the file will be created if needed.
  1142. Args:
  1143. filename (str): file name to map
  1144. shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the
  1145. underlying `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_)
  1146. size (int): number of elements in the storage
  1147. """
  1148. _warn_typed_storage_removal()
  1149. if cls == TypedStorage:
  1150. raise RuntimeError("from_file can only be called on derived classes")
  1151. untyped_storage = UntypedStorage.from_file(
  1152. filename, shared, size * torch._utils._element_size(cls.dtype)
  1153. )
  1154. storage = cls(wrap_storage=untyped_storage)
  1155. return storage
  1156. @classmethod
  1157. def _expired(cls, *args, **kwargs):
  1158. return UntypedStorage._expired(*args, **kwargs)
  1159. def _write_file(self, *args, **kwargs):
  1160. return self._untyped_storage._write_file(*args, **kwargs)
  1161. def _set_from_file(self, *args, **kwargs):
  1162. return self._untyped_storage._set_from_file(*args, **kwargs)
  1163. def _set_cdata(self, *args, **kwargs):
  1164. return self._untyped_storage._set_cdata(*args, **kwargs)
  1165. def _share_cuda_(self, *args, **kwargs):
  1166. return self._untyped_storage._share_cuda_(*args, **kwargs)
  1167. def is_shared(self):
  1168. _warn_typed_storage_removal()
  1169. return self._is_shared()
  1170. # For internal use only, to avoid deprecation warning
  1171. def _is_shared(self):
  1172. return self._untyped_storage.is_shared()
  1173. @classmethod
  1174. def _new_shared_cuda(cls, *args, **kwargs):
  1175. return torch.UntypedStorage._new_shared_cuda(*args, **kwargs)
  1176. def _share_filename_cpu_(self, *args, **kwargs):
  1177. (
  1178. manager_handle,
  1179. storage_handle,
  1180. size,
  1181. ) = self._untyped_storage._share_filename_cpu_(*args, **kwargs)
  1182. return manager_handle, storage_handle, size // self._element_size()
  1183. def _shared_decref(self):
  1184. self._untyped_storage._shared_decref()
  1185. return self
  1186. @classmethod
  1187. def _release_ipc_counter(cls, *args, device=None, **kwargs):
  1188. return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
  1189. def _shared_incref(self, *args, **kwargs):
  1190. return self._untyped_storage._shared_incref(*args, **kwargs)
  1191. def _share_fd_cpu_(self, *args, **kwargs):
  1192. fd, size = self._untyped_storage._share_fd_cpu_(*args, **kwargs)
  1193. return fd, size // self._element_size()
  1194. def _get_legacy_storage_class(self):
  1195. if self.dtype not in _dtype_to_storage_type_map():
  1196. return None
  1197. storage_name = _dtype_to_storage_type_map()[self.dtype]
  1198. if self.device.type not in [
  1199. "cpu",
  1200. "cuda",
  1201. "hpu",
  1202. torch._C._get_privateuse1_backend_name(),
  1203. ]:
  1204. return None
  1205. module = (
  1206. torch if self.device.type == "cpu" else getattr(torch, self.device.type)
  1207. )
  1208. try:
  1209. return getattr(module, storage_name)
  1210. except AttributeError:
  1211. return None
  1212. TypedStorage.type.__doc__ = _type.__doc__
  1213. TypedStorage.cuda.__doc__ = _StorageBase.cuda.__doc__
  1214. TypedStorage.hpu.__doc__ = _StorageBase.hpu.__doc__
  1215. TypedStorage.to.__doc__ = _to.__doc__
  1216. class _LegacyStorageMeta(type):
  1217. dtype: torch.dtype
  1218. def __instancecheck__(cls, instance):
  1219. if type(instance) is TypedStorage:
  1220. cls_device = _get_device_from_module(cls.__module__)
  1221. return (cls_device == instance.device.type) and (
  1222. cls.dtype == instance.dtype
  1223. )
  1224. return False
  1225. class _LegacyStorage(TypedStorage, metaclass=_LegacyStorageMeta):
  1226. @classmethod
  1227. def _new_shared(cls, size): # type: ignore[override]
  1228. """Create a new storage in shared memory with the same data type."""
  1229. untyped_storage = torch.UntypedStorage._new_shared(size * cls()._element_size())
  1230. return cls(wrap_storage=untyped_storage)
  1231. @classmethod
  1232. def _release_ipc_counter(cls, *args, **kwargs):
  1233. return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
  1234. @classmethod
  1235. def _new_shared_filename(cls, manager, obj, size):
  1236. bytes_size = size * torch._utils._element_size(cls.dtype)
  1237. return cls(
  1238. wrap_storage=torch.UntypedStorage._new_shared_filename_cpu(
  1239. manager, obj, bytes_size
  1240. )
  1241. )
  1242. def _get_dtype_from_pickle_storage_type(pickle_storage_type: str):
  1243. try:
  1244. return _storage_type_to_dtype_map()[pickle_storage_type]
  1245. except KeyError as e:
  1246. raise KeyError(
  1247. f'pickle storage type "{pickle_storage_type}" is not recognized'
  1248. ) from e