hf_downloader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. """Utilities for downloading and initializing model weights."""
  2. import filelock
  3. import glob
  4. import fnmatch
  5. import json
  6. import os
  7. from collections import defaultdict
  8. from typing import Any, Iterator, List, Optional, Tuple
  9. from huggingface_hub import snapshot_download, HfFileSystem
  10. import numpy as np
  11. from safetensors.torch import load_file, save_file, safe_open
  12. import torch
  13. from transformers import PretrainedConfig
  14. from tqdm.auto import tqdm
  15. from aphrodite.common.logger import init_logger
  16. from aphrodite.modeling.layers.quantization import (get_quantization_config,
  17. QuantizationConfig)
  18. logger = init_logger(__name__)
  19. class Disabledtqdm(tqdm): # pylint: disable=inconsistent-mro
  20. def __init__(self, *args, **kwargs):
  21. super().__init__(*args, **kwargs, disable=True)
  22. def get_lock(model_name_or_path: str, cache_dir: Optional[str] = None):
  23. lock_dir = cache_dir if cache_dir is not None else "/tmp"
  24. lock_file_name = model_name_or_path.replace("/", "-") + ".lock"
  25. lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name))
  26. return lock
  27. def _shared_pointers(tensors):
  28. ptrs = defaultdict(list)
  29. for k, v in tensors.items():
  30. ptrs[v.data_ptr()].append(k)
  31. failing = []
  32. for _, names in ptrs.items():
  33. if len(names) > 1:
  34. failing.append(names)
  35. return failing
  36. def convert_bin_to_safetensor_file(
  37. pt_filename: str,
  38. sf_filename: str,
  39. ) -> None:
  40. loaded = torch.load(pt_filename, map_location="cpu")
  41. if "state_dict" in loaded:
  42. loaded = loaded["state_dict"]
  43. shared = _shared_pointers(loaded)
  44. for shared_weights in shared:
  45. for name in shared_weights[1:]:
  46. loaded.pop(name)
  47. # For tensors to be contiguous
  48. loaded = {k: v.contiguous() for k, v in loaded.items()}
  49. dirname = os.path.dirname(sf_filename)
  50. os.makedirs(dirname, exist_ok=True)
  51. save_file(loaded, sf_filename, metadata={"format": "pt"})
  52. # check file size
  53. sf_size = os.stat(sf_filename).st_size
  54. pt_size = os.stat(pt_filename).st_size
  55. if (sf_size - pt_size) / pt_size > 0.01:
  56. raise RuntimeError(f"""The file size different is more than 1%:
  57. - {sf_filename}: {sf_size}
  58. - {pt_filename}: {pt_size}
  59. """)
  60. # check if the tensors are the same
  61. reloaded = load_file(sf_filename)
  62. for k in loaded:
  63. pt_tensor = loaded[k]
  64. sf_tensor = reloaded[k]
  65. if not torch.equal(pt_tensor, sf_tensor):
  66. raise RuntimeError(f"The output tensors do not match for key {k}")
  67. # TODO: Move this to another place.
  68. def get_quant_config(
  69. quantization: str,
  70. model_name_or_path: str,
  71. hf_config: PretrainedConfig,
  72. cache_dir: Optional[str] = None,
  73. ) -> QuantizationConfig:
  74. quant_cls = get_quantization_config(quantization)
  75. # Read the quantization config from the HF model config, if available.
  76. hf_quant_config = getattr(hf_config, "quantization_config", None)
  77. if hf_quant_config is not None:
  78. return quant_cls.from_config(hf_quant_config)
  79. is_local = os.path.isdir(model_name_or_path)
  80. if not is_local:
  81. # Download the config files.
  82. with get_lock(model_name_or_path, cache_dir):
  83. hf_folder = snapshot_download(model_name_or_path,
  84. allow_patterns="*.json",
  85. cache_dir=cache_dir,
  86. tqdm_class=Disabledtqdm)
  87. else:
  88. hf_folder = model_name_or_path
  89. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  90. quant_config_files = [
  91. f for f in config_files if any(
  92. f.endswith(x) for x in quant_cls.get_config_filenames())
  93. ]
  94. if len(quant_config_files) == 0:
  95. raise ValueError(f"Cannot find the config file for {quantization}")
  96. if len(quant_config_files) > 1:
  97. raise ValueError(f"Found multiple config files for {quantization}: "
  98. f"{quant_config_files}")
  99. quant_config_file = quant_config_files[0]
  100. with open(quant_config_file, "r") as f:
  101. config = json.load(f)
  102. return quant_cls.from_config(config)
  103. def prepare_hf_model_weights(
  104. model_name_or_path: str,
  105. cache_dir: Optional[str] = None,
  106. load_format: str = "auto",
  107. fall_back_to_pt: bool = True,
  108. revision: Optional[str] = None,
  109. ) -> Tuple[str, List[str], bool]:
  110. # Download model weights from huggingface.
  111. is_local = os.path.isdir(model_name_or_path)
  112. use_safetensors = False
  113. # Some quantized models use .pt files for storing the weights.
  114. if load_format == "auto":
  115. allow_patterns = ["*.safetensors", "*.bin"]
  116. elif load_format == "safetensors":
  117. use_safetensors = True
  118. allow_patterns = ["*.safetensors"]
  119. elif load_format == "pt":
  120. allow_patterns = ["*.pt"]
  121. elif load_format == "npcache":
  122. allow_patterns = ["*.bin"]
  123. else:
  124. raise ValueError(f"Unknown load_format: {load_format}")
  125. if fall_back_to_pt:
  126. allow_patterns += ["*.pt"]
  127. if not is_local:
  128. # Before we download we look at that is available:
  129. fs = HfFileSystem()
  130. file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
  131. # depending on what is available we download different things
  132. for pattern in allow_patterns:
  133. matching = fnmatch.filter(file_list, pattern)
  134. if len(matching) > 0:
  135. allow_patterns = [pattern]
  136. break
  137. logger.info(f"Downloading model weights {allow_patterns}")
  138. # Use file lock to prevent multiple processes from
  139. # downloading the same model weights at the same time.
  140. with get_lock(model_name_or_path, cache_dir):
  141. hf_folder = snapshot_download(model_name_or_path,
  142. allow_patterns=allow_patterns,
  143. cache_dir=cache_dir,
  144. tqdm_class=Disabledtqdm,
  145. revision=revision)
  146. else:
  147. hf_folder = model_name_or_path
  148. hf_weights_files: List[str] = []
  149. for pattern in allow_patterns:
  150. hf_weights_files += glob.glob(os.path.join(hf_folder, pattern))
  151. if len(hf_weights_files) > 0:
  152. if pattern == "*.safetensors":
  153. use_safetensors = True
  154. break
  155. if not use_safetensors:
  156. # Exclude files that are not needed for inference.
  157. # https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  158. blacklist = [
  159. "training_args.bin",
  160. "optimizer.bin",
  161. "optimizer.pt",
  162. "scheduler.pt",
  163. "scaler.pt",
  164. "trainer_state.json",
  165. ]
  166. hf_weights_files = [
  167. f for f in hf_weights_files
  168. if not any(f.endswith(x) for x in blacklist)
  169. ]
  170. if len(hf_weights_files) == 0:
  171. raise RuntimeError(
  172. f"Cannot find any model weights with `{model_name_or_path}`")
  173. return hf_folder, hf_weights_files, use_safetensors
  174. def hf_model_weights_iterator(
  175. model_name_or_path: str,
  176. cache_dir: Optional[str] = None,
  177. load_format: str = "auto",
  178. revision: Optional[str] = None,
  179. fall_back_to_pt: Optional[bool] = True,
  180. ) -> Iterator[Tuple[str, torch.Tensor]]:
  181. hf_folder, hf_weights_files, use_safetensors = prepare_hf_model_weights(
  182. model_name_or_path,
  183. cache_dir=cache_dir,
  184. load_format=load_format,
  185. fall_back_to_pt=fall_back_to_pt,
  186. revision=revision)
  187. if load_format == "npcache":
  188. # Currently np_cache only support *.bin checkpoints
  189. assert use_safetensors is False
  190. # Convert the model weights from torch tensors to numpy arrays for
  191. # faster loading.
  192. np_folder = os.path.join(hf_folder, "np")
  193. os.makedirs(np_folder, exist_ok=True)
  194. weight_names_file = os.path.join(np_folder, "weight_names.json")
  195. # Use file lock to prevent multiple processes from
  196. # dumping the same model weights to numpy at the same time.
  197. with get_lock(model_name_or_path, cache_dir):
  198. if not os.path.exists(weight_names_file):
  199. weight_names = []
  200. for bin_file in hf_weights_files:
  201. state = torch.load(bin_file, map_location="cpu")
  202. for name, param in state.items():
  203. param_path = os.path.join(np_folder, name)
  204. with open(param_path, "wb") as f:
  205. np.save(f, param.cpu().detach().numpy())
  206. weight_names.append(name)
  207. with open(weight_names_file, "w") as f:
  208. json.dump(weight_names, f)
  209. with open(weight_names_file, "r") as f:
  210. weight_names = json.load(f)
  211. for name in weight_names:
  212. param_path = os.path.join(np_folder, name)
  213. with open(param_path, "rb") as f:
  214. param = np.load(f)
  215. yield name, torch.from_numpy(param)
  216. elif use_safetensors:
  217. for st_file in hf_weights_files:
  218. with safe_open(st_file, framework="pt") as f:
  219. for name in f.keys(): # noqa: SIM118
  220. param = f.get_tensor(name)
  221. yield name, param
  222. else:
  223. for bin_file in hf_weights_files:
  224. state = torch.load(bin_file, map_location="cpu")
  225. for name, param in state.items():
  226. yield name, param
  227. del state
  228. torch.cuda.empty_cache()
  229. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  230. """convert PySafeSlice object from safetensors to torch.Tensor
  231. PySafeSlice object supports indexing, which is done before loading the
  232. actual tensor and can reduce the amount of memory being read into the
  233. memory. However, it does not support more advanced functionalities
  234. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  235. tensor with these more complicated operators, we need to convert to
  236. tensor first.
  237. """
  238. if not isinstance(x, torch.Tensor):
  239. x = x[:]
  240. return x
  241. def default_weight_loader(param: torch.Tensor,
  242. loaded_weight: torch.Tensor) -> None:
  243. """Default weight loader."""
  244. assert param.size() == loaded_weight.size()
  245. param.data.copy_(loaded_weight)
  246. def initialize_dummy_weights(
  247. model: torch.nn.Module,
  248. low: float = -1e-3,
  249. high: float = 1e-3,
  250. ) -> None:
  251. """Initialize model weights with random values.
  252. The model weights must be randomly initialized for accurate performance
  253. measurements. Additionally, the model weights should not cause NaNs in the
  254. forward pass. We empirically found that initializing the weights with
  255. values between -1e-3 and 1e-3 works well for most models.
  256. """
  257. for param in model.state_dict().values():
  258. if torch.is_floating_point(param):
  259. param.data.uniform_(low, high)