Skip to content

vllm.model_executor.models.utils

Classes:

Functions:

Attributes:

ShardId = str | int | tuple[int, ...] module-attribute

One shard of a stacked parameter. A tuple is a single contiguous span.

ShardIds = ShardId | list[ShardId] module-attribute

One shard, or a list of shards the same weight is loaded into in turn.

WeightsTransformFn = Callable[[Iterable[tuple[str, torch.Tensor]]], Iterable[tuple[str, torch.Tensor]]] module-attribute

A lazy transform over a raw checkpoint (name, tensor) stream, passing unrecognized tensors through unchanged.

AutoWeightsLoader

Helper class to load weights into a torch.nn.Module. It is able to automatically detect child modules and parameters while iterating over the weights only once.

The weight loading logic for individual modules can be overridden by defining a load_weights method.

Similarly, the weight loading logic for individual parameters can be overridden by defining a weight_loader method.

Detailed weight loading information can be viewed by setting the environment variable VLLM_LOGGING_LEVEL=DEBUG.

_add_loadable_non_param_tensors(module, child_params)

Add tensor names that are not in the model params that may be in the safetensors, e.g., batch normalization stats and registered buffers.

PPMissingLayer

Bases: Identity

A placeholder layer for missing layers in a pipeline parallel model.

Methods:

  • forward –

    Return the first arg from args or the first value from kwargs.

forward(*args, **kwargs)

Return the first arg from args or the first value from kwargs.

StageMissingLayer

Bases: Module

Methods:

  • tie_weights –

    Omitted layers do not need to share embedding weights.

tie_weights(embed_tokens)

Omitted layers do not need to share embedding weights.

WeightsMapper dataclass

Maps the name of each weight if they match the following patterns.

If a key maps to a value of None, the corresponding weight is ignored.

Fields are applied in declaration order. weights_transforms rewrite the raw weight stream in list order before any name mapping, and stacked rules run last so that they see the final vLLM names.

Methods:

  • __or__ –

    Combine two WeightsMappers by merging their mappings.

  • get_rename_mapper –

    Mapper variant keeping only the renames.

  • map_name –

    Map a weight name; returns None if the weight should be ignored.

__or__(other)

Combine two WeightsMappers by merging their mappings.

_map_name(key)

Backward-compatible alias for map_name.

_map_name_with_shard(key)

Map a weight name and extract any shard_id metadata.

Returns:

  • tuple[str, ShardIds | None] | None –

    (mapped_name, shard_id) if the name should be kept. A list of shard

  • tuple[str, ShardIds | None] | None –

    ids means the weight is loaded into each of those shards in turn.

  • tuple[str, ShardIds | None] | None –

    None if the name should be dropped.

get_rename_mapper()

Mapper variant keeping only the renames.

This is what consumers that name modules rather than load them need: LoRA name parsing and the quantization config's layer lists.

Stacked maps are dropped so that constituent names (e.g. q_proj) survive rather than being rewritten to the stacked vLLM name (qkv_proj). Mappings to None are dropped because "do not load this weight" is meaningless to such a consumer, and applying it would silently shrink a quantization config's ignore list or make LoRA name parsing fail.

map_name(key)

Map a weight name; returns None if the weight should be ignored.

_embedding_count_expression(embeddings)

Constructs a debugging representation of the number of embeddings in the NestedTensors.

_flatten_embeddings(embeddings)

Recursively flattens and concatenates NestedTensors on all but the last dimension.

_get_tied_embedding_params(module)

Map each tied word embedding qualname to the first name it aliases.

_merge_multimodal_embeddings(inputs_embeds, multimodal_embeddings, is_multimodal)

Merge multimodal_embeddings into inputs_embeds by overwriting the positions in inputs_embeds corresponding to placeholder tokens in input_ids.

Note

This updates inputs_embeds in place.

collect_children(module, *, targets=None)

Within this context, collect all direct child assignments to module, returning a list of children names that is internally updated until the context is exited.

