hf_downloader.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. """Utilities for downloading and initializing model weights."""
  2. import fnmatch
  3. import glob
  4. import json
  5. import os
  6. import re
  7. from collections import defaultdict
  8. from typing import Any, Iterable, Iterator, List, Optional, Tuple
  9. import filelock
  10. import huggingface_hub.constants
  11. import numpy as np
  12. import torch
  13. from huggingface_hub import HfFileSystem, snapshot_download
  14. from loguru import logger
  15. from safetensors.torch import load_file, safe_open, save_file
  16. from tqdm.auto import tqdm
  17. from transformers import PretrainedConfig, AutoModelForCausalLM
  18. from aphrodite.common.config import ModelConfig
  19. from aphrodite.quantization.gguf_utils import (GGUFReader, get_tensor_name_map,
  20. MODEL_ARCH_NAMES)
  21. from aphrodite.common.logger import get_loading_progress_bar
  22. from aphrodite.quantization import (QuantizationConfig,
  23. get_quantization_config)
  24. from aphrodite.quantization.schema import QuantParamSchema
  25. _xdg_cache_home = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
  26. _aphrodite_filelocks_path = os.path.join(_xdg_cache_home, "aphrodite/locks/")
  27. def enable_hf_transfer():
  28. """automatically activates hf_transfer
  29. """
  30. if "HF_HUB_ENABLE_HF_TRANSFER" not in os.environ:
  31. try:
  32. # enable hf hub transfer if available
  33. import hf_transfer # type: ignore # noqa
  34. huggingface_hub.constants.HF_HUB_ENABLE_HF_TRANSFER = True
  35. except ImportError:
  36. pass
  37. enable_hf_transfer()
  38. class Disabledtqdm(tqdm):
  39. def __init__(self, *args, **kwargs):
  40. super().__init__(*args, **kwargs, disable=True)
  41. def get_lock(model_name_or_path: str, cache_dir: Optional[str] = None):
  42. lock_dir = cache_dir if cache_dir is not None else _aphrodite_filelocks_path
  43. os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
  44. lock_file_name = model_name_or_path.replace("/", "-") + ".lock"
  45. lock = filelock.SoftFileLock(os.path.join(lock_dir, lock_file_name))
  46. return lock
  47. def _shared_pointers(tensors):
  48. ptrs = defaultdict(list)
  49. for k, v in tensors.items():
  50. ptrs[v.data_ptr()].append(k)
  51. failing = []
  52. for _, names in ptrs.items():
  53. if len(names) > 1:
  54. failing.append(names)
  55. return failing
  56. def convert_bin_to_safetensor_file(
  57. pt_filename: str,
  58. sf_filename: str,
  59. ) -> None:
  60. loaded = torch.load(pt_filename, map_location="cpu")
  61. if "state_dict" in loaded:
  62. loaded = loaded["state_dict"]
  63. shared = _shared_pointers(loaded)
  64. for shared_weights in shared:
  65. for name in shared_weights[1:]:
  66. loaded.pop(name)
  67. # For tensors to be contiguous
  68. loaded = {k: v.contiguous() for k, v in loaded.items()}
  69. dirname = os.path.dirname(sf_filename)
  70. os.makedirs(dirname, exist_ok=True)
  71. save_file(loaded, sf_filename, metadata={"format": "pt"})
  72. # check file size
  73. sf_size = os.stat(sf_filename).st_size
  74. pt_size = os.stat(pt_filename).st_size
  75. if (sf_size - pt_size) / pt_size > 0.01:
  76. raise RuntimeError(f"""The file size different is more than 1%:
  77. - {sf_filename}: {sf_size}
  78. - {pt_filename}: {pt_size}
  79. """)
  80. # check if the tensors are the same
  81. reloaded = load_file(sf_filename)
  82. for k in loaded:
  83. pt_tensor = loaded[k]
  84. sf_tensor = reloaded[k]
  85. if not torch.equal(pt_tensor, sf_tensor):
  86. raise RuntimeError(f"The output tensors do not match for key {k}")
  87. # TODO: Move this to another place.
  88. def get_quant_config(model_config: ModelConfig) -> QuantizationConfig:
  89. quant_cls = get_quantization_config(model_config.quantization)
  90. # Read the quantization config from the HF model config, if available.
  91. # if the quantization if "gguf", we skip and return quant_cls()
  92. if model_config.quantization in ["exl2", "gguf"]:
  93. return quant_cls()
  94. hf_quant_config = getattr(model_config.hf_config, "quantization_config",
  95. None)
  96. if hf_quant_config is not None:
  97. return quant_cls.from_config(hf_quant_config)
  98. model_name_or_path = model_config.model
  99. is_local = os.path.isdir(model_name_or_path)
  100. if not is_local:
  101. # Download the config files.
  102. with get_lock(model_name_or_path, model_config.download_dir):
  103. hf_folder = snapshot_download(
  104. model_name_or_path,
  105. revision=model_config.revision,
  106. allow_patterns="*.json",
  107. cache_dir=model_config.download_dir,
  108. tqdm_class=Disabledtqdm,
  109. )
  110. else:
  111. hf_folder = model_name_or_path
  112. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  113. quant_config_files = [
  114. f for f in config_files if any(
  115. f.endswith(x) for x in quant_cls.get_config_filenames())
  116. ]
  117. if len(quant_config_files) == 0:
  118. raise ValueError(
  119. f"Cannot find the config file for {model_config.quantization}")
  120. if len(quant_config_files) > 1:
  121. raise ValueError(
  122. f"Found multiple config files for {model_config.quantization}: "
  123. f"{quant_config_files}")
  124. quant_config_file = quant_config_files[0]
  125. with open(quant_config_file, "r") as f:
  126. config = json.load(f)
  127. return quant_cls.from_config(config)
  128. def prepare_hf_model_weights(
  129. model_name_or_path: str,
  130. cache_dir: Optional[str] = None,
  131. load_format: str = "auto",
  132. fall_back_to_pt: bool = True,
  133. revision: Optional[str] = None,
  134. ) -> Tuple[str, List[str], bool]:
  135. # Download model weights from huggingface.
  136. is_local = os.path.isdir(model_name_or_path)
  137. use_safetensors = False
  138. # Some quantized models use .pt files for storing the weights.
  139. if load_format == "auto":
  140. allow_patterns = ["*.safetensors", "*.bin"]
  141. elif load_format == "safetensors":
  142. use_safetensors = True
  143. allow_patterns = ["*.safetensors"]
  144. elif load_format == "pt":
  145. allow_patterns = ["*.pt"]
  146. elif load_format == "npcache":
  147. allow_patterns = ["*.bin"]
  148. else:
  149. raise ValueError(f"Unknown load_format: {load_format}")
  150. if fall_back_to_pt:
  151. allow_patterns += ["*.pt"]
  152. if not is_local:
  153. # Before we download we look at that is available:
  154. fs = HfFileSystem()
  155. file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
  156. # depending on what is available we download different things
  157. for pattern in allow_patterns:
  158. matching = fnmatch.filter(file_list, pattern)
  159. if len(matching) > 0:
  160. allow_patterns = [pattern]
  161. break
  162. logger.info(f"Using model weights format {allow_patterns}")
  163. # Use file lock to prevent multiple processes from
  164. # downloading the same model weights at the same time.
  165. with get_lock(model_name_or_path, cache_dir):
  166. hf_folder = snapshot_download(
  167. model_name_or_path,
  168. allow_patterns=allow_patterns,
  169. cache_dir=cache_dir,
  170. tqdm_class=Disabledtqdm,
  171. revision=revision,
  172. )
  173. else:
  174. hf_folder = model_name_or_path
  175. hf_weights_files: List[str] = []
  176. for pattern in allow_patterns:
  177. hf_weights_files += glob.glob(os.path.join(hf_folder, pattern))
  178. if len(hf_weights_files) > 0:
  179. if pattern == "*.safetensors":
  180. use_safetensors = True
  181. break
  182. if not use_safetensors:
  183. # Exclude files that are not needed for inference.
  184. # https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  185. blacklist = [
  186. "training_args.bin",
  187. "optimizer.bin",
  188. "optimizer.pt",
  189. "scheduler.pt",
  190. "scaler.pt",
  191. "trainer_state.json",
  192. "hidden_states.safetensors", # exllamav2
  193. ]
  194. hf_weights_files = [
  195. f for f in hf_weights_files
  196. if not any(f.endswith(x) for x in blacklist)
  197. ]
  198. if len(hf_weights_files) == 0:
  199. raise RuntimeError(
  200. f"Cannot find any model weights with `{model_name_or_path}`")
  201. return hf_folder, hf_weights_files, use_safetensors
  202. def convert_gguf_to_state_dict(checkpoint, config):
  203. model_type = config.model_type
  204. # hack: ggufs have a different name than transformers
  205. if model_type == "cohere":
  206. model_type = "command-r"
  207. elif model_type == "mistral" or model_type == "mixtral":
  208. model_type = "llama"
  209. arch = None
  210. for key, value in MODEL_ARCH_NAMES.items():
  211. if value == model_type:
  212. arch = key
  213. break
  214. if arch is None:
  215. raise RuntimeError(f"Unknown model_type: {model_type}")
  216. num_layers = config.num_hidden_layers
  217. name_map = get_tensor_name_map(arch, num_layers)
  218. with torch.device("meta"):
  219. dummy_model = AutoModelForCausalLM.from_config(config)
  220. state_dict = dummy_model.state_dict()
  221. gguf_to_hf_name_map = {}
  222. keys_to_remove = []
  223. prog = re.compile(
  224. r"model.layers.([^\.]*).block_sparse_moe.experts.([^\.]*).([^\.]*)")
  225. for hf_name in state_dict:
  226. name, suffix = hf_name.rsplit(".", 1)
  227. if match := prog.fullmatch(name): # mixtral
  228. bid, xid, wid = match.groups()
  229. if wid == "w1":
  230. wname = "ffn_gate"
  231. elif wid == "w2":
  232. wname = "ffn_down"
  233. elif wid == "w3":
  234. wname = "ffn_up"
  235. gguf_name = f"blk.{bid}.{wname}.{xid}"
  236. gguf_to_hf_name_map[f"{gguf_name}.{suffix}"] = hf_name
  237. continue
  238. gguf_name = name_map.get_name(name)
  239. if gguf_name:
  240. gguf_to_hf_name_map[f"{gguf_name}.{suffix}"] = hf_name
  241. elif name == "lm_head":
  242. keys_to_remove.append(hf_name)
  243. logger.warning(
  244. f"GGUF tensor name for {hf_name} not found, "
  245. "this is normal if the model uses tie word embeddings.")
  246. else:
  247. logger.warning(
  248. f"GGUF tensor name for {hf_name} in hf state_dict not found.")
  249. for key in keys_to_remove:
  250. state_dict.pop(key)
  251. if os.path.isfile(checkpoint):
  252. results = [GGUFReader(checkpoint)]
  253. elif os.path.isdir(checkpoint):
  254. results = [
  255. GGUFReader(os.path.join(checkpoint, file))
  256. for file in os.listdir(checkpoint)
  257. if os.path.splitext(file)[-1].lower() == ".gguf"
  258. ]
  259. else:
  260. raise RuntimeError(
  261. f"Cannot find any model weights with `{checkpoint}`")
  262. with get_loading_progress_bar() as progress:
  263. task = progress.add_task(
  264. "[cyan]Converting GGUF tensors to PyTorch...",
  265. total=sum([len(result.tensors) for result in results]),
  266. )
  267. for result in results:
  268. for ts in result.tensors:
  269. try:
  270. hf_name = gguf_to_hf_name_map[ts.name]
  271. except KeyError:
  272. logger.warning(
  273. f"hf tensor name for {ts.name} in GGUF not found.")
  274. continue
  275. data = torch.tensor(ts.data)
  276. if state_dict[hf_name].dim() == 2:
  277. data = data.view(state_dict[hf_name].shape[0], -1)
  278. state_dict[hf_name] = data
  279. weight_type = torch.tensor(int(ts.tensor_type),
  280. dtype=torch.int)
  281. if weight_type > 1:
  282. state_dict[hf_name.replace("weight",
  283. "weight_type")] = weight_type
  284. progress.update(task, advance=1)
  285. return state_dict
  286. def hf_model_weights_iterator(
  287. model_name_or_path: str,
  288. cache_dir: Optional[str] = None,
  289. load_format: str = "auto",
  290. revision: Optional[str] = None,
  291. config: Optional[PretrainedConfig] = None,
  292. fall_back_to_pt: Optional[bool] = True,
  293. ) -> Iterator[Tuple[str, torch.Tensor]]:
  294. if model_name_or_path.endswith("gguf"):
  295. for name, param in convert_gguf_to_state_dict(model_name_or_path,
  296. config).items():
  297. yield name, param
  298. return
  299. hf_folder, hf_weights_files, use_safetensors = prepare_hf_model_weights(
  300. model_name_or_path,
  301. cache_dir=cache_dir,
  302. load_format=load_format,
  303. fall_back_to_pt=fall_back_to_pt,
  304. revision=revision,
  305. )
  306. if load_format == "npcache":
  307. # Currently np_cache only support *.bin checkpoints
  308. assert use_safetensors is False
  309. # Convert the model weights from torch tensors to numpy arrays for
  310. # faster loading.
  311. np_folder = os.path.join(hf_folder, "np")
  312. os.makedirs(np_folder, exist_ok=True)
  313. weight_names_file = os.path.join(np_folder, "weight_names.json")
  314. # Use file lock to prevent multiple processes from
  315. # dumping the same model weights to numpy at the same time.
  316. with get_lock(model_name_or_path, cache_dir):
  317. if not os.path.exists(weight_names_file):
  318. weight_names = []
  319. for bin_file in hf_weights_files:
  320. state = torch.load(bin_file, map_location="cpu")
  321. for name, param in state.items():
  322. param_path = os.path.join(np_folder, name)
  323. with open(param_path, "wb") as f:
  324. np.save(f, param.cpu().detach().numpy())
  325. weight_names.append(name)
  326. with open(weight_names_file, "w") as f:
  327. json.dump(weight_names, f)
  328. with open(weight_names_file, "r") as f:
  329. weight_names = json.load(f)
  330. for name in weight_names:
  331. param_path = os.path.join(np_folder, name)
  332. with open(param_path, "rb") as f:
  333. param = np.load(f)
  334. yield name, torch.from_numpy(param)
  335. elif use_safetensors:
  336. for st_file in hf_weights_files:
  337. with safe_open(st_file, framework="pt") as f:
  338. for name in f.keys(): # noqa: SIM118
  339. param = f.get_tensor(name)
  340. yield name, param
  341. else:
  342. for bin_file in hf_weights_files:
  343. state = torch.load(bin_file, map_location="cpu")
  344. for name, param in state.items():
  345. yield name, param
  346. del state
  347. torch.cuda.empty_cache()
  348. def kv_cache_scales_loader(
  349. filename: str, tp_rank: int, tp_size: int, num_hidden_layers: int,
  350. model_type: Optional[str]) -> Iterable[Tuple[int, float]]:
  351. """
  352. A simple utility to read in KV cache scaling factors that have been
  353. previously serialized to disk. Used by the model to populate the appropriate
  354. KV cache scaling factors. The serialization should represent a dictionary
  355. whose keys are the TP ranks and values are another dictionary mapping layers
  356. to their KV cache scaling factors.
  357. Keep this function in sync with the output of examples/fp8/extract_scales.py
  358. """
  359. try:
  360. with open(filename) as f:
  361. context = {
  362. "model_type": model_type,
  363. "num_hidden_layers": num_hidden_layers,
  364. "tp_rank": tp_rank,
  365. "tp_size": tp_size,
  366. }
  367. schema_dct = json.load(f)
  368. schema = QuantParamSchema.model_validate(schema_dct,
  369. context=context)
  370. layer_scales_map = schema.kv_cache.scaling_factor[tp_rank]
  371. return layer_scales_map.items()
  372. except FileNotFoundError:
  373. logger.error(f"File or directory '{filename}' not found.")
  374. except json.JSONDecodeError:
  375. logger.error(f"Error decoding JSON in file '{filename}'.")
  376. except Exception as e:
  377. logger.error(f"An error occurred while reading '{filename}': {e}")
  378. # This section is reached if and only if any of the excepts are hit
  379. # Return an empty iterable (list) => no KV cache scales are loaded
  380. # which ultimately defaults to 1.0 scales
  381. logger.warning("Defaulting to KV cache scaling factors = 1.0 "
  382. f"for all layers in TP rank {tp_rank} "
  383. "as an error occurred during loading.")
  384. return []
  385. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  386. """convert PySafeSlice object from safetensors to torch.Tensor
  387. PySafeSlice object supports indexing, which is done before loading the
  388. actual tensor and can reduce the amount of memory being read into the
  389. memory. However, it does not support more advanced functionalities
  390. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  391. tensor with these more complicated operators, we need to convert to
  392. tensor first.
  393. """
  394. if not isinstance(x, torch.Tensor):
  395. x = x[:]
  396. return x
  397. def default_weight_loader(param: torch.Tensor,
  398. loaded_weight: torch.Tensor) -> None:
  399. """Default weight loader."""
  400. if isinstance(param, torch.nn.parameter.UninitializedParameter):
  401. param.materialize(loaded_weight.shape, dtype=loaded_weight.dtype)
  402. assert param.size() == loaded_weight.size()
  403. param.data.copy_(loaded_weight)
  404. def initialize_dummy_weights(
  405. model: torch.nn.Module,
  406. low: float = -1e-3,
  407. high: float = 1e-3,
  408. ) -> None:
  409. """Initialize model weights with random values.
  410. The model weights must be randomly initialized for accurate performance
  411. measurements. Additionally, the model weights should not cause NaNs in the
  412. forward pass. We empirically found that initializing the weights with
  413. values between -1e-3 and 1e-3 works well for most models.
  414. """
  415. for param in model.state_dict().values():
  416. if torch.is_floating_point(param):
  417. param.data.uniform_(low, high)