weight_utils.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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, Dict, Generator, Iterable, List, Optional, Tuple, Union
  10. import filelock
  11. import gguf
  12. import huggingface_hub.constants
  13. import numpy as np
  14. import torch
  15. from huggingface_hub import HfFileSystem, hf_hub_download, snapshot_download
  16. from loguru import logger
  17. from safetensors.torch import load_file, safe_open, save_file
  18. from tqdm.auto import tqdm
  19. from aphrodite.common.config import LoadConfig, ModelConfig
  20. from aphrodite.common.utils import print_warning_once
  21. from aphrodite.distributed import get_tensor_model_parallel_rank
  22. from aphrodite.platforms import current_platform
  23. from aphrodite.quantization import QuantizationConfig, get_quantization_config
  24. from aphrodite.quantization.schema import QuantParamSchema
  25. # use system-level temp directory for file locks, so that multiple users
  26. # can share the same lock without error.
  27. # lock files in the temp directory will be automatically deleted when the
  28. # system reboots, so users will not complain about annoying lock files
  29. temp_dir = tempfile.gettempdir()
  30. def enable_hf_transfer():
  31. """automatically activates hf_transfer
  32. """
  33. if "HF_HUB_ENABLE_HF_TRANSFER" not in os.environ:
  34. try:
  35. # enable hf hub transfer if available
  36. import hf_transfer # type: ignore # noqa
  37. huggingface_hub.constants.HF_HUB_ENABLE_HF_TRANSFER = True
  38. except ImportError:
  39. pass
  40. enable_hf_transfer()
  41. class DisabledTqdm(tqdm):
  42. def __init__(self, *args, **kwargs):
  43. super().__init__(*args, **kwargs, disable=True)
  44. def get_lock(model_name_or_path: str, cache_dir: Optional[str] = None):
  45. lock_dir = cache_dir or temp_dir
  46. os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
  47. model_name = model_name_or_path.replace("/", "-")
  48. hash_name = hashlib.sha256(model_name.encode()).hexdigest()
  49. # add hash to avoid conflict with old users' lock files
  50. lock_file_name = hash_name + model_name + ".lock"
  51. # mode 0o666 is required for the filelock to be shared across users
  52. lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name),
  53. mode=0o666)
  54. return lock
  55. def _shared_pointers(tensors):
  56. ptrs = defaultdict(list)
  57. for k, v in tensors.items():
  58. ptrs[v.data_ptr()].append(k)
  59. failing = []
  60. for _, names in ptrs.items():
  61. if len(names) > 1:
  62. failing.append(names)
  63. return failing
  64. def convert_bin_to_safetensor_file(
  65. pt_filename: str,
  66. sf_filename: str,
  67. ) -> None:
  68. loaded = torch.load(pt_filename, map_location="cpu")
  69. if "state_dict" in loaded:
  70. loaded = loaded["state_dict"]
  71. shared = _shared_pointers(loaded)
  72. for shared_weights in shared:
  73. for name in shared_weights[1:]:
  74. loaded.pop(name)
  75. # For tensors to be contiguous
  76. loaded = {k: v.contiguous() for k, v in loaded.items()}
  77. dirname = os.path.dirname(sf_filename)
  78. os.makedirs(dirname, exist_ok=True)
  79. save_file(loaded, sf_filename, metadata={"format": "pt"})
  80. # check file size
  81. sf_size = os.stat(sf_filename).st_size
  82. pt_size = os.stat(pt_filename).st_size
  83. if (sf_size - pt_size) / pt_size > 0.01:
  84. raise RuntimeError(f"""The file size different is more than 1%:
  85. - {sf_filename}: {sf_size}
  86. - {pt_filename}: {pt_size}
  87. """)
  88. # check if the tensors are the same
  89. reloaded = load_file(sf_filename)
  90. for k in loaded:
  91. pt_tensor = loaded[k]
  92. sf_tensor = reloaded[k]
  93. if not torch.equal(pt_tensor, sf_tensor):
  94. raise RuntimeError(f"The output tensors do not match for key {k}")
  95. # TODO: Move this to other place.
  96. def get_quant_config(model_config: ModelConfig,
  97. load_config: LoadConfig) -> QuantizationConfig:
  98. quant_cls = get_quantization_config(model_config.quantization)
  99. # GGUF doesn't have config file
  100. if model_config.quantization == "gguf":
  101. return quant_cls.from_config({})
  102. # Read the quantization config from the HF model config, if available.
  103. hf_quant_config = getattr(model_config.hf_config, "quantization_config",
  104. None)
  105. # some vision model may keep quantization_config in their text_config
  106. hf_text_config = getattr(model_config.hf_config, "text_config", None)
  107. if hf_quant_config is None and hf_text_config is not None:
  108. hf_quant_config = getattr(hf_text_config, "quantization_config", None)
  109. if hf_quant_config is None:
  110. # compressed-tensors uses a compressions_config
  111. hf_quant_config = getattr(model_config.hf_config, "compression_config",
  112. None)
  113. if hf_quant_config is not None:
  114. return quant_cls.from_config(hf_quant_config)
  115. # In case of bitsandbytes/QLoRA, get quant config from the adapter model.
  116. if model_config.quantization == "bitsandbytes":
  117. if (not load_config.model_loader_extra_config
  118. or "qlora_adapter_name_or_path"
  119. not in load_config.model_loader_extra_config):
  120. return quant_cls.from_config({"adapter_name_or_path": ""})
  121. model_name_or_path = load_config.model_loader_extra_config[
  122. "qlora_adapter_name_or_path"]
  123. else:
  124. model_name_or_path = model_config.model
  125. is_local = os.path.isdir(model_name_or_path)
  126. if not is_local:
  127. # Download the config files.
  128. with get_lock(model_name_or_path, load_config.download_dir):
  129. hf_folder = snapshot_download(
  130. model_name_or_path,
  131. revision=model_config.revision,
  132. allow_patterns="*.json",
  133. cache_dir=load_config.download_dir,
  134. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  135. tqdm_class=DisabledTqdm,
  136. )
  137. else:
  138. hf_folder = model_name_or_path
  139. possible_config_filenames = quant_cls.get_config_filenames()
  140. # If the quantization config is not found, use the default config.
  141. if not possible_config_filenames:
  142. return quant_cls()
  143. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  144. quant_config_files = [
  145. f for f in config_files if any(
  146. f.endswith(x) for x in possible_config_filenames)
  147. ]
  148. if len(quant_config_files) == 0:
  149. raise ValueError(
  150. f"Cannot find the config file for {model_config.quantization}")
  151. if len(quant_config_files) > 1:
  152. raise ValueError(
  153. f"Found multiple config files for {model_config.quantization}: "
  154. f"{quant_config_files}")
  155. quant_config_file = quant_config_files[0]
  156. with open(quant_config_file, "r") as f:
  157. config = json.load(f)
  158. if model_config.quantization == "bitsandbytes":
  159. config["adapter_name_or_path"] = model_name_or_path
  160. elif model_config.quantization == "modelopt":
  161. if config["producer"]["name"] == "modelopt":
  162. return quant_cls.from_config(config)
  163. else:
  164. raise ValueError(
  165. f"Unsupported quantization config"
  166. f" found for {model_config.quantization} in {f}.")
  167. return quant_cls.from_config(config)
  168. def download_weights_from_hf(
  169. model_name_or_path: str,
  170. cache_dir: Optional[str],
  171. allow_patterns: List[str],
  172. revision: Optional[str] = None,
  173. ignore_patterns: Optional[Union[str, List[str]]] = None,
  174. ) -> str:
  175. """Download model weights from Hugging Face Hub.
  176. Args:
  177. model_name_or_path (str): The model name or path.
  178. cache_dir (Optional[str]): The cache directory to store the model
  179. weights. If None, will use HF defaults.
  180. allow_patterns (List[str]): The allowed patterns for the
  181. weight files. Files matched by any of the patterns will be
  182. downloaded.
  183. revision (Optional[str]): The revision of the model.
  184. ignore_patterns (Optional[Union[str, List[str]]]): The patterns to
  185. filter out the weight files. Files matched by any of the patterns
  186. will be ignored.
  187. Returns:
  188. str: The path to the downloaded model weights.
  189. """
  190. if not huggingface_hub.constants.HF_HUB_OFFLINE:
  191. # Before we download we look at that is available:
  192. fs = HfFileSystem()
  193. file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
  194. # depending on what is available we download different things
  195. for pattern in allow_patterns:
  196. matching = fnmatch.filter(file_list, pattern)
  197. if len(matching) > 0:
  198. allow_patterns = [pattern]
  199. break
  200. rank = (get_tensor_model_parallel_rank() if
  201. torch.distributed.is_initialized() else 0)
  202. if rank == 0:
  203. logger.info(f"Using model weights format {allow_patterns}")
  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. hf_folder = snapshot_download(
  208. model_name_or_path,
  209. allow_patterns=allow_patterns,
  210. ignore_patterns=ignore_patterns,
  211. cache_dir=cache_dir,
  212. tqdm_class=DisabledTqdm,
  213. revision=revision,
  214. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  215. )
  216. return hf_folder
  217. def download_safetensors_index_file_from_hf(
  218. model_name_or_path: str,
  219. index_file: str,
  220. cache_dir: Optional[str],
  221. revision: Optional[str] = None,
  222. ) -> None:
  223. """Download hf safetensors index file from Hugging Face Hub.
  224. Args:
  225. model_name_or_path (str): The model name or path.
  226. cache_dir (Optional[str]): The cache directory to store the model
  227. weights. If None, will use HF defaults.
  228. revision (Optional[str]): The revision of the model.
  229. """
  230. # Use file lock to prevent multiple processes from
  231. # downloading the same model weights at the same time.
  232. with get_lock(model_name_or_path, cache_dir):
  233. try:
  234. # Download the safetensors index file.
  235. hf_hub_download(
  236. repo_id=model_name_or_path,
  237. filename=index_file,
  238. cache_dir=cache_dir,
  239. revision=revision,
  240. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  241. )
  242. # If file not found on remote or locally, we should not fail since
  243. # only some models will have index_file.
  244. except huggingface_hub.utils.EntryNotFoundError:
  245. logger.info(f"No {index_file} found in remote.")
  246. except huggingface_hub.utils.LocalEntryNotFoundError:
  247. logger.info(f"No {index_file} found in local cache.")
  248. # For models like Mistral-7B-v0.3, there are both sharded
  249. # safetensors files and a consolidated safetensors file.
  250. # Passing both of these to the weight loader functionality breaks.
  251. # So, we use the index_file to
  252. # look up which safetensors files should be used.
  253. def filter_duplicate_safetensors_files(hf_weights_files: List[str],
  254. hf_folder: str,
  255. index_file: str) -> List[str]:
  256. # model.safetensors.index.json is a mapping from keys in the
  257. # torch state_dict to safetensors file holding that weight.
  258. index_file_name = os.path.join(hf_folder, index_file)
  259. if not os.path.isfile(index_file_name):
  260. return hf_weights_files
  261. # Iterate through the weight_map (weight_name: safetensors files)
  262. # to identify weights that we should use.
  263. with open(index_file_name, "r") as f:
  264. weight_map = json.load(f)["weight_map"]
  265. weight_files_in_index = set()
  266. for weight_name in weight_map:
  267. weight_files_in_index.add(
  268. os.path.join(hf_folder, weight_map[weight_name]))
  269. # Filter out any fields that are not found in the index file.
  270. hf_weights_files = [
  271. f for f in hf_weights_files if f in weight_files_in_index
  272. ]
  273. return hf_weights_files
  274. def filter_files_not_needed_for_inference(
  275. hf_weights_files: List[str]) -> List[str]:
  276. """
  277. Exclude files that are not needed for inference.
  278. See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  279. """
  280. blacklist = [
  281. "training_args.bin",
  282. "optimizer.bin",
  283. "optimizer.pt",
  284. "scheduler.pt",
  285. "scaler.pt",
  286. ]
  287. hf_weights_files = [
  288. f for f in hf_weights_files
  289. if not any(f.endswith(x) for x in blacklist)
  290. ]
  291. return hf_weights_files
  292. def np_cache_weights_iterator(
  293. model_name_or_path: str, cache_dir: Optional[str], hf_folder: str,
  294. hf_weights_files: List[str]
  295. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  296. """Iterate over the weights in the model np files.
  297. Will dump the model weights to numpy files if they are not already dumped.
  298. """
  299. enable_tqdm = False #not torch.distributed.is_initialized(
  300. #) or torch.distributed.get_rank() == 0
  301. # Convert the model weights from torch tensors to numpy arrays for
  302. # faster loading.
  303. np_folder = os.path.join(hf_folder, "np")
  304. os.makedirs(np_folder, exist_ok=True)
  305. weight_names_file = os.path.join(np_folder, "weight_names.json")
  306. # Use file lock to prevent multiple processes from
  307. # dumping the same model weights to numpy at the same time.
  308. with get_lock(model_name_or_path, cache_dir):
  309. if not os.path.exists(weight_names_file):
  310. weight_names = []
  311. for bin_file in tqdm(
  312. hf_weights_files,
  313. desc="Loading np_cache checkpoint shards",
  314. disable=not enable_tqdm,
  315. ):
  316. state = torch.load(bin_file, map_location="cpu")
  317. for name, param in state.items():
  318. param_path = os.path.join(np_folder, name)
  319. with open(param_path, "wb") as f:
  320. np.save(f, param.cpu().detach().numpy())
  321. weight_names.append(name)
  322. with open(weight_names_file, "w") as f:
  323. json.dump(weight_names, f)
  324. with open(weight_names_file, "r") as f:
  325. weight_names = json.load(f)
  326. for name in weight_names:
  327. param_path = os.path.join(np_folder, name)
  328. with open(param_path, "rb") as f:
  329. param = np.load(f)
  330. yield name, torch.from_numpy(param)
  331. def safetensors_weights_iterator(
  332. hf_weights_files: List[str]
  333. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  334. """Iterate over the weights in the model safetensor files."""
  335. enable_tqdm = False #not torch.distributed.is_initialized(
  336. #) or torch.distributed.get_rank() == 0
  337. for st_file in tqdm(
  338. hf_weights_files,
  339. desc="Loading safetensors checkpoint shards",
  340. disable=not enable_tqdm,
  341. ):
  342. with safe_open(st_file, framework="pt") as f:
  343. for name in f.keys(): # noqa: SIM118
  344. param = f.get_tensor(name)
  345. yield name, param
  346. def pt_weights_iterator(
  347. hf_weights_files: List[str]
  348. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  349. """Iterate over the weights in the model bin/pt files."""
  350. enable_tqdm = False #not torch.distributed.is_initialized(
  351. #) or torch.distributed.get_rank() == 0
  352. for bin_file in tqdm(
  353. hf_weights_files,
  354. desc="Loading pt checkpoint shards",
  355. disable=not enable_tqdm,
  356. ):
  357. state = torch.load(bin_file, map_location="cpu")
  358. for name, param in state.items():
  359. yield name, param
  360. del state
  361. torch.cuda.empty_cache()
  362. def get_model_config_yaml(
  363. model_name_or_path: str,
  364. cache_dir: Optional[str] = None) -> Optional[dict]:
  365. """Look for aphrodite_config.yaml in model directory or HF repo.
  366. Args:
  367. model_name_or_path: Local path or HF model name
  368. cache_dir: Optional cache directory for HF downloads
  369. Returns:
  370. Dict containing the config if found, None otherwise
  371. """
  372. is_local = os.path.isdir(model_name_or_path)
  373. config_path = None
  374. if is_local:
  375. config_path = os.path.join(model_name_or_path, "aphrodite_config.yaml")
  376. if not os.path.exists(config_path):
  377. return None
  378. else:
  379. try:
  380. with get_lock(model_name_or_path, cache_dir):
  381. valid_names = ["aphrodite_config.yaml",
  382. "aphrodite_config.yml"]
  383. for name in valid_names:
  384. config_path = hf_hub_download(
  385. model_name_or_path,
  386. filename=name,
  387. cache_dir=cache_dir,
  388. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  389. )
  390. if os.path.exists(config_path):
  391. break
  392. except (huggingface_hub.utils.EntryNotFoundError,
  393. huggingface_hub.utils.LocalEntryNotFoundError):
  394. return None
  395. try:
  396. import yaml
  397. with open(config_path, 'r') as f:
  398. config = yaml.safe_load(f)
  399. return config
  400. except Exception as e:
  401. logger.warning(f"Failed to load aphrodite_config.yaml: {e}")
  402. return None
  403. def get_gguf_extra_tensor_names(
  404. gguf_file: str, gguf_to_hf_name_map: Dict[str, str]) -> List[str]:
  405. reader = gguf.GGUFReader(gguf_file)
  406. expected_gguf_keys = set(gguf_to_hf_name_map.keys())
  407. exact_gguf_keys = set([tensor.name for tensor in reader.tensors])
  408. extra_keys = expected_gguf_keys - exact_gguf_keys
  409. return [gguf_to_hf_name_map[key] for key in extra_keys]
  410. def gguf_quant_weights_iterator(
  411. gguf_file: str, gguf_to_hf_name_map: Dict[str, str]
  412. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  413. """
  414. Iterate over the quant weights in the model gguf files and convert
  415. them to torch tensors
  416. """
  417. reader = gguf.GGUFReader(gguf_file)
  418. for tensor in reader.tensors:
  419. if tensor.name in gguf_to_hf_name_map:
  420. weight_type = tensor.tensor_type
  421. name = gguf_to_hf_name_map[tensor.name]
  422. if weight_type.name != "F32":
  423. weight_type_name = name.replace("weight", "qweight_type")
  424. weight_type = torch.tensor(weight_type)
  425. yield weight_type_name, weight_type
  426. for tensor in reader.tensors:
  427. if tensor.name in gguf_to_hf_name_map:
  428. weight = tensor.data
  429. weight_type = tensor.tensor_type
  430. name = gguf_to_hf_name_map[tensor.name]
  431. if weight_type.name != "F32":
  432. name = name.replace("weight", "qweight")
  433. param = torch.tensor(weight)
  434. yield name, param
  435. def kv_cache_scales_loader(
  436. filename: str, tp_rank: int, tp_size: int, num_hidden_layers: int,
  437. model_type: Optional[str]) -> Iterable[Tuple[int, float]]:
  438. """
  439. A simple utility to read in KV cache scaling factors that have been
  440. previously serialized to disk. Used by the model to populate the appropriate
  441. KV cache scaling factors. The serialization should represent a dictionary
  442. whose keys are the TP ranks and values are another dictionary mapping layers
  443. to their KV cache scaling factors.
  444. Keep this function in sync with the output of examples/fp8/extract_scales.py
  445. """
  446. try:
  447. with open(filename) as f:
  448. context = {
  449. "model_type": model_type,
  450. "num_hidden_layers": num_hidden_layers,
  451. "tp_rank": tp_rank,
  452. "tp_size": tp_size,
  453. }
  454. schema_dct = json.load(f)
  455. schema = QuantParamSchema.model_validate(schema_dct,
  456. context=context)
  457. layer_scales_map = schema.kv_cache.scaling_factor[tp_rank]
  458. return layer_scales_map.items()
  459. except FileNotFoundError:
  460. logger.error(f"File or directory '{filename}' not found.")
  461. except json.JSONDecodeError:
  462. logger.error(f"Error decoding JSON in file '{filename}'.")
  463. except Exception as e:
  464. logger.error(f"An error occurred while reading '{filename}': {e}")
  465. # This section is reached if and only if any of the excepts are hit
  466. # Return an empty iterable (list) => no KV cache scales are loaded
  467. # which ultimately defaults to 1.0 scales
  468. logger.warning("Defaulting to KV cache scaling factors = 1.0 "
  469. f"for all layers in TP rank {tp_rank} "
  470. "as an error occurred during loading.")
  471. return []
  472. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  473. """convert PySafeSlice object from safetensors to torch.Tensor
  474. PySafeSlice object supports indexing, which is done before loading the
  475. actual tensor and can reduce the amount of memory being read into the
  476. memory. However, it does not support more advanced functionalities
  477. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  478. tensor with these more complicated operators, we need to convert to
  479. tensor first.
  480. """
  481. if not isinstance(x, torch.Tensor):
  482. x = x[:]
  483. return x
  484. def default_weight_loader(param: torch.Tensor,
  485. loaded_weight: torch.Tensor) -> None:
  486. """Default weight loader."""
  487. try:
  488. if param.numel() == 1 and loaded_weight.numel() == 1:
  489. # Sometimes scalar values aren't considered tensors with shapes
  490. # so if both param and loaded_weight are a scalar,
  491. # "broadcast" instead of copy
  492. param.data.fill_(loaded_weight.item())
  493. else:
  494. assert param.size() == loaded_weight.size(), (
  495. f"Attempted to load weight ({loaded_weight.size()}) "
  496. f"into parameter ({param.size()})")
  497. param.data.copy_(loaded_weight)
  498. except Exception:
  499. # NOTE: This exception is added for the purpose of setting breakpoint to
  500. # debug weight loading issues.
  501. raise
  502. def row_parallel_weight_loader(param: torch.Tensor,
  503. loaded_weight: torch.Tensor) -> None:
  504. """Load weights that are row-parallelized."""
  505. tp_rank = get_tensor_model_parallel_rank()
  506. shard_dim = 0 if param.dim() != 1 else None
  507. if shard_dim is not None:
  508. shard_size = param.data.shape[shard_dim]
  509. start_idx = tp_rank * shard_size
  510. loaded_weight = loaded_weight.narrow(shard_dim, start_idx, shard_size)
  511. return default_weight_loader(param, loaded_weight)
  512. def initialize_dummy_weights(
  513. model: torch.nn.Module,
  514. low: float = -1e-3,
  515. high: float = 1e-3,
  516. seed: int = 1234,
  517. ) -> None:
  518. """Initialize model weights with random values.
  519. The model weights must be randomly initialized for accurate performance
  520. measurements. Additionally, the model weights should not cause NaNs in the
  521. forward pass. We empirically found that initializing the weights with
  522. values between -1e-3 and 1e-3 works well for most models.
  523. We use per-parameter random seed, so that dummy weights are consistent,
  524. even if the model is partitioned across multiple devices. When the seed
  525. is fixed, the random values generated by this function only depends on
  526. the parameter's number of elements and its data type.
  527. """
  528. for param in model.state_dict().values():
  529. if torch.is_floating_point(param):
  530. if current_platform.is_tpu():
  531. # XLA device does not support torch.Generator()
  532. param.uniform_(low, high)
  533. continue
  534. generator = torch.Generator(device=param.data.device)
  535. generator.manual_seed(seed)
  536. if torch.finfo(param.data.dtype).bits < 16:
  537. # uniform_ doesn't support < 16-bit datatypes (FP8)
  538. dtype = param.data.dtype
  539. tmp_param = param.data.to(torch.float16)
  540. tmp_param = tmp_param.uniform_(low, high,
  541. generator=generator).to(dtype)
  542. tmp_param = tmp_param.uniform_(low, high).to(dtype)
  543. param.data.copy_(tmp_param)
  544. else:
  545. param.uniform_(low, high, generator=generator)
  546. def maybe_remap_kv_scale_name(name: str, params_dict: dict) -> Optional[str]:
  547. """Remap the name of FP8 k/v_scale parameters.
  548. This function handles the remapping of FP8 k/v_scale parameter names.
  549. It detects if the given name ends with a suffix and attempts to remap
  550. it to the expected name format in the model. If the remapped name is not
  551. found in the params_dict, a warning is printed and None is returned.
  552. Args:
  553. name (str): The original loaded checkpoint parameter name.
  554. params_dict (dict): Dictionary containing the model's named parameters.
  555. Returns:
  556. str: The remapped parameter name if successful, or the original name
  557. if no remapping is needed.
  558. None: If the remapped name is not found in params_dict.
  559. """
  560. if name.endswith(".kv_scale"):
  561. print_warning_once(
  562. "DEPRECATED. Found kv_scale in the checkpoint. "
  563. "This format is deprecated in favor of separate k_scale and "
  564. "v_scale tensors and will be removed in a future release. "
  565. "Functionally, we will remap kv_scale to k_scale and duplicate "
  566. "k_scale to v_scale")
  567. # NOTE: we remap the deprecated kv_scale to k_scale
  568. remapped_name = name.replace(".kv_scale", ".attn.k_scale")
  569. if remapped_name not in params_dict:
  570. print_warning_once(
  571. f"Found kv_scale in the checkpoint (e.g. {name}), "
  572. "but not found the expected name in the model "
  573. f"(e.g. {remapped_name}). kv_scale is "
  574. "not loaded.")
  575. return None
  576. return remapped_name
  577. possible_scale_names = [".k_scale", ".v_scale"]
  578. for scale_name in possible_scale_names:
  579. if name.endswith(scale_name):
  580. remapped_name = name.replace(scale_name, f".attn{scale_name}")
  581. if remapped_name not in params_dict:
  582. print_warning_once(
  583. f"Found {scale_name} in the checkpoint (e.g. {name}), "
  584. "but not found the expected name in the model "
  585. f"(e.g. {remapped_name}). {scale_name} is "
  586. "not loaded.")
  587. return None
  588. return remapped_name
  589. # If there were no matches, return the untouched param name
  590. return name