If targets is set, instead collect descendents of module that are an instance of targets, even if they aren't direct children.

compute_skip_topk_layers(config)

Backbone layers that reuse the top-k of the closest preceding indexer layer instead of building their own indexer.

copy_pp_buffers(intermediate_tensors, buffers)

Copy cross-layer state received from the previous PP stage into place.

extract_layer_index(layer_name, num_attn_module=1)

Extract the layer index from the module name.

Examples: - "encoder.layers.0" -> 0 - "encoder.layers.1.self_attn" -> 1 - "2.self_attn" -> 2 - "model.encoder.layers.0.sub.1" -> ValueError if num_attn_module == 1

fast_topk(values, topk, dim)

Optimized topk implementation that uses torch.max for k=1 case.

This function provides better performance for the common case of k=1 by using torch.max instead of the more general torch.topk.

Parameters:

  • values

    (Tensor) –

    Input tensor to find top-k values from

  • topk

    (int) –

    Number of top values to return (k). Must be > 0.

  • dim

    (int) –

    Dimension along which to compute topk

Returns:

  • Tensor –

    Tuple of (values, indices) where values are the top-k values

  • Tensor –

    and indices are their corresponding indices in the input tensor

flatten_bn(x, *, concat=False)

flatten_bn(x: list[torch.Tensor]) -> list[torch.Tensor]
flatten_bn(x: torch.Tensor) -> torch.Tensor
flatten_bn(
    x: list[torch.Tensor] | torch.Tensor,
    *,
    concat: Literal[True],
) -> torch.Tensor
flatten_bn(
    x: list[torch.Tensor] | torch.Tensor,
    *,
    concat: bool = False,
) -> list[torch.Tensor] | torch.Tensor

Flatten the B and N dimensions of batched multimodal inputs.

The input tensor should have shape (B, N, ...).

get_draft_quant_config(vllm_config)

Get quantization config for Draft models.

Draft models should use their own quantization config instead of the verifier/target model's config. This helper retrieves the draft model's quantization config.

Parameters:

  • vllm_config

    (VllmConfig) –

    The vLLM configuration object.

Returns:

get_fused_shared_expert_layers(module, moe_cls, enable_eplb=False)

Resolve fused-shared-expert layer indices from the live module tree.

The index is taken from each MoE module's qualified name, so it follows the same index space as the caller's weight names: 0-based for modules stored in an nn.ModuleList, and absolute for nn.ModuleDict MTP layers keyed by layer index. No loader needs to hard-code an offset.

Also rejects mixed fusion when EPLB is enabled or an elastic-buffer all2all backend is selected, and logs the resolved policy.

get_layer_index(feature_layer_index, num_hidden_layers)

Given a signed vision feature layer, get the number of hidden layers needed to leverage it.

Parameters:

  • feature_layer_index

    (int) –

    Index of a required layer in the visual encoder.

  • num_hidden_layers

    (int) –

    The total number of hidden layers in the visual encoder.

get_pp_missing_layer_names(model)

Get the names of the missing layers in a pipeline parallel model.

get_spec_layer_idx_from_weight_name(config, weight_name)

Return the MTP layer index a weight belongs to, or None.

Parameters:

  • config

    (PreTrainedConfig) –

    The model config; must expose num_hidden_layers and, for MTP checkpoints, num_nextn_predict_layers.

  • weight_name

    (str) –

    Checkpoint weight name to classify.

Returns:

  • int | None –

    The absolute layer index for an MTP-layer weight, else None.

init_vllm_registered_model(vllm_config, *, prefix='', hf_config=None, architectures=None)

Helper function to initialize an inner model registered to vLLM, based on the arguments passed to the outer vLLM model.

is_pp_missing_parameter(name, model)

Check if a parameter is missing in a pipeline parallel model.

make_empty_intermediate_tensors_factory(keys, hidden_size, buffers=None)

