weight_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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, snapshot_download
  15. from safetensors.torch import load_file, safe_open, save_file
  16. from tqdm.auto import tqdm
  17. from loguru import logger
  18. from aphrodite.common.config import LoadConfig, ModelConfig
  19. from aphrodite.quantization import (QuantizationConfig,
  20. 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 not None:
  100. return quant_cls.from_config(hf_quant_config)
  101. model_name_or_path = model_config.model
  102. is_local = os.path.isdir(model_name_or_path)
  103. if not is_local:
  104. # Download the config files.
  105. with get_lock(model_name_or_path, load_config.download_dir):
  106. hf_folder = snapshot_download(model_name_or_path,
  107. revision=model_config.revision,
  108. allow_patterns="*.json",
  109. cache_dir=load_config.download_dir,
  110. tqdm_class=DisabledTqdm)
  111. else:
  112. hf_folder = model_name_or_path
  113. possible_config_filenames = quant_cls.get_config_filenames()
  114. # If the quantization config is not found, use the default config.
  115. if not possible_config_filenames:
  116. return quant_cls()
  117. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  118. quant_config_files = [
  119. f for f in config_files if any(
  120. f.endswith(x) for x in possible_config_filenames)
  121. ]
  122. if len(quant_config_files) == 0:
  123. raise ValueError(
  124. f"Cannot find the config file for {model_config.quantization}")
  125. if len(quant_config_files) > 1:
  126. raise ValueError(
  127. f"Found multiple config files for {model_config.quantization}: "
  128. f"{quant_config_files}")
  129. quant_config_file = quant_config_files[0]
  130. with open(quant_config_file, "r") as f:
  131. config = json.load(f)
  132. return quant_cls.from_config(config)
  133. def download_weights_from_hf(model_name_or_path: str,
  134. cache_dir: Optional[str],
  135. allow_patterns: List[str],
  136. revision: Optional[str] = None) -> str:
  137. """Download model weights from Hugging Face Hub.
  138. Args:
  139. model_name_or_path (str): The model name or path.
  140. cache_dir (Optional[str]): The cache directory to store the model
  141. weights. If None, will use HF defaults.
  142. allow_patterns (List[str]): The allowed patterns for the
  143. weight files. Files matched by any of the patterns will be
  144. downloaded.
  145. revision (Optional[str]): The revision of the model.
  146. Returns:
  147. str: The path to the downloaded model weights.
  148. """
  149. # Before we download we look at that is available:
  150. fs = HfFileSystem()
  151. file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
  152. # depending on what is available we download different things
  153. for pattern in allow_patterns:
  154. matching = fnmatch.filter(file_list, pattern)
  155. if len(matching) > 0:
  156. allow_patterns = [pattern]
  157. break
  158. logger.info(f"Using model weights format {allow_patterns}")
  159. # Use file lock to prevent multiple processes from
  160. # downloading the same model weights at the same time.
  161. with get_lock(model_name_or_path, cache_dir):
  162. hf_folder = snapshot_download(model_name_or_path,
  163. allow_patterns=allow_patterns,
  164. cache_dir=cache_dir,
  165. tqdm_class=DisabledTqdm,
  166. revision=revision)
  167. return hf_folder
  168. def filter_files_not_needed_for_inference(
  169. hf_weights_files: List[str]) -> List[str]:
  170. """
  171. Exclude files that are not needed for inference.
  172. See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  173. """
  174. blacklist = [
  175. "training_args.bin",
  176. "optimizer.bin",
  177. "optimizer.pt",
  178. "scheduler.pt",
  179. "scaler.pt",
  180. ]
  181. hf_weights_files = [
  182. f for f in hf_weights_files
  183. if not any(f.endswith(x) for x in blacklist)
  184. ]
  185. return hf_weights_files
  186. def np_cache_weights_iterator(
  187. model_name_or_path: str, cache_dir: Optional[str], hf_folder: str,
  188. hf_weights_files: List[str]
  189. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  190. """Iterate over the weights in the model np files.
  191. Will dump the model weights to numpy files if they are not already dumped.
  192. """
  193. # Convert the model weights from torch tensors to numpy arrays for
  194. # faster loading.
  195. np_folder = os.path.join(hf_folder, "np")
  196. os.makedirs(np_folder, exist_ok=True)
  197. weight_names_file = os.path.join(np_folder, "weight_names.json")
  198. # Use file lock to prevent multiple processes from
  199. # dumping the same model weights to numpy at the same time.
  200. with get_lock(model_name_or_path, cache_dir):
  201. if not os.path.exists(weight_names_file):
  202. weight_names = []
  203. for bin_file in hf_weights_files:
  204. state = torch.load(bin_file, map_location="cpu")
  205. for name, param in state.items():
  206. param_path = os.path.join(np_folder, name)
  207. with open(param_path, "wb") as f:
  208. np.save(f, param.cpu().detach().numpy())
  209. weight_names.append(name)
  210. with open(weight_names_file, "w") as f:
  211. json.dump(weight_names, f)
  212. with open(weight_names_file, "r") as f:
  213. weight_names = json.load(f)
  214. for name in weight_names:
  215. param_path = os.path.join(np_folder, name)
  216. with open(param_path, "rb") as f:
  217. param = np.load(f)
  218. yield name, torch.from_numpy(param)
  219. def safetensors_weights_iterator(
  220. hf_weights_files: List[str]
  221. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  222. """Iterate over the weights in the model safetensor files."""
  223. for st_file in hf_weights_files:
  224. with safe_open(st_file, framework="pt") as f:
  225. for name in f.keys(): # noqa: SIM118
  226. param = f.get_tensor(name)
  227. yield name, param
  228. def pt_weights_iterator(
  229. hf_weights_files: List[str]
  230. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  231. """Iterate over the weights in the model bin/pt files."""
  232. for bin_file in hf_weights_files:
  233. state = torch.load(bin_file, map_location="cpu")
  234. for name, param in state.items():
  235. yield name, param
  236. del state
  237. torch.cuda.empty_cache()
  238. def kv_cache_scales_loader(
  239. filename: str, tp_rank: int, tp_size: int, num_hidden_layers: int,
  240. model_type: Optional[str]) -> Iterable[Tuple[int, float]]:
  241. """
  242. A simple utility to read in KV cache scaling factors that have been
  243. previously serialized to disk. Used by the model to populate the appropriate
  244. KV cache scaling factors. The serialization should represent a dictionary
  245. whose keys are the TP ranks and values are another dictionary mapping layers
  246. to their KV cache scaling factors.
  247. Keep this function in sync with the output of examples/fp8/extract_scales.py
  248. """
  249. try:
  250. with open(filename) as f:
  251. context = {
  252. "model_type": model_type,
  253. "num_hidden_layers": num_hidden_layers,
  254. "tp_rank": tp_rank,
  255. "tp_size": tp_size,
  256. }
  257. schema_dct = json.load(f)
  258. schema = QuantParamSchema.model_validate(schema_dct,
  259. context=context)
  260. layer_scales_map = schema.kv_cache.scaling_factor[tp_rank]
  261. return layer_scales_map.items()
  262. except FileNotFoundError:
  263. logger.error(f"File or directory '{filename}' not found.")
  264. except json.JSONDecodeError:
  265. logger.error(f"Error decoding JSON in file '{filename}'.")
  266. except Exception as e:
  267. logger.error(f"An error occurred while reading '{filename}': {e}")
  268. # This section is reached if and only if any of the excepts are hit
  269. # Return an empty iterable (list) => no KV cache scales are loaded
  270. # which ultimately defaults to 1.0 scales
  271. logger.warning("Defaulting to KV cache scaling factors = 1.0 "
  272. f"for all layers in TP rank {tp_rank} "
  273. "as an error occurred during loading.")
  274. return []
  275. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  276. """convert PySafeSlice object from safetensors to torch.Tensor
  277. PySafeSlice object supports indexing, which is done before loading the
  278. actual tensor and can reduce the amount of memory being read into the
  279. memory. However, it does not support more advanced functionalities
  280. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  281. tensor with these more complicated operators, we need to convert to
  282. tensor first.
  283. """
  284. if not isinstance(x, torch.Tensor):
  285. x = x[:]
  286. return x
  287. def default_weight_loader(param: torch.Tensor,
  288. loaded_weight: torch.Tensor) -> None:
  289. """Default weight loader."""
  290. assert param.size() == loaded_weight.size()
  291. param.data.copy_(loaded_weight)
  292. def initialize_dummy_weights(
  293. model: torch.nn.Module,
  294. low: float = -1e-3,
  295. high: float = 1e-3,
  296. ) -> None:
  297. """Initialize model weights with random values.
  298. The model weights must be randomly initialized for accurate performance
  299. measurements. Additionally, the model weights should not cause NaNs in the
  300. forward pass. We empirically found that initializing the weights with
  301. values between -1e-3 and 1e-3 works well for most models.
  302. """
  303. for param in model.state_dict().values():
  304. if torch.is_floating_point(param):
  305. param.data.uniform_(low, high)