weight_utils.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. # SPDX-License-Identifier: Apache-2.0
  2. # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
  3. """Utilities for downloading and initializing model weights."""
  4. import asyncio
  5. import concurrent.futures
  6. import fnmatch
  7. import glob
  8. import hashlib
  9. import json
  10. import os
  11. _DSV41_ENGRAM_DISK = os.environ.get("DSV41_ENGRAM_DISK", "0") == "1"
  12. import tempfile
  13. import threading
  14. import time
  15. from collections import defaultdict
  16. from collections.abc import Callable, Generator, Iterable
  17. from contextlib import contextmanager
  18. from pathlib import Path
  19. from typing import IO, Any
  20. import filelock
  21. import huggingface_hub.constants
  22. import numpy as np
  23. import regex as re
  24. import torch
  25. from safetensors.torch import load, load_file, safe_open, save_file
  26. from tqdm.auto import tqdm
  27. from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
  28. from vllm import envs
  29. from vllm.config import ModelConfig
  30. from vllm.config.load import (
  31. DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE,
  32. DEFAULT_SAFETENSORS_PREFETCH_NUM_THREADS,
  33. LoadConfig,
  34. )
  35. from vllm.distributed import get_tensor_model_parallel_rank, get_world_group
  36. from vllm.logger import init_logger
  37. from vllm.model_executor.layers.quantization import (
  38. QuantizationConfig,
  39. get_quantization_config,
  40. )
  41. from vllm.model_executor.model_loader.ep_weight_filter import (
  42. should_skip_weight,
  43. )
  44. from vllm.platforms import current_platform
  45. from vllm.tracing import instrument
  46. from vllm.transformers_utils.repo_utils import hf_api, hf_fs
  47. from vllm.utils.import_utils import PlaceholderModule
  48. try:
  49. from runai_model_streamer import SafetensorsStreamer
  50. except ImportError:
  51. runai_model_streamer = PlaceholderModule("runai_model_streamer") # type: ignore[assignment]
  52. SafetensorsStreamer = runai_model_streamer.placeholder_attr("SafetensorsStreamer")
  53. try:
  54. from fastsafetensors import SingleGroup
  55. except ImportError:
  56. fastsafetensors = PlaceholderModule("fastsafetensors")
  57. SingleGroup = fastsafetensors.placeholder_attr("SingleGroup")
  58. from vllm.model_executor.layers.quantization.torchao import torchao_version_at_least
  59. logger = init_logger(__name__)
  60. # use system-level temp directory for file locks, so that multiple users
  61. # can share the same lock without error.
  62. # lock files in the temp directory will be automatically deleted when the
  63. # system reboots, so users will not complain about annoying lock files
  64. temp_dir = tempfile.gettempdir()
  65. def enable_xet_high_performance():
  66. """automatically activates xet high performance mode"""
  67. if "HF_XET_HIGH_PERFORMANCE" not in os.environ:
  68. huggingface_hub.constants.HF_XET_HIGH_PERFORMANCE = True
  69. enable_xet_high_performance()
  70. class DisabledTqdm(tqdm):
  71. def __init__(self, *args, **kwargs):
  72. kwargs["disable"] = True
  73. super().__init__(*args, **kwargs)
  74. def get_lock(model_name_or_path: str | Path, cache_dir: str | None = None):
  75. lock_dir = cache_dir or temp_dir
  76. model_name_or_path = str(model_name_or_path)
  77. os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
  78. model_name = model_name_or_path.replace("/", "-")
  79. hash_name = hashlib.sha256(model_name.encode()).hexdigest()
  80. # add hash to avoid conflict with old users' lock files
  81. lock_file_name = hash_name + model_name + ".lock"
  82. # mode 0o666 is required for the filelock to be shared across users
  83. lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name), mode=0o666)
  84. return lock
  85. @contextmanager
  86. def atomic_writer(
  87. filepath: str | Path, mode: str = "w", encoding: str | None = None
  88. ) -> Generator[IO]:
  89. """
  90. Context manager that provides an atomic file writing routine.
  91. The context manager writes to a temporary file and, if successful,
  92. atomically replaces the original file.
  93. Args:
  94. filepath (str or Path): The path to the file to write.
  95. mode (str): The file mode for the temporary file (e.g., 'w', 'wb').
  96. encoding (str): The encoding for text mode.
  97. Yields:
  98. file object: A handle to the temporary file.
  99. """
  100. # Create a temporary file in the same directory as the target file
  101. # to ensure it's on the same filesystem for an atomic replace.
  102. temp_dir = os.path.dirname(filepath)
  103. temp_fd, temp_path = tempfile.mkstemp(dir=temp_dir)
  104. try:
  105. # Open the temporary file for writing
  106. with os.fdopen(temp_fd, mode=mode, encoding=encoding) as temp_file:
  107. yield temp_file
  108. # If the 'with' block completes successfully,
  109. # perform the atomic replace.
  110. os.replace(temp_path, filepath)
  111. except Exception:
  112. logger.exception(
  113. "Error during atomic write. Original file '%s' not modified", filepath
  114. )
  115. raise
  116. finally:
  117. # Clean up the temporary file if it still exists.
  118. if os.path.exists(temp_path):
  119. os.remove(temp_path)
  120. def _natural_sort_key(filepath: str) -> list:
  121. """Natural sort key for filenames with numeric components, such as
  122. model-00001-of-00005.safetensors -> ['model-', 1, '-of-', 5, '.safetensors']"""
  123. return [
  124. int(s) if s.isdigit() else s
  125. for s in re.split(r"(\d+)", os.path.basename(filepath))
  126. ]
  127. def maybe_download_from_modelscope(
  128. model: str,
  129. revision: str | None = None,
  130. download_dir: str | None = None,
  131. ignore_patterns: str | list[str] | None = None,
  132. allow_patterns: list[str] | str | None = None,
  133. ) -> str | None:
  134. """Download model from ModelScope hub if VLLM_USE_MODELSCOPE is True.
  135. Returns the path to the downloaded model, or None if the model is not
  136. downloaded from ModelScope."""
  137. if envs.VLLM_USE_MODELSCOPE:
  138. # download model from ModelScope hub,
  139. # lazy import so that modelscope is not required for normal use.
  140. # pylint: disable=C.
  141. from modelscope.hub.snapshot_download import snapshot_download
  142. # Use file lock to prevent multiple processes from
  143. # downloading the same model weights at the same time.
  144. with get_lock(model, download_dir):
  145. if not os.path.exists(model):
  146. model_path = snapshot_download(
  147. model_id=model,
  148. cache_dir=download_dir,
  149. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  150. revision=revision,
  151. ignore_file_pattern=ignore_patterns,
  152. allow_patterns=allow_patterns,
  153. )
  154. else:
  155. model_path = model
  156. return model_path
  157. return None
  158. def _shared_pointers(tensors):
  159. ptrs = defaultdict(list)
  160. for k, v in tensors.items():
  161. ptrs[v.data_ptr()].append(k)
  162. failing = []
  163. for _, names in ptrs.items():
  164. if len(names) > 1:
  165. failing.append(names)
  166. return failing
  167. def convert_bin_to_safetensor_file(
  168. pt_filename: str,
  169. sf_filename: str,
  170. ) -> None:
  171. loaded = torch.load(pt_filename, map_location="cpu", weights_only=True)
  172. if "state_dict" in loaded:
  173. loaded = loaded["state_dict"]
  174. shared = _shared_pointers(loaded)
  175. for shared_weights in shared:
  176. for name in shared_weights[1:]:
  177. loaded.pop(name)
  178. # For tensors to be contiguous
  179. loaded = {k: v.contiguous() for k, v in loaded.items()}
  180. dirname = os.path.dirname(sf_filename)
  181. os.makedirs(dirname, exist_ok=True)
  182. save_file(loaded, sf_filename, metadata={"format": "pt"})
  183. # check file size
  184. sf_size = os.stat(sf_filename).st_size
  185. pt_size = os.stat(pt_filename).st_size
  186. if (sf_size - pt_size) / pt_size > 0.01:
  187. raise RuntimeError(
  188. f"""The file size different is more than 1%:
  189. - {sf_filename}: {sf_size}
  190. - {pt_filename}: {pt_size}
  191. """
  192. )
  193. # check if the tensors are the same
  194. reloaded = load_file(sf_filename)
  195. for k in loaded:
  196. pt_tensor = loaded[k]
  197. sf_tensor = reloaded[k]
  198. if not torch.equal(pt_tensor, sf_tensor):
  199. raise RuntimeError(f"The output tensors do not match for key {k}")
  200. # TODO(woosuk): Move this to other place.
  201. def get_quant_config(
  202. model_config: ModelConfig, load_config: LoadConfig
  203. ) -> QuantizationConfig:
  204. if model_config.quantization is None:
  205. raise ValueError("Model quantization method is not specified in the config.")
  206. quant_cls = get_quantization_config(model_config.quantization)
  207. # Read the quantization config from the HF model config, if available.
  208. hf_quant_config = getattr(model_config.hf_config, "quantization_config", None)
  209. # some vision model may keep quantization_config in their text_config
  210. hf_text_config = getattr(model_config.hf_config, "text_config", None)
  211. if hf_quant_config is None and hf_text_config is not None:
  212. hf_quant_config = getattr(hf_text_config, "quantization_config", None)
  213. if hf_quant_config is None:
  214. # compressed-tensors uses a compressions_config
  215. hf_quant_config = getattr(model_config.hf_config, "compression_config", None)
  216. # Pipe information about heads to enable TP-aware loading of attn_head scales
  217. if (
  218. hf_quant_config is not None
  219. and hf_quant_config.get("quant_method") == "compressed-tensors"
  220. and "config_groups" in hf_quant_config
  221. ):
  222. n_heads = model_config.model_arch_config.total_num_attention_heads
  223. n_kv_heads = model_config.model_arch_config.total_num_kv_heads
  224. hf_quant_config["total_num_heads"] = n_heads
  225. hf_quant_config["total_num_kv_heads"] = (
  226. n_kv_heads if n_kv_heads is not None else n_heads
  227. )
  228. if hf_quant_config is not None:
  229. # `model_config.quantization_config` may be set alongside a checkpoint
  230. # quant config: the checkpoint determines `quant_cls`, and the user's
  231. # QuantizationConfigArgs is consulted by individual quant methods
  232. # (e.g. for activation overrides via the MXFP4 oracle).
  233. # For modelopt_mixed, config.json's quantization_config may or may
  234. # not contain the per-layer quantized_layers map. Newer checkpoints
  235. # embed it directly; older ones keep it only in hf_quant_config.json.
  236. # If it is missing, fall through to the file-based loading path.
  237. if (
  238. model_config.quantization == "modelopt_mixed"
  239. and "quantized_layers" not in hf_quant_config
  240. ):
  241. pass # fall through to file-based loading below
  242. else:
  243. return quant_cls.from_config(hf_quant_config)
  244. # if hf_quant_config is None, we will try to get config from
  245. # hf_overrides
  246. hf_overrides = model_config.hf_overrides
  247. if callable(hf_overrides):
  248. # A callable hf_overrides is a config-to-config transform (e.g. the
  249. # one SpeculativeConfig installs on draft model configs); it cannot
  250. # carry quantization config entries, so treat it as no overrides.
  251. hf_overrides = {}
  252. if not isinstance(hf_overrides, dict):
  253. raise ValueError(
  254. "hf_overrides must be a dict for get_quant_config "
  255. "to get the quantization config from it."
  256. )
  257. quantization_config_file = hf_overrides.get("quantization_config_file")
  258. if quantization_config_file is not None:
  259. if hasattr(quant_cls, "from_config_file"):
  260. return quant_cls.from_config_file(quantization_config_file)
  261. else:
  262. raise NotImplementedError(
  263. "from_config_file is specified in hf_override config, "
  264. "but quant_cls.from_config_file is not implemented in "
  265. f"{quant_cls}"
  266. )
  267. quantization_config_json = hf_overrides.get("quantization_config_dict_json")
  268. if quantization_config_json is not None:
  269. if hasattr(quant_cls, "from_config_dict_json"):
  270. return quant_cls.from_config_dict_json(quantization_config_json)
  271. else:
  272. raise NotImplementedError(
  273. "from_config_dict_json is specified in hf_override config, "
  274. "but quant_cls.from_config_dict_json is not implemented in "
  275. f"{quant_cls}"
  276. )
  277. # Online quantization doesn't read from checkpoint configs - it quantizes
  278. # fp16/bf16 weights on the fly during loading.
  279. if model_config.quantization_config is not None:
  280. from vllm.config.quantization import QuantizationConfigArgs
  281. from vllm.model_executor.layers.quantization.online.base import (
  282. OnlineQuantizationConfig,
  283. )
  284. assert isinstance(model_config.quantization_config, QuantizationConfigArgs)
  285. return OnlineQuantizationConfig(args=model_config.quantization_config)
  286. model_name_or_path = (
  287. maybe_download_from_modelscope(
  288. model_config.model,
  289. revision=model_config.revision,
  290. download_dir=load_config.download_dir,
  291. allow_patterns=["*.json"],
  292. )
  293. or model_config.model
  294. )
  295. is_local = os.path.isdir(model_name_or_path)
  296. if not is_local:
  297. # Download the config files.
  298. with get_lock(model_config.model, load_config.download_dir):
  299. hf_folder = hf_api().snapshot_download(
  300. model_config.model,
  301. revision=model_config.revision,
  302. allow_patterns="*.json",
  303. cache_dir=load_config.download_dir,
  304. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  305. tqdm_class=DisabledTqdm,
  306. )
  307. else:
  308. hf_folder = model_name_or_path
  309. possible_config_filenames = quant_cls.get_config_filenames()
  310. # If the quantization config is not found, use the default config.
  311. if not possible_config_filenames:
  312. return quant_cls()
  313. config_files = glob.glob(os.path.join(hf_folder, "*.json"))
  314. quant_config_files = [
  315. f for f in config_files if any(f.endswith(x) for x in possible_config_filenames)
  316. ]
  317. if len(quant_config_files) == 0:
  318. raise ValueError(f"Cannot find the config file for {model_config.quantization}")
  319. if len(quant_config_files) > 1:
  320. raise ValueError(
  321. f"Found multiple config files for {model_config.quantization}: "
  322. f"{quant_config_files}"
  323. )
  324. quant_config_file = quant_config_files[0]
  325. with open(quant_config_file) as f:
  326. config = json.load(f)
  327. if model_config.quantization in ("modelopt", "modelopt_mixed"):
  328. if config.get("producer", {}).get("name") == "modelopt":
  329. return quant_cls.from_config(config)
  330. else:
  331. raise ValueError(
  332. f"Unsupported quantization config"
  333. f" found for {model_config.quantization} in {f}."
  334. )
  335. return quant_cls.from_config(config)
  336. def get_sparse_attention_config(
  337. model_config: ModelConfig,
  338. load_config: LoadConfig,
  339. sparse_attention_config_filename: str = "sparse_attention_config.json",
  340. ) -> dict[str, Any]:
  341. model_name_or_path = model_config.model
  342. is_local = os.path.isdir(model_name_or_path)
  343. if not is_local:
  344. # Download the config files.
  345. with get_lock(model_name_or_path, load_config.download_dir):
  346. hf_folder = hf_api().snapshot_download(
  347. model_name_or_path,
  348. revision=model_config.revision,
  349. allow_patterns="*.json",
  350. cache_dir=load_config.download_dir,
  351. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  352. tqdm_class=DisabledTqdm,
  353. )
  354. else:
  355. hf_folder = model_name_or_path
  356. config_file = os.path.join(hf_folder, sparse_attention_config_filename)
  357. if not os.path.exists(config_file):
  358. return {}
  359. # Load the sparse attention config.
  360. with open(config_file) as f:
  361. config = json.load(f)
  362. logger.info("Loaded sparse attention config from %s", config_file)
  363. return config
  364. @instrument(span_name="Download weights - HF")
  365. def download_weights_from_hf(
  366. model_name_or_path: str,
  367. cache_dir: str | None,
  368. allow_patterns: list[str],
  369. revision: str | None = None,
  370. subfolder: str | None = None,
  371. ignore_patterns: str | list[str] | None = None,
  372. ) -> str:
  373. """Download model weights from Hugging Face Hub.
  374. Args:
  375. model_name_or_path (str): The model name or path.
  376. cache_dir (Optional[str]): The cache directory to store the model
  377. weights. If None, will use HF defaults.
  378. allow_patterns (list[str]): The allowed patterns for the
  379. weight files. Files matched by any of the patterns will be
  380. downloaded.
  381. revision (Optional[str]): The revision of the model.
  382. subfolder (Optional[str]): The subfolder within the model repository
  383. to download weights from.
  384. ignore_patterns (Optional[Union[str, list[str]]]): The patterns to
  385. filter out the weight files. Files matched by any of the patterns
  386. will be ignored.
  387. Returns:
  388. str: The path to the downloaded model weights.
  389. """
  390. assert len(allow_patterns) > 0
  391. local_only = huggingface_hub.constants.HF_HUB_OFFLINE
  392. if not local_only:
  393. # Attempt to reduce allow_patterns to a single pattern
  394. # so we only have to call snapshot_download once.
  395. try:
  396. fs = hf_fs()
  397. file_list = fs.ls(
  398. os.path.join(model_name_or_path, subfolder or ""),
  399. detail=False,
  400. revision=revision,
  401. )
  402. # If downloading safetensors and an index file exists, use the
  403. # specific file names from the index to avoid downloading
  404. # unnecessary files (e.g., from subdirectories like "original/").
  405. index_file = f"{model_name_or_path}/{SAFE_WEIGHTS_INDEX_NAME}"
  406. if "*.safetensors" in allow_patterns and index_file in file_list:
  407. index_path = hf_api().hf_hub_download(
  408. repo_id=model_name_or_path,
  409. filename=SAFE_WEIGHTS_INDEX_NAME,
  410. cache_dir=cache_dir,
  411. revision=revision,
  412. subfolder=subfolder,
  413. )
  414. with open(index_path) as f:
  415. weight_map = json.load(f)["weight_map"]
  416. if weight_map:
  417. # Extra [] so that weight_map files are treated as a
  418. # single allow_pattern in the loop below
  419. allow_patterns = [list(set(weight_map.values()))] # type: ignore[list-item]
  420. else:
  421. allow_patterns = ["*.safetensors"]
  422. else:
  423. # Use the first pattern found in the HF repo's files.
  424. for pattern in allow_patterns:
  425. if fnmatch.filter(file_list, pattern):
  426. allow_patterns = [pattern]
  427. break
  428. except Exception as e:
  429. logger.warning(
  430. "Failed to get file list for '%s'. Trying each pattern in "
  431. "allow_patterns individually until weights have been "
  432. "downloaded. Error: %s",
  433. model_name_or_path,
  434. e,
  435. )
  436. logger.debug("Using model weights format %s", allow_patterns)
  437. # Use file lock to prevent multiple processes from
  438. # downloading the same model weights at the same time.
  439. with get_lock(model_name_or_path, cache_dir):
  440. start_time = time.perf_counter()
  441. for allow_pattern in allow_patterns:
  442. hf_folder = hf_api().snapshot_download(
  443. model_name_or_path,
  444. allow_patterns=allow_pattern,
  445. ignore_patterns=ignore_patterns,
  446. cache_dir=cache_dir,
  447. tqdm_class=DisabledTqdm,
  448. revision=revision,
  449. local_files_only=local_only,
  450. )
  451. # If we have downloaded weights for this allow_pattern,
  452. # we don't need to check the rest.
  453. # allow_pattern can be a list (from weight_map) or str (glob)
  454. if isinstance(allow_pattern, list):
  455. break
  456. if any(Path(hf_folder).glob(allow_pattern)):
  457. break
  458. time_taken = time.perf_counter() - start_time
  459. if time_taken > 0.5:
  460. logger.info(
  461. "Time spent downloading weights for %s: %.6f seconds",
  462. model_name_or_path,
  463. time_taken,
  464. )
  465. return hf_folder
  466. def download_safetensors_index_file_from_hf(
  467. model_name_or_path: str,
  468. index_file: str,
  469. cache_dir: str | None,
  470. subfolder: str | None = None,
  471. revision: str | None = None,
  472. ) -> None:
  473. """Download hf safetensors index file from Hugging Face Hub.
  474. Args:
  475. model_name_or_path (str): The model name or path.
  476. index_file (str): The safetensors index file name
  477. cache_dir (Optional[str]): The cache directory to store the model
  478. weights. If None, will use HF defaults.
  479. subfolder (Optional[str]): The subfolder within the model repository
  480. to download weights from.
  481. revision (Optional[str]): The revision of the model.
  482. """
  483. # Use file lock to prevent multiple processes from
  484. # downloading the same model weights at the same time.
  485. with get_lock(model_name_or_path, cache_dir):
  486. try:
  487. # Download the safetensors index file.
  488. hf_api().hf_hub_download(
  489. repo_id=model_name_or_path,
  490. filename=index_file,
  491. cache_dir=cache_dir,
  492. revision=revision,
  493. subfolder=subfolder,
  494. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  495. )
  496. # If file not found on remote or locally, we should not fail since
  497. # only some models will have index_file.
  498. except huggingface_hub.utils.LocalEntryNotFoundError:
  499. logger.info("No %s found in local cache.", index_file)
  500. except huggingface_hub.utils.EntryNotFoundError:
  501. logger.info("No %s found in remote.", index_file)
  502. # For models like Mistral-7B-v0.3, there are both sharded
  503. # safetensors files and a consolidated safetensors file.
  504. # Passing both of these to the weight loader functionality breaks.
  505. # So, we use the index_file to
  506. # look up which safetensors files should be used.
  507. def filter_duplicate_safetensors_files(
  508. hf_weights_files: list[str], hf_folder: str, index_file: str
  509. ) -> list[str]:
  510. # model.safetensors.index.json is a mapping from keys in the
  511. # torch state_dict to safetensors file holding that weight.
  512. index_file_name = os.path.join(hf_folder, index_file)
  513. if not os.path.isfile(index_file_name):
  514. return hf_weights_files
  515. # Iterate through the weight_map (weight_name: safetensors files)
  516. # to identify weights that we should use.
  517. with open(index_file_name) as f:
  518. weight_map = json.load(f)["weight_map"]
  519. weight_files_in_index = set()
  520. for weight_name in weight_map:
  521. weight_files_in_index.add(os.path.join(hf_folder, weight_map[weight_name]))
  522. # Check if files referenced in model.safetensors.index.json actually exist.
  523. # Raise error if any file is missing.
  524. hf_weights_files_set = set(hf_weights_files)
  525. missing_files = weight_files_in_index - hf_weights_files_set
  526. if missing_files:
  527. raise FileNotFoundError(
  528. f"Weight files referenced in index but missing: {missing_files}"
  529. )
  530. # Filter out any fields that are not found in the index file.
  531. hf_weights_files = [f for f in hf_weights_files if f in weight_files_in_index]
  532. return hf_weights_files
  533. def filter_files_not_needed_for_inference(hf_weights_files: list[str]) -> list[str]:
  534. """
  535. Exclude files that are not needed for inference.
  536. See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
  537. """
  538. blacklist = [
  539. "training_args.bin",
  540. "optimizer.bin",
  541. "optimizer.pt",
  542. "scheduler.pt",
  543. "scaler.pt",
  544. ]
  545. hf_weights_files = [
  546. f for f in hf_weights_files if not any(f.endswith(x) for x in blacklist)
  547. ]
  548. return hf_weights_files
  549. # explicitly use pure text format, with a newline at the end
  550. # this makes it impossible to see the animation in the progress bar
  551. # but will avoid messing up with ray or multiprocessing, which wraps
  552. # each line of output with some prefix.
  553. _BAR_FORMAT = "{desc}: {percentage:3.0f}% Completed | {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]\n" # noqa: E501
  554. def enable_tqdm(use_tqdm_on_load: bool):
  555. return use_tqdm_on_load and (
  556. not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0
  557. )
  558. def np_cache_weights_iterator(
  559. model_name_or_path: str,
  560. cache_dir: str | None,
  561. hf_folder: str,
  562. hf_weights_files: list[str],
  563. use_tqdm_on_load: bool,
  564. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  565. """Iterate over the weights in the model np files.
  566. Will dump the model weights to numpy files if they are not already dumped.
  567. """
  568. # Convert the model weights from torch tensors to numpy arrays for
  569. # faster loading.
  570. np_folder = os.path.join(hf_folder, "np")
  571. os.makedirs(np_folder, exist_ok=True)
  572. weight_names_file = os.path.join(np_folder, "weight_names.json")
  573. # Use file lock to prevent multiple processes from
  574. # dumping the same model weights to numpy at the same time.
  575. with get_lock(model_name_or_path, cache_dir):
  576. if not os.path.exists(weight_names_file):
  577. weight_names: list[str] = []
  578. for bin_file in tqdm(
  579. hf_weights_files,
  580. desc="Loading np_cache checkpoint shards",
  581. disable=not enable_tqdm(use_tqdm_on_load),
  582. bar_format=_BAR_FORMAT,
  583. ):
  584. state = torch.load(bin_file, map_location="cpu", weights_only=True)
  585. for name, param in state.items():
  586. param_path = os.path.join(np_folder, name)
  587. with open(param_path, "wb") as f:
  588. np.save(f, param.cpu().detach().numpy())
  589. weight_names.append(name)
  590. with open(weight_names_file, "w") as f:
  591. json.dump(weight_names, f)
  592. with open(weight_names_file) as f:
  593. weight_names = json.load(f)
  594. for name in weight_names:
  595. param_path = os.path.join(np_folder, name)
  596. with open(param_path, "rb") as f:
  597. param = np.load(f)
  598. yield name, torch.from_numpy(param)
  599. def _get_checkpoints_size_bytes(files: list[str]) -> int:
  600. """Return the total size of the checkpoint files in bytes."""
  601. if not files:
  602. return 0
  603. return sum(os.path.getsize(f) for f in files)
  604. def _get_available_ram_bytes() -> int:
  605. """Return available RAM, honoring cgroup limits."""
  606. import psutil
  607. host_available = psutil.virtual_memory().available
  608. from vllm.utils.cpu_resource_utils import get_cgroup_memory_limit
  609. cgroup_limit, cgroup_usage = get_cgroup_memory_limit()
  610. if cgroup_limit is None:
  611. return host_available
  612. cgroup_available = (
  613. cgroup_limit if cgroup_usage is None else max(0, cgroup_limit - cgroup_usage)
  614. )
  615. return min(host_available, cgroup_available)
  616. def _get_fs_type(files: list[str]) -> str:
  617. """Get the filesystem type of the first file in *files* (Linux only)."""
  618. if not files:
  619. return ""
  620. try:
  621. # Only the first file is checked — all checkpoint shards reside
  622. # in the same directory and therefore on the same filesystem.
  623. resolved = os.path.realpath(files[0])
  624. best_mount = ""
  625. best_fstype = ""
  626. # /proc/mounts may contain nested mount points (e.g. "/" -> ext4,
  627. # "/data" -> nfs4, "/data/local" -> ext4). We pick the entry with
  628. # the longest matching mount_point — the same "longest prefix match"
  629. # rule the kernel uses to decide which filesystem serves a path.
  630. with open("/proc/mounts") as f:
  631. for line in f:
  632. parts = line.split()
  633. if len(parts) < 3:
  634. continue
  635. mount_point, fstype = parts[1], parts[2]
  636. if (
  637. resolved == mount_point
  638. or resolved.startswith(os.path.join(mount_point, ""))
  639. ) and len(mount_point) > len(best_mount):
  640. best_mount = mount_point
  641. best_fstype = fstype
  642. return best_fstype
  643. except Exception:
  644. # /proc/mounts is Linux-specific; on other OSes (or if the read
  645. # fails for any reason) we fall back to an empty string.
  646. return ""
  647. def _prefetch_checkpoint(
  648. file_path: str,
  649. block_size: int = DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE,
  650. ) -> None:
  651. """Prefetch a checkpoint file into the OS page cache.
  652. Reads the file in blocks so the kernel caches its pages before workers load
  653. the same file.
  654. """
  655. if block_size < 1:
  656. raise ValueError("safetensors prefetch block size must be >= 1")
  657. with open(file_path, "rb") as f:
  658. while f.read(block_size):
  659. pass
  660. def _prefetch_all_checkpoints(
  661. sorted_files: list[str],
  662. num_prefetch_threads: int = DEFAULT_SAFETENSORS_PREFETCH_NUM_THREADS,
  663. block_size: int = DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE,
  664. ) -> None:
  665. """Start prefetching checkpoint files into page cache in a background thread."""
  666. if num_prefetch_threads < 1:
  667. raise ValueError("safetensors prefetch num threads must be >= 1")
  668. if block_size < 1:
  669. raise ValueError("safetensors prefetch block size must be >= 1")
  670. if torch.distributed.is_initialized():
  671. rank = torch.distributed.get_rank()
  672. world_size = torch.distributed.get_world_size()
  673. else:
  674. rank = 0
  675. world_size = 1
  676. paths_to_prefetch = sorted_files[rank::world_size]
  677. total_for_rank = len(paths_to_prefetch)
  678. async def _prefetch_all() -> None:
  679. loop = asyncio.get_running_loop()
  680. completed = 0
  681. next_log_pct = 10
  682. async def prefetch_one(
  683. path: str,
  684. executor: concurrent.futures.ThreadPoolExecutor,
  685. ) -> None:
  686. nonlocal completed, next_log_pct
  687. try:
  688. await loop.run_in_executor(
  689. executor, _prefetch_checkpoint, path, block_size
  690. )
  691. completed += 1
  692. if total_for_rank > 0 and next_log_pct <= 100:
  693. pct = 100 * completed / total_for_rank
  694. if pct >= next_log_pct:
  695. logger.info(
  696. "Prefetching checkpoint files: %d%% (%d/%d)",
  697. next_log_pct,
  698. completed,
  699. total_for_rank,
  700. )
  701. next_log_pct += 10
  702. except Exception:
  703. logger.warning(
  704. "Failed to prefetch checkpoint file %r.", path, exc_info=True
  705. )
  706. with concurrent.futures.ThreadPoolExecutor(
  707. max_workers=num_prefetch_threads
  708. ) as executor:
  709. await asyncio.gather(
  710. *(prefetch_one(p, executor) for p in paths_to_prefetch)
  711. )
  712. def _run_prefetch() -> None:
  713. start = time.perf_counter()
  714. asyncio.run(_prefetch_all())
  715. elapsed = time.perf_counter() - start
  716. logger.info(
  717. "Prefetching checkpoint files into page cache finished in %.2fs",
  718. elapsed,
  719. )
  720. logger.info(
  721. "Prefetching checkpoint files into page cache started "
  722. "(in background, num_threads=%d, block_size=%d bytes)",
  723. num_prefetch_threads,
  724. block_size,
  725. )
  726. threading.Thread(target=_run_prefetch, daemon=True).start()
  727. def safetensors_weights_iterator(
  728. hf_weights_files: list[str],
  729. use_tqdm_on_load: bool,
  730. safetensors_load_strategy: str | None = None,
  731. local_expert_ids: set[int] | None = None,
  732. *,
  733. safetensors_prefetch_num_threads: int = DEFAULT_SAFETENSORS_PREFETCH_NUM_THREADS,
  734. safetensors_prefetch_block_size: int = DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE,
  735. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  736. """Iterate over the weights in the model safetensor files.
  737. When *local_expert_ids* is provided, expert weights not belonging to
  738. this rank are skipped **before** reading from disk, which drastically
  739. reduces storage I/O for MoE models under EP.
  740. """
  741. loading_desc = "Loading safetensors checkpoint shards"
  742. if safetensors_load_strategy == "eager":
  743. loading_desc += " (eager)"
  744. sorted_files = sorted(hf_weights_files, key=_natural_sort_key)
  745. fs_type = _get_fs_type(sorted_files)
  746. is_net_fs = fs_type in ("nfs", "nfs4", "lustre")
  747. total_bytes = _get_checkpoints_size_bytes(sorted_files)
  748. avail_bytes = _get_available_ram_bytes()
  749. ram_threshold_pct = 90
  750. fits_in_ram = total_bytes <= (ram_threshold_pct / 100.0) * avail_bytes
  751. fs_name = fs_type.upper() if fs_type else "unknown"
  752. logger.info_once(
  753. "Filesystem type for checkpoints: %s. Checkpoint size: %.2f GiB. "
  754. "Available RAM: %.2f GiB.",
  755. fs_name,
  756. total_bytes / 1024**3,
  757. avail_bytes / 1024**3,
  758. )
  759. should_prefetch = safetensors_load_strategy == "prefetch"
  760. if safetensors_load_strategy is None:
  761. if is_net_fs and fits_in_ram:
  762. should_prefetch = True
  763. elif is_net_fs and not fits_in_ram:
  764. logger.warning_once(
  765. "Network filesystem (%s) detected but checkpoint total size "
  766. "(%.2f GiB) exceeds %d%% of available RAM (%.2f GiB). "
  767. "Skipping auto-prefetch.",
  768. fs_name,
  769. total_bytes / 1024**3,
  770. ram_threshold_pct,
  771. avail_bytes / 1024**3,
  772. )
  773. elif not is_net_fs and fits_in_ram:
  774. logger.info_once(
  775. "Auto-prefetch is disabled because the filesystem (%s) is not a "
  776. "recognized network FS (NFS/Lustre). If you want to force "
  777. "prefetching, start vLLM with --safetensors-load-strategy=prefetch.",
  778. fs_name,
  779. )
  780. elif not is_net_fs and not fits_in_ram:
  781. logger.info_once(
  782. "Auto-prefetch is disabled because the filesystem (%s) is not a "
  783. "recognized network FS (NFS/Lustre) and the checkpoint size "
  784. "(%.2f GiB) exceeds %d%% of available RAM (%.2f GiB).",
  785. fs_name,
  786. total_bytes / 1024**3,
  787. ram_threshold_pct,
  788. avail_bytes / 1024**3,
  789. )
  790. elif should_prefetch and not fits_in_ram:
  791. logger.warning_once(
  792. "safetensors_load_strategy='prefetch' was explicitly specified, but "
  793. "checkpoint total size (%.2f GiB) exceeds %d%% of available RAM "
  794. "(%.2f GiB). This may cause out-of-memory errors.",
  795. total_bytes / 1024**3,
  796. ram_threshold_pct,
  797. avail_bytes / 1024**3,
  798. )
  799. if should_prefetch:
  800. _prefetch_all_checkpoints(
  801. sorted_files,
  802. num_prefetch_threads=safetensors_prefetch_num_threads,
  803. block_size=safetensors_prefetch_block_size,
  804. )
  805. leftover_state_dict: dict[str, torch.Tensor] = {}
  806. for st_file in tqdm(
  807. sorted_files,
  808. desc=loading_desc,
  809. disable=not enable_tqdm(use_tqdm_on_load),
  810. bar_format=_BAR_FORMAT,
  811. ):
  812. if safetensors_load_strategy == "eager":
  813. with open(st_file, "rb") as f:
  814. state_dict = load(f.read())
  815. for name, param in state_dict.items():
  816. if not should_skip_weight(name, local_expert_ids):
  817. yield name, param
  818. elif safetensors_load_strategy == "torchao":
  819. # we can't load flattened torchao tensor subclasses directly into the model
  820. # instead we reconstruct the subclasses here before returning
  821. if not torchao_version_at_least("0.15.0"):
  822. raise ValueError(
  823. "Please use torchao version >= 0.15.0 "
  824. "to load torchao safetensors checkpoint"
  825. )
  826. from torchao.prototype.safetensors.safetensors_support import (
  827. unflatten_tensor_state_dict,
  828. )
  829. with safe_open(st_file, framework="pt") as f:
  830. state_dict = {}
  831. for name in f.keys(): # noqa: SIM118
  832. if should_skip_weight(name, local_expert_ids):
  833. continue
  834. state_dict[name] = f.get_tensor(name)
  835. # update with leftover tensor data from previous iteration, if any
  836. state_dict.update(leftover_state_dict)
  837. metadata = f.metadata()
  838. # due to sharded checkpoints, we are not guaranteed that we have all
  839. # tensor subclass data on one file
  840. # state_dict has the leftover data from this step and we wait for
  841. # missing information to be provided in a future iteration
  842. unflattened_state_dict, leftover_state_dict = (
  843. unflatten_tensor_state_dict(state_dict, metadata)
  844. )
  845. yield from unflattened_state_dict.items()
  846. else:
  847. with safe_open(st_file, framework="pt") as f:
  848. for name in f.keys(): # noqa: SIM118
  849. if should_skip_weight(name, local_expert_ids):
  850. continue
  851. # Tech2Wild/Kai 2026-09-10: DSV41_ENGRAM_DISK=1 leaves the
  852. # Engram tables on disk (see deepseek_v4_1/common/engram.py)
  853. if _DSV41_ENGRAM_DISK and name.endswith((".engram.embed.weight", ".engram.embed.scale")):
  854. continue
  855. param = f.get_tensor(name)
  856. yield name, param
  857. def multi_thread_safetensors_weights_iterator(
  858. hf_weights_files: list[str],
  859. use_tqdm_on_load: bool,
  860. max_workers: int = 4,
  861. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  862. """Multi-Thread iterate over the weights in the model safetensor files."""
  863. def _load_file(st_file: str):
  864. result = load_file(st_file, device="cpu")
  865. return result
  866. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  867. # Note to use generator here so we do not store all the loaded files in memory
  868. # at the same time, which can cause OOM for large models.
  869. futures = (executor.submit(_load_file, st_file) for st_file in hf_weights_files)
  870. futures_iter = tqdm(
  871. concurrent.futures.as_completed(futures),
  872. total=len(hf_weights_files),
  873. desc="Multi-thread loading shards",
  874. disable=not enable_tqdm(use_tqdm_on_load),
  875. bar_format=_BAR_FORMAT,
  876. )
  877. for future in futures_iter:
  878. state_dict = future.result()
  879. del future
  880. for key in list(state_dict):
  881. yield key, state_dict.pop(key)
  882. def runai_safetensors_weights_iterator(
  883. hf_weights_files: list[str],
  884. use_tqdm_on_load: bool,
  885. is_distributed: bool = False,
  886. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  887. """Iterate over the weights in the model safetensor files."""
  888. with SafetensorsStreamer() as streamer:
  889. is_cuda_alike = current_platform.is_cuda_alike()
  890. device = (
  891. f"cuda:{current_platform.current_device()}"
  892. if is_distributed and is_cuda_alike
  893. else "cpu"
  894. )
  895. streamer.stream_files(
  896. hf_weights_files,
  897. device=device,
  898. is_distributed=is_distributed,
  899. )
  900. total_tensors = sum(
  901. len(tensors_meta)
  902. for tensors_meta in streamer.files_to_tensors_metadata.values()
  903. )
  904. tensor_iter = tqdm(
  905. streamer.get_tensors(),
  906. total=total_tensors,
  907. desc="Loading safetensors using Runai Model Streamer",
  908. bar_format=_BAR_FORMAT,
  909. disable=not enable_tqdm(use_tqdm_on_load),
  910. mininterval=2,
  911. )
  912. for name, tensor in tensor_iter:
  913. yield name, tensor.clone()
  914. def fastsafetensors_weights_iterator(
  915. hf_weights_files: list[str],
  916. use_tqdm_on_load: bool,
  917. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  918. """Iterate over the weights in the model safetensor files
  919. using fastsafetensor library.
  920. Uses ParallelLoader for pipelined loading: the producer thread
  921. prepares metadata for the next shard while the consumer yields
  922. tensors from the current shard.
  923. """
  924. from fastsafetensors.parallel_loader import ParallelLoader
  925. if torch.distributed.is_initialized():
  926. pg = torch.distributed.group.WORLD
  927. else:
  928. pg = SingleGroup()
  929. device = torch.device(f"cuda:{current_platform.current_device()}")
  930. hf_weights_files = sorted(hf_weights_files, key=_natural_sort_key)
  931. # Use nogds=True for TP > 1 to avoid cuFileDriverOpen() which
  932. # initializes the GDS DMA subsystem for all visible GPUs, creating
  933. # unwanted CUDA contexts on every device.
  934. nogds = pg.size() > 1
  935. queue_size = envs.VLLM_FASTSAFETENSORS_QUEUE_SIZE
  936. tqdm_enabled = enable_tqdm(use_tqdm_on_load)
  937. def _make_loader(nogds: bool) -> "ParallelLoader":
  938. return ParallelLoader(
  939. pg=pg,
  940. hf_weights_files=hf_weights_files,
  941. queue_size=queue_size,
  942. use_tqdm_on_load=tqdm_enabled,
  943. device=str(device),
  944. nogds=nogds,
  945. )
  946. # GDS can fail either at construction or lazily inside the producer
  947. # thread during iteration (e.g. cuFileHandleRegister returning
  948. # CU_FILE_HANDLE_NOT_REGISTERED on a filesystem without GDS support).
  949. # Catch both and fall back to nogds, but only before yielding any
  950. # tensor -- restarting mid-stream would reload earlier shards.
  951. pl = None
  952. yielded = False
  953. try:
  954. try:
  955. pl = _make_loader(nogds)
  956. for name, tensor in pl.iterate_weights():
  957. yielded = True
  958. yield name, tensor
  959. except RuntimeError as e:
  960. if nogds or yielded or "gds" not in str(e):
  961. raise
  962. logger.warning_once(
  963. "GDS not enabled, setting `nogds=True`.\n"
  964. "For more information, see: https://github.com/foundation-model-stack/"
  965. "fastsafetensors?tab=readme-ov-file#basic-api-usages"
  966. )
  967. if pl is not None:
  968. pl.close()
  969. pl = _make_loader(nogds=True)
  970. yield from pl.iterate_weights()
  971. finally:
  972. if pl is not None:
  973. pl.close()
  974. def instanttensor_weights_iterator(
  975. hf_weights_files: list[str],
  976. use_tqdm_on_load: bool,
  977. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  978. """Iterate over the weights in the model safetensor files
  979. using instanttensor library."""
  980. try:
  981. import instanttensor
  982. except ImportError as e:
  983. raise ImportError(
  984. "Please install instanttensor via `pip install vllm[instanttensor]`"
  985. ) from e
  986. if not current_platform.is_cuda():
  987. raise ValueError("InstantTensor requires NVIDIA GPUs")
  988. try:
  989. world_group = get_world_group()
  990. except AssertionError:
  991. # Entering here only in unit tests where the world group is not initialized.
  992. process_group = None
  993. else:
  994. process_group = world_group.device_group if world_group.world_size > 1 else None
  995. device = current_platform.current_device()
  996. # copy=True yields tensors that own their memory, staying valid after the
  997. # context exits or InstantTensor reuses its buffer.
  998. with instanttensor.safe_open(
  999. hf_weights_files,
  1000. framework="pt",
  1001. device=device,
  1002. process_group=process_group,
  1003. copy=True,
  1004. ) as f:
  1005. # Track bytes so the bar reports load throughput (GB/s).
  1006. pbar = tqdm(
  1007. total=f.total_tensor_size,
  1008. desc="Loading safetensors using InstantTensor loader",
  1009. disable=not enable_tqdm(use_tqdm_on_load),
  1010. bar_format=_BAR_FORMAT,
  1011. position=tqdm._get_free_pos(),
  1012. unit="B",
  1013. unit_scale=True,
  1014. unit_divisor=1024,
  1015. mininterval=1.0,
  1016. )
  1017. try:
  1018. for name, tensor in f.tensors():
  1019. pbar.update(tensor.numel() * tensor.element_size())
  1020. yield name, tensor
  1021. finally:
  1022. pbar.close()
  1023. def pt_weights_iterator(
  1024. hf_weights_files: list[str],
  1025. use_tqdm_on_load: bool,
  1026. pt_load_map_location: str | dict[str, str] = "cpu",
  1027. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  1028. """Iterate over the weights in the model bin/pt files."""
  1029. for bin_file in tqdm(
  1030. hf_weights_files,
  1031. desc="Loading pt checkpoint shards",
  1032. disable=not enable_tqdm(use_tqdm_on_load),
  1033. bar_format=_BAR_FORMAT,
  1034. ):
  1035. state = torch.load(
  1036. bin_file, map_location=pt_load_map_location, weights_only=True
  1037. )
  1038. yield from state.items()
  1039. del state
  1040. def multi_thread_pt_weights_iterator(
  1041. hf_weights_files: list[str],
  1042. use_tqdm_on_load: bool,
  1043. pt_load_map_location: str | dict[str, str] = "cpu",
  1044. max_workers: int = 4,
  1045. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  1046. """Multi-Thread iterate over the weights in the model bin/pt files."""
  1047. def _load_file(bin_file: str):
  1048. return torch.load(
  1049. bin_file, map_location=pt_load_map_location, weights_only=True
  1050. )
  1051. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  1052. futures = [
  1053. executor.submit(_load_file, bin_file) for bin_file in hf_weights_files
  1054. ]
  1055. futures_iter = tqdm(
  1056. concurrent.futures.as_completed(futures),
  1057. total=len(hf_weights_files),
  1058. desc="Multi-thread loading pt checkpoint shards",
  1059. disable=not enable_tqdm(use_tqdm_on_load),
  1060. bar_format=_BAR_FORMAT,
  1061. )
  1062. for future in futures_iter:
  1063. state = future.result()
  1064. yield from state.items()
  1065. del state
  1066. def convert_pyslice_to_tensor(x: Any) -> torch.Tensor:
  1067. """convert PySafeSlice object from safetensors to torch.Tensor
  1068. PySafeSlice object supports indexing, which is done before loading the
  1069. actual tensor and can reduce the amount of memory being read into the
  1070. memory. However, it does not support more advanced functionalities
  1071. like `.view()` or `.t()`. Therefore, if we need to modify the loaded
  1072. tensor with these more complicated operators, we need to convert to
  1073. tensor first.
  1074. """
  1075. if not isinstance(x, torch.Tensor):
  1076. x = x[:]
  1077. return x
  1078. def default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
  1079. """Default weight loader."""
  1080. try:
  1081. if param.numel() == 1 and loaded_weight.numel() == 1:
  1082. # Sometimes scalar values aren't considered tensors with shapes
  1083. # so if both param and loaded_weight are a scalar,
  1084. # reshape to match before copying
  1085. param.data.copy_(loaded_weight.view(param.shape))
  1086. else:
  1087. assert param.size() == loaded_weight.size(), (
  1088. f"Attempted to load weight ({loaded_weight.size()}) "
  1089. f"into parameter ({param.size()})"
  1090. )
  1091. param.data.copy_(loaded_weight)
  1092. except Exception:
  1093. # NOTE: This exception is added for the purpose of setting breakpoint to
  1094. # debug weight loading issues.
  1095. raise
  1096. def row_parallel_weight_loader(
  1097. param: torch.Tensor, loaded_weight: torch.Tensor
  1098. ) -> None:
  1099. """Load weights that are row-parallelized."""
  1100. tp_rank = get_tensor_model_parallel_rank()
  1101. shard_dim = 0 if param.dim() != 1 else None
  1102. if shard_dim is not None:
  1103. shard_size = param.data.shape[shard_dim]
  1104. start_idx = tp_rank * shard_size
  1105. loaded_weight = loaded_weight.narrow(shard_dim, start_idx, shard_size)
  1106. return default_weight_loader(param, loaded_weight)
  1107. LoaderFunction = Callable[[torch.Tensor, torch.Tensor], None]
  1108. def sharded_weight_loader(shard_axis: int) -> LoaderFunction:
  1109. """Create a weight loader that shards the weights along the given axis"""
  1110. def loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
  1111. tp_rank = get_tensor_model_parallel_rank()
  1112. shard_size = param.data.shape[shard_axis]
  1113. start_idx = tp_rank * shard_size
  1114. loaded_weight = loaded_weight.narrow(shard_axis, start_idx, shard_size)
  1115. return default_weight_loader(param, loaded_weight)
  1116. return loader
  1117. def composed_weight_loader(
  1118. loader: LoaderFunction, fn: Callable[[torch.Tensor], torch.Tensor]
  1119. ) -> LoaderFunction:
  1120. """Create a weight loader that post-processes the weights after loading"""
  1121. def composed_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
  1122. loader(param, loaded_weight)
  1123. param.data.copy_(fn(param))
  1124. return
  1125. return composed_loader
  1126. def initialize_dummy_weights(
  1127. model: torch.nn.Module,
  1128. model_config: ModelConfig,
  1129. low: float = -1e-3,
  1130. high: float = 1e-3,
  1131. seed: int = 1234,
  1132. ) -> None:
  1133. """Initialize model weights with random values.
  1134. The model weights must be randomly initialized for accurate performance
  1135. measurements. Additionally, the model weights should not cause NaNs in the
  1136. forward pass. We empirically found that initializing the weights with
  1137. values between -1e-3 and 1e-3 works well for most models.
  1138. We use per-parameter random seed, so that dummy weights are consistent,
  1139. even if the model is partitioned across multiple devices. When the seed
  1140. is fixed, the random values generated by this function only depends on
  1141. the parameter's number of elements and its data type.
  1142. """
  1143. for param in model.state_dict().values():
  1144. initialize_single_dummy_weight(param, low, high, seed)
  1145. @torch.no_grad()
  1146. def initialize_single_dummy_weight(
  1147. param: torch.Tensor,
  1148. low: float = -1e-3,
  1149. high: float = 1e-3,
  1150. seed: int = 1234,
  1151. ) -> None:
  1152. if param.device.type == "meta":
  1153. return # deferred to finalize_layerwise_processing (e.g. online quant)
  1154. if not torch.is_floating_point(param):
  1155. if current_platform.is_rocm():
  1156. # On ROCm, integer params (e.g. GPTQ qweight/qzeros) are left
  1157. # as torch.empty() by default, giving non-deterministic values
  1158. # across processes. Zero them for reproducibility.
  1159. param.zero_()
  1160. return
  1161. if current_platform.is_tpu():
  1162. generator = torch.Generator(device="cpu")
  1163. generator.manual_seed(seed)
  1164. # Note: The param.uniform_ function cannot be used in this
  1165. # context because it demands more TPU HBM than directly copying
  1166. # from a CPU tensor.
  1167. # Note: We avoid using torch.rank_like as it doesn't currently
  1168. # support the generator argument.
  1169. param.copy_(
  1170. (high - low)
  1171. * torch.rand(
  1172. param.shape,
  1173. generator=generator,
  1174. dtype=param.dtype,
  1175. layout=param.layout,
  1176. requires_grad=param.requires_grad,
  1177. device="cpu",
  1178. )
  1179. + low
  1180. )
  1181. torch._sync(param)
  1182. return
  1183. generator = torch.Generator(device=param.data.device)
  1184. generator.manual_seed(seed)
  1185. if torch.finfo(param.data.dtype).bits < 16:
  1186. # uniform_ doesn't support < 16-bit datatypes (FP8)
  1187. dtype = param.data.dtype
  1188. tmp_param = param.data.to(torch.float16)
  1189. tmp_param = tmp_param.uniform_(low, high, generator=generator).to(dtype)
  1190. param.data.copy_(tmp_param)
  1191. else:
  1192. param.uniform_(low, high, generator=generator)
  1193. def maybe_remap_kv_scale_name(name: str, params_dict: dict) -> str | None:
  1194. """Remap the name of FP8 k/v_scale parameters.
  1195. This function handles the remapping of FP8 k/v_scale parameter names.
  1196. It detects if the given name ends with a suffix and attempts to remap
  1197. it to the expected name format in the model. If the remapped name is not
  1198. found in the params_dict, a warning is printed and None is returned.
  1199. Args:
  1200. name (str): The original loaded checkpoint parameter name.
  1201. params_dict (dict): Dictionary containing the model's named parameters.
  1202. Returns:
  1203. str: The remapped parameter name if successful, or the original name
  1204. if no remapping is needed.
  1205. None: If the remapped name is not found in params_dict.
  1206. """
  1207. # Already in vLLM's expected form (e.g. weights pre-renamed by a
  1208. # `WeightsMapper` from the quant config). Skip the regex remap, which
  1209. # would otherwise double-apply the `.attn` prefix and drop the weight.
  1210. if name in params_dict:
  1211. return name
  1212. if name.endswith(".kv_scale"):
  1213. logger.warning_once(
  1214. "DEPRECATED. Found kv_scale in the checkpoint. "
  1215. "This format is deprecated in favor of separate k_scale and "
  1216. "v_scale tensors and will be removed in a future release. "
  1217. "Functionally, we will remap kv_scale to k_scale and duplicate "
  1218. "k_scale to v_scale"
  1219. )
  1220. # NOTE: we remap the deprecated kv_scale to k_scale
  1221. remapped_name = name.replace(".kv_scale", ".attn.k_scale")
  1222. if remapped_name not in params_dict:
  1223. logger.warning_once(
  1224. "Found kv_scale in the checkpoint (e.g. %s), but not found the expected name in the model (e.g. %s). kv_scale is not loaded.", # noqa: E501
  1225. name,
  1226. remapped_name,
  1227. )
  1228. return None
  1229. return remapped_name
  1230. if any("mla_attn" in key for key in params_dict):
  1231. attn_str = "mla_attn.mla_attn"
  1232. logger.debug_once(
  1233. f"Found mla_attn with k_scale and v_scale in "
  1234. f"the checkpoint, using {attn_str} as attn_str"
  1235. )
  1236. else:
  1237. attn_str = "attn"
  1238. # Define scale name mapping patterns in order of precedence
  1239. scale_mapping_patterns = [
  1240. # ModelOpt format: .self_attn.{k,v}_proj.{k,v}_scale ->
  1241. # .self_attn.attn.{k,v}_scale
  1242. (
  1243. r"\.self_attn\.([kv])_proj\.([kv])_scale$",
  1244. rf".self_attn.{attn_str}.\2_scale",
  1245. ),
  1246. # QKV proj format: .self_attn.qkv_proj.{k,v}_scale ->
  1247. # .self_attn.attn.{k,v}_scale
  1248. (r"\.self_attn\.qkv_proj\.([kv])_scale$", r".self_attn.attn.\1_scale"),
  1249. # Qwen3 MoE format: .self_attn.qkqkv_proj.{k,v}_scale ->
  1250. # .self_attn.attn.{k,v}_scale
  1251. (r"\.self_attn\.qkqkv_proj\.([kv])_scale$", r".self_attn.attn.\1_scale"),
  1252. # NemotronH format: .mixer.{k,v}_proj.{k,v}_scale ->
  1253. # .mixer.attn.{k,v}_scale
  1254. (r"\.mixer\.[kv]_proj\.([kv])_scale$", r".mixer.attn.\1_scale"),
  1255. # HYV3 format: .self_attn.q.scale -> .self_attn.attn.q_scale
  1256. (r"\.self_attn\.q\.scale$", r".self_attn.attn.q_scale"),
  1257. # HYV3 format: .self_attn.{k,v}_cache.scale ->
  1258. # .self_attn.attn.{k,v}_scale
  1259. (r"\.self_attn\.([kv])_cache\.scale$", r".self_attn.attn.\1_scale"),
  1260. # Default format: .{k,v}_scale -> .attn.{k,v}_scale
  1261. (r"\.([qkv])_scale$", r".attn.\1_scale"),
  1262. (r"\.([qkv])_zero_point$", r".attn.\1_zero_point"),
  1263. ]
  1264. # Check if name ends with k_scale or v_scale
  1265. if name.endswith(
  1266. (
  1267. ".k_scale",
  1268. ".v_scale",
  1269. ".q_scale",
  1270. ".k_zero_point",
  1271. ".v_zero_point",
  1272. ".q_zero_point",
  1273. ".q.scale",
  1274. ".k_cache.scale",
  1275. ".v_cache.scale",
  1276. )
  1277. ):
  1278. import regex as re
  1279. for pattern, replacement in scale_mapping_patterns:
  1280. if re.search(pattern, name):
  1281. remapped_name = re.sub(pattern, replacement, name)
  1282. if remapped_name not in params_dict:
  1283. scale_type = name.split(".")[-1]
  1284. logger.warning_once(
  1285. "Found %s in the checkpoint (e.g. %s), but not found the expected name in the model (e.g. %s). %s is not loaded.", # noqa: E501
  1286. scale_type,
  1287. name,
  1288. remapped_name,
  1289. scale_type,
  1290. )
  1291. return None
  1292. return remapped_name
  1293. # If there were no matches, return the untouched param name
  1294. return name
  1295. def maybe_remap_moe_expert_param_name(
  1296. name: str,
  1297. params_dict: dict[str, torch.nn.Parameter],
  1298. ) -> str:
  1299. """
  1300. Remap MoE expert parameter names to account for routed_experts hierarchy.
  1301. This handles the transition from the old FusedMoE structure where weights
  1302. were directly in the experts module, to the new MoERunner → RoutedExperts
  1303. structure.
  1304. Checkpoint weights have names like:
  1305. layers.0.mlp.experts.w13_weight
  1306. layers.0.feed_forward.experts.w2_input_scale
  1307. But actual parameters are now:
  1308. layers.0.mlp.experts.routed_experts.w13_weight
  1309. layers.0.feed_forward.experts.routed_experts.w2_input_scale
  1310. This function inserts 'routed_experts.' into the path when needed.
  1311. Args:
  1312. name: Parameter name from checkpoint
  1313. params_dict: Dictionary of model parameters (from named_parameters())
  1314. Returns:
  1315. Remapped parameter name if routed_experts hierarchy exists,
  1316. otherwise the original name
  1317. """
  1318. # Only remap if this looks like an expert parameter
  1319. if ".experts." not in name:
  1320. return name
  1321. # Skip if already has routed_experts
  1322. if ".experts.routed_experts." in name:
  1323. return name
  1324. # Expert parameter patterns to check
  1325. expert_param_suffixes = [
  1326. "w13_weight",
  1327. "w2_weight",
  1328. "w13_weight_scale",
  1329. "w2_weight_scale",
  1330. "w13_input_scale",
  1331. "w2_input_scale",
  1332. "w13_bias",
  1333. "w2_bias",
  1334. "w13_scale",
  1335. "w2_scale",
  1336. "w13_g_idx",
  1337. "w2_g_idx",
  1338. "w13_qweight",
  1339. "w2_qweight",
  1340. "w13_qzeros",
  1341. "w2_qzeros",
  1342. "w13_weight_shape",
  1343. "w2_weight_shape",
  1344. ]
  1345. # Check if this is an expert weight parameter
  1346. is_expert_param = any(
  1347. f".{suffix}" in name or name.endswith(suffix)
  1348. for suffix in expert_param_suffixes
  1349. )
  1350. if not is_expert_param:
  1351. return name
  1352. # Try inserting routed_experts after .experts.
  1353. new_name = name.replace(".experts.", ".experts.routed_experts.", 1)
  1354. # Only use the new name if it exists in the model
  1355. if new_name in params_dict:
  1356. return new_name
  1357. # Otherwise return original name (old checkpoint format or different structure)
  1358. return name
  1359. def remap_moe_expert_weights(
  1360. weights: Iterable[tuple[str, torch.Tensor]],
  1361. params_dict: dict[str, torch.nn.Parameter],
  1362. ) -> Generator[tuple[str, torch.Tensor], None, None]:
  1363. """
  1364. Wrapper generator that remaps MoE expert parameter names for backward compatibility.
  1365. This allows models with custom weight loading to automatically handle both old
  1366. and new checkpoint formats without needing model-specific remapping code.
  1367. Usage:
  1368. params_dict = dict(model.named_parameters())
  1369. for name, weight in remap_moe_expert_weights(weights, params_dict):
  1370. # name is automatically remapped if needed
  1371. param = params_dict[name]
  1372. ...
  1373. Args:
  1374. weights: Iterator of (name, tensor) tuples from checkpoint
  1375. params_dict: Dictionary of model parameters (from named_parameters())
  1376. Yields:
  1377. (remapped_name, tensor) tuples
  1378. """
  1379. for name, weight in weights:
  1380. remapped_name = maybe_remap_moe_expert_param_name(name, params_dict)
  1381. yield (remapped_name, weight)