buffers are token-major cross-layer state sent along with keys.

make_layers(num_hidden_layers, layer_fn, prefix)

Make a list of layers with the given layer function, taking pipeline parallelism into account.

Parameters:

  • num_hidden_layers

    (int) –

    Total number of hidden layers in the model.

  • layer_fn

    (LayerFn) –

    Function to create a layer given its index.

  • prefix

    (str) –

    Prefix for layer names.

Returns:

map_draft_quant_config(quant_config, weight_mapper, prefix, start_layer_id, num_hidden_layers)

Map draft quantization settings to runtime module names.

maybe_fuse_shared_experts(weights, *, n_routed_experts, n_shared_experts, fused_shared_expert_layers, ckpt_prefix='mlp.shared_experts', experts_prefix='mlp.experts')

Route AITER fused-shared-expert checkpoint weights into fused slots.

When AITER fused-shared-experts is active, shared experts are packed into the routed expert tensor. The checkpoint stores them under ckpt_prefix as a single (possibly widened) tensor; this splits it into n_shared_experts chunks named {experts_prefix}.{n_routed_experts + j} so the RoutedExperts loader treats them as extra experts. Yields the input unchanged when the fusion is inactive, so callers can wrap unconditionally.

Parameters:

  • weights

    (Iterable[tuple[str, Tensor]]) –

    Iterable of (name, tensor) checkpoint pairs.

  • n_routed_experts

    (int) –

    Number of routed experts; offsets the fused slots.

  • n_shared_experts

    (int) –

    Number of shared experts packed into the tensor.

  • ckpt_prefix

    (str, default: 'mlp.shared_experts' ) –

    Checkpoint module name of the shared experts.

  • experts_prefix

    (str, default: 'mlp.experts' ) –

    Checkpoint module name of the routed experts.

  • fused_shared_expert_layers

    (frozenset[int]) –

    Layer indices whose shared expert was fused at construction time, as returned by get_fused_shared_expert_layers. Only weights belonging to these layers are routed to fused slots.

Yields:

maybe_prefix(prefix, name)

Add a prefix to a name if the prefix is non-empty.

Parameters:

  • prefix

    (str) –

    The prefix to add. If empty, no prefix will be added.

  • name

    (str) –

    The name to potentially prefix.

Returns:

  • str –

    The string "prefix.name" if prefix was non-empty, otherwise just "name".

no_init_weights(module, placeholder, *, targets=None)

Within this context, prevent weight initialization from using device memory and replace direct child assignments to module with the result of placeholder().

If targets is set, instead prevent weight initialization and replace assignments where the child is an instance of targets, even if they aren't direct children of module.

pp_splits_layer_sharing(num_hidden_layers, users, consumers)

Whether a later PP stage's first users layer is one of consumers, which read state an earlier layer wrote in the same forward pass.

pp_topk_buffers(config, topk_indices_buffer, topk_layers)

The shared top-k, if a later PP stage starts on a layer that reuses it.

process_eagle_weight(model, name)

Update EAGLE model flags based on loaded weight name. This should be called during weight loading to detect if a model has its own lm_head or embed_tokens weight.

Parameters:

  • model

    (Module) –

    The model instance (must support EAGLE)

  • name

    (str) –

    The name of the weight to process

scatter_output_slices(output, indices, per_item_out_tokens, dest, clone=False)

Slice a concatenated output tensor and scatter into dest by index.

skip_spec_layers(weights, config)

Drop MTP spec-layer weights (loaded by the MTP head, not the base model).

Parameters:

  • weights

    (Iterable[tuple[str, Tensor]]) –

    Iterable of (name, tensor) checkpoint pairs.

  • config

    (PreTrainedConfig) –

    The model config, passed to get_spec_layer_idx_from_weight_name.

Yields:

spec_decode_needs_target_embed(vllm_config)

Whether the last PP rank needs the target input embedding, for a hidden-state drafter that may reuse it (see maybe_share_target_embed).