Skip to content

vllm.model_executor.models.transformers.base

Transformers modeling backend base class.

Classes:

Attributes:

  • NESTED_ATTN_SCALE_MAPPER –

    For Transformers attention modules named VLLM_ATTN_ATTR (e.g. GPT-J). Their

  • VLLM_ATTN_ATTR –

    Attribute in which to store the vLLM Attention instance that serves a Transformers

NESTED_ATTN_SCALE_MAPPER = WeightsMapper(orig_to_new_regex={re.compile(f'(?<!\\.{VLLM_ATTN_ATTR})\\.{VLLM_ATTN_ATTR}\\.([qkv]_(?:scale|zero_point))$'): f'.{VLLM_ATTN_ATTR}.{VLLM_ATTN_ATTR}.\\1'}) module-attribute

For Transformers attention modules named VLLM_ATTN_ATTR (e.g. GPT-J). Their checkpoint KV-cache scales belong to the nested vLLM Attention, but the cache scale mapper skips them because they already end in .attn.k_scale.

VLLM_ATTN_ATTR = 'attn' module-attribute

Attribute in which to store the vLLM Attention instance that serves a Transformers attention module. "attn" is chosen deliberately to match the mappings generated by maybe_remap_kv_scale_name.

Base

Bases: Module, VllmModel, SupportsQuant, SupportsLoRA, SupportsPP, SupportsEagle, SupportsEagle3, EagleModelMixin

Methods:

Attributes:

_aux_hidden_states = [] instance-attribute

Eagle3 aux hidden states recorded by hooks during the forward pass.

_decoder_layers cached property

The decoder layers, i.e. the only ModuleList in self._pp_split, if it has num_hidden_layers entries.

_from_config_kwargs cached property

The kwargs used to create self.model.

_layer_names = {} instance-attribute

Mapping from layer index to layer name for Eagle3.

_pp_split cached property

The module the pipeline parallel split is applied to, and the names (in order) of its children that the split assigns to ranks.

_pre_decoder_layer_replace = lambda layer, prefix: None instance-attribute

Called on each decoder layer before recursive_replace replaces it.

_pre_trained_model_classes cached property

The decoder class and the encoder class of each modality that has one.

Both come from a single throwaway model, since building one is not cheap.

_tower_model_names = () class-attribute instance-attribute

Read by recursive_replace, so text-only models need this empty default.

attention_fusers = {} instance-attribute

layer_idx -> the qualname and fuser of the module computing that layer's attention, populated by recursive_replace for _create_attention_instances.

fusers = {} instance-attribute

Module qualname -> the fusers applied to it, populated by recursive_replace for _create_attention_instances.

ignore_unexpected_prefixes = [] instance-attribute

Ignore unexpected weights whose qualname starts with these prefixes.

ignore_unexpected_suffixes = [] instance-attribute

Ignore unexpected weights whose qualname ends with these suffixes.

packed_modules_mapping = {} instance-attribute

Fused module -> constituent projections, populated by recursive_replace for the quantization machinery and loaders (e.g. bitsandbytes).

_apply_conversion_mapping(weights)

Apply the supported Transformers renamings and conversions to the weights.

_create_attention_instances(prefix='')

Create Attention instances to inform KV cache allocation.

_create_hf_to_vllm_mapper()

Create a WeightsMapper to map checkpoint weight names to module qualnames.

This handles:

  • Transformers weight renaming from WeightRenaming
  • Checkpoints saved with a base model prefix that is not model
  • Checkpoints saved with no base model prefix
  • Any quantization config specific mappings

_create_model()

Create the Transformers model that self.model wraps.

_decorate_cls_for_torch_compile(cls, dynamic_arg_dims, enable_if, is_encoder)

Decorate cls to indicate to vLLM that it supports torch compile.

Parameters:

  • cls

    (type[PreTrainedModel]) –

    The PreTrainedModel class to decorate.

  • dynamic_arg_dims

    (DynamicArgDims | None) –

    A mapping from argument name to the dynamic dimensions of the argument. If None, default dynamic arg dims will be used. See support_torch_compile for more details.

  • enable_if

    (Callable[[VllmConfig], bool]) –

    A function which takes in the vLLM config and returns whether torch compile should be enabled for this class.

  • is_encoder

    (bool) –

    Whether the class being decorated is an encoder.

_decorate_for_torch_compile()

Decorate the model's decoder class to indicate to vLLM that it supports torch compile if can_enable_torch_compile is True.

_drop_ignored_unexpected(weights)

Drop weights matching _keys_to_ignore_on_load_unexpected.

Transformers merges these up without prefixes, so a match is only dropped if it has nowhere to go. Like Transformers, the patterns match renamed keys. Parameters are read at load time, after fusers and pipeline parallelism have renamed or removed them.

_find_encoder_classes(model)

Find the encoder class of each modality model has one for.

Text models have none. Multi-modal ones override this.

_get_attn_cls()

Return the Attention class to use for this model's layers.

_get_tie_word_embeddings()

Check if the model has tied word embeddings.

_inject_intermediate_hidden_states(module, args, kwargs)

Pass the hidden states from the previous pipeline rank to module unchanged.

The decoder still runs its pre-layer code for masks and rotary embeddings, but anything it does to the hidden states was already done on the first rank.

_mark_model_components(vllm_config)

Mark language model and tower submodules as self.model is created.

Nothing to do in Base, MultiModalMixin will override.

_offloader()

The offloader for the decoder layers.

_patch_config()

Patch the config to ensure that the model is created correctly:

  • Sets the attention implementation to "vllm" so the attention instances from _create_attention_instances are used
  • Sets the dtype to the default torch dtype set by vLLM because Transformers uses the config dtype when creating the model

_pp_indices()

The range of decoder layers on this pipeline parallel rank.

_tp_plan()

The tensor parallel plan of self.model, relative to self.model.

_vocab_embeddings()

The nn.Embeddings in self.model which hold a vocab table.

_weight_conversions()

The Transformers weight conversions that apply to self.model.

init_parameters(module, dtype=None)

If a parameter is on the meta device, then its parent module is the original module created by:

with torch.device("meta"):
    self.model: "PreTrainedModel" = AutoModel.from_config(...)

keep_in_fp32(module, prefix='')

Honor _keep_in_fp32_modules_strict as from_pretrained would.

module is self.model or one of its submodules, whose qualname from self.model is prefix.

pipeline_parallel()

Apply the model's pipeline parallelization plan.

recursive_replace()

Recursively replace modules in the model as needed.

Currently, this replaces:

  • GLUs with a fused MergedColumnParallelLinear + ...AndMul
  • Attention QKV projections with a fused QKVParallelLinear + split
  • nn.Linear with vLLM's tensor parallel linear classes
  • nn.Conv2d / nn.Conv3d with vLLM's Conv2d / Conv3d
  • Vocab nn.Embeddings with vLLM's VocabParallelEmbedding
  • RMSNorm (detected from their dataflow) with vLLM's RMSNormor GemmaRMSNorm
  • nn.LayerNorm with vLLM's LayerNorm

PPMissingScalar

Bases: PPMissingLayer

A PPMissingLayer that returns a scalar zero instead of its input.

For layers whose input is not hidden states (e.g. learned position embeddings), where passing the input through would give the wrong shape.

PreTrainedModelClasses

Bases: NamedTuple

Attributes:

  • encoders (dict[str, type[PreTrainedModel]]) –

    Modality -> encoder class, for each modality that has one.

encoders instance-attribute

Modality -> encoder class, for each modality that has one.