_torch.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. # Copyright 2024 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains pytorch-specific helpers."""
  15. import importlib
  16. import json
  17. import os
  18. import re
  19. from collections import defaultdict, namedtuple
  20. from functools import lru_cache
  21. from pathlib import Path
  22. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Union
  23. from packaging import version
  24. from .. import constants, logging
  25. from ._base import MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory
  26. logger = logging.get_logger(__file__)
  27. if TYPE_CHECKING:
  28. import torch
  29. # SAVING
  30. def save_torch_model(
  31. model: "torch.nn.Module",
  32. save_directory: Union[str, Path],
  33. *,
  34. filename_pattern: Optional[str] = None,
  35. force_contiguous: bool = True,
  36. max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
  37. metadata: Optional[Dict[str, str]] = None,
  38. safe_serialization: bool = True,
  39. is_main_process: bool = True,
  40. shared_tensors_to_discard: Optional[List[str]] = None,
  41. ):
  42. """
  43. Saves a given torch model to disk, handling sharding and shared tensors issues.
  44. See also [`save_torch_state_dict`] to save a state dict with more flexibility.
  45. For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).
  46. The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
  47. saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
  48. an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
  49. [`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
  50. safetensors (the default). Otherwise, the shards are saved as pickle.
  51. Before saving the model, the `save_directory` is cleaned from any previous shard files.
  52. > [!WARNING]
  53. > If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
  54. > size greater than `max_shard_size`.
  55. > [!WARNING]
  56. > If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.
  57. Args:
  58. model (`torch.nn.Module`):
  59. The model to save on disk.
  60. save_directory (`str` or `Path`):
  61. The directory in which the model will be saved.
  62. filename_pattern (`str`, *optional*):
  63. The pattern to generate the files names in which the model will be saved. Pattern must be a string that
  64. can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
  65. Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
  66. parameter.
  67. force_contiguous (`boolean`, *optional*):
  68. Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
  69. model, but it could potentially change performance if the layout of the tensor was chosen specifically for
  70. that reason. Defaults to `True`.
  71. max_shard_size (`int` or `str`, *optional*):
  72. The maximum size of each shard, in bytes. Defaults to 5GB.
  73. metadata (`Dict[str, str]`, *optional*):
  74. Extra information to save along with the model. Some metadata will be added for each dropped tensors.
  75. This information will not be enough to recover the entire shared structure but might help understanding
  76. things.
  77. safe_serialization (`bool`, *optional*):
  78. Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
  79. Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
  80. in a future version.
  81. is_main_process (`bool`, *optional*):
  82. Whether the process calling this is the main process or not. Useful when in distributed training like
  83. TPUs and need to call this function from all processes. In this case, set `is_main_process=True` only on
  84. the main process to avoid race conditions. Defaults to True.
  85. shared_tensors_to_discard (`List[str]`, *optional*):
  86. List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
  87. detected, it will drop the first name alphabetically.
  88. Example:
  89. ```py
  90. >>> from huggingface_hub import save_torch_model
  91. >>> model = ... # A PyTorch model
  92. # Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
  93. >>> save_torch_model(model, "path/to/folder")
  94. # Load model back
  95. >>> from huggingface_hub import load_torch_model # TODO
  96. >>> load_torch_model(model, "path/to/folder")
  97. >>>
  98. ```
  99. """
  100. save_torch_state_dict(
  101. state_dict=model.state_dict(),
  102. filename_pattern=filename_pattern,
  103. force_contiguous=force_contiguous,
  104. max_shard_size=max_shard_size,
  105. metadata=metadata,
  106. safe_serialization=safe_serialization,
  107. save_directory=save_directory,
  108. is_main_process=is_main_process,
  109. shared_tensors_to_discard=shared_tensors_to_discard,
  110. )
  111. def save_torch_state_dict(
  112. state_dict: Dict[str, "torch.Tensor"],
  113. save_directory: Union[str, Path],
  114. *,
  115. filename_pattern: Optional[str] = None,
  116. force_contiguous: bool = True,
  117. max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
  118. metadata: Optional[Dict[str, str]] = None,
  119. safe_serialization: bool = True,
  120. is_main_process: bool = True,
  121. shared_tensors_to_discard: Optional[List[str]] = None,
  122. ) -> None:
  123. """
  124. Save a model state dictionary to the disk, handling sharding and shared tensors issues.
  125. See also [`save_torch_model`] to directly save a PyTorch model.
  126. For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).
  127. The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
  128. saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
  129. an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
  130. [`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
  131. safetensors (the default). Otherwise, the shards are saved as pickle.
  132. Before saving the model, the `save_directory` is cleaned from any previous shard files.
  133. > [!WARNING]
  134. > If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
  135. > size greater than `max_shard_size`.
  136. > [!WARNING]
  137. > If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.
  138. Args:
  139. state_dict (`Dict[str, torch.Tensor]`):
  140. The state dictionary to save.
  141. save_directory (`str` or `Path`):
  142. The directory in which the model will be saved.
  143. filename_pattern (`str`, *optional*):
  144. The pattern to generate the files names in which the model will be saved. Pattern must be a string that
  145. can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
  146. Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
  147. parameter.
  148. force_contiguous (`boolean`, *optional*):
  149. Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
  150. model, but it could potentially change performance if the layout of the tensor was chosen specifically for
  151. that reason. Defaults to `True`.
  152. max_shard_size (`int` or `str`, *optional*):
  153. The maximum size of each shard, in bytes. Defaults to 5GB.
  154. metadata (`Dict[str, str]`, *optional*):
  155. Extra information to save along with the model. Some metadata will be added for each dropped tensors.
  156. This information will not be enough to recover the entire shared structure but might help understanding
  157. things.
  158. safe_serialization (`bool`, *optional*):
  159. Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
  160. Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
  161. in a future version.
  162. is_main_process (`bool`, *optional*):
  163. Whether the process calling this is the main process or not. Useful when in distributed training like
  164. TPUs and need to call this function from all processes. In this case, set `is_main_process=True` only on
  165. the main process to avoid race conditions. Defaults to True.
  166. shared_tensors_to_discard (`List[str]`, *optional*):
  167. List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
  168. detected, it will drop the first name alphabetically.
  169. Example:
  170. ```py
  171. >>> from huggingface_hub import save_torch_state_dict
  172. >>> model = ... # A PyTorch model
  173. # Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
  174. >>> state_dict = model_to_save.state_dict()
  175. >>> save_torch_state_dict(state_dict, "path/to/folder")
  176. ```
  177. """
  178. save_directory = str(save_directory)
  179. if filename_pattern is None:
  180. filename_pattern = (
  181. constants.SAFETENSORS_WEIGHTS_FILE_PATTERN
  182. if safe_serialization
  183. else constants.PYTORCH_WEIGHTS_FILE_PATTERN
  184. )
  185. if metadata is None:
  186. metadata = {}
  187. if safe_serialization:
  188. try:
  189. from safetensors.torch import save_file as save_file_fn
  190. except ImportError as e:
  191. raise ImportError(
  192. "Please install `safetensors` to use safe serialization. "
  193. "You can install it with `pip install safetensors`."
  194. ) from e
  195. # Clean state dict for safetensors
  196. state_dict = _clean_state_dict_for_safetensors(
  197. state_dict,
  198. metadata,
  199. force_contiguous=force_contiguous,
  200. shared_tensors_to_discard=shared_tensors_to_discard,
  201. )
  202. else:
  203. from torch import save as save_file_fn # type: ignore[assignment, no-redef]
  204. logger.warning(
  205. "You are using unsafe serialization. Due to security reasons, it is recommended not to load "
  206. "pickled models from untrusted sources. If you intend to share your model, we strongly recommend "
  207. "using safe serialization by installing `safetensors` with `pip install safetensors`."
  208. )
  209. # Split dict
  210. state_dict_split = split_torch_state_dict_into_shards(
  211. state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size
  212. )
  213. # Only main process should clean up existing files to avoid race conditions in distributed environment
  214. if is_main_process:
  215. existing_files_regex = re.compile(filename_pattern.format(suffix=r"(-\d{5}-of-\d{5})?") + r"(\.index\.json)?")
  216. for filename in os.listdir(save_directory):
  217. if existing_files_regex.match(filename):
  218. try:
  219. logger.debug(f"Removing existing file '{filename}' from folder.")
  220. os.remove(os.path.join(save_directory, filename))
  221. except Exception as e:
  222. logger.warning(
  223. f"Error when trying to remove existing '{filename}' from folder: {e}. Continuing..."
  224. )
  225. # Save each shard
  226. per_file_metadata = {"format": "pt"}
  227. if not state_dict_split.is_sharded:
  228. per_file_metadata.update(metadata)
  229. safe_file_kwargs = {"metadata": per_file_metadata} if safe_serialization else {}
  230. for filename, tensors in state_dict_split.filename_to_tensors.items():
  231. shard = {tensor: state_dict[tensor] for tensor in tensors}
  232. save_file_fn(shard, os.path.join(save_directory, filename), **safe_file_kwargs) # ty: ignore[invalid-argument-type]
  233. logger.debug(f"Shard saved to {filename}")
  234. # Save the index (if any)
  235. if state_dict_split.is_sharded:
  236. index_path = filename_pattern.format(suffix="") + ".index.json"
  237. index = {
  238. "metadata": {**state_dict_split.metadata, **metadata},
  239. "weight_map": state_dict_split.tensor_to_filename,
  240. }
  241. with open(os.path.join(save_directory, index_path), "w") as f:
  242. json.dump(index, f, indent=2)
  243. logger.info(
  244. f"The model is bigger than the maximum size per checkpoint ({max_shard_size}). "
  245. f"Model weighs have been saved in {len(state_dict_split.filename_to_tensors)} checkpoint shards. "
  246. f"You can find where each parameters has been saved in the index located at {index_path}."
  247. )
  248. logger.info(f"Model weights successfully saved to {save_directory}!")
  249. def split_torch_state_dict_into_shards(
  250. state_dict: Dict[str, "torch.Tensor"],
  251. *,
  252. filename_pattern: str = constants.SAFETENSORS_WEIGHTS_FILE_PATTERN,
  253. max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
  254. ) -> StateDictSplit:
  255. """
  256. Split a model state dictionary in shards so that each shard is smaller than a given size.
  257. The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization
  258. made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we
  259. have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
  260. [6+2+2GB], [6+2GB], [6GB].
  261. > [!TIP]
  262. > To save a model state dictionary to the disk, see [`save_torch_state_dict`]. This helper uses
  263. > `split_torch_state_dict_into_shards` under the hood.
  264. > [!WARNING]
  265. > If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
  266. > size greater than `max_shard_size`.
  267. Args:
  268. state_dict (`Dict[str, torch.Tensor]`):
  269. The state dictionary to save.
  270. filename_pattern (`str`, *optional*):
  271. The pattern to generate the files names in which the model will be saved. Pattern must be a string that
  272. can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
  273. Defaults to `"model{suffix}.safetensors"`.
  274. max_shard_size (`int` or `str`, *optional*):
  275. The maximum size of each shard, in bytes. Defaults to 5GB.
  276. Returns:
  277. [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them.
  278. Example:
  279. ```py
  280. >>> import json
  281. >>> import os
  282. >>> from safetensors.torch import save_file as safe_save_file
  283. >>> from huggingface_hub import split_torch_state_dict_into_shards
  284. >>> def save_state_dict(state_dict: Dict[str, torch.Tensor], save_directory: str):
  285. ... state_dict_split = split_torch_state_dict_into_shards(state_dict)
  286. ... for filename, tensors in state_dict_split.filename_to_tensors.items():
  287. ... shard = {tensor: state_dict[tensor] for tensor in tensors}
  288. ... safe_save_file(
  289. ... shard,
  290. ... os.path.join(save_directory, filename),
  291. ... metadata={"format": "pt"},
  292. ... )
  293. ... if state_dict_split.is_sharded:
  294. ... index = {
  295. ... "metadata": state_dict_split.metadata,
  296. ... "weight_map": state_dict_split.tensor_to_filename,
  297. ... }
  298. ... with open(os.path.join(save_directory, "model.safetensors.index.json"), "w") as f:
  299. ... f.write(json.dumps(index, indent=2))
  300. ```
  301. """
  302. return split_state_dict_into_shards_factory(
  303. state_dict,
  304. max_shard_size=max_shard_size,
  305. filename_pattern=filename_pattern,
  306. get_storage_size=get_torch_storage_size,
  307. get_storage_id=get_torch_storage_id,
  308. )
  309. # LOADING
  310. def load_torch_model(
  311. model: "torch.nn.Module",
  312. checkpoint_path: Union[str, os.PathLike],
  313. *,
  314. strict: bool = False,
  315. safe: bool = True,
  316. weights_only: bool = False,
  317. map_location: Optional[Union[str, "torch.device"]] = None,
  318. mmap: bool = False,
  319. filename_pattern: Optional[str] = None,
  320. ) -> NamedTuple:
  321. """
  322. Load a checkpoint into a model, handling both sharded and non-sharded checkpoints.
  323. Args:
  324. model (`torch.nn.Module`):
  325. The model in which to load the checkpoint.
  326. checkpoint_path (`str` or `os.PathLike`):
  327. Path to either the checkpoint file or directory containing the checkpoint(s).
  328. strict (`bool`, *optional*, defaults to `False`):
  329. Whether to strictly enforce that the keys in the model state dict match the keys in the checkpoint.
  330. safe (`bool`, *optional*, defaults to `True`):
  331. If `safe` is True, the safetensors files will be loaded. If `safe` is False, the function
  332. will first attempt to load safetensors files if they are available, otherwise it will fall back to loading
  333. pickle files. `filename_pattern` parameter takes precedence over `safe` parameter.
  334. weights_only (`bool`, *optional*, defaults to `False`):
  335. If True, only loads the model weights without optimizer states and other metadata.
  336. Only supported in PyTorch >= 1.13.
  337. map_location (`str` or `torch.device`, *optional*):
  338. A `torch.device` object, string or a dict specifying how to remap storage locations. It
  339. indicates the location where all tensors should be loaded.
  340. mmap (`bool`, *optional*, defaults to `False`):
  341. Whether to use memory-mapped file loading. Memory mapping can improve loading performance
  342. for large models in PyTorch >= 2.1.0 with zipfile-based checkpoints.
  343. filename_pattern (`str`, *optional*):
  344. The pattern to look for the index file. Pattern must be a string that
  345. can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
  346. Defaults to `"model{suffix}.safetensors"`.
  347. Returns:
  348. `NamedTuple`: A named tuple with `missing_keys` and `unexpected_keys` fields.
  349. - `missing_keys` is a list of str containing the missing keys, i.e. keys that are in the model but not in the checkpoint.
  350. - `unexpected_keys` is a list of str containing the unexpected keys, i.e. keys that are in the checkpoint but not in the model.
  351. Raises:
  352. [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError)
  353. If the checkpoint file or directory does not exist.
  354. [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
  355. If safetensors or torch is not installed when trying to load a .safetensors file or a PyTorch checkpoint respectively.
  356. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  357. If the checkpoint path is invalid or if the checkpoint format cannot be determined.
  358. Example:
  359. ```python
  360. >>> from huggingface_hub import load_torch_model
  361. >>> model = ... # A PyTorch model
  362. >>> load_torch_model(model, "path/to/checkpoint")
  363. ```
  364. """
  365. checkpoint_path = Path(checkpoint_path)
  366. if not checkpoint_path.exists():
  367. raise ValueError(f"Checkpoint path {checkpoint_path} does not exist")
  368. # 1. Check if checkpoint is a single file
  369. if checkpoint_path.is_file():
  370. state_dict = load_state_dict_from_file(
  371. checkpoint_file=checkpoint_path,
  372. map_location=map_location,
  373. weights_only=weights_only,
  374. )
  375. return model.load_state_dict(state_dict, strict=strict)
  376. # 2. If not, checkpoint_path is a directory
  377. if filename_pattern is None:
  378. filename_pattern = constants.SAFETENSORS_WEIGHTS_FILE_PATTERN
  379. index_path = checkpoint_path / (filename_pattern.format(suffix="") + ".index.json")
  380. # Only fallback to pickle format if safetensors index is not found and safe is False.
  381. if not index_path.is_file() and not safe:
  382. filename_pattern = constants.PYTORCH_WEIGHTS_FILE_PATTERN
  383. index_path = checkpoint_path / (filename_pattern.format(suffix="") + ".index.json")
  384. if index_path.is_file():
  385. return _load_sharded_checkpoint(
  386. model=model,
  387. save_directory=checkpoint_path,
  388. strict=strict,
  389. weights_only=weights_only,
  390. filename_pattern=filename_pattern,
  391. )
  392. # Look for single model file
  393. model_files = list(checkpoint_path.glob("*.safetensors" if safe else "*.bin"))
  394. if len(model_files) == 1:
  395. state_dict = load_state_dict_from_file(
  396. checkpoint_file=model_files[0],
  397. map_location=map_location,
  398. weights_only=weights_only,
  399. mmap=mmap,
  400. )
  401. return model.load_state_dict(state_dict, strict=strict)
  402. raise ValueError(
  403. f"Directory '{checkpoint_path}' does not contain a valid checkpoint. "
  404. "Expected either a sharded checkpoint with an index file, or a single model file."
  405. )
  406. def _load_sharded_checkpoint(
  407. model: "torch.nn.Module",
  408. save_directory: os.PathLike,
  409. *,
  410. strict: bool = False,
  411. weights_only: bool = False,
  412. filename_pattern: str = constants.SAFETENSORS_WEIGHTS_FILE_PATTERN,
  413. ) -> NamedTuple:
  414. """
  415. Loads a sharded checkpoint into a model. This is the same as
  416. [`torch.nn.Module.load_state_dict`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=load_state_dict#torch.nn.Module.load_state_dict)
  417. but for a sharded checkpoint. Each shard is loaded one by one and removed from memory after being loaded into the model.
  418. Args:
  419. model (`torch.nn.Module`):
  420. The model in which to load the checkpoint.
  421. save_directory (`str` or `os.PathLike`):
  422. A path to a folder containing the sharded checkpoint.
  423. strict (`bool`, *optional*, defaults to `False`):
  424. Whether to strictly enforce that the keys in the model state dict match the keys in the sharded checkpoint.
  425. weights_only (`bool`, *optional*, defaults to `False`):
  426. If True, only loads the model weights without optimizer states and other metadata.
  427. Only supported in PyTorch >= 1.13.
  428. filename_pattern (`str`, *optional*, defaults to `"model{suffix}.safetensors"`):
  429. The pattern to look for the index file. Pattern must be a string that
  430. can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
  431. Defaults to `"model{suffix}.safetensors"`.
  432. Returns:
  433. `NamedTuple`: A named tuple with `missing_keys` and `unexpected_keys` fields,
  434. - `missing_keys` is a list of str containing the missing keys
  435. - `unexpected_keys` is a list of str containing the unexpected keys
  436. """
  437. # 1. Load and validate index file
  438. # The index file contains mapping of parameter names to shard files
  439. index_path = filename_pattern.format(suffix="") + ".index.json"
  440. index_file = os.path.join(save_directory, index_path)
  441. with open(index_file, "r", encoding="utf-8") as f:
  442. index = json.load(f)
  443. # 2. Validate keys if in strict mode
  444. # This is done before loading any shards to fail fast
  445. if strict:
  446. _validate_keys_for_strict_loading(model, index["weight_map"].keys())
  447. # 3. Load each shard using `load_state_dict`
  448. # Get unique shard files (multiple parameters can be in same shard)
  449. shard_files = list(set(index["weight_map"].values()))
  450. for shard_file in shard_files:
  451. # Load shard into memory
  452. shard_path = os.path.join(save_directory, shard_file)
  453. state_dict = load_state_dict_from_file(
  454. shard_path,
  455. map_location="cpu",
  456. weights_only=weights_only,
  457. )
  458. # Update model with parameters from this shard
  459. model.load_state_dict(state_dict, strict=strict)
  460. # Explicitly remove the state dict from memory
  461. del state_dict
  462. # 4. Return compatibility info
  463. loaded_keys = set(index["weight_map"].keys())
  464. model_keys = set(model.state_dict().keys())
  465. return _IncompatibleKeys(
  466. missing_keys=list(model_keys - loaded_keys), unexpected_keys=list(loaded_keys - model_keys)
  467. )
  468. def load_state_dict_from_file(
  469. checkpoint_file: Union[str, os.PathLike],
  470. map_location: Optional[Union[str, "torch.device"]] = None,
  471. weights_only: bool = False,
  472. mmap: bool = False,
  473. ) -> Union[Dict[str, "torch.Tensor"], Any]:
  474. """
  475. Loads a checkpoint file, handling both safetensors and pickle checkpoint formats.
  476. Args:
  477. checkpoint_file (`str` or `os.PathLike`):
  478. Path to the checkpoint file to load. Can be either a safetensors or pickle (`.bin`) checkpoint.
  479. map_location (`str` or `torch.device`, *optional*):
  480. A `torch.device` object, string or a dict specifying how to remap storage locations. It
  481. indicates the location where all tensors should be loaded.
  482. weights_only (`bool`, *optional*, defaults to `False`):
  483. If True, only loads the model weights without optimizer states and other metadata.
  484. Only supported for pickle (`.bin`) checkpoints with PyTorch >= 1.13. Has no effect when
  485. loading safetensors files.
  486. mmap (`bool`, *optional*, defaults to `False`):
  487. Whether to use memory-mapped file loading. Memory mapping can improve loading performance
  488. for large models in PyTorch >= 2.1.0 with zipfile-based checkpoints. Has no effect when
  489. loading safetensors files, as the `safetensors` library uses memory mapping by default.
  490. Returns:
  491. `Union[Dict[str, "torch.Tensor"], Any]`: The loaded checkpoint.
  492. - For safetensors files: always returns a dictionary mapping parameter names to tensors.
  493. - For pickle files: returns any Python object that was pickled (commonly a state dict, but could be
  494. an entire model, optimizer state, or any other Python object).
  495. Raises:
  496. [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError)
  497. If the checkpoint file does not exist.
  498. [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
  499. If safetensors or torch is not installed when trying to load a .safetensors file or a PyTorch checkpoint respectively.
  500. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
  501. If the checkpoint file format is invalid or if git-lfs files are not properly downloaded.
  502. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  503. If the checkpoint file path is empty or invalid.
  504. Example:
  505. ```python
  506. >>> from huggingface_hub import load_state_dict_from_file
  507. # Load a PyTorch checkpoint
  508. >>> state_dict = load_state_dict_from_file("path/to/model.bin", map_location="cpu")
  509. >>> model.load_state_dict(state_dict)
  510. # Load a safetensors checkpoint
  511. >>> state_dict = load_state_dict_from_file("path/to/model.safetensors")
  512. >>> model.load_state_dict(state_dict)
  513. ```
  514. """
  515. checkpoint_path = Path(checkpoint_file)
  516. # Check if file exists and is a regular file (not a directory)
  517. if not checkpoint_path.is_file():
  518. raise FileNotFoundError(
  519. f"No checkpoint file found at '{checkpoint_path}'. Please verify the path is correct and "
  520. "the file has been properly downloaded."
  521. )
  522. # Load safetensors checkpoint
  523. if checkpoint_path.suffix == ".safetensors":
  524. try:
  525. from safetensors import safe_open
  526. from safetensors.torch import load_file
  527. except ImportError as e:
  528. raise ImportError(
  529. "Please install `safetensors` to load safetensors checkpoint. "
  530. "You can install it with `pip install safetensors`."
  531. ) from e
  532. # Check format of the archive
  533. with safe_open(checkpoint_file, framework="pt") as f: # type: ignore[attr-defined]
  534. metadata = f.metadata()
  535. # see comment: https://github.com/huggingface/transformers/blob/3d213b57fe74302e5902d68ed9478c3ad1aaa713/src/transformers/modeling_utils.py#L3966
  536. if metadata is not None and metadata.get("format") not in ["pt", "mlx"]:
  537. raise OSError(
  538. f"The safetensors archive passed at {checkpoint_file} does not contain the valid metadata. Make sure "
  539. "you save your model with the `save_torch_model` method."
  540. )
  541. device = str(map_location.type) if map_location is not None and hasattr(map_location, "type") else map_location
  542. # meta device is not supported with safetensors, falling back to CPU
  543. if device == "meta":
  544. logger.warning("Meta device is not supported with safetensors. Falling back to CPU device.")
  545. device = "cpu"
  546. return load_file(checkpoint_file, device=device) # type: ignore[arg-type]
  547. # Otherwise, load from pickle
  548. try:
  549. import torch
  550. from torch import load
  551. except ImportError as e:
  552. raise ImportError(
  553. "Please install `torch` to load torch tensors. You can install it with `pip install torch`."
  554. ) from e
  555. # Add additional kwargs, mmap is only supported in torch >= 2.1.0
  556. additional_kwargs = {}
  557. if version.parse(torch.__version__) >= version.parse("2.1.0"):
  558. additional_kwargs["mmap"] = mmap
  559. # weights_only is only supported in torch >= 1.13.0
  560. if version.parse(torch.__version__) >= version.parse("1.13.0"):
  561. additional_kwargs["weights_only"] = weights_only
  562. return load(
  563. checkpoint_file,
  564. map_location=map_location,
  565. **additional_kwargs,
  566. )
  567. # HELPERS
  568. def _validate_keys_for_strict_loading(
  569. model: "torch.nn.Module",
  570. loaded_keys: Iterable[str],
  571. ) -> None:
  572. """
  573. Validate that model keys match loaded keys when strict loading is enabled.
  574. Args:
  575. model: The PyTorch model being loaded
  576. loaded_keys: The keys present in the checkpoint
  577. Raises:
  578. RuntimeError: If there are missing or unexpected keys in strict mode
  579. """
  580. loaded_keys_set = set(loaded_keys)
  581. model_keys = set(model.state_dict().keys())
  582. missing_keys = model_keys - loaded_keys_set # Keys in model but not in checkpoint
  583. unexpected_keys = loaded_keys_set - model_keys # Keys in checkpoint but not in model
  584. if missing_keys or unexpected_keys:
  585. error_message = f"Error(s) in loading state_dict for {model.__class__.__name__}"
  586. if missing_keys:
  587. str_missing_keys = ",".join([f'"{k}"' for k in sorted(missing_keys)])
  588. error_message += f"\nMissing key(s): {str_missing_keys}."
  589. if unexpected_keys:
  590. str_unexpected_keys = ",".join([f'"{k}"' for k in sorted(unexpected_keys)])
  591. error_message += f"\nUnexpected key(s): {str_unexpected_keys}."
  592. raise RuntimeError(error_message)
  593. def _get_unique_id(tensor: "torch.Tensor") -> Union[int, Tuple[Any, ...]]:
  594. """Returns a unique id for plain tensor
  595. or a (potentially nested) Tuple of unique id for the flattened Tensor
  596. if the input is a wrapper tensor subclass Tensor
  597. """
  598. try:
  599. from torch.distributed.tensor import DTensor
  600. if isinstance(tensor, DTensor):
  601. local_tensor = tensor.to_local()
  602. return local_tensor.storage().data_ptr()
  603. except ImportError:
  604. pass
  605. try:
  606. # for torch 2.1 and above we can also handle tensor subclasses
  607. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  608. if is_traceable_wrapper_subclass(tensor):
  609. attrs, _ = tensor.__tensor_flatten__() # type: ignore[attr-defined]
  610. return tuple(_get_unique_id(getattr(tensor, attr)) for attr in attrs)
  611. except ImportError:
  612. # for torch version less than 2.1, we can fallback to original implementation
  613. pass
  614. if tensor.device.type == "xla" and is_torch_tpu_available():
  615. # NOTE: xla tensors dont have storage
  616. # use some other unique id to distinguish.
  617. # this is a XLA tensor, it must be created using torch_xla's
  618. # device. So the following import is safe:
  619. import torch_xla # type: ignore[import]
  620. unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor)
  621. else:
  622. unique_id = storage_ptr(tensor)
  623. return unique_id
  624. def get_torch_storage_id(tensor: "torch.Tensor") -> Optional[Tuple["torch.device", Union[int, Tuple[Any, ...]], int]]:
  625. """
  626. Return unique identifier to a tensor storage.
  627. Multiple different tensors can share the same underlying storage. This identifier is
  628. guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
  629. non-overlapping lifetimes may have the same id.
  630. In the case of meta tensors, we return None since we can't tell if they share the same storage.
  631. Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/pytorch_utils.py#L278.
  632. """
  633. if tensor.device.type == "meta":
  634. return None
  635. else:
  636. return tensor.device, _get_unique_id(tensor), get_torch_storage_size(tensor)
  637. def get_torch_storage_size(tensor: "torch.Tensor") -> int:
  638. """
  639. Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L31C1-L41C59
  640. """
  641. try:
  642. from torch.distributed.tensor import DTensor
  643. if isinstance(tensor, DTensor):
  644. # this returns the size of the FULL tensor in bytes
  645. return tensor.nbytes
  646. except ImportError:
  647. pass
  648. try:
  649. # for torch 2.1 and above we can also handle tensor subclasses
  650. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  651. if is_traceable_wrapper_subclass(tensor):
  652. attrs, _ = tensor.__tensor_flatten__() # type: ignore[attr-defined]
  653. return sum(get_torch_storage_size(getattr(tensor, attr)) for attr in attrs)
  654. except ImportError:
  655. # for torch version less than 2.1, we can fallback to original implementation
  656. pass
  657. try:
  658. return tensor.untyped_storage().nbytes()
  659. except AttributeError:
  660. # Fallback for torch==1.10
  661. try:
  662. return tensor.storage().size() * _get_dtype_size(tensor.dtype)
  663. except NotImplementedError:
  664. # Fallback for meta storage
  665. # On torch >=2.0 this is the tensor size
  666. return tensor.nelement() * _get_dtype_size(tensor.dtype)
  667. @lru_cache()
  668. def is_torch_tpu_available(check_device=True):
  669. """
  670. Checks if `torch_xla` is installed and potentially if a TPU is in the environment
  671. Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/utils/import_utils.py#L463.
  672. """
  673. if importlib.util.find_spec("torch_xla") is not None:
  674. if check_device:
  675. # We need to check if `xla_device` can be found, will raise a RuntimeError if not
  676. try:
  677. import torch_xla.core.xla_model as xm # type: ignore[import]
  678. _ = xm.xla_device()
  679. return True
  680. except RuntimeError:
  681. return False
  682. return True
  683. return False
  684. def storage_ptr(tensor: "torch.Tensor") -> Union[int, Tuple[Any, ...]]:
  685. """
  686. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L11.
  687. """
  688. try:
  689. # for torch 2.1 and above we can also handle tensor subclasses
  690. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  691. if is_traceable_wrapper_subclass(tensor):
  692. return _get_unique_id(tensor) # type: ignore
  693. except ImportError:
  694. # for torch version less than 2.1, we can fallback to original implementation
  695. pass
  696. try:
  697. return tensor.untyped_storage().data_ptr()
  698. except Exception:
  699. # Fallback for torch==1.10
  700. try:
  701. return tensor.storage().data_ptr()
  702. except NotImplementedError:
  703. # Fallback for meta storage
  704. return 0
  705. def _clean_state_dict_for_safetensors(
  706. state_dict: Dict[str, "torch.Tensor"],
  707. metadata: Dict[str, str],
  708. force_contiguous: bool = True,
  709. shared_tensors_to_discard: Optional[List[str]] = None,
  710. ):
  711. """Remove shared tensors from state_dict and update metadata accordingly (for reloading).
  712. Warning: `state_dict` and `metadata` are mutated in-place!
  713. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L155.
  714. """
  715. to_removes = _remove_duplicate_names(state_dict, discard_names=shared_tensors_to_discard)
  716. for kept_name, to_remove_group in to_removes.items():
  717. for to_remove in to_remove_group:
  718. if metadata is None:
  719. metadata = {}
  720. if to_remove not in metadata:
  721. # Do not override user data
  722. metadata[to_remove] = kept_name
  723. del state_dict[to_remove]
  724. if force_contiguous:
  725. state_dict = {k: v.contiguous() for k, v in state_dict.items()}
  726. return state_dict
  727. def _end_ptr(tensor: "torch.Tensor") -> int:
  728. """
  729. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L23.
  730. """
  731. if tensor.nelement():
  732. stop = tensor.view(-1)[-1].data_ptr() + _get_dtype_size(tensor.dtype)
  733. else:
  734. stop = tensor.data_ptr()
  735. return stop
  736. def _filter_shared_not_shared(tensors: List[Set[str]], state_dict: Dict[str, "torch.Tensor"]) -> List[Set[str]]:
  737. """
  738. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L44
  739. """
  740. filtered_tensors = []
  741. for shared in tensors:
  742. if len(shared) < 2:
  743. filtered_tensors.append(shared)
  744. continue
  745. areas = []
  746. for name in shared:
  747. tensor = state_dict[name]
  748. areas.append((tensor.data_ptr(), _end_ptr(tensor), name))
  749. areas.sort()
  750. _, last_stop, last_name = areas[0]
  751. filtered_tensors.append({last_name})
  752. for start, stop, name in areas[1:]:
  753. if start >= last_stop:
  754. filtered_tensors.append({name})
  755. else:
  756. filtered_tensors[-1].add(name)
  757. last_stop = stop
  758. return filtered_tensors
  759. def _find_shared_tensors(state_dict: Dict[str, "torch.Tensor"]) -> List[Set[str]]:
  760. """
  761. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L69.
  762. """
  763. import torch
  764. tensors_dict = defaultdict(set)
  765. for k, v in state_dict.items():
  766. if v.device != torch.device("meta") and storage_ptr(v) != 0 and get_torch_storage_size(v) != 0:
  767. # Need to add device as key because of multiple GPU.
  768. tensors_dict[(v.device, storage_ptr(v), get_torch_storage_size(v))].add(k)
  769. tensors = list(sorted(tensors_dict.values()))
  770. tensors = _filter_shared_not_shared(tensors, state_dict)
  771. return tensors
  772. def _is_complete(tensor: "torch.Tensor") -> bool:
  773. """
  774. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L80
  775. """
  776. try:
  777. # for torch 2.1 and above we can also handle tensor subclasses
  778. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  779. if is_traceable_wrapper_subclass(tensor):
  780. attrs, _ = tensor.__tensor_flatten__() # type: ignore[attr-defined]
  781. return all(_is_complete(getattr(tensor, attr)) for attr in attrs)
  782. except ImportError:
  783. # for torch version less than 2.1, we can fallback to original implementation
  784. pass
  785. return tensor.data_ptr() == storage_ptr(tensor) and tensor.nelement() * _get_dtype_size(
  786. tensor.dtype
  787. ) == get_torch_storage_size(tensor)
  788. def _remove_duplicate_names(
  789. state_dict: Dict[str, "torch.Tensor"],
  790. *,
  791. preferred_names: Optional[List[str]] = None,
  792. discard_names: Optional[List[str]] = None,
  793. ) -> Dict[str, List[str]]:
  794. """
  795. Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L80
  796. """
  797. if preferred_names is None:
  798. preferred_names = []
  799. unique_preferred_names = set(preferred_names)
  800. if discard_names is None:
  801. discard_names = []
  802. unique_discard_names = set(discard_names)
  803. shareds = _find_shared_tensors(state_dict)
  804. to_remove = defaultdict(list)
  805. for shared in shareds:
  806. complete_names = set([name for name in shared if _is_complete(state_dict[name])])
  807. if not complete_names:
  808. raise RuntimeError(
  809. "Error while trying to find names to remove to save state dict, but found no suitable name to keep"
  810. f" for saving amongst: {shared}. None is covering the entire storage. Refusing to save/load the model"
  811. " since you could be storing much more memory than needed. Please refer to"
  812. " https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an"
  813. " issue."
  814. )
  815. keep_name = sorted(list(complete_names))[0]
  816. # Mechanism to preferentially select keys to keep
  817. # coming from the on-disk file to allow
  818. # loading models saved with a different choice
  819. # of keep_name
  820. preferred = complete_names.difference(unique_discard_names)
  821. if preferred:
  822. keep_name = sorted(list(preferred))[0]
  823. if unique_preferred_names:
  824. preferred = unique_preferred_names.intersection(complete_names)
  825. if preferred:
  826. keep_name = sorted(list(preferred))[0]
  827. for name in sorted(shared):
  828. if name != keep_name:
  829. to_remove[keep_name].append(name)
  830. return to_remove
  831. @lru_cache()
  832. def _get_dtype_size(dtype: "torch.dtype") -> int:
  833. """
  834. Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L344
  835. """
  836. import torch
  837. # torch.float8 formats require 2.1; we do not support these dtypes on earlier versions
  838. _float8_e4m3fn = getattr(torch, "float8_e4m3fn", None)
  839. _float8_e5m2 = getattr(torch, "float8_e5m2", None)
  840. _SIZE = {
  841. torch.int64: 8,
  842. torch.float32: 4,
  843. torch.int32: 4,
  844. torch.bfloat16: 2,
  845. torch.float16: 2,
  846. torch.int16: 2,
  847. torch.uint8: 1,
  848. torch.int8: 1,
  849. torch.bool: 1,
  850. torch.float64: 8,
  851. _float8_e4m3fn: 1,
  852. _float8_e5m2: 1,
  853. }
  854. return _SIZE[dtype]
  855. class _IncompatibleKeys(namedtuple("IncompatibleKeys", ["missing_keys", "unexpected_keys"])):
  856. """
  857. This is used to report missing and unexpected keys in the state dict.
  858. Taken from https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/module.py#L52.
  859. """
  860. def __repr__(self) -> str:
  861. if not self.missing_keys and not self.unexpected_keys:
  862. return "<All keys matched successfully>"
  863. return super().__repr__()
  864. __str__ = __repr__