diff --git a/docs/models/supported_models.md b/docs/models/supported_models.md index 296c2b1900af..73ede646e0f6 100644 --- a/docs/models/supported_models.md +++ b/docs/models/supported_models.md @@ -20,7 +20,7 @@ vLLM also supports model implementations that are available in Transformers. We Currently, the Transformers modeling backend works for the following: - Modalities: embedding models, language models, vision-language models, audio-language models and omni models -- Architectures: encoder-only, decoder-only, mixture-of-experts +- Architectures: encoder-only, decoder-only, mixture-of-experts, looped (layers run more than once per forward pass, each pass with its own KV cache; not with pipeline parallelism) - Attention types: full attention and/or sliding attention - [Speculative decoding](../features/speculative_decoding/README.md) methods: EAGLE-3, DFlash, DFlash2, DSpark, XPress and MTP (for models following the Transformers MTP standard) diff --git a/tests/models/transformers/test_backend.py b/tests/models/transformers/test_backend.py index cd54e4cb2fb8..a58c33506c70 100644 --- a/tests/models/transformers/test_backend.py +++ b/tests/models/transformers/test_backend.py @@ -78,6 +78,7 @@ def check_implementation( kwargs_ref: dict[str, Any] | None = None, kwargs_test: dict[str, Any] | None = None, num_fused: dict[str, int] | None = None, + num_loops: int = 1, **kwargs, ): if num_fused is None: @@ -105,7 +106,7 @@ def check_implementation( from vllm.model_executor.layers.attention import Attention counts = model_test.apply_model(partial(count_modules, cls=Attention)) - assert counts == [num_layers] * tp_size + assert counts == [num_layers * num_loops] * tp_size outputs_test = model_test.generate_greedy_logprobs(*args) @@ -239,6 +240,21 @@ def test_hybrid_attention(vllm_runner: type[VllmRunner]) -> None: ) +def test_looped_model( + hf_runner: type[HfRunner], vllm_runner: type[VllmRunner], example_prompts: list[str] +) -> None: + """Each pass of a looped model through its shared layers has its own KV cache.""" + pytest.importorskip("transformers.models.nanbeige") + check_implementation( + hf_runner, + vllm_runner, + example_prompts, + "Nanbeige/Nanbeige4.2-3B", + kwargs_test={"model_impl": "transformers"}, + num_loops=2, + ) + + def test_whole_graph_compile( vllm_runner: type[VllmRunner], example_prompts: list[str] ) -> None: @@ -839,6 +855,7 @@ def test_attention_dispatch_is_required(): model = SimpleNamespace( text_config=SimpleNamespace(num_hidden_layers=1), attention_fusers={}, + cache_offsets={}, _get_attn_cls=lambda: None, _pp_indices=lambda: (0, 1), ) diff --git a/vllm/model_executor/models/transformers/__init__.py b/vllm/model_executor/models/transformers/__init__.py index 40a6aebe8bfb..bfe9d1fd7dd0 100644 --- a/vllm/model_executor/models/transformers/__init__.py +++ b/vllm/model_executor/models/transformers/__init__.py @@ -21,7 +21,10 @@ import torch.nn.functional as F from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS -from vllm.model_executor.models.transformers.base import VLLM_ATTN_ATTR +from vllm.model_executor.models.transformers.base import ( + VLLM_ATTN_ATTR, + VLLM_ATTN_KWARG, +) from vllm.model_executor.models.transformers.causal import CausalMixin from vllm.model_executor.models.transformers.legacy import LegacyMixin from vllm.model_executor.models.transformers.moe import MoEMixin @@ -77,7 +80,7 @@ def vllm_attention_forward( attention_mask: "torch.Tensor", **kwargs, ): - self_attn = getattr(module, VLLM_ATTN_ATTR) + self_attn = kwargs.get(VLLM_ATTN_KWARG, getattr(module, VLLM_ATTN_ATTR)) check_sinks(module, self_attn, kwargs.get("s_aux")) hidden = query.shape[-2] head_dim_qk = query.shape[-1] diff --git a/vllm/model_executor/models/transformers/base.py b/vllm/model_executor/models/transformers/base.py index 75da910f7aaf..493e181d06df 100644 --- a/vllm/model_executor/models/transformers/base.py +++ b/vllm/model_executor/models/transformers/base.py @@ -17,6 +17,7 @@ """Transformers modeling backend base class.""" import os +from collections import defaultdict from collections.abc import Callable, Iterable from contextlib import contextmanager from functools import cached_property @@ -39,6 +40,7 @@ ) from vllm.compilation.decorators import DynamicArgDims, support_torch_compile +from vllm.compilation.wrapper import remove_bytecode_hooks from vllm.config.utils import getattr_iter from vllm.distributed import get_pp_group, get_tp_group from vllm.distributed.utils import get_pp_indices @@ -176,6 +178,10 @@ def __call__( 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_KWARG = "vllm_attn" +"""Keyword argument in which a looped model's attention module hands the attention +interface the vLLM `Attention` instance of the call's cache layer.""" + class PPMissingScalar(PPMissingLayer): """A `PPMissingLayer` that returns a scalar zero instead of its input. @@ -191,6 +197,13 @@ def forward(self, *args, **kwargs) -> torch.Tensor: return self.zero +class NoAttention(nn.Module): + """Stands in for vLLM attention in the forward pass of `_find_cache_offsets`.""" + + def forward(self, query: torch.Tensor, *args, **kwargs) -> torch.Tensor: + return query + + class PreTrainedModelClasses(NamedTuple): decoder: type["PreTrainedModel"] encoders: dict[str, type["PreTrainedModel"]] @@ -243,7 +256,8 @@ def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): self.attention_fusers: dict[int, tuple[str, AttentionFuser]] = {} """`layer_idx` -> the qualname and fuser of the module computing that layer's attention, populated by `recursive_replace` for - `_create_attention_instances`.""" + `_create_attention_instances`. A looped model's modules have one entry per + cache layer, at `layer_idx` plus each call's offset.""" # Attrs for Eagle3 (see self.set_aux_hidden_state_layers) self._layer_names: dict[int, str] = {} @@ -278,6 +292,9 @@ def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): init_on_device_without_buffers("meta"), ): self.model: PreTrainedModel = self._create_model() + self.cache_offsets = self._find_cache_offsets() + """Attention module qualname -> the cache offset of each of its calls, for the + modules a looped model calls once per cache layer.""" # LoRA matches embeddings by the last part of their name, which varies by model input_embeddings = set(self.model.get_input_embeddings().modules()) @@ -377,6 +394,39 @@ def _find_encoder_classes( """ return {} + def _find_cache_offsets(self) -> dict[str, list[int]]: + """Find the offsets that a looped model's attention modules add to their + `layer_idx` (see `cache_offset_arg`), by running a meta-device copy of + `self.model` on one token. vLLM's attention interface needs no masks.""" + + def attention_modules(model: nn.Module): + for name, module in model.named_modules(): + fuser = AttentionFuser.match(None, module) + if fuser is not None and fuser.validate(module, self.vllm_config): + yield f"model.{name}", module, fuser.cache_offset_arg + + if not any(arg for _, _, arg in attention_modules(self.model)): + return {} + with torch.device("meta"): + model = AutoModel.from_config(**self._from_config_kwargs) + offsets: dict[str, list[int]] = defaultdict(list) + for name, module, arg in attention_modules(model): + setattr(module, VLLM_ATTN_ATTR, NoAttention()) + if arg is not None: + module.register_forward_pre_hook( + lambda m, args, kwargs, name=name, arg=arg: offsets[name].append( + kwargs.get(arg, 0) + ), + with_kwargs=True, + ) + context = set_forward_context(None, self.vllm_config, skip_compiled=True) + with torch.device("meta"), context: + model(input_ids=torch.zeros(1, 1, dtype=torch.long), use_cache=False) + # The copy's decoder is compile-decorated, and its bytecode hook would pin it + remove_bytecode_hooks(model) + # A module called once, without an offset, is not looped + return {name: o for name, o in offsets.items() if o != [0]} + @cached_property def _pre_trained_model_classes(self) -> PreTrainedModelClasses: """The decoder class and the encoder class of each modality that has one. @@ -539,6 +589,11 @@ def pipeline_parallel(self): """Apply the model's pipeline parallelization plan.""" if self.pp_group.world_size <= 1: return + if self.cache_offsets: + raise ValueError( + "Transformers modeling backend does not support pipeline " + "parallelism for looped models." + ) module, names = self._pp_split if not self.model.supports_pp_plan: @@ -710,16 +765,18 @@ def register_fusion(fuser: BaseFuser, prefix: str, module: nn.Module): if ( isinstance(fuser, AttentionFuser) - and (index := fuser.layer_index(module)) is not None + and (layer := fuser.layer_index(module)) is not None ): - if index in self.attention_fusers: - other, _ = self.attention_fusers[index] - raise ValueError( - f"Layer {index} dispatches attention from more than one " - f"module ({other} and {prefix}), which one vLLM attention " - "layer cannot serve." - ) - self.attention_fusers[index] = (prefix, fuser) + for offset in self.cache_offsets.get(prefix, [0]): + index = layer + offset + if index in self.attention_fusers: + other, _ = self.attention_fusers[index] + raise ValueError( + f"Layer {index} dispatches attention from more than one " + f"module ({other} and {prefix}), which one vLLM attention " + "layer cannot serve." + ) + self.attention_fusers[index] = (prefix, fuser) orig_to_new_stacked.update(fuser.orig_to_new_stacked(prefix)) @@ -862,8 +919,12 @@ def _create_attention_instances(self, prefix: str = ""): layer_types = getattr(text_config, "layer_types", None) start, end = self._pp_indices() + indices: Iterable[int] = range(start, end) + if self.cache_offsets: + # A looped model has a cache layer for each pass through a layer + indices = sorted({*indices, *self.attention_fusers}) - for i in range(start, end): + for i in indices: if i not in self.attention_fusers: layer = ( f"{i} ({layer_types[i]})" @@ -876,10 +937,15 @@ def _create_attention_instances(self, prefix: str = ""): ) attn_prefix, attn_fuser = self.attention_fusers[i] attn_module = self.get_submodule(attn_prefix) + layer_idx = attn_module.layer_idx + attn_name = f"{attn_prefix}.{VLLM_ATTN_ATTR}" + if i != layer_idx: + # Named after its cache layer, which vLLM reads off the name + attn_name = re.sub(rf"\.{layer_idx}\.", f".{i}.", attn_name, count=1) - # `[i]` is the whole-model config unless the checkpoint is + # `[layer_idx]` is the whole-model config unless the checkpoint is # heterogeneous, in which case it is this layer's own geometry. - arch_config = self.model_config.model_arch_config[i] + arch_config = self.model_config.model_arch_config[layer_idx] num_heads = self.model_config.get_num_attention_heads( self.parallel_config, arch_config ) @@ -893,7 +959,7 @@ def _create_attention_instances(self, prefix: str = ""): scale=scale, cache_config=self.cache_config, quant_config=self.quant_config, - prefix=maybe_prefix(prefix, f"{attn_prefix}.{VLLM_ATTN_ATTR}"), + prefix=maybe_prefix(prefix, attn_name), ) if attn_cls is MLAAttention: @@ -925,7 +991,7 @@ def _create_attention_instances(self, prefix: str = ""): ) # Handle interleaved sliding window attention - if layer_types and layer_types[i] == "sliding_attention": + if layer_types and layer_types[layer_idx] == "sliding_attention": kwargs["per_layer_sliding_window"] = text_config.sliding_window # Handle attention sinks if (sinks := attn_fuser.sinks(attn_module)) is not None: @@ -941,7 +1007,20 @@ def _create_attention_instances(self, prefix: str = ""): # module rather than index by `module.layer_idx`, an `int` that bakes # layer identity into the traced graph and so costs one compiled # artifact per layer. - setattr(attn_module, VLLM_ATTN_ATTR, attn_instance) + if attn_prefix not in self.cache_offsets: + setattr(attn_module, VLLM_ATTN_ATTR, attn_instance) + continue + # A looped model's module holds one per cache layer, keyed by offset, and + # hands the attention interface the one of each call + if not hasattr(attn_module, VLLM_ATTN_ATTR): + setattr(attn_module, VLLM_ATTN_ATTR, nn.ModuleDict()) + + def select(module, args, kwargs, arg=attn_fuser.cache_offset_arg): + attn = getattr(module, VLLM_ATTN_ATTR)[str(kwargs.get(arg, 0))] + return args, kwargs | {VLLM_ATTN_KWARG: attn} + + attn_module.register_forward_pre_hook(select, with_kwargs=True) + getattr(attn_module, VLLM_ATTN_ATTR)[str(i - layer_idx)] = attn_instance attn_prefixes = (prefix for prefix, _ in self.attention_fusers.values()) if any(p.endswith(f".{VLLM_ATTN_ATTR}") for p in attn_prefixes): diff --git a/vllm/model_executor/models/transformers/fusers/attention.py b/vllm/model_executor/models/transformers/fusers/attention.py index d8d324536d27..ce9546deb300 100644 --- a/vllm/model_executor/models/transformers/fusers/attention.py +++ b/vllm/model_executor/models/transformers/fusers/attention.py @@ -36,15 +36,20 @@ def _is_interface_lookup(node: ast.expr | None) -> bool: ) -@cache -def interface_call(forward: Callable) -> ast.Call | None: - """The attention interface call in `forward`, if it makes exactly one.""" +def _parse(forward: Callable) -> ast.Module | None: try: source = inspect.getsource(inspect.unwrap(forward)) - tree = ast.parse(textwrap.dedent(source)) + return ast.parse(textwrap.dedent(source)) except (AttributeError, OSError, SyntaxError, TypeError): return None + +@cache +def interface_call(forward: Callable) -> ast.Call | None: + """The attention interface call in `forward`, if it makes exactly one.""" + if (tree := _parse(forward)) is None: + return None + # Find the names of the local variables that read from the interface lookup names: set[str] = set() for node in ast.walk(tree): @@ -65,6 +70,27 @@ def interface_call(forward: Callable) -> ast.Call | None: return calls[0] if len(calls) == 1 else None +@cache +def cache_offset_arg(forward: Callable) -> str | None: + """The argument `forward` adds to `self.layer_idx` to get its cache layer, if any. + + Looped models run a module more than once per forward pass and give each pass + its own cache layer this way (e.g. Dory's `cache_offset`, HRM-Text's + `cycle_offset`).""" + if (tree := _parse(forward)) is None: + return None + params = inspect.signature(forward).parameters + for node in ast.walk(tree): + if not (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add)): + continue + operands = {ast.unparse(node.left), ast.unparse(node.right)} + if "self.layer_idx" in operands and len(operands) == 2: + (arg,) = operands - {"self.layer_idx"} + if arg in params: + return arg + return None + + def _resolve(node: ast.expr, module: nn.Module) -> object: """The value of `node` on `module`, for literals and `self.`.""" if isinstance(node, ast.Constant): @@ -90,6 +116,8 @@ class AttentionFuser(BaseFuser): """Source of the `scaling=` the module hands the interface, if it hands one.""" s_aux_expr: ast.expr | None = None """Source of the `s_aux=` the module hands the interface, if it hands one.""" + cache_offset_arg: str | None = None + """The argument that offsets the module's cache layer, see `cache_offset_arg`.""" def info(self, name: str) -> str: return f"Found: {name} ({self.source_cls}) -> attention interface" @@ -108,6 +136,7 @@ def match( source_cls=type(module).__name__, scale_expr=scale_expr, s_aux_expr=s_aux_expr, + cache_offset_arg=cache_offset_arg(type(module).forward), ) def validate(self, module: nn.Module, vllm_config: "VllmConfig") -> bool: