Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions tests/models/transformers/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
import pytest
import torch
import torch.nn as nn
from transformers import AutoConfig, AutoModel

from vllm.config import ModelConfig, VllmConfig
from vllm.model_executor.models.interfaces import SupportsMultiModal
from vllm.model_executor.models.transformers.base import Base
from vllm.model_executor.models.transformers.multimodal import MultiModalMixin
from vllm.model_executor.models.utils import StageMissingLayer

from ...conftest import HfRunner, VllmRunner
from ...utils import multi_gpu_test, prep_prompts
Expand Down Expand Up @@ -468,3 +475,50 @@ def test_replaced_embedding_exposes_one_vpe(vpe):

lm_head = ParallelLMHead(VOCAB_SIZE, HIDDEN_SIZE)
assert lm_head.tie_weights(composed.embed).weight is composed.embed.weight


MULTIMODAL_MODEL = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"


class MarkingStub(SupportsMultiModal, nn.Module):
"""Just enough of the backend to exercise component marking."""

_mark_model_components = MultiModalMixin._mark_model_components
_find_encoder_classes = MultiModalMixin._find_encoder_classes
_from_config_kwargs = Base._from_config_kwargs
_pre_trained_model_classes = Base._pre_trained_model_classes


def build_marked_model(image_limit: int, skip_tokenizer_init: bool = False):
"""Build the HF model inside the marking context and return it."""
model_config = ModelConfig(
model=MULTIMODAL_MODEL,
model_impl="transformers",
limit_mm_per_prompt={"image": image_limit},
)
# Set after construction: building the config itself needs the tokenizer
model_config.skip_tokenizer_init = skip_tokenizer_init
stub = MarkingStub()
stub.config = AutoConfig.from_pretrained(MULTIMODAL_MODEL)
stub.model_config = model_config

vllm_config = VllmConfig(model_config=model_config)
with stub._mark_model_components(vllm_config), torch.device("meta"):
stub.model = AutoModel.from_config(**stub._from_config_kwargs)
return stub.model


@pytest.mark.parametrize(("image_limit", "skipped"), [(0, True), (4, False)])
def test_tower_weights_skipped_when_modality_disabled(image_limit, skipped):
"""`--limit-mm-per-prompt image=0` should drop the vision tower's weights."""
vision_tower = build_marked_model(image_limit).vision_tower
assert isinstance(vision_tower, StageMissingLayer) is skipped


def test_marking_skipped_without_tokenizer():
"""Marking needs the HF processor, which needs a tokenizer, so it is skipped.
The tower is built as normal rather than the model failing to load.
"""
vision_tower = build_marked_model(0, skip_tokenizer_init=True).vision_tower
assert not isinstance(vision_tower, StageMissingLayer)
72 changes: 52 additions & 20 deletions vllm/model_executor/models/transformers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@

import os
from collections.abc import Callable, Iterable
from contextlib import contextmanager
from functools import cached_property
from itertools import chain
from operator import attrgetter
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any, NamedTuple

import regex as re
import torch
Expand Down Expand Up @@ -85,6 +87,12 @@
logger = init_logger(__name__)


class PreTrainedModelClasses(NamedTuple):
decoder: type["PreTrainedModel"]
encoders: dict[str, type["PreTrainedModel"]]
"""Modality -> encoder class, for each modality that has one."""


class Base(
nn.Module,
VllmModel,
Expand Down Expand Up @@ -147,14 +155,13 @@ def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""):
)

self._patch_config()
from_config_kwargs = dict(
config=self.config,
dtype=self.model_config.dtype,
trust_remote_code=self.model_config.trust_remote_code,
)
self._decorate_for_torch_compile(**from_config_kwargs)
self._decorate_for_torch_compile()
# Init on "meta" to delay allocating GPU tensors
with init_on_device_without_buffers("meta"):
with (
self._mark_model_components(vllm_config),
init_on_device_without_buffers("meta"),
):
from_config_kwargs = self._from_config_kwargs
self.model: PreTrainedModel = AutoModel.from_config(**from_config_kwargs)

# Create weight name to module qualname mapper
Expand Down Expand Up @@ -196,22 +203,47 @@ def _patch_config(self):
self.text_config._attn_implementation = "vllm"
self.config.dtype = torch.get_default_dtype()

def _get_decoder_cls(self, **kwargs: dict) -> type["PreTrainedModel"]:
@contextmanager
def _mark_model_components(self, vllm_config: "VllmConfig"):
"""Mark language model and tower submodules as `self.model` is created.

Nothing to do in `Base`, `MultiModalMixin` will override."""
yield

@cached_property
def _from_config_kwargs(self) -> dict[str, Any]:
"""The kwargs used to create `self.model`."""
return dict(
config=self.config,
dtype=self.model_config.dtype,
trust_remote_code=self.model_config.trust_remote_code,
)

def _find_encoder_classes(
self, model: "PreTrainedModel"
) -> dict[str, type["PreTrainedModel"]]:
"""Find the encoder class of each modality `model` has one for.

Text models have none. Multi-modal ones override this.
"""
Get the decoder class from the model.
return {}

Args:
kwargs: The kwargs to create the model.
@cached_property
def _pre_trained_model_classes(self) -> PreTrainedModelClasses:
"""The decoder class and the encoder class of each modality that has one.

Returns:
The decoder class.
Both come from a single throwaway model, since building one is not cheap.
"""
with torch.device("meta"):
model: PreTrainedModel = AutoModel.from_config(**kwargs)
decoder_cls = type(model.get_decoder())
logger.debug("Identified decoder class as: %s", decoder_cls)
model: PreTrainedModel = AutoModel.from_config(**self._from_config_kwargs)
model_classes = PreTrainedModelClasses(
decoder=type(model.get_decoder()),
encoders=self._find_encoder_classes(model),
)
del model
return decoder_cls

logger.debug("Identified model classes as: %s", model_classes)
return model_classes

def _decorate_cls_for_torch_compile(
self,
Expand Down Expand Up @@ -246,7 +278,7 @@ def _decorate_cls_for_torch_compile(
is_encoder=is_encoder,
)(cls)

def _decorate_for_torch_compile(self, **kwargs: dict):
def _decorate_for_torch_compile(self):
"""
Decorate the model's decoder class to indicate to vLLM that it supports torch
compile if `can_enable_torch_compile` is True.
Expand All @@ -256,7 +288,7 @@ def _decorate_for_torch_compile(self, **kwargs: dict):
class.
"""
self._decorate_cls_for_torch_compile(
cls=self._get_decoder_cls(**kwargs),
cls=self._pre_trained_model_classes.decoder,
# Applied to a PreTrainedModel so the batch dimension will exist
dynamic_arg_dims=dict[str, int](
input_ids=1, # shape: [1, seq_len]
Expand Down
Loading
Loading