storage.py 51 KB

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