serialization.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  1. # mypy: allow-untyped-defs
  2. import copyreg
  3. import difflib
  4. import functools
  5. import io
  6. import os
  7. import pickle
  8. import re
  9. import shutil
  10. import struct
  11. import sys
  12. import tarfile
  13. import tempfile
  14. import threading
  15. import warnings
  16. from collections.abc import Callable
  17. from contextlib import closing, contextmanager
  18. from enum import Enum
  19. from typing import Any, cast, Generic, IO, TypeAlias, TypeVar
  20. from typing_extensions import TypeIs
  21. import torch
  22. import torch._weights_only_unpickler as _weights_only_unpickler
  23. from torch._sources import get_source_lines_and_file
  24. from torch._utils import _import_dotted_name
  25. from torch.storage import _get_dtype_from_pickle_storage_type
  26. from torch.types import FileLike, Storage
  27. __all__ = [
  28. "SourceChangeWarning",
  29. "mkdtemp",
  30. "register_package",
  31. "check_module_version_greater_or_equal",
  32. "validate_cuda_device",
  33. "validate_hpu_device",
  34. "location_tag",
  35. "default_restore_location",
  36. "normalize_storage_type",
  37. "storage_to_tensor_type",
  38. "save",
  39. "load",
  40. "StorageType",
  41. "LoadEndianness",
  42. "get_crc32_options",
  43. "set_crc32_options",
  44. "get_default_load_endianness",
  45. "set_default_load_endianness",
  46. "get_default_mmap_options",
  47. "set_default_mmap_options",
  48. "clear_safe_globals",
  49. "get_safe_globals",
  50. "add_safe_globals",
  51. "safe_globals",
  52. "get_unsafe_globals_in_checkpoint",
  53. "skip_data",
  54. ]
  55. DEFAULT_PROTOCOL = 2
  56. LONG_SIZE = struct.Struct("=l").size
  57. INT_SIZE = struct.Struct("=i").size
  58. SHORT_SIZE = struct.Struct("=h").size
  59. MAGIC_NUMBER = 0x1950A86A20F9469CFC6C
  60. PROTOCOL_VERSION = 1001
  61. STORAGE_KEY_SEPARATOR = ","
  62. MAP_LOCATION: TypeAlias = (
  63. Callable[[Storage, str], Storage] | torch.device | str | dict[str, str] | None
  64. )
  65. STORAGE: TypeAlias = Storage | torch.storage.TypedStorage | torch.UntypedStorage
  66. IS_WINDOWS = sys.platform == "win32"
  67. UNSAFE_MESSAGE = (
  68. "In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` "
  69. "from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, "
  70. "but it can result in arbitrary code execution. Do it only if you got the file from a "
  71. "trusted source."
  72. )
  73. if not IS_WINDOWS:
  74. from mmap import MAP_PRIVATE, MAP_SHARED
  75. else:
  76. MAP_SHARED, MAP_PRIVATE = None, None # type: ignore[assignment]
  77. def _default_to_weights_only(pickle_module):
  78. is_fbcode = not hasattr(torch.version, "git_version")
  79. return pickle_module is None and not is_fbcode
  80. # _serialization_tls is used to store thread local state specific to serialization
  81. # that needs to be propagated to other files, in particular we use this for
  82. # (1) map_location (needed for wrapper subclasses/third party devices to torch._utils)
  83. # (2) skip_data (needed for torch.Tensor.__reduce_ex__ for skip_data ctx)
  84. # (3) materialize_fake_tensors (needed for torch.Tensor.__reduce_ex__ for skip_data ctx)
  85. class _SerializationLocal(threading.local):
  86. def __init__(self):
  87. super().__init__()
  88. self.map_location: MAP_LOCATION | None = None
  89. self.skip_data: bool = False
  90. self.materialize_fake_tensors: bool = False
  91. _serialization_tls = _SerializationLocal()
  92. class SourceChangeWarning(Warning):
  93. pass
  94. @contextmanager
  95. def mkdtemp():
  96. path = tempfile.mkdtemp()
  97. try:
  98. yield path
  99. finally:
  100. shutil.rmtree(path)
  101. _package_registry: list[
  102. tuple[
  103. int,
  104. Callable[[STORAGE], str | None],
  105. Callable[[STORAGE, str], STORAGE | None],
  106. ]
  107. ] = []
  108. class LoadEndianness(Enum):
  109. NATIVE = 1
  110. LITTLE = 2
  111. BIG = 3
  112. def get_default_load_endianness() -> LoadEndianness | None:
  113. """
  114. Get fallback byte order for loading files
  115. If byteorder mark is not present in saved checkpoint,
  116. this byte order is used as fallback.
  117. By default, it's "native" byte order.
  118. Returns:
  119. default_load_endian: Optional[LoadEndianness]
  120. """
  121. from torch.utils.serialization import config
  122. return config.load.endianness
  123. def set_default_load_endianness(endianness):
  124. """
  125. Set fallback byte order for loading files
  126. If byteorder mark is not present in saved checkpoint,
  127. this byte order is used as fallback.
  128. By default, it's "native" byte order.
  129. Args:
  130. endianness: the new fallback byte order
  131. """
  132. if not isinstance(endianness, LoadEndianness) and endianness is not None:
  133. raise TypeError("Invalid argument type in function set_default_load_endianness")
  134. from torch.utils.serialization import config
  135. config.load.endianness = endianness
  136. def get_crc32_options() -> bool:
  137. """
  138. Get whether :func:`torch.save` computes and writes crc32 for each record.
  139. Defaults to ``True``.
  140. """
  141. from torch.utils.serialization import config
  142. return config.save.compute_crc32
  143. def set_crc32_options(compute_crc32: bool):
  144. """
  145. Set whether :func:`torch.save` computes and writes crc32 for each record.
  146. .. note::
  147. Setting this to ``False`` may make unzipping of the ``torch.save`` output
  148. fail or warn due to corrupted CRC32. However ``torch.load`` will be
  149. able to load the file.
  150. Args:
  151. compute_crc32 (bool): set crc32 computation flag
  152. """
  153. from torch.utils.serialization import config
  154. config.save.compute_crc32 = compute_crc32
  155. def get_default_mmap_options() -> int | None:
  156. """
  157. Get default mmap options for :func:`torch.load` with ``mmap=True``.
  158. Defaults to ``mmap.MAP_PRIVATE``.
  159. Returns:
  160. default_mmap_options: int
  161. """
  162. from torch.utils.serialization import config
  163. return config.load.mmap_flags
  164. def _get_storage_alignment() -> int:
  165. """
  166. Gets alignment for storages in torch.save files/
  167. Defaults to 64.
  168. Returns:
  169. storage_alginment: int
  170. """
  171. from torch.utils.serialization import config
  172. return config.save.storage_alignment
  173. class set_default_mmap_options:
  174. """
  175. Context manager or function to set default mmap options for :func:`torch.load` with ``mmap=True`` to flags.
  176. For now, only either ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED`` are supported.
  177. Please open an issue if you need any other option to be added here.
  178. .. note::
  179. This feature is currently not supported for Windows.
  180. Args:
  181. flags: ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED``
  182. """
  183. def __init__(self, flags: int) -> None:
  184. if IS_WINDOWS:
  185. raise RuntimeError(
  186. "Changing the default mmap options is currently not supported for Windows"
  187. )
  188. if flags != MAP_PRIVATE and flags != MAP_SHARED:
  189. raise ValueError(
  190. "Invalid argument in function set_default_mmap_options, "
  191. f"expected mmap.MAP_PRIVATE or mmap.MAP_SHARED, but got {flags}"
  192. )
  193. # global config
  194. from torch.utils.serialization import config
  195. self.prev = config.load.mmap_flags
  196. config.load.mmap_flags = flags
  197. def __enter__(self) -> None:
  198. pass
  199. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  200. from torch.utils.serialization import config
  201. config.load.mmap_flags = self.prev
  202. def clear_safe_globals() -> None:
  203. """
  204. Clears the list of globals that are safe for ``weights_only`` load.
  205. """
  206. _weights_only_unpickler._clear_safe_globals()
  207. def get_safe_globals() -> list[Callable | tuple[Callable, str]]:
  208. """
  209. Returns the list of user-added globals that are safe for ``weights_only`` load.
  210. """
  211. return _weights_only_unpickler._get_safe_globals()
  212. def add_safe_globals(safe_globals: list[Callable | tuple[Callable, str]]) -> None:
  213. """
  214. Marks the given globals as safe for ``weights_only`` load. For example, functions
  215. added to this list can be called during unpickling, classes could be instantiated
  216. and have state set.
  217. Each item in the list can either be a function/class or a tuple of the form
  218. (function/class, string) where string is the full path of the function/class.
  219. Within the serialized format, each function is identified with its full
  220. path as ``{__module__}.{__qualname__}``. When calling this API, you can provide this
  221. full path that should match the one in the checkpoint otherwise the default
  222. ``{fn.__module__}.{fn.__qualname__}`` will be used.
  223. Args:
  224. safe_globals (List[Union[Callable, Tuple[Callable, str]]]): list of globals to mark as safe
  225. Example:
  226. >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization")
  227. >>> import tempfile
  228. >>> class MyTensor(torch.Tensor):
  229. ... pass
  230. >>> t = MyTensor(torch.randn(2, 3))
  231. >>> with tempfile.NamedTemporaryFile() as f:
  232. ... torch.save(t, f.name)
  233. # Running `torch.load(f.name, weights_only=True)` will fail with
  234. # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.
  235. # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.
  236. ... torch.serialization.add_safe_globals([MyTensor])
  237. ... torch.load(f.name, weights_only=True)
  238. # MyTensor([[-0.5024, -1.8152, -0.5455],
  239. # [-0.8234, 2.0500, -0.3657]])
  240. """
  241. _weights_only_unpickler._add_safe_globals(safe_globals)
  242. class safe_globals(_weights_only_unpickler._safe_globals):
  243. r"""Context-manager that adds certain globals as safe for ``weights_only`` load.
  244. Args:
  245. safe_globals: List of globals for weights_only load.
  246. Example:
  247. >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization")
  248. >>> import tempfile
  249. >>> class MyTensor(torch.Tensor):
  250. ... pass
  251. >>> t = MyTensor(torch.randn(2, 3))
  252. >>> with tempfile.NamedTemporaryFile() as f:
  253. ... torch.save(t, f.name)
  254. # Running `torch.load(f.name, weights_only=True)` will fail with
  255. # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.
  256. # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.
  257. ... with torch.serialization.safe_globals([MyTensor]):
  258. ... torch.load(f.name, weights_only=True)
  259. # MyTensor([[-0.5024, -1.8152, -0.5455],
  260. # [-0.8234, 2.0500, -0.3657]])
  261. >>> assert torch.serialization.get_safe_globals() == []
  262. """
  263. def get_unsafe_globals_in_checkpoint(f: FileLike) -> list[str]:
  264. """Returns a list of strings of functions/classes in a ``torch.save`` object that are not safe for ``weights_only``.
  265. For a given function or class ``f``, the corresponding string will be of the form
  266. ``{f.__module__}.{f.__name__}``.
  267. This function will return any GLOBALs in the checkpoint that are not in the set marked safe
  268. for ``weights_only`` (either via :func:`add_safe_globals` or :class:`safe_globals` context or
  269. allowlisted by ``torch`` by default).
  270. .. note::
  271. This function will statically disassemble the pickle file in the checkpoint.
  272. The implication is any classes dynamically pushed onto the stack during unpickling
  273. will not be included in the output.
  274. Args:
  275. f: File-like object or string containing the checkpoint object saved via ``torch.save``
  276. Returns:
  277. A list of strings of pickle GLOBALs in the checkpoint that are not allowlisted for ``weights_only``.
  278. """
  279. default_safe_globals_strings = set(
  280. _weights_only_unpickler._get_allowed_globals().keys()
  281. )
  282. user_safe_global_strings = set(
  283. _weights_only_unpickler._get_user_allowed_globals().keys()
  284. )
  285. safe_global_strings = default_safe_globals_strings.union(user_safe_global_strings)
  286. with _open_file_like(f, "rb") as opened_file:
  287. if not _is_zipfile(opened_file):
  288. raise ValueError("Expected input to be a checkpoint returned by torch.save")
  289. with _open_zipfile_reader(opened_file) as zip_file:
  290. if _is_torchscript_zip(zip_file):
  291. raise ValueError(
  292. "Expected input to be a checkpoint returned by torch.save but got a torchscript checkpoint"
  293. )
  294. data_file = io.BytesIO(zip_file.get_record("data.pkl"))
  295. all_globals = _weights_only_unpickler.get_globals_in_pkl(data_file)
  296. return list(all_globals.difference(safe_global_strings))
  297. class skip_data:
  298. """
  299. Context-manager that skips writing/reading storage bytes for ``torch.save`` / ``torch.load`` calls.
  300. For the save path, storages will still be saved, but the space that their bytes would usually be written to
  301. will be empty space. The storage bytes can then be populated in a separate pass.
  302. For the load path, tensors will be loaded per the checkpoint but their storages will not be populated with data.
  303. .. warning::
  304. The ``skip_data`` context manager is an early prototype and is subject to change.
  305. Args:
  306. materialize_fake_tensors: Whether to materialize FakeTensors during save. This is a no-op for the load path.
  307. Example:
  308. >>> # xdoctest: +SKIP("NamedTemporaryFile on Windows")
  309. >>> import tempfile
  310. >>> t = torch.randn(2, 3)
  311. >>> with tempfile.NamedTemporaryFile() as f:
  312. ... with torch.serialization.skip_data():
  313. ... torch.save(t, f.name)
  314. ... torch.load(f.name, weights_only=True)
  315. tensor([[0., 0., 0.],
  316. [0., 0., 0.]])
  317. """
  318. def __init__(self, materialize_fake_tensors: bool = False):
  319. self.materialize_fake_tensors = materialize_fake_tensors
  320. def __enter__(self):
  321. global _serialization_tls
  322. self._old_skip_data = _serialization_tls.skip_data
  323. self._old_materialize_fake_tensors = _serialization_tls.materialize_fake_tensors
  324. _serialization_tls.skip_data = True
  325. _serialization_tls.materialize_fake_tensors = self.materialize_fake_tensors
  326. def __exit__(self, type, value, tb):
  327. global _serialization_tls
  328. _serialization_tls.skip_data = self._old_skip_data
  329. _serialization_tls.materialize_fake_tensors = self._old_materialize_fake_tensors
  330. def _is_zipfile(f) -> bool:
  331. # This is a stricter implementation than zipfile.is_zipfile().
  332. # zipfile.is_zipfile() is True if the magic number appears anywhere in the
  333. # binary. Since we expect the files here to be generated by torch.save or
  334. # torch.jit.save, it's safe to only check the start bytes and avoid
  335. # collisions and assume the zip has only 1 file.
  336. # See bugs.python.org/issue28494.
  337. start = f.tell()
  338. # Read the first few bytes and match against the ZIP file signature
  339. local_header_magic_number = b"PK\x03\x04"
  340. read_bytes = f.read(len(local_header_magic_number))
  341. f.seek(start)
  342. return read_bytes == local_header_magic_number
  343. def register_package(
  344. priority: int,
  345. tagger: Callable[[STORAGE], str | None],
  346. deserializer: Callable[[STORAGE, str], STORAGE | None],
  347. ):
  348. """
  349. Registers callables for tagging and deserializing storage objects with an associated priority.
  350. Tagging associates a device with a storage object at save time while deserializing moves a
  351. storage object to an appropriate device at load time. :attr:`tagger` and :attr:`deserializer`
  352. are run in the order given by their :attr:`priority` until a tagger/deserializer returns a
  353. value that is not `None`.
  354. To override the deserialization behavior for a device in the global registry, one can register a
  355. tagger with a higher priority than the existing tagger.
  356. This function can also be used to register a tagger and deserializer for new devices.
  357. Args:
  358. priority: Indicates the priority associated with the tagger and deserializer, where a lower
  359. value indicates higher priority.
  360. tagger: Callable that takes in a storage object and returns its tagged device as a string
  361. or None.
  362. deserializer: Callable that takes in storage object and a device string and returns a storage
  363. object on the appropriate device or None.
  364. Returns:
  365. `None`
  366. Example:
  367. >>> def ipu_tag(obj):
  368. >>> if obj.device.type == 'ipu':
  369. >>> return 'ipu'
  370. >>> def ipu_deserialize(obj, location):
  371. >>> if location.startswith('ipu'):
  372. >>> ipu = getattr(torch, "ipu", None)
  373. >>> assert ipu is not None, "IPU device module is not loaded"
  374. >>> assert torch.ipu.is_available(), "ipu is not available"
  375. >>> return obj.ipu(location)
  376. >>> torch.serialization.register_package(11, ipu_tag, ipu_deserialize)
  377. """
  378. queue_elem = (priority, tagger, deserializer)
  379. _package_registry.append(queue_elem)
  380. _package_registry.sort()
  381. def check_module_version_greater_or_equal(
  382. module,
  383. req_version_tuple,
  384. error_if_malformed=True,
  385. ):
  386. """
  387. Check if a module's version satisfies requirements
  388. Usually, a module's version string will be like 'x.y.z', which would be represented
  389. as a tuple (x, y, z), but sometimes it could be an unexpected format. If the version
  390. string does not match the given tuple's format up to the length of the tuple, then
  391. error and exit or emit a warning.
  392. Args:
  393. module: the module to check the version of
  394. req_version_tuple: tuple (usually of ints) representing the required version
  395. error_if_malformed: whether we should exit if module version string is malformed
  396. Returns:
  397. requirement_is_met: bool
  398. """
  399. try:
  400. version_strs = module.__version__.split(".")
  401. # Cast module version fields to match the types of the required version
  402. module_version = tuple(
  403. type(req_field)(version_strs[idx])
  404. for idx, req_field in enumerate(req_version_tuple)
  405. )
  406. requirement_is_met = module_version >= req_version_tuple
  407. except Exception as e:
  408. message = (
  409. f"'{module.__name__}' module version string is malformed '{module.__version__}' and cannot be compared"
  410. f" with tuple {str(req_version_tuple)}"
  411. )
  412. if error_if_malformed:
  413. raise RuntimeError(message) from e
  414. else:
  415. warnings.warn(
  416. message + ", but continuing assuming that requirement is met",
  417. stacklevel=2,
  418. )
  419. requirement_is_met = True
  420. return requirement_is_met
  421. def _cpu_tag(obj):
  422. if obj.device.type == "cpu":
  423. return "cpu"
  424. def _mps_tag(obj):
  425. if obj.device.type == "mps":
  426. return "mps"
  427. def _meta_tag(obj):
  428. if obj.device.type == "meta":
  429. return "meta"
  430. def _backend_tag(backend_name, obj):
  431. if backend_name == "privateuse1":
  432. backend_name = torch._C._get_privateuse1_backend_name()
  433. if obj.device.type == backend_name:
  434. if obj.device.index is None:
  435. return backend_name
  436. else:
  437. return backend_name + ":" + str(obj.device.index)
  438. def _cpu_deserialize(obj, location):
  439. if location == "cpu":
  440. return obj
  441. def _mps_deserialize(obj, location):
  442. if location.startswith("mps"):
  443. return obj.mps()
  444. def _meta_deserialize(obj, location):
  445. if location == "meta":
  446. return torch.UntypedStorage(obj.nbytes(), device="meta")
  447. def _validate_device(location, backend_name):
  448. """
  449. Check whether the device index of specified backend is valid
  450. In case of privateuse1 backend, your must first register a device_module for
  451. privateuse1 using torch._register_device_module. Implement the following
  452. methods in device_module like cuda: device_module._utils._get_device_index(location, True),
  453. device_module.device_count().
  454. Args:
  455. location: string of device
  456. backend_name: the backend name or the name of privateuse1, which can be renamed
  457. Returns:
  458. device_index: int
  459. """
  460. if not hasattr(torch, backend_name):
  461. raise RuntimeError(
  462. f"The {backend_name.upper()} device module is not registered. "
  463. "If you are running on a CPU-only machine, "
  464. "please use torch.load with map_location=torch.device('cpu') "
  465. "to map your storages to the CPU."
  466. )
  467. device_module = getattr(torch, backend_name)
  468. if hasattr(device_module, "_utils") and hasattr(
  469. device_module._utils, "_get_device_index"
  470. ):
  471. device_index = device_module._utils._get_device_index(location, True)
  472. device = torch.device(backend_name, device_index)
  473. else:
  474. device = torch.device(location)
  475. device_index = device.index if device.index else 0
  476. if hasattr(device_module, "is_available") and not device_module.is_available():
  477. raise RuntimeError(
  478. f"Attempting to deserialize object on a {backend_name.upper()} "
  479. f"device but torch.{backend_name}.is_available() is False. "
  480. "If you are running on a CPU-only machine, "
  481. "please use torch.load with map_location=torch.device('cpu') "
  482. "to map your storages to the CPU."
  483. )
  484. if hasattr(device_module, "device_count"):
  485. device_count = device_module.device_count()
  486. if device_index >= device_count:
  487. raise RuntimeError(
  488. f"Attempting to deserialize object on {backend_name.upper()} device "
  489. f"{device_index} but torch.{backend_name}.device_count() is {device_count}. "
  490. "Please use torch.load with map_location to map your storages "
  491. "to an existing device."
  492. )
  493. return device
  494. def validate_cuda_device(location):
  495. return _validate_device(location, "cuda").index
  496. def validate_hpu_device(location):
  497. return _validate_device(location, "hpu").index
  498. def _deserialize(backend_name, obj, location):
  499. if backend_name == "privateuse1":
  500. backend_name = torch._C._get_privateuse1_backend_name()
  501. if location.startswith(backend_name):
  502. device = _validate_device(location, backend_name)
  503. return obj.to(device=device)
  504. register_package(10, _cpu_tag, _cpu_deserialize)
  505. register_package(
  506. 20,
  507. functools.partial(_backend_tag, "cuda"),
  508. functools.partial(_deserialize, "cuda"),
  509. )
  510. register_package(21, _mps_tag, _mps_deserialize)
  511. register_package(22, _meta_tag, _meta_deserialize)
  512. register_package(
  513. 23,
  514. functools.partial(_backend_tag, "privateuse1"),
  515. functools.partial(_deserialize, "privateuse1"),
  516. )
  517. register_package(
  518. 24,
  519. functools.partial(_backend_tag, "hpu"),
  520. functools.partial(_deserialize, "hpu"),
  521. )
  522. register_package(
  523. 25,
  524. functools.partial(_backend_tag, "xpu"),
  525. functools.partial(_deserialize, "xpu"),
  526. )
  527. register_package(
  528. 26,
  529. functools.partial(_backend_tag, "mtia"),
  530. functools.partial(_deserialize, "mtia"),
  531. )
  532. def location_tag(
  533. storage: Storage | torch.storage.TypedStorage | torch.UntypedStorage,
  534. ):
  535. for _, tagger, _ in _package_registry:
  536. location = tagger(storage)
  537. if location:
  538. return location
  539. raise RuntimeError(
  540. "don't know how to determine data location of " + torch.typename(storage)
  541. )
  542. def default_restore_location(storage, location):
  543. """
  544. Restores `storage` using a deserializer function registered for the `location`.
  545. This function looks in the registry for deserializer functions that match the `location`.
  546. If found, it attempts to use them, in priority order, to restore `storage` until one
  547. returns a not `None` result. If no deserializer can be found in the registry, or all found fail
  548. to bear a result, it raises a `RuntimeError`.
  549. Args:
  550. storage (STORAGE): the storage object to restore
  551. location (str): the location tag associated with the storage object
  552. Returns:
  553. storage: Optional[STORAGE]
  554. Raises:
  555. RuntimeError: If no deserializer matching `location` is found in the registry or if
  556. all matching ones return `None`.
  557. """
  558. for _, _, fn in _package_registry:
  559. result = fn(storage, location)
  560. if result is not None:
  561. return result
  562. raise RuntimeError(
  563. "don't know how to restore data location of "
  564. + torch.typename(storage)
  565. + " (tagged with "
  566. + location
  567. + ")"
  568. )
  569. def normalize_storage_type(storage_type):
  570. return getattr(torch, storage_type.__name__)
  571. def storage_to_tensor_type(storage):
  572. storage_type = type(storage)
  573. module = _import_dotted_name(storage_type.__module__)
  574. return getattr(module, storage_type.__name__.replace("Storage", "Tensor"))
  575. def _is_path(name_or_buffer: object) -> TypeIs[str | os.PathLike]:
  576. return isinstance(name_or_buffer, (str, os.PathLike))
  577. T = TypeVar("T")
  578. class _opener(Generic[T]):
  579. def __init__(self, file_like: T) -> None:
  580. self.file_like: T = file_like
  581. def __enter__(self):
  582. return self.file_like
  583. def __exit__(self, *args):
  584. pass
  585. class _open_file(_opener[IO[bytes]]):
  586. def __init__(self, name: str | os.PathLike[str], mode: str) -> None:
  587. super().__init__(open(name, mode)) # noqa: SIM115
  588. def __exit__(self, *args):
  589. self.file_like.close()
  590. class _open_buffer_reader(_opener[IO[bytes]]):
  591. def __init__(self, buffer: IO[bytes]) -> None:
  592. super().__init__(buffer)
  593. _check_seekable(buffer)
  594. class _open_buffer_writer(_opener[IO[bytes]]):
  595. def __exit__(self, *args):
  596. self.file_like.flush()
  597. def _open_file_like(name_or_buffer: FileLike, mode: str) -> _opener[IO[bytes]]:
  598. if _is_path(name_or_buffer):
  599. return _open_file(name_or_buffer, mode)
  600. else:
  601. if "w" in mode:
  602. return _open_buffer_writer(name_or_buffer)
  603. elif "r" in mode:
  604. return _open_buffer_reader(name_or_buffer)
  605. else:
  606. raise RuntimeError(f"Expected 'r' or 'w' in mode but got {mode}")
  607. class _open_zipfile_reader(_opener[torch._C.PyTorchFileReader]):
  608. def __init__(self, name_or_buffer: str | IO[bytes]) -> None:
  609. super().__init__(torch._C.PyTorchFileReader(name_or_buffer))
  610. class _open_zipfile_writer_file(_opener[torch._C.PyTorchFileWriter]):
  611. def __init__(self, name: str) -> None:
  612. self.file_stream = None
  613. self.name = name
  614. try:
  615. self.name.encode("ascii")
  616. except UnicodeEncodeError:
  617. # PyTorchFileWriter only supports ascii filename.
  618. # For filenames with non-ascii characters, we rely on Python
  619. # for writing out the file.
  620. # pyrefly: ignore [bad-assignment]
  621. self.file_stream = io.FileIO(self.name, mode="w")
  622. super().__init__(
  623. torch._C.PyTorchFileWriter( # pyrefly: ignore # no-matching-overload
  624. self.file_stream, get_crc32_options(), _get_storage_alignment()
  625. )
  626. )
  627. else:
  628. super().__init__(
  629. torch._C.PyTorchFileWriter(
  630. self.name, get_crc32_options(), _get_storage_alignment()
  631. )
  632. )
  633. def __exit__(self, *args) -> None:
  634. self.file_like.write_end_of_file()
  635. if self.file_stream is not None:
  636. self.file_stream.close()
  637. class _open_zipfile_writer_buffer(_opener[torch._C.PyTorchFileWriter]):
  638. def __init__(self, buffer: IO[bytes]) -> None:
  639. if not callable(getattr(buffer, "write", None)):
  640. msg = f"Buffer of {str(type(buffer)).strip('<>')} has no callable attribute 'write'"
  641. if not hasattr(buffer, "write"):
  642. raise AttributeError(msg)
  643. raise TypeError(msg)
  644. self.buffer = buffer
  645. super().__init__(
  646. torch._C.PyTorchFileWriter(
  647. buffer, get_crc32_options(), _get_storage_alignment()
  648. )
  649. )
  650. def __exit__(self, *args) -> None:
  651. self.file_like.write_end_of_file()
  652. self.buffer.flush()
  653. def _open_zipfile_writer(name_or_buffer: str | IO[bytes]) -> _opener:
  654. container: type[_opener]
  655. if _is_path(name_or_buffer):
  656. container = _open_zipfile_writer_file
  657. else:
  658. container = _open_zipfile_writer_buffer
  659. return container(name_or_buffer) # type: ignore[arg-type]
  660. def _is_compressed_file(f) -> bool:
  661. compress_modules = ["gzip"]
  662. try:
  663. return f.__module__ in compress_modules
  664. except AttributeError:
  665. return False
  666. def _should_read_directly(f):
  667. """
  668. Checks if f is a file that should be read directly. It should be read
  669. directly if it is backed by a real file (has a fileno) and is not a
  670. a compressed file (e.g. gzip)
  671. """
  672. if _is_compressed_file(f):
  673. return False
  674. try:
  675. return f.fileno() >= 0
  676. except io.UnsupportedOperation:
  677. return False
  678. except AttributeError:
  679. return False
  680. def _check_seekable(f) -> bool:
  681. def raise_err_msg(patterns, e):
  682. for p in patterns:
  683. if p in str(e):
  684. msg = (
  685. str(e)
  686. + ". You can only torch.load from a file that is seekable."
  687. + " Please pre-load the data into a buffer like io.BytesIO and"
  688. + " try to load from it instead."
  689. )
  690. raise type(e)(msg)
  691. raise e
  692. try:
  693. f.seek(f.tell())
  694. return True
  695. except (io.UnsupportedOperation, AttributeError) as e:
  696. raise_err_msg(["seek", "tell"], e)
  697. return False
  698. def _check_dill_version(pickle_module) -> None:
  699. """Checks if using dill as the pickle module, and if so, checks if it is the correct version.
  700. If dill version is lower than 0.3.1, a ValueError is raised.
  701. Args:
  702. pickle_module: module used for pickling metadata and objects
  703. """
  704. if pickle_module is not None and pickle_module.__name__ == "dill":
  705. required_dill_version = (0, 3, 1)
  706. if not check_module_version_greater_or_equal(
  707. pickle_module, required_dill_version, False
  708. ):
  709. raise ValueError(
  710. (
  711. "'torch' supports dill >= {}, but you have dill {}."
  712. " Please upgrade dill or switch to 'pickle'"
  713. ).format(
  714. ".".join([str(num) for num in required_dill_version]),
  715. pickle_module.__version__,
  716. )
  717. )
  718. def _check_save_filelike(f):
  719. if not _is_path(f) and not hasattr(f, "write"):
  720. raise AttributeError(
  721. "expected 'f' to be string, path, or a file-like object with "
  722. "a 'write' attribute"
  723. )
  724. def save(
  725. obj: object,
  726. f: FileLike,
  727. pickle_module: Any = pickle,
  728. pickle_protocol: int = DEFAULT_PROTOCOL,
  729. _use_new_zipfile_serialization: bool = True,
  730. _disable_byteorder_record: bool = False,
  731. ) -> None:
  732. # Reference: https://github.com/pytorch/pytorch/issues/54354
  733. # The first line of this docstring overrides the one Sphinx generates for the
  734. # documentation. We need it so that Sphinx doesn't leak `pickle`s path from
  735. # the build environment (e.g. `<module 'pickle' from '/leaked/path').
  736. """save(obj, f, pickle_module=pickle, pickle_protocol=2, _use_new_zipfile_serialization=True)
  737. Saves an object to a disk file.
  738. See also: :ref:`saving-loading-tensors`
  739. See :ref:`layout-control` for more advanced tools to manipulate a checkpoint.
  740. Args:
  741. obj: saved object
  742. f: a file-like object (has to implement write and flush) or a string or
  743. os.PathLike object containing a file name
  744. pickle_module: module used for pickling metadata and objects
  745. pickle_protocol: can be specified to override the default protocol
  746. .. note::
  747. A common PyTorch convention is to save tensors using .pt file extension.
  748. .. note::
  749. PyTorch preserves storage sharing across serialization. See
  750. :ref:`preserve-storage-sharing` for more details.
  751. .. note::
  752. The 1.6 release of PyTorch switched ``torch.save`` to use a new
  753. zipfile-based file format. ``torch.load`` still retains the ability to
  754. load files in the old format. If for any reason you want ``torch.save``
  755. to use the old format, pass the kwarg ``_use_new_zipfile_serialization=False``.
  756. Example:
  757. >>> # xdoctest: +SKIP("makes cwd dirty")
  758. >>> # Save to file
  759. >>> x = torch.tensor([0, 1, 2, 3, 4])
  760. >>> torch.save(x, "tensor.pt")
  761. >>> # Save to io.BytesIO buffer
  762. >>> buffer = io.BytesIO()
  763. >>> torch.save(x, buffer)
  764. """
  765. torch._C._log_api_usage_once("torch.save")
  766. _check_dill_version(pickle_module)
  767. _check_save_filelike(f)
  768. if isinstance(f, (str, os.PathLike)):
  769. f = os.fspath(f)
  770. if _use_new_zipfile_serialization:
  771. with _open_zipfile_writer(f) as opened_zipfile:
  772. _save(
  773. obj,
  774. opened_zipfile,
  775. pickle_module,
  776. pickle_protocol,
  777. _disable_byteorder_record,
  778. )
  779. return
  780. else:
  781. global _serialization_tls
  782. if _serialization_tls.skip_data:
  783. raise RuntimeError(
  784. "Cannot use skip_data=True with _use_new_zipfile_serialization=False"
  785. )
  786. with _open_file_like(f, "wb") as opened_file:
  787. _legacy_save(obj, opened_file, pickle_module, pickle_protocol)
  788. def _legacy_save(obj, f, pickle_module, pickle_protocol) -> None:
  789. import torch.nn as nn
  790. serialized_container_types = {}
  791. serialized_storages: dict[str, tuple[torch.UntypedStorage, torch.dtype]] = {}
  792. # Since loading storages that view the same data with different dtypes is
  793. # not supported, we need to keep track of the dtype associated with each
  794. # storage data_ptr and throw an error if the dtype is ever different.
  795. # TODO: This feature could be added in the future
  796. storage_dtypes: dict[int, torch.dtype] = {}
  797. def persistent_id(obj: Any) -> tuple | None:
  798. # FIXME: the docs say that persistent_id should only return a string
  799. # but torch store returns tuples. This works only in the binary protocol
  800. # see
  801. # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects
  802. # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537
  803. if isinstance(obj, type) and issubclass(obj, nn.Module):
  804. if obj in serialized_container_types:
  805. return None
  806. serialized_container_types[obj] = True
  807. source_file = source = None
  808. try:
  809. source_lines, _, source_file = get_source_lines_and_file(obj)
  810. source = "".join(source_lines)
  811. except (
  812. Exception
  813. ): # saving the source is optional, so we can ignore any errors
  814. warnings.warn(
  815. "Couldn't retrieve source code for container of "
  816. "type " + obj.__name__ + ". It won't be checked "
  817. "for correctness upon loading.",
  818. stacklevel=2,
  819. )
  820. return ("module", obj, source_file, source)
  821. if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj):
  822. storage: torch.UntypedStorage
  823. if isinstance(obj, torch.storage.TypedStorage):
  824. # TODO: Once we decide to break serialization FC, this case
  825. # can be deleted
  826. storage = obj._untyped_storage
  827. storage_dtype = obj.dtype
  828. storage_type_str = obj._pickle_storage_type()
  829. storage_type = getattr(torch, storage_type_str)
  830. dtype = obj.dtype
  831. storage_numel = obj._size()
  832. elif isinstance(obj, torch.UntypedStorage):
  833. storage = obj
  834. storage_dtype = torch.uint8
  835. storage_type = normalize_storage_type(type(obj))
  836. dtype = torch.uint8
  837. storage_numel = storage.nbytes()
  838. else:
  839. raise TypeError(f"type not recognized: {type(obj)}")
  840. # If storage is allocated, ensure that any other saved storages
  841. # pointing to the same data all have the same dtype. If storage is
  842. # not allocated, don't perform this check
  843. if storage.data_ptr() != 0:
  844. if storage.data_ptr() in storage_dtypes:
  845. if storage_dtype != storage_dtypes[storage.data_ptr()]:
  846. raise RuntimeError(
  847. "Cannot save multiple tensors or storages that "
  848. "view the same data as different types"
  849. )
  850. else:
  851. storage_dtypes[storage.data_ptr()] = storage_dtype
  852. view_metadata: tuple[str, int, int] | None
  853. # Offset is always 0, but we keep it for backwards compatibility
  854. # with the old serialization format (which supported storage views)
  855. offset = 0
  856. storage_key = str(storage._cdata)
  857. location = location_tag(storage)
  858. # TODO: There's an issue here with FC. It might be impossible to
  859. # solve, but it's worth noting. Imagine we save a list `[storage,
  860. # tensor]`, where `tensor.storage()` is the same as `storage`, and
  861. # `tensor.element_size() > 1`. Let's say that `tensor.dtype ==
  862. # torch.float`. The storage will be serialized with element size
  863. # of 1, since we're choosing to serialize the first occurrence of
  864. # a duplicate storage. Since this legacy serialization format saves
  865. # the numel of the storage, rather than nbytes directly, we'll be
  866. # effectively saving nbytes in this case. We'll be able to load it
  867. # and the tensor back up with no problems in _this_ and future
  868. # versions of pytorch, but in older versions, here's the problem:
  869. # the storage will be loaded up as a UntypedStorage, and then the
  870. # FloatTensor will loaded and the UntypedStorage will be assigned to
  871. # it. Since the storage dtype does not match the tensor dtype, this
  872. # will cause an error. If we reverse the list, like `[tensor,
  873. # storage]`, then we will save the `tensor.storage()` as a faked
  874. # `FloatStorage`, and the saved size will be the correct
  875. # dtype-specific numel count that old versions expect. `tensor`
  876. # will be able to load up properly in old versions, pointing to
  877. # a FloatStorage. However, `storage` is still being translated to
  878. # a UntypedStorage, and it will try to resolve to the same
  879. # FloatStorage that `tensor` contains. This will also cause an
  880. # error. It doesn't seem like there's any way around this.
  881. # Probably, we just cannot maintain FC for the legacy format if the
  882. # saved list contains both a tensor and a storage that point to the
  883. # same data. We should still be able to maintain FC for lists of
  884. # just tensors, as long as all views share the same dtype as the
  885. # tensor they are viewing.
  886. if storage_key not in serialized_storages:
  887. serialized_storages[storage_key] = (storage, dtype)
  888. is_view = storage._cdata != storage._cdata
  889. if is_view:
  890. view_metadata = (str(storage._cdata), offset, storage.nbytes())
  891. else:
  892. view_metadata = None
  893. res = (
  894. "storage",
  895. storage_type,
  896. storage_key,
  897. location,
  898. storage_numel,
  899. view_metadata,
  900. )
  901. return res
  902. return None
  903. sys_info = {
  904. "protocol_version": PROTOCOL_VERSION,
  905. "little_endian": sys.byteorder == "little",
  906. "type_sizes": {
  907. "short": SHORT_SIZE,
  908. "int": INT_SIZE,
  909. "long": LONG_SIZE,
  910. },
  911. }
  912. pickle_module.dump(MAGIC_NUMBER, f, protocol=pickle_protocol)
  913. pickle_module.dump(PROTOCOL_VERSION, f, protocol=pickle_protocol)
  914. pickle_module.dump(sys_info, f, protocol=pickle_protocol)
  915. class PyTorchLegacyPickler(pickle_module.Pickler):
  916. def persistent_id(self, obj):
  917. return persistent_id(obj) # noqa: F821
  918. pickler = PyTorchLegacyPickler(f, protocol=pickle_protocol)
  919. pickler.dump(obj)
  920. # The class def keeps the persistent_id closure alive, leaking memory.
  921. del persistent_id
  922. serialized_storage_keys = sorted(serialized_storages.keys())
  923. pickle_module.dump(serialized_storage_keys, f, protocol=pickle_protocol)
  924. f.flush()
  925. for key in serialized_storage_keys:
  926. storage, dtype = serialized_storages[key]
  927. storage._write_file(
  928. f, _should_read_directly(f), True, torch._utils._element_size(dtype)
  929. )
  930. def _save(
  931. obj,
  932. zip_file,
  933. pickle_module,
  934. pickle_protocol,
  935. _disable_byteorder_record,
  936. ):
  937. serialized_storages: dict[str, torch.storage.UntypedStorage] = {}
  938. id_map: dict[int, str] = {}
  939. # Since loading storages that view the same data with different dtypes is
  940. # not supported, we need to keep track of the dtype associated with each
  941. # storage data_ptr and throw an error if the dtype is ever different.
  942. # TODO: This feature could be added in the future
  943. storage_dtypes: dict[int, torch.dtype] = {}
  944. def persistent_id(obj):
  945. # FIXME: the docs say that persistent_id should only return a string
  946. # but torch store returns tuples. This works only in the binary protocol
  947. # see
  948. # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects
  949. # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537
  950. if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj):
  951. if isinstance(obj, torch.storage.TypedStorage):
  952. # TODO: Once we decide to break serialization FC, this case
  953. # can be deleted
  954. storage = obj._untyped_storage
  955. storage_dtype = obj.dtype
  956. storage_type_str = obj._pickle_storage_type()
  957. storage_type = getattr(torch, storage_type_str)
  958. storage_numel = obj._size()
  959. else:
  960. storage = obj
  961. storage_dtype = torch.uint8
  962. storage_type = normalize_storage_type(type(obj))
  963. storage_numel = storage.nbytes()
  964. # If storage is allocated, ensure that any other saved storages
  965. # pointing to the same data all have the same dtype. If storage is
  966. # not allocated, don't perform this check
  967. if str(storage.device) != "meta" and storage.data_ptr() != 0:
  968. if storage.data_ptr() in storage_dtypes:
  969. if storage_dtype != storage_dtypes[storage.data_ptr()]:
  970. raise RuntimeError(
  971. "Cannot save multiple tensors or storages that "
  972. "view the same data as different types"
  973. )
  974. else:
  975. storage_dtypes[storage.data_ptr()] = storage_dtype
  976. storage_key = id_map.setdefault(storage._cdata, str(len(id_map)))
  977. if hasattr(obj, "_fake_device") and obj._fake_device is not None:
  978. location = str(obj._fake_device)
  979. else:
  980. location = location_tag(storage)
  981. serialized_storages[storage_key] = storage
  982. return ("storage", storage_type, storage_key, location, storage_numel)
  983. return None
  984. # Write the pickle data for `obj`
  985. data_buf = io.BytesIO()
  986. class PyTorchPickler(pickle_module.Pickler): # type: ignore[name-defined]
  987. def persistent_id(self, obj):
  988. return persistent_id(obj) # noqa: F821
  989. pickler = PyTorchPickler(data_buf, protocol=pickle_protocol)
  990. pickler.dump(obj)
  991. # The class def keeps the persistent_id closure alive, leaking memory.
  992. del persistent_id
  993. data_value = data_buf.getvalue()
  994. zip_file.write_record("data.pkl", data_value, len(data_value))
  995. # .format_version is used to track
  996. # 1. version 1 represents the order of storages being changed from
  997. # lexicographical based on keys to numerically ordered based on keys
  998. # 2. version 2 represents including storage_alignment as a record
  999. # within the zipfile
  1000. zip_file.write_record(".format_version", "1", len("1"))
  1001. storage_alignment = str(_get_storage_alignment())
  1002. zip_file.write_record(
  1003. ".storage_alignment", storage_alignment, len(storage_alignment)
  1004. )
  1005. # Write byte order marker
  1006. if not _disable_byteorder_record:
  1007. if sys.byteorder not in ["little", "big"]:
  1008. raise ValueError("Unknown endianness type: " + sys.byteorder)
  1009. zip_file.write_record("byteorder", sys.byteorder, len(sys.byteorder))
  1010. # Write each tensor to a file named tensor/the_tensor_key in the zip archive
  1011. for key in serialized_storages:
  1012. name = f"data/{key}"
  1013. storage = serialized_storages[key]
  1014. num_bytes = storage.nbytes()
  1015. global _serialization_tls
  1016. if _serialization_tls.skip_data:
  1017. zip_file.write_record_metadata(name, num_bytes)
  1018. else:
  1019. # given that we copy things around anyway, we might use storage.cpu()
  1020. # this means to that to get tensors serialized, you need to implement
  1021. # .cpu() on the underlying Storage
  1022. if storage.device.type != "cpu":
  1023. from torch.utils.serialization import config
  1024. if (
  1025. config.save.use_pinned_memory_for_d2h
  1026. and (
  1027. acc := torch.accelerator.current_accelerator(
  1028. check_available=True
  1029. )
  1030. )
  1031. is not None
  1032. and acc.type == storage.device.type
  1033. ):
  1034. new_storage = torch.empty(
  1035. num_bytes, dtype=torch.uint8, device="cpu", pin_memory=True
  1036. ).untyped_storage()
  1037. new_storage.copy_(storage)
  1038. torch.accelerator.current_stream(storage.device.index).synchronize()
  1039. storage = new_storage
  1040. else:
  1041. storage = storage.cpu()
  1042. # Now that it is on the CPU we can directly copy it into the zip file
  1043. zip_file.write_record(name, storage, num_bytes)
  1044. def load(
  1045. f: FileLike,
  1046. map_location: MAP_LOCATION = None,
  1047. pickle_module: Any = None,
  1048. *,
  1049. weights_only: bool | None = None,
  1050. mmap: bool | None = None,
  1051. **pickle_load_args: Any,
  1052. ) -> Any:
  1053. # Reference: https://github.com/pytorch/pytorch/issues/54354
  1054. # The first line of this docstring overrides the one Sphinx generates for the
  1055. # documentation. We need it so that Sphinx doesn't leak `pickle`s path from
  1056. # the build environment (e.g. `<module 'pickle' from '/leaked/path').
  1057. """load(f, map_location=None, pickle_module=pickle, *, weights_only=True, mmap=None, **pickle_load_args)
  1058. Loads an object saved with :func:`torch.save` from a file.
  1059. .. warning::
  1060. :func:`torch.load()` uses an unpickler under the hood. **Never load data from an untrusted source.**
  1061. See :ref:`weights-only-security` for more details.
  1062. :func:`torch.load` uses Python's unpickling facilities but treats storages,
  1063. which underlie tensors, specially. They are first deserialized on the
  1064. CPU and are then moved to the device they were saved from. If this fails
  1065. (e.g. because the run time system doesn't have certain devices), an exception
  1066. is raised. However, storages can be dynamically remapped to an alternative
  1067. set of devices using the :attr:`map_location` argument.
  1068. If :attr:`map_location` is a callable, it will be called once for each serialized
  1069. storage with two arguments: storage and location. The storage argument
  1070. will be the initial deserialization of the storage, residing on the CPU.
  1071. Each serialized storage has a location tag associated with it which
  1072. identifies the device it was saved from, and this tag is the second
  1073. argument passed to :attr:`map_location`. The builtin location tags are ``'cpu'``
  1074. for CPU tensors and ``'cuda:device_id'`` (e.g. ``'cuda:2'``) for CUDA tensors.
  1075. :attr:`map_location` should return either ``None`` or a storage. If
  1076. :attr:`map_location` returns a storage, it will be used as the final deserialized
  1077. object, already moved to the right device. Otherwise, :func:`torch.load` will
  1078. fall back to the default behavior, as if :attr:`map_location` wasn't specified.
  1079. If :attr:`map_location` is a :class:`torch.device` object or a string containing
  1080. a device tag, it indicates the location where all tensors should be loaded.
  1081. Otherwise, if :attr:`map_location` is a dict, it will be used to remap location tags
  1082. appearing in the file (keys), to ones that specify where to put the
  1083. storages (values).
  1084. User extensions can register their own location tags and tagging and
  1085. deserialization methods using :func:`torch.serialization.register_package`.
  1086. See :ref:`layout-control` for more advanced tools to manipulate a checkpoint.
  1087. Args:
  1088. f: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`),
  1089. or a string or os.PathLike object containing a file name
  1090. map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage
  1091. locations
  1092. pickle_module: module used for unpickling metadata and objects (has to
  1093. match the :attr:`pickle_module` used to serialize file)
  1094. weights_only: Indicates whether unpickler should be restricted to
  1095. loading only tensors, primitive types, dictionaries
  1096. and any types added via :func:`torch.serialization.add_safe_globals`.
  1097. See :ref:`weights-only` for more details.
  1098. mmap: Indicates whether the file should be mapped rather than loading all the storages into memory.
  1099. Typically, tensor storages in the file will first be moved from disk to CPU memory, after which they
  1100. are moved to the location that they were tagged with when saving, or specified by ``map_location``. This
  1101. second step is a no-op if the final location is CPU. When the ``mmap`` flag is set, instead of copying the
  1102. tensor storages from disk to CPU memory in the first step, ``f`` is mapped, which means tensor storages
  1103. will be lazily loaded when their data is accessed.
  1104. pickle_load_args: (Python 3 only) optional keyword arguments passed over to
  1105. :func:`pickle_module.load` and :func:`pickle_module.Unpickler`, e.g.,
  1106. :attr:`errors=...`.
  1107. .. note::
  1108. When you call :func:`torch.load()` on a file which contains GPU tensors, those tensors
  1109. will be loaded to GPU by default. You can call ``torch.load(.., map_location='cpu')``
  1110. and then :meth:`load_state_dict` to avoid GPU RAM surge when loading a model checkpoint.
  1111. .. note::
  1112. By default, we decode byte strings as ``utf-8``. This is to avoid a common error
  1113. case ``UnicodeDecodeError: 'ascii' codec can't decode byte 0x...``
  1114. when loading files saved by Python 2 in Python 3. If this default
  1115. is incorrect, you may use an extra :attr:`encoding` keyword argument to specify how
  1116. these objects should be loaded, e.g., :attr:`encoding='latin1'` decodes them
  1117. to strings using ``latin1`` encoding, and :attr:`encoding='bytes'` keeps them
  1118. as byte arrays which can be decoded later with ``byte_array.decode(...)``.
  1119. Example:
  1120. >>> # xdoctest: +SKIP("undefined filepaths")
  1121. >>> torch.load("tensors.pt", weights_only=True)
  1122. # Load all tensors onto the CPU
  1123. >>> torch.load(
  1124. ... "tensors.pt",
  1125. ... map_location=torch.device("cpu"),
  1126. ... weights_only=True,
  1127. ... )
  1128. # Load all tensors onto the CPU, using a function
  1129. >>> torch.load(
  1130. ... "tensors.pt",
  1131. ... map_location=lambda storage, loc: storage,
  1132. ... weights_only=True,
  1133. ... )
  1134. # Load all tensors onto GPU 1
  1135. >>> torch.load(
  1136. ... "tensors.pt",
  1137. ... map_location=lambda storage, loc: storage.cuda(1), # type: ignore[attr-defined]
  1138. ... weights_only=True,
  1139. ... ) # type: ignore[attr-defined]
  1140. # Map tensors from GPU 1 to GPU 0
  1141. >>> torch.load(
  1142. ... "tensors.pt",
  1143. ... map_location={"cuda:1": "cuda:0"},
  1144. ... weights_only=True,
  1145. ... )
  1146. # Load tensor from io.BytesIO object
  1147. # Loading from a buffer setting weights_only=False, warning this can be unsafe
  1148. >>> with open("tensor.pt", "rb") as f:
  1149. ... buffer = io.BytesIO(f.read())
  1150. >>> torch.load(buffer, weights_only=False)
  1151. # Load a module with 'ascii' encoding for unpickling
  1152. # Loading from a module setting weights_only=False, warning this can be unsafe
  1153. >>> torch.load("module.pt", encoding="ascii", weights_only=False)
  1154. """
  1155. torch._C._log_api_usage_once("torch.load")
  1156. DOCS_MESSAGE = (
  1157. "\n\nCheck the documentation of torch.load to learn more about types accepted by default with "
  1158. "weights_only https://pytorch.org/docs/stable/generated/torch.load.html."
  1159. )
  1160. def _get_wo_message(message: str) -> str:
  1161. unsafe_global_pattern = r"GLOBAL (\S+) was not an allowed global by default."
  1162. has_unsafe_global = re.search(unsafe_global_pattern, message) is not None
  1163. blocklist_pattern = r"whose module (\S+) is blocked"
  1164. has_blocklist = re.search(blocklist_pattern, message) is not None
  1165. import_pattern = r"(\S+) must be (\S+) to load"
  1166. has_import = re.search(import_pattern, message) is not None
  1167. if has_unsafe_global:
  1168. updated_message = (
  1169. "Weights only load failed. This file can still be loaded, to do so you have two options, "
  1170. "\033[1mdo those steps only if you trust the source of the checkpoint\033[0m. "
  1171. f"\n\t(1) {UNSAFE_MESSAGE}\n\t(2) Alternatively, to load with `weights_only=True` please check "
  1172. "the recommended steps in the following error message.\n\tWeightsUnpickler error: "
  1173. + message
  1174. )
  1175. else:
  1176. if has_import:
  1177. return f"Weights only load failed. {message}\n {UNSAFE_MESSAGE}\n"
  1178. else:
  1179. updated_message = f"Weights only load failed. {UNSAFE_MESSAGE}\n"
  1180. if not has_blocklist:
  1181. updated_message += (
  1182. "Please file an issue with the following so that we can make "
  1183. "`weights_only=True` compatible with your use case: WeightsUnpickler error: "
  1184. )
  1185. updated_message += "\n\n" + message
  1186. return updated_message + DOCS_MESSAGE
  1187. weights_only_not_set = weights_only is None
  1188. if weights_only_not_set:
  1189. weights_only = _default_to_weights_only(pickle_module)
  1190. true_values = ["1", "y", "yes", "true"]
  1191. # Add ability to force safe only or non-safe weight loads via environment variables
  1192. force_weights_only_load = (
  1193. os.getenv("TORCH_FORCE_WEIGHTS_ONLY_LOAD", "0") in true_values
  1194. )
  1195. force_no_weights_only_load = (
  1196. os.getenv("TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD", "0") in true_values
  1197. )
  1198. if force_weights_only_load and force_no_weights_only_load:
  1199. raise RuntimeError(
  1200. "Only one of `TORCH_FORCE_WEIGHTS_ONLY_LOAD` or `TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD` "
  1201. "should be set, but both were set."
  1202. )
  1203. elif force_weights_only_load:
  1204. weights_only = True
  1205. elif force_no_weights_only_load:
  1206. # TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD can only override if callsite did not explicitly set weights_only
  1207. if weights_only_not_set:
  1208. warnings.warn(
  1209. "Environment variable TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD detected, since the"
  1210. "`weights_only` argument was not explicitly passed to `torch.load`, forcing weights_only=False.",
  1211. UserWarning,
  1212. stacklevel=2,
  1213. )
  1214. weights_only = False
  1215. if weights_only:
  1216. if pickle_module is not None:
  1217. raise RuntimeError(
  1218. "Can not safely load weights when explicit pickle_module is specified"
  1219. )
  1220. else:
  1221. if pickle_module is None:
  1222. pickle_module = pickle
  1223. # make flipping default BC-compatible
  1224. if mmap is None:
  1225. from torch.utils.serialization import config
  1226. mmap = config.load.mmap
  1227. _check_dill_version(pickle_module)
  1228. if "encoding" not in pickle_load_args:
  1229. pickle_load_args["encoding"] = "utf-8"
  1230. with _open_file_like(f, "rb") as opened_file:
  1231. if _is_zipfile(opened_file):
  1232. # The zipfile reader is going to advance the current file position.
  1233. # If we want to actually tail call to torch.jit.load, we need to
  1234. # reset back to the original position.
  1235. orig_position = opened_file.tell()
  1236. overall_storage = None
  1237. with _open_zipfile_reader(opened_file) as opened_zipfile:
  1238. if _is_torchscript_zip(opened_zipfile):
  1239. warnings.warn(
  1240. "'torch.load' received a zip file that looks like a TorchScript archive"
  1241. " dispatching to 'torch.jit.load' (call 'torch.jit.load' directly to"
  1242. " silence this warning)",
  1243. UserWarning,
  1244. stacklevel=2,
  1245. )
  1246. if weights_only:
  1247. raise RuntimeError(
  1248. "Cannot use ``weights_only=True`` with TorchScript archives passed to "
  1249. "``torch.load``. " + UNSAFE_MESSAGE
  1250. )
  1251. opened_file.seek(orig_position)
  1252. return torch.jit.load(opened_file, map_location=map_location)
  1253. if mmap:
  1254. if not _is_path(f):
  1255. raise ValueError(
  1256. "f must be a file path in order to use the mmap argument"
  1257. )
  1258. size = os.path.getsize(f)
  1259. if not IS_WINDOWS:
  1260. shared = get_default_mmap_options() == MAP_SHARED
  1261. else:
  1262. shared = False
  1263. overall_storage = torch.UntypedStorage.from_file(
  1264. os.fspath(f),
  1265. shared,
  1266. size,
  1267. )
  1268. if weights_only:
  1269. try:
  1270. return _load(
  1271. opened_zipfile,
  1272. map_location,
  1273. _weights_only_unpickler,
  1274. overall_storage=overall_storage,
  1275. **pickle_load_args,
  1276. )
  1277. except pickle.UnpicklingError as e:
  1278. raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
  1279. return _load(
  1280. opened_zipfile,
  1281. map_location,
  1282. pickle_module,
  1283. overall_storage=overall_storage,
  1284. **pickle_load_args,
  1285. )
  1286. if mmap:
  1287. f_name = "" if not isinstance(f, str) else f"{f}, "
  1288. raise RuntimeError(
  1289. "mmap can only be used with files saved with "
  1290. f"`torch.save({f_name}_use_new_zipfile_serialization=True), "
  1291. "please torch.save your checkpoint with this option in order to use mmap."
  1292. )
  1293. if weights_only:
  1294. try:
  1295. return _legacy_load(
  1296. opened_file,
  1297. map_location,
  1298. _weights_only_unpickler,
  1299. **pickle_load_args,
  1300. )
  1301. except pickle.UnpicklingError as e:
  1302. raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
  1303. return _legacy_load(
  1304. opened_file, map_location, pickle_module, **pickle_load_args
  1305. )
  1306. # Register pickling support for layout instances such as
  1307. # torch.sparse_coo, etc
  1308. def _get_layout(name):
  1309. """Get layout extension object from its string representation."""
  1310. cache = _get_layout.cache # type: ignore[attr-defined]
  1311. if not cache:
  1312. for v in torch.__dict__.values():
  1313. if isinstance(v, torch.layout):
  1314. cache[str(v)] = v
  1315. return cache[name]
  1316. # There are yet not good way to type annotate function attributes https://github.com/python/mypy/issues/2087
  1317. _get_layout.cache = {} # type: ignore[attr-defined]
  1318. copyreg.pickle(torch.layout, lambda obj: (_get_layout, (str(obj),)))
  1319. def _legacy_load(f, map_location, pickle_module, **pickle_load_args):
  1320. deserialized_objects: dict[int, Any] = {}
  1321. restore_location = _get_restore_location(map_location)
  1322. class UnpicklerWrapper(pickle_module.Unpickler): # type: ignore[name-defined]
  1323. def find_class(self, mod_name, name):
  1324. if type(name) is str and "Storage" in name:
  1325. try:
  1326. return StorageType(name)
  1327. except KeyError:
  1328. pass
  1329. return super().find_class(mod_name, name)
  1330. def _check_container_source(container_type, source_file, original_source):
  1331. try:
  1332. current_source = "".join(get_source_lines_and_file(container_type)[0])
  1333. except Exception: # saving the source is optional, so we can ignore any errors
  1334. warnings.warn(
  1335. "Couldn't retrieve source code for container of "
  1336. "type " + container_type.__name__ + ". It won't be checked "
  1337. "for correctness upon loading.",
  1338. stacklevel=2,
  1339. )
  1340. return
  1341. if original_source != current_source:
  1342. if container_type.dump_patches:
  1343. file_name = container_type.__name__ + ".patch"
  1344. diff = difflib.unified_diff(
  1345. current_source.split("\n"),
  1346. original_source.split("\n"),
  1347. source_file,
  1348. source_file,
  1349. lineterm="",
  1350. )
  1351. lines = "\n".join(diff)
  1352. try:
  1353. with open(file_name, "a+") as f:
  1354. file_size = f.seek(0, 2)
  1355. f.seek(0)
  1356. if file_size == 0:
  1357. f.write(lines)
  1358. elif file_size != len(lines) or f.read() != lines:
  1359. raise OSError
  1360. msg = (
  1361. "Saved a reverse patch to " + file_name + ". "
  1362. "Run `patch -p0 < " + file_name + "` to revert your "
  1363. "changes."
  1364. )
  1365. except OSError:
  1366. msg = (
  1367. "Tried to save a patch, but couldn't create a "
  1368. "writable file " + file_name + ". Make sure it "
  1369. "doesn't exist and your working directory is "
  1370. "writable."
  1371. )
  1372. else:
  1373. msg = (
  1374. "you can retrieve the original source code by "
  1375. "accessing the object's source attribute or set "
  1376. "`torch.nn.Module.dump_patches = True` and use the "
  1377. "patch tool to revert the changes."
  1378. )
  1379. msg = f"source code of class '{torch.typename(container_type)}' has changed. {msg}"
  1380. warnings.warn(msg, SourceChangeWarning, stacklevel=2)
  1381. def legacy_load(f):
  1382. deserialized_objects: dict[int, Any] = {}
  1383. def persistent_load(saved_id):
  1384. if isinstance(saved_id, tuple):
  1385. # Ignore containers that don't have any sources saved
  1386. if all(saved_id[1:]):
  1387. _check_container_source(*saved_id)
  1388. return saved_id[0]
  1389. return deserialized_objects[int(saved_id)]
  1390. with (
  1391. closing(
  1392. tarfile.open(fileobj=f, mode="r:", format=tarfile.PAX_FORMAT)
  1393. ) as tar,
  1394. mkdtemp() as tmpdir,
  1395. ):
  1396. if pickle_module is _weights_only_unpickler:
  1397. raise RuntimeError(
  1398. "Cannot use ``weights_only=True`` with files saved in the "
  1399. "legacy .tar format. " + UNSAFE_MESSAGE
  1400. )
  1401. tar.extract("storages", path=tmpdir)
  1402. with open(os.path.join(tmpdir, "storages"), "rb", 0) as f:
  1403. num_storages = pickle_module.load(f, **pickle_load_args)
  1404. for _ in range(num_storages):
  1405. args = pickle_module.load(f, **pickle_load_args)
  1406. key, location, storage_type = args
  1407. dtype = storage_type._dtype
  1408. obj = cast(Storage, torch.UntypedStorage)._new_with_file(
  1409. f, torch._utils._element_size(dtype)
  1410. )
  1411. obj = restore_location(obj, location)
  1412. # TODO: Once we decide to break serialization FC, we can
  1413. # stop wrapping with TypedStorage
  1414. deserialized_objects[key] = torch.storage.TypedStorage(
  1415. wrap_storage=obj, dtype=dtype, _internal=True
  1416. )
  1417. storage_views = pickle_module.load(f, **pickle_load_args)
  1418. for target_cdata, root_cdata, offset, numel in storage_views:
  1419. root = deserialized_objects[root_cdata]
  1420. element_size = torch._utils._element_size(root.dtype)
  1421. offset_bytes = offset * element_size
  1422. # TODO: Once we decide to break serialization FC, we can
  1423. # stop wrapping with TypedStorage
  1424. deserialized_objects[target_cdata] = torch.storage.TypedStorage(
  1425. wrap_storage=root._untyped_storage[
  1426. offset_bytes : offset_bytes + numel * element_size
  1427. ],
  1428. dtype=root.dtype,
  1429. _internal=True,
  1430. )
  1431. tar.extract("tensors", path=tmpdir)
  1432. with open(os.path.join(tmpdir, "tensors"), "rb", 0) as f:
  1433. num_tensors = pickle_module.load(f, **pickle_load_args)
  1434. for _ in range(num_tensors):
  1435. args = pickle_module.load(f, **pickle_load_args)
  1436. key, storage_id, _original_tensor_type = args
  1437. storage = deserialized_objects[storage_id]
  1438. (ndim,) = struct.unpack("<i", f.read(4))
  1439. # skip next 4 bytes; legacy encoding treated ndim as 8 bytes
  1440. f.read(4)
  1441. numel = struct.unpack(f"<{ndim}q", f.read(8 * ndim))
  1442. stride = struct.unpack(f"<{ndim}q", f.read(8 * ndim))
  1443. (storage_offset,) = struct.unpack("<q", f.read(8))
  1444. tensor = torch.empty((0,), dtype=storage.dtype).set_(
  1445. storage._untyped_storage, storage_offset, numel, stride
  1446. )
  1447. deserialized_objects[key] = tensor
  1448. pickle_file = tar.extractfile("pickle")
  1449. unpickler = UnpicklerWrapper(pickle_file, **pickle_load_args)
  1450. unpickler.persistent_load = persistent_load
  1451. result = unpickler.load()
  1452. return result
  1453. deserialized_objects = {}
  1454. def persistent_load(saved_id):
  1455. assert isinstance(saved_id, tuple)
  1456. typename = _maybe_decode_ascii(saved_id[0])
  1457. data = saved_id[1:]
  1458. if typename == "module":
  1459. # Ignore containers that don't have any sources saved
  1460. if all(data[1:]):
  1461. _check_container_source(*data)
  1462. return data[0]
  1463. elif typename == "storage":
  1464. storage_type, root_key, location, numel, view_metadata = data
  1465. location = _maybe_decode_ascii(location)
  1466. dtype = storage_type.dtype
  1467. nbytes = numel * torch._utils._element_size(dtype)
  1468. if root_key not in deserialized_objects:
  1469. if torch._guards.active_fake_mode() is not None:
  1470. obj = cast(Storage, torch.UntypedStorage(nbytes, device="meta"))
  1471. elif _serialization_tls.skip_data:
  1472. obj = cast(Storage, torch.UntypedStorage(nbytes))
  1473. obj = restore_location(obj, location)
  1474. else:
  1475. obj = cast(Storage, torch.UntypedStorage(nbytes))
  1476. obj._torch_load_uninitialized = True
  1477. obj = restore_location(obj, location)
  1478. # TODO: Once we decide to break serialization FC, we can
  1479. # stop wrapping with TypedStorage
  1480. typed_storage = torch.storage.TypedStorage(
  1481. wrap_storage=obj, dtype=dtype, _internal=True
  1482. )
  1483. deserialized_objects[root_key] = typed_storage
  1484. else:
  1485. typed_storage = deserialized_objects[root_key]
  1486. if typed_storage._data_ptr() == 0:
  1487. typed_storage = torch.storage.TypedStorage(
  1488. device=typed_storage._untyped_storage.device,
  1489. dtype=dtype,
  1490. _internal=True,
  1491. )
  1492. if view_metadata is not None:
  1493. view_key, offset, view_size = view_metadata
  1494. offset_bytes = offset * torch._utils._element_size(dtype)
  1495. view_size_bytes = view_size * torch._utils._element_size(dtype)
  1496. if view_key not in deserialized_objects:
  1497. # TODO: Once we decide to break serialization FC, we can
  1498. # stop wrapping with TypedStorage
  1499. deserialized_objects[view_key] = torch.storage.TypedStorage(
  1500. wrap_storage=typed_storage._untyped_storage[
  1501. offset_bytes : offset_bytes + view_size_bytes
  1502. ],
  1503. dtype=dtype,
  1504. _internal=True,
  1505. )
  1506. res = deserialized_objects[view_key]
  1507. else:
  1508. res = typed_storage
  1509. return res
  1510. else:
  1511. raise RuntimeError(f"Unknown saved id type: {saved_id[0]}")
  1512. _check_seekable(f)
  1513. f_should_read_directly = _should_read_directly(f)
  1514. if f_should_read_directly and f.tell() == 0:
  1515. # legacy_load requires that f has fileno()
  1516. # only if offset is zero we can attempt the legacy tar file loader
  1517. try:
  1518. return legacy_load(f)
  1519. except tarfile.TarError:
  1520. if _is_zipfile(f):
  1521. # .zip is used for torch.jit.save and will throw an un-pickling error here
  1522. raise RuntimeError(
  1523. f"{f.name} is a zip archive (did you mean to use torch.jit.load()?)"
  1524. ) from None
  1525. # if not a tarfile, reset file offset and proceed
  1526. f.seek(0)
  1527. magic_number = pickle_module.load(f, **pickle_load_args)
  1528. if magic_number != MAGIC_NUMBER:
  1529. raise RuntimeError("Invalid magic number; corrupt file?")
  1530. protocol_version = pickle_module.load(f, **pickle_load_args)
  1531. if protocol_version != PROTOCOL_VERSION:
  1532. raise RuntimeError(f"Invalid protocol version: {protocol_version}")
  1533. _sys_info = pickle_module.load(f, **pickle_load_args)
  1534. unpickler = UnpicklerWrapper(f, **pickle_load_args)
  1535. unpickler.persistent_load = persistent_load
  1536. result = unpickler.load()
  1537. deserialized_storage_keys = pickle_module.load(f, **pickle_load_args)
  1538. if torch._guards.active_fake_mode() is None and not _serialization_tls.skip_data:
  1539. offset = f.tell() if f_should_read_directly else None
  1540. for key in deserialized_storage_keys:
  1541. assert key in deserialized_objects
  1542. typed_storage = deserialized_objects[key]
  1543. typed_storage._untyped_storage._set_from_file(
  1544. f,
  1545. offset,
  1546. f_should_read_directly,
  1547. torch._utils._element_size(typed_storage.dtype),
  1548. )
  1549. if offset is not None:
  1550. offset = f.tell()
  1551. torch._utils._validate_loaded_sparse_tensors()
  1552. return result
  1553. def _maybe_decode_ascii(bytes_str: bytes | str) -> str:
  1554. # When using encoding='bytes' in Py3, some **internal** keys stored as
  1555. # strings in Py2 are loaded as bytes. This function decodes them with
  1556. # ascii encoding, one that Py3 uses by default.
  1557. #
  1558. # NOTE: This should only be used on internal keys (e.g., `typename` and
  1559. # `location` in `persistent_load` below!
  1560. if isinstance(bytes_str, bytes):
  1561. return bytes_str.decode("ascii")
  1562. return bytes_str
  1563. def _get_restore_location(map_location):
  1564. if map_location is None:
  1565. restore_location = default_restore_location
  1566. elif isinstance(map_location, dict):
  1567. def restore_location(storage, location):
  1568. location = map_location.get(location, location)
  1569. return default_restore_location(storage, location)
  1570. elif isinstance(map_location, (str, bytes)):
  1571. def restore_location(storage, location):
  1572. return default_restore_location(storage, map_location)
  1573. elif isinstance(map_location, torch.device):
  1574. def restore_location(storage, location):
  1575. return default_restore_location(storage, str(map_location))
  1576. else:
  1577. def restore_location(storage, location):
  1578. result = map_location(storage, location)
  1579. if result is None:
  1580. result = default_restore_location(storage, location)
  1581. return result
  1582. return restore_location
  1583. class StorageType:
  1584. def __init__(self, name):
  1585. self._dtype = _get_dtype_from_pickle_storage_type(name)
  1586. @property
  1587. def dtype(self):
  1588. return self._dtype
  1589. def __str__(self):
  1590. return f"StorageType(dtype={self.dtype})"
  1591. def _load(
  1592. zip_file,
  1593. map_location,
  1594. pickle_module,
  1595. pickle_file="data.pkl",
  1596. overall_storage=None,
  1597. **pickle_load_args,
  1598. ):
  1599. restore_location = _get_restore_location(map_location)
  1600. loaded_storages = {}
  1601. can_calculate_storage_offsets = False
  1602. if zip_file.has_record(".format_version"):
  1603. version = zip_file.get_record(".format_version")
  1604. can_calculate_storage_offsets = version >= b"1"
  1605. # check if byteswapping is needed
  1606. byteordername = "byteorder"
  1607. byteorderdata = None
  1608. if zip_file.has_record(byteordername):
  1609. byteorderdata = zip_file.get_record(byteordername)
  1610. if byteorderdata not in [b"little", b"big"]:
  1611. raise ValueError("Unknown endianness type: " + byteorderdata.decode())
  1612. elif (
  1613. get_default_load_endianness() == LoadEndianness.LITTLE
  1614. or get_default_load_endianness() is None
  1615. ):
  1616. byteorderdata = b"little"
  1617. elif get_default_load_endianness() == LoadEndianness.BIG:
  1618. byteorderdata = b"big"
  1619. elif get_default_load_endianness() == LoadEndianness.NATIVE:
  1620. pass
  1621. else:
  1622. raise ValueError("Invalid load endianness type")
  1623. storage_alignment = 64
  1624. if zip_file.has_record(".storage_alignment"):
  1625. storage_alignment = int(zip_file.get_record(".storage_alignment"))
  1626. if (
  1627. not zip_file.has_record(byteordername)
  1628. and get_default_load_endianness() is None
  1629. and sys.byteorder == "big"
  1630. ):
  1631. # Default behaviour was changed
  1632. # See https://github.com/pytorch/pytorch/issues/101688
  1633. warnings.warn(
  1634. "The default load endianness for checkpoints without a byteorder mark "
  1635. "on big endian machines was changed from 'native' to 'little' endian, "
  1636. "to avoid this behavior please use "
  1637. "torch.serialization.set_default_load_endianness to set "
  1638. "the desired default load endianness",
  1639. UserWarning,
  1640. stacklevel=2,
  1641. )
  1642. from torch.utils.serialization import config
  1643. calculate_storage_offsets = config.load.calculate_storage_offsets
  1644. run_debug_asserts = os.environ.get("TORCH_SERIALIZATION_DEBUG", "0") == "1"
  1645. current_offset = None
  1646. # constants from miniz.h/miniz.c
  1647. data_descripter_size64 = 24
  1648. data_descripter_size32 = 16
  1649. mz_uint32_max = 0xFFFFFFFF
  1650. offsets: dict[str, int] = dict()
  1651. def _get_offset(key, name, numel):
  1652. """
  1653. Return the offset of the storage associated with key with record name `name` and size numel.
  1654. It is expected that the zipfile header of this storage starts at current_offset.
  1655. WARNING: This function relies on the behavior of the zipwriter in miniz.c. In particular,
  1656. the behavior of `mz_zip_writer_add_mem_ex_v2`. The behavior of this function must be kept
  1657. in sync with that of miniz!
  1658. After reading a storage of size numel that starts at storage_offset
  1659. if it is the first time that storage was read, update nonlocal variable
  1660. current_offset to the start of the next zipfile header by incrementing
  1661. it by numel and the data descriptor size.
  1662. """
  1663. nonlocal current_offset, offsets
  1664. if name in offsets:
  1665. storage_offset = offsets[name]
  1666. return storage_offset
  1667. if current_offset is None:
  1668. assert key == "0"
  1669. current_offset = zip_file.get_record_offset(name)
  1670. local_header_offset = zip_file.get_record_header_offset(name)
  1671. storage_offset = current_offset
  1672. else:
  1673. storage_offset = zip_file.get_record_offset_no_read(
  1674. current_offset, name, numel, storage_alignment
  1675. )
  1676. local_header_offset = current_offset
  1677. # This is only actually needed for storages that have typed_storage._data_ptr() == 0
  1678. # after being read. Otherwise persistent_load would never "re-call" load_tensor
  1679. # for a given key.
  1680. offsets[name] = storage_offset
  1681. # Increment current_offset to offset where next zipfile header starts
  1682. current_offset = storage_offset + numel
  1683. # add size of data descriptor after payload
  1684. if numel > 0:
  1685. if local_header_offset >= mz_uint32_max or numel >= mz_uint32_max:
  1686. current_offset += data_descripter_size64
  1687. else:
  1688. current_offset += data_descripter_size32
  1689. return storage_offset
  1690. def load_tensor(dtype, numel, key, location):
  1691. name = f"data/{key}"
  1692. if torch._guards.detect_fake_mode(None) is not None:
  1693. nbytes = numel * torch._utils._element_size(dtype)
  1694. storage = torch.UntypedStorage(nbytes, device="meta")
  1695. if can_calculate_storage_offsets:
  1696. storage._checkpoint_offset = _get_offset(key, name, numel)
  1697. else:
  1698. storage._checkpoint_offset = zip_file.get_record_offset(name)
  1699. elif _serialization_tls.skip_data:
  1700. nbytes = numel * torch._utils._element_size(dtype)
  1701. storage = torch.UntypedStorage(nbytes)
  1702. elif overall_storage is not None:
  1703. if can_calculate_storage_offsets and calculate_storage_offsets:
  1704. storage_offset = _get_offset(key, name, numel)
  1705. if run_debug_asserts:
  1706. if storage_offset != zip_file.get_record_offset(name):
  1707. raise RuntimeError(
  1708. "This is a debug assert that was run as the `TORCH_SERIALIZATION_DEBUG` environment "
  1709. f"variable was set: Incorrect offset for {name}, got {storage_offset} expected "
  1710. f"{zip_file.get_record_offset(name)}"
  1711. )
  1712. else:
  1713. storage_offset = zip_file.get_record_offset(name)
  1714. storage = overall_storage[storage_offset : storage_offset + numel]
  1715. else:
  1716. if can_calculate_storage_offsets and run_debug_asserts:
  1717. # This is debug code that we use to test the validity of
  1718. # torch.utils.serialization.config.load.calculate_storage_offsets throughout CI
  1719. storage_offset = _get_offset(key, name, numel)
  1720. if storage_offset != zip_file.get_record_offset(name):
  1721. raise RuntimeError(
  1722. "This is a debug assert that was run as the `TORCH_SERIALIZATION_DEBUG` environment "
  1723. f"variable was set: Incorrect offset for {name}, got {storage_offset} expected "
  1724. f"{zip_file.get_record_offset(name)}"
  1725. )
  1726. storage = (
  1727. zip_file.get_storage_from_record(name, numel, torch.UntypedStorage)
  1728. ._typed_storage()
  1729. ._untyped_storage
  1730. )
  1731. # swap here if byteswapping is needed
  1732. if byteorderdata is not None:
  1733. if byteorderdata.decode() != sys.byteorder:
  1734. storage.byteswap(dtype)
  1735. # TODO: Once we decide to break serialization FC, we can
  1736. # stop wrapping with TypedStorage
  1737. if torch._guards.detect_fake_mode(None) is None:
  1738. wrap_storage = restore_location(storage, location)
  1739. else:
  1740. storage._fake_device = location
  1741. wrap_storage = storage
  1742. typed_storage = torch.storage.TypedStorage(
  1743. wrap_storage=wrap_storage,
  1744. dtype=dtype,
  1745. _internal=True,
  1746. )
  1747. if typed_storage._data_ptr() != 0:
  1748. loaded_storages[key] = typed_storage
  1749. return typed_storage
  1750. def persistent_load(saved_id):
  1751. assert isinstance(saved_id, tuple)
  1752. typename = _maybe_decode_ascii(saved_id[0])
  1753. data = saved_id[1:]
  1754. assert typename == "storage", (
  1755. f"Unknown typename for persistent_load, expected 'storage' but got '{typename}'"
  1756. )
  1757. storage_type, key, location, numel = data
  1758. if storage_type is torch.UntypedStorage:
  1759. dtype = torch.uint8
  1760. else:
  1761. dtype = storage_type.dtype
  1762. if key in loaded_storages:
  1763. typed_storage = loaded_storages[key]
  1764. else:
  1765. nbytes = numel * torch._utils._element_size(dtype)
  1766. typed_storage = load_tensor(
  1767. dtype, nbytes, key, _maybe_decode_ascii(location)
  1768. )
  1769. return typed_storage
  1770. load_module_mapping: dict[str, str] = {
  1771. # See https://github.com/pytorch/pytorch/pull/51633
  1772. "torch.tensor": "torch._tensor"
  1773. }
  1774. # Need to subclass Unpickler instead of directly monkey-patching the find_class method
  1775. # because it's marked readonly in pickle.
  1776. # The type: ignore is because mypy can't statically determine the type of this class.
  1777. class UnpicklerWrapper(pickle_module.Unpickler): # type: ignore[name-defined]
  1778. # from https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path/13405732
  1779. # Lets us override the imports that pickle uses when unpickling an object.
  1780. # This is useful for maintaining BC if we change a module path that tensor instantiation relies on.
  1781. def find_class(self, mod_name, name):
  1782. if type(name) is str and "Storage" in name:
  1783. try:
  1784. return StorageType(name)
  1785. except KeyError:
  1786. pass
  1787. mod_name = load_module_mapping.get(mod_name, mod_name)
  1788. return super().find_class(mod_name, name)
  1789. # Load the data (which may in turn use `persistent_load` to load tensors)
  1790. data_file = io.BytesIO(zip_file.get_record(pickle_file))
  1791. unpickler = UnpicklerWrapper(data_file, **pickle_load_args)
  1792. unpickler.persistent_load = persistent_load
  1793. # Needed for tensors where storage device and rebuild tensor device are
  1794. # not connected (wrapper subclasses and tensors rebuilt using numpy)
  1795. global _serialization_tls
  1796. _serialization_tls.map_location = map_location
  1797. result = unpickler.load()
  1798. _serialization_tls.map_location = None
  1799. torch._utils._validate_loaded_sparse_tensors()
  1800. torch._C._log_api_usage_metadata(
  1801. "torch.load.metadata", {"serialization_id": zip_file.serialization_id()}
  1802. )
  1803. return result
  1804. def _is_torchscript_zip(zip_file):
  1805. return "constants.pkl" in zip_file.get_all_records()