hf_downloader.py 19 KB

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