vllm.model_executor.model_loader.weight_utils
¶
Utilities for downloading and initializing model weights.
Functions:
-
composed_weight_loader–Create a weight loader that post-processes the weights after loading
-
default_weight_loader–Default weight loader.
-
download_safetensors_index_file_from_hf–Download hf safetensors index file from Hugging Face Hub.
-
download_weights_from_hf–Download model weights from Hugging Face Hub.
-
enable_xet_high_performance–Automatically activates xet high performance mode
-
fastsafetensors_weights_iterator–Iterate over the weights in the model safetensor files
-
filter_files_not_needed_for_inference–Exclude files that are not needed for inference.
-
filter_mm_encoder_only_safetensors_files–Drop safetensors shards that only contain language-model weights.
-
filter_safetensors_files_by_weight_name–Drop safetensors shards in which
is_unused_weightaccepts every tensor. -
finalize_model_weights–Run every module's own post-load hook after a full load or reload, each
-
get_safetensors_files_in_index–Return the files the safetensors index lists, or None without an index.
-
initialize_single_dummy_weight–Fill
paramwith deterministic dummy values suited to its dtype. -
instanttensor_weights_iterator–Load with InstantTensor, optionally mapping Engram tables on CPU.
-
load_attention_sink–Load this rank's heads of a global sink; padded heads are set to -inf.
-
make_attention_sink–Create a sink with -inf padding and register its TP weight loader.
-
maybe_download_from_modelscope–Download model from ModelScope hub if VLLM_USE_MODELSCOPE is True.
-
maybe_remap_kv_scale_name–Remap the name of FP8 k/v_scale parameters.
-
maybe_remap_moe_expert_param_name–Remap MoE expert parameter names to account for routed_experts hierarchy.
-
multi_thread_pt_weights_iterator–Multi-Thread iterate over the weights in the model bin/pt files.
-
multi_thread_safetensors_weights_iterator–Multi-Thread iterate over the weights in the model safetensor files.
-
np_cache_weights_iterator–Iterate over the weights in the model np files.
-
pt_weights_iterator–Iterate over the weights in the model bin/pt files.
-
remap_moe_expert_weights–Remap MoE expert parameter names for backward compatibility.
-
resolve_mm_encoder_only_lm_prefixes–Resolve vLLM LM module prefixes for
--mm-encoder-onlyshard skip. -
row_parallel_weight_loader–Load weights that are row-parallelized.
-
runai_safetensors_weights_iterator–Iterate over the weights in the model safetensor files.
-
safetensors_weights_iterator–Iterate over the weights in the model safetensor files.
-
sharded_weight_loader–Create a weight loader that shards the weights along the given axis
_fill_random_fp8_codes(param, generator)
¶
Fill an 8-bit float tensor with random finite codes across its range.
Real checkpoints scale FP8 weights to use the whole range, and the bit activity of the operands sets GEMM power draw: values from a narrow range (few exponent codes) let power-capped GPUs run measurably faster than real weights do.
_get_checkpoints_size_bytes(files)
¶
Return the total size of the checkpoint files in bytes.
_get_fs_type(files)
¶
Get the filesystem type of the first file in files (Linux only).
_local_snapshot_dirs(model_name_or_path, cache_dir)
¶
Snapshot directories of a cached repo, found from the cache layout alone.
Offline, snapshot_download() resolves a revision only through refs/
_mapped_weight_name(weights_mapper, key)
¶
Apply WeightsMapper.map_name when present; else identity.
_natural_sort_key(filepath)
¶
Natural sort key for filenames with numeric components, such as model-00001-of-00005.safetensors -> ['model-', 1, '-of-', 5, '.safetensors']
_prefetch_all_checkpoints(sorted_files, num_prefetch_threads=DEFAULT_SAFETENSORS_PREFETCH_NUM_THREADS, block_size=DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE)
¶
Start prefetching checkpoint files into page cache in a background thread.
_prefetch_checkpoint(file_path, block_size=DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE)
¶
Prefetch a checkpoint file into the OS page cache.
Reads the file in blocks so the kernel caches its pages before workers load the same file.
_shuffle_files(files)
¶
Return files shuffled with a rank-dependent seed.
composed_weight_loader(loader, fn)
¶
Create a weight loader that post-processes the weights after loading
default_weight_loader(param, loaded_weight)
¶
Default weight loader.
download_safetensors_index_file_from_hf(model_name_or_path, index_file, cache_dir, subfolder=None, revision=None)
¶
Download hf safetensors index file from Hugging Face Hub.
Parameters:
-
(model_name_or_path¶str) –The model name or path.
-
(index_file¶str) –The safetensors index file name
-
(cache_dir¶Optional[str]) –The cache directory to store the model weights. If None, will use HF defaults.
-
(subfolder¶Optional[str], default:None) –The subfolder within the model repository to download weights from.
-
(revision¶Optional[str], default:None) –The revision of the model.
download_weights_from_hf(model_name_or_path, cache_dir, allow_patterns, revision=None, subfolder=None, ignore_patterns=None)
¶
Download model weights from Hugging Face Hub.
Parameters:
-
(model_name_or_path¶str) –The model name or path.
-
(cache_dir¶Optional[str]) –The cache directory to store the model weights. If None, will use HF defaults.
-
(allow_patterns¶list[str]) –The allowed patterns for the weight files. Files matched by any of the patterns will be downloaded.
-
(revision¶Optional[str], default:None) –The revision of the model.
-
(subfolder¶Optional[str], default:None) –The subfolder within the model repository to download weights from.
-
(ignore_patterns¶Optional[Union[str, list[str]]], default:None) –The patterns to filter out the weight files. Files matched by any of the patterns will be ignored.
Returns:
-
str(str) –The path to the downloaded model weights.
enable_xet_high_performance()
¶
Automatically activates xet high performance mode
fastsafetensors_weights_iterator(hf_weights_files, use_tqdm_on_load)
¶
Iterate over the weights in the model safetensor files using fastsafetensor library.
Uses ParallelLoader for pipelined loading: the producer thread prepares metadata for the next shard while the consumer yields tensors from the current shard.
filter_files_not_needed_for_inference(hf_weights_files)
¶
Exclude files that are not needed for inference.
See https://github.com/huggingface/transformers/blob/v4.34.0/src/transformers/trainer.py#L227-L233
filter_mm_encoder_only_safetensors_files(hf_weights_files, hf_folder, index_file, language_model_prefixes, *, weights_mapper=None)
¶
Drop safetensors shards that only contain language-model weights.
Used with --mm-encoder-only so Encoder-only EPD instances avoid reading
pure LM shards from disk/DRAM.
Each HF index key is classified by mapping through weights_mapper (when
provided) and testing the vLLM name against language_model_prefixes.
Without a mapper, HF names are compared directly (identity checkpoint
layout, e.g. Kimi language_model.*).
A shard is kept if it contains any non-LM key. Without an index file, or when
an LM module prefix is also the HF root of non-LM keys, returns
hf_weights_files unchanged: this fails closed so Molmo / Phi-4-MM / Muse
cannot under-load the encoder.
filter_safetensors_files_by_weight_name(hf_weights_files, is_unused_weight)
¶
Drop safetensors shards in which is_unused_weight accepts every tensor.
Loaders that read whole files (InstantTensor, fastsafetensors, multi-thread, eager, prefetch) cannot skip single tensors, so dropping shards is their only way to avoid reading weights the model does not load.
Parameters:
-
(hf_weights_files¶list[str]) –Safetensors shard paths.
-
(is_unused_weight¶Callable[[str], bool]) –Returns True for checkpoint weight names the model does not load.
Returns:
finalize_model_weights(model, target_device=None)
¶
Run every module's own post-load hook after a full load or reload, each after all of its submodules. Every load and update path finishes here.
Quantization methods and the submodules of quantized layers are skipped: their quant method processes them, in the loader's per-layer pass.
get_safetensors_files_in_index(hf_folder, index_file)
¶
Return the files the safetensors index lists, or None without an index.
The files may sit in a subdirectory, like tensors/, and may be missing. Raises ValueError if the index lists a file outside hf_folder.
initialize_single_dummy_weight(param, low=None, high=None, seed=1234, name='')
¶
Fill param with deterministic dummy values suited to its dtype.
8-bit integer and packed FP4 params get random bytes (every FP4 code is
finite), except uint8 params named like a scale, which hold E8M0 scales
and get a fixed exponent. 8-bit float params get random finite codes
across their range, as real checkpoints use it, unless low/high are
given. Other integer params (e.g. indices) are left untouched. Other float
params are sampled from [low, high], which defaults to +-1e-3.
instanttensor_weights_iterator(hf_weights_files, use_tqdm_on_load, local_expert_ids=None, *, load_engram_on_cpu=False)
¶
Load with InstantTensor, optionally mapping Engram tables on CPU.
load_attention_sink(param, loaded_weight)
¶
Load this rank's heads of a global sink; padded heads are set to -inf.
make_attention_sink(num_heads, dtype=None)
¶
Create a sink with -inf padding and register its TP weight loader.
maybe_download_from_modelscope(model, revision=None, download_dir=None, ignore_patterns=None, allow_patterns=None)
¶
Download model from ModelScope hub if VLLM_USE_MODELSCOPE is True.
Returns the path to the downloaded model, or None if the model is not downloaded from ModelScope.
maybe_remap_kv_scale_name(name, params_dict)
¶
Remap the name of FP8 k/v_scale parameters.
This function handles the remapping of FP8 k/v_scale parameter names. It detects if the given name ends with a suffix and attempts to remap it to the expected name format in the model. If the remapped name is not found in the params_dict, a warning is printed and None is returned.
Parameters:
-
(name¶str) –The original loaded checkpoint parameter name.
-
(params_dict¶dict) –Dictionary containing the model's named parameters.
Returns:
maybe_remap_moe_expert_param_name(name, params_dict)
¶
Remap MoE expert parameter names to account for routed_experts hierarchy.
This handles the transition from the old FusedMoE structure where weights were directly in the experts module, to the new MoERunner → RoutedExperts structure.
Checkpoint weights have names like
layers.0.mlp.experts.w13_weight layers.0.feed_forward.experts.w2_input_scale
But actual parameters are now: layers.0.mlp.experts.routed_experts.w13_weight layers.0.feed_forward.experts.routed_experts.w2_input_scale
This function inserts 'routed_experts.' into the path when needed.
Parameters:
-
(name¶str) –Parameter name from checkpoint
-
(params_dict¶dict[str, Parameter]) –Dictionary of model parameters (from named_parameters())
Returns:
multi_thread_pt_weights_iterator(hf_weights_files, use_tqdm_on_load, pt_load_map_location='cpu', max_workers=4)
¶
Multi-Thread iterate over the weights in the model bin/pt files.
multi_thread_safetensors_weights_iterator(hf_weights_files, use_tqdm_on_load, max_workers=4, shuffle_safetensors_files=False)
¶
Multi-Thread iterate over the weights in the model safetensor files.
np_cache_weights_iterator(model_name_or_path, cache_dir, hf_folder, hf_weights_files, use_tqdm_on_load)
¶
Iterate over the weights in the model np files.
Will dump the model weights to numpy files if they are not already dumped.
pt_weights_iterator(hf_weights_files, use_tqdm_on_load, pt_load_map_location='cpu')
¶
Iterate over the weights in the model bin/pt files.
remap_moe_expert_weights(weights, params_dict)
¶
Remap MoE expert parameter names for backward compatibility.
This allows models with custom weight loading to automatically handle both old and new checkpoint formats without needing model-specific remapping code.
Usage
params_dict = dict(model.named_parameters()) for name, weight in remap_moe_expert_weights(weights, params_dict): # name is automatically remapped if needed param = params_dict[name] ...
Parameters:
-
(weights¶Iterable[tuple[str, Tensor]]) –Iterator of (name, tensor) tuples from checkpoint
-
(params_dict¶dict[str, Parameter]) –Dictionary of model parameters (from named_parameters())
Yields:
resolve_mm_encoder_only_lm_prefixes(language_model_names)
¶
Resolve vLLM LM module prefixes for --mm-encoder-only shard skip.
Prefixes come from _language_model_names. Classification of HF index
keys is done later via optional weights_mapper (see
filter_mm_encoder_only_safetensors_files), so this helper does not
hard-code Qwen/HF nest lists.
Returns None (leave the safetensors file list unchanged) when
_language_model_names is empty/missing.
row_parallel_weight_loader(param, loaded_weight)
¶
Load weights that are row-parallelized.
runai_safetensors_weights_iterator(hf_weights_files, use_tqdm_on_load, is_distributed=False)
¶
Iterate over the weights in the model safetensor files.
safetensors_weights_iterator(hf_weights_files, use_tqdm_on_load, safetensors_load_strategy=None, local_expert_ids=None, *, safetensors_prefetch_num_threads=DEFAULT_SAFETENSORS_PREFETCH_NUM_THREADS, safetensors_prefetch_block_size=DEFAULT_SAFETENSORS_PREFETCH_BLOCK_SIZE, shuffle_safetensors_files=False)
¶
Iterate over the weights in the model safetensor files.
When local_expert_ids is provided, expert weights not belonging to this rank are skipped before reading from disk, which drastically reduces storage I/O for MoE models under EP.
sharded_weight_loader(shard_axis)
¶
Create a weight loader that shards the weights along the given axis