weight_utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. """Utilities for downloading and initializing model weights."""
  2. import fnmatch
  3. import glob
  4. import hashlib
  5. import json
  6. import os
  7. import tempfile
  8. from collections import defaultdict
  9. from typing import Any, Generator, Iterable, List, Optional, Tuple
  10. import filelock
  11. import huggingface_hub.constants
  12. import numpy as np
  13. import torch
  14. from huggingface_hub import HfFileSystem, hf_hub_download, snapshot_download
  15. from loguru import logger
  16. from safetensors.torch import load_file, safe_open, save_file
  17. from tqdm.auto import tqdm
  18. from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
  19. from aphrodite.common.config import LoadConfig, ModelConfig
  20. from aphrodite.quantization import QuantizationConfig, get_quantization_config
  21. from aphrodite.quantization.schema import QuantParamSchema
  22. # use system-level temp directory for file locks, so that multiple users
  23. # can share the same lock without error.
  24. # lock files in the temp directory will be automatically deleted when the
  25. # system reboots, so users will not complain about annoying lock files
  26. temp_dir = tempfile.gettempdir()
  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 or temp_dir
  43. os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
  44. model_name = model_name_or_path.replace("/", "-")
  45. hash_name = hashlib.sha256(model_name.encode()).hexdigest()
  46. # add hash to avoid conflict with old users' lock files
  47. lock_file_name = hash_name + model_name + ".lock"
  48. # mode 0o666 is required for the filelock to be shared across users
  49. lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name),
  50. mode=0o666)
  51. return lock
  52. def _shared_pointers(tensors):
  53. ptrs = defaultdict(list)
  54. for k, v in tensors.items():
  55. ptrs[v.data_ptr()].append(k)
  56. failing = []
  57. for _, names in ptrs.items():
  58. if len(names) > 1:
  59. failing.append(names)
  60. return failing
  61. def convert_bin_to_safetensor_file(
  62. pt_filename: str,
  63. sf_filename: str,
  64. ) -> None:
  65. loaded = torch.load(pt_filename, map_location="cpu")
  66. if "state_dict" in loaded:
  67. loaded = loaded["state_dict"]
  68. shared = _shared_pointers(loaded)
  69. for shared_weights in shared:
  70. for name in shared_weights[1:]:
  71. loaded.pop(name)
  72. # For tensors to be contiguous
  73. loaded = {k: v.contiguous() for k, v in loaded.items()}
  74. dirname = os.path.dirname(sf_filename)
  75. os.makedirs(dirname, exist_ok=True)
  76. save_file(loaded, sf_filename, metadata={"format": "pt"})
  77. # check file size
  78. sf_size = os.stat(sf_filename).st_size
  79. pt_size = os.stat(pt_filename).st_size
  80. if (sf_size - pt_size) / pt_size > 0.01:
  81. raise RuntimeError(f"""The file size different is more than 1%:
  82. - {sf_filename}: {sf_size}
  83. - {pt_filename}: {pt_size}
  84. """)
  85. # check if the tensors are the same
  86. reloaded = load_file(sf_filename)
  87. for k in loaded:
  88. pt_tensor = loaded[k]
  89. sf_tensor = reloaded[k]
  90. if not torch.equal(pt_tensor, sf_tensor):
  91. raise RuntimeError(f"The output tensors do not match for key {k}")
  92. # TODO: Move this to other place.
  93. def get_quant_config(model_config: ModelConfig,
  94. load_config: LoadConfig) -> QuantizationConfig:
  95. quant_cls = get_quantization_config(model_config.quantization)
  96. # Read the quantization config from the HF model config, if available.
  97. hf_quant_config = getattr(model_config.hf_config, "quantization_config",
  98. None)
  99. if hf_quant_config is None:
  100. # compressed-tensors uses a compressions_config
  101. hf_quant_config = getattr(model_config.hf_config, "compression_config",
  102. None)
  103. if hf_quant_config is not None:
  104. return quant_cls.from_config(hf_quant_config)
  105. # In case of bitsandbytes/QLoRA, get quant config from the adapter model.
  106. if model_config.quantization == "bitsandbytes":
  107. if (not load_config.model_loader_extra_config
  108. or "qlora_adapter_name_or_path"
  109. not in load_config.model_loader_extra_config):
  110. return quant_cls.from_config({"adapter_name_or_path": ""})
  111. model_name_or_path = load_config.model_loader_extra_config[
  112. "qlora_adapter_name_or_path"]
  113. else:
  114. model_name_or_path = model_config.model
  115. is_local = os.path.isdir(model_name_or_path)
  116. if not is_local:
  117. # Download the config files.
  118. with get_lock(model_name_or_path, load_config.download_dir):
  119. hf_folder = snapshot_download(
  120. model_name_or_path,
  121. revision=model_config.revision,
  122. allow_patterns="*.json",
  123. cache_dir=load_config.download_dir,
  124. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  125. tqdm_class=DisabledTqdm,
  126. )
  127. else:
  128. hf_folder = model_name_or_path
  129. possible_config_filenames = quant_cls.get_config_filenames()
  130. # If the quantization config is not found, use the default config.
  131. if not possible_config_filenames:
  132. return quant_cls()
  133. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  134. quant_config_files = [
  135. f for f in config_files if any(
  136. f.endswith(x) for x in possible_config_filenames)
  137. ]
  138. if len(quant_config_files) == 0:
  139. raise ValueError(
  140. f"Cannot find the config file for {model_config.quantization}")
  141. if len(quant_config_files) > 1:
  142. raise ValueError(
  143. f"Found multiple config files for {model_config.quantization}: "
  144. f"{quant_config_files}")
  145. quant_config_file = quant_config_files[0]
  146. with open(quant_config_file, "r") as f:
  147. config = json.load(f)
  148. if model_config.quantization == "bitsandbytes":
  149. config["adapter_name_or_path"] = model_name_or_path
  150. return quant_cls.from_config(config)
  151. def download_weights_from_hf(
  152. model_name_or_path: str,
  153. cache_dir: Optional[str],
  154. allow_patterns: List[str],
  155. revision: Optional[str] = None,
  156. ) -> str:
  157. """Download model weights from Hugging Face Hub.
  158. Args:
  159. model_name_or_path (str): The model name or path.
  160. cache_dir (Optional[str]): The cache directory to store the model
  161. weights. If None, will use HF defaults.
  162. allow_patterns (List[str]): The allowed patterns for the
  163. weight files. Files matched by any of the patterns will be
  164. downloaded.
  165. revision (Optional[str]): The revision of the model.
  166. Returns:
  167. str: The path to the downloaded model weights.
  168. """
  169. if not huggingface_hub.constants.HF_HUB_OFFLINE:
  170. # Before we download we look at that is available:
  171. fs = HfFileSystem()
  172. file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
  173. # depending on what is available we download different things
  174. for pattern in allow_patterns:
  175. matching = fnmatch.filter(file_list, pattern)
  176. if len(matching) > 0:
  177. allow_patterns = [pattern]
  178. break
  179. logger.info(f"Using model weights format {allow_patterns}")
  180. # Use file lock to prevent multiple processes from
  181. # downloading the same model weights at the same time.
  182. with get_lock(model_name_or_path, cache_dir):
  183. hf_folder = snapshot_download(
  184. model_name_or_path,
  185. allow_patterns=allow_patterns,
  186. cache_dir=cache_dir,
  187. tqdm_class=DisabledTqdm,
  188. revision=revision,
  189. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  190. )
  191. return hf_folder
  192. def download_safetensors_index_file_from_hf(
  193. model_name_or_path: str,
  194. cache_dir: Optional[str],
  195. revision: Optional[str] = None,
  196. ) -> None:
  197. """Download hf safetensors index file from Hugging Face Hub.
  198. Args:
  199. model_name_or_path (str): The model name or path.
  200. cache_dir (Optional[str]): The cache directory to store the model
  201. weights. If None, will use HF defaults.
  202. revision (Optional[str]): The revision of the model.
  203. """
  204. # Use file lock to prevent multiple processes from
  205. # downloading the same model weights at the same time.
  206. with get_lock(model_name_or_path, cache_dir):
  207. try:
  208. # Download the safetensors index file.
  209. hf_hub_download(
  210. repo_id=model_name_or_path,
  211. filename=SAFE_WEIGHTS_INDEX_NAME,
  212. cache_dir=cache_dir,
  213. revision=revision,
  214. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  215. )
  216. # If file not found on remote or locally, we should not fail since
  217. # only some models will have SAFE_WEIGHTS_INDEX_NAME.
  218. except huggingface_hub.utils.EntryNotFoundError:
  219. logger.info(f"No {SAFE_WEIGHTS_INDEX_NAME} found in remote.")
  220. except huggingface_hub.utils.LocalEntryNotFoundError:
  221. logger.info(f"No {SAFE_WEIGHTS_INDEX_NAME} found in local cache.")
  222. # For models like Mistral-7B-v0.3, there are both sharded
  223. # safetensors files and a consolidated safetensors file.
  224. # Passing both of these to the weight loader functionality breaks.
  225. # So, we use the SAFE_WEIGHTS_INDEX_NAME to
  226. # look up which safetensors files should be used.
  227. def filter_duplicate_safetensors_files(hf_weights_files: List[str],
  228. hf_folder: str) -> List[str]:
  229. # model.safetensors.index.json is a mapping from keys in the
  230. # torch state_dict to safetensors file holding that weight.
  231. index_file_name = os.path.join(hf_folder, SAFE_WEIGHTS_INDEX_NAME)
  232. if not os.path.isfile(index_file_name):
  233. return hf_weights_files
  234. # Iterate through the weight_map (weight_name: safetensors files)
  235. # to identify weights that we should use.
  236. with open(index_file_name) as index_file:
  237. weight_map = json.load(index_file)["weight_map"]
  238. weight_files_in_index = set()
  239. for weight_name in weight_map:
  240. weight_files_in_index.add(
  241. os.path.join(hf_folder, weight_map[weight_name]))
  242. # Filter out any fields that are not found in the index file.
  243. hf_weights_files = [
  244. f for f in hf_weights_files if f in weight_files_in_index
  245. ]
  246. return hf_weights_files
  247. def filter_files_not_needed_for_inference(
  248. hf_weights_files: List[str]) -> List[str]:
  249. """
  250. Exclude files that are not needed for inference.
  251. See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  252. """
  253. blacklist = [
  254. "training_args.bin",
  255. "optimizer.bin",
  256. "optimizer.pt",
  257. "scheduler.pt",
  258. "scaler.pt",
  259. ]
  260. hf_weights_files = [
  261. f for f in hf_weights_files
  262. if not any(f.endswith(x) for x in blacklist)
  263. ]
  264. return hf_weights_files
  265. def np_cache_weights_iterator(
  266. model_name_or_path: str, cache_dir: Optional[str], hf_folder: str,
  267. hf_weights_files: List[str]
  268. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  269. """Iterate over the weights in the model np files.
  270. Will dump the model weights to numpy files if they are not already dumped.
  271. """
  272. # Convert the model weights from torch tensors to numpy arrays for
  273. # faster loading.
  274. np_folder = os.path.join(hf_folder, "np")
  275. os.makedirs(np_folder, exist_ok=True)
  276. weight_names_file = os.path.join(np_folder, "weight_names.json")
  277. # Use file lock to prevent multiple processes from
  278. # dumping the same model weights to numpy at the same time.
  279. with get_lock(model_name_or_path, cache_dir):
  280. if not os.path.exists(weight_names_file):
  281. weight_names = []
  282. for bin_file in hf_weights_files:
  283. state = torch.load(bin_file, map_location="cpu")
  284. for name, param in state.items():
  285. param_path = os.path.join(np_folder, name)
  286. with open(param_path, "wb") as f:
  287. np.save(f, param.cpu().detach().numpy())
  288. weight_names.append(name)
  289. with open(weight_names_file, "w") as f:
  290. json.dump(weight_names, f)
  291. with open(weight_names_file, "r") as f:
  292. weight_names = json.load(f)
  293. for name in weight_names:
  294. param_path = os.path.join(np_folder, name)
  295. with open(param_path, "rb") as f:
  296. param = np.load(f)
  297. yield name, torch.from_numpy(param)
  298. def safetensors_weights_iterator(
  299. hf_weights_files: List[str]
  300. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  301. """Iterate over the weights in the model safetensor files."""
  302. for st_file in hf_weights_files:
  303. with safe_open(st_file, framework="pt") as f:
  304. for name in f.keys(): # noqa: SIM118
  305. param = f.get_tensor(name)
  306. yield name, param
  307. def pt_weights_iterator(
  308. hf_weights_files: List[str]
  309. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  310. """Iterate over the weights in the model bin/pt files."""
  311. for bin_file in hf_weights_files:
  312. state = torch.load(bin_file, map_location="cpu")
  313. for name, param in state.items():
  314. yield name, param
  315. del state
  316. torch.cuda.empty_cache()
  317. def kv_cache_scales_loader(
  318. filename: str, tp_rank: int, tp_size: int, num_hidden_layers: int,
  319. model_type: Optional[str]) -> Iterable[Tuple[int, float]]:
  320. """
  321. A simple utility to read in KV cache scaling factors that have been
  322. previously serialized to disk. Used by the model to populate the appropriate
  323. KV cache scaling factors. The serialization should represent a dictionary
  324. whose keys are the TP ranks and values are another dictionary mapping layers
  325. to their KV cache scaling factors.
  326. Keep this function in sync with the output of examples/fp8/extract_scales.py
  327. """
  328. try:
  329. with open(filename) as f:
  330. context = {
  331. "model_type": model_type,
  332. "num_hidden_layers": num_hidden_layers,
  333. "tp_rank": tp_rank,
  334. "tp_size": tp_size,
  335. }
  336. schema_dct = json.load(f)
  337. schema = QuantParamSchema.model_validate(schema_dct,
  338. context=context)
  339. layer_scales_map = schema.kv_cache.scaling_factor[tp_rank]
  340. return layer_scales_map.items()
  341. except FileNotFoundError:
  342. logger.error(f"File or directory '{filename}' not found.")
  343. except json.JSONDecodeError:
  344. logger.error(f"Error decoding JSON in file '{filename}'.")
  345. except Exception as e:
  346. logger.error(f"An error occurred while reading '{filename}': {e}")
  347. # This section is reached if and only if any of the excepts are hit
  348. # Return an empty iterable (list) => no KV cache scales are loaded
  349. # which ultimately defaults to 1.0 scales
  350. logger.warning("Defaulting to KV cache scaling factors = 1.0 "
  351. f"for all layers in TP rank {tp_rank} "
  352. "as an error occurred during loading.")
  353. return []
  354. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  355. """convert PySafeSlice object from safetensors to torch.Tensor
  356. PySafeSlice object supports indexing, which is done before loading the
  357. actual tensor and can reduce the amount of memory being read into the
  358. memory. However, it does not support more advanced functionalities
  359. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  360. tensor with these more complicated operators, we need to convert to
  361. tensor first.
  362. """
  363. if not isinstance(x, torch.Tensor):
  364. x = x[:]
  365. return x
  366. def default_weight_loader(param: torch.Tensor,
  367. loaded_weight: torch.Tensor) -> None:
  368. """Default weight loader."""
  369. assert param.size() == loaded_weight.size()
  370. param.data.copy_(loaded_weight)
  371. def initialize_dummy_weights(
  372. model: torch.nn.Module,
  373. low: float = -1e-3,
  374. high: float = 1e-3,
  375. ) -> None:
  376. """Initialize model weights with random values.
  377. The model weights must be randomly initialized for accurate performance
  378. measurements. Additionally, the model weights should not cause NaNs in the
  379. forward pass. We empirically found that initializing the weights with
  380. values between -1e-3 and 1e-3 works well for most models.
  381. """
  382. for param in model.state_dict().values():
  383. if torch.is_floating_point(param):
  384. if torch.finfo(param.data.dtype).bits < 16:
  385. # uniform_ doesn't support < 16-bit datatypes (FP8)
  386. dtype = param.data.dtype
  387. tmp_param = param.data.to(torch.float16)
  388. tmp_param = tmp_param.uniform_(low, high).to(dtype)
  389. param.data.copy_(tmp_param)
  390. else:
  391. param.uniform_(low, high)