[Attention] Allow selecting a different attention backend per KV-cache group (#48012)

Signed-off-by: NickLucche <nicolo.lucchesi@mistral.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Nicolò Lucchesi
2026-07-17 15:19:02 -04:00
committed by GitHub
co-authored by Claude Opus 4.8
parent bf578e1abd
commit 5784507da4
4 changed files with 258 additions and 3 deletions
+38
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import field
from typing import Any, Literal
from pydantic import field_validator
@@ -19,6 +20,17 @@ class AttentionConfig:
backend: AttentionBackendEnum | None = None
"""Attention backend to use. Use "auto" or None for automatic selection."""
backend_per_kind: dict[str, AttentionBackendEnum] = field(default_factory=dict)
"""Per-KV-cache-group attention backend overrides, keyed by
`KVCacheSpecKind` (e.g. `{"mla_attention": "FLASHINFER_MLA",
"sliding_window_mla": "TRITON_MLA"}`). This lets a model that splits its
layers across multiple KV-cache groups (e.g. interleaved full and
sliding-window attention) use a different backend per group.
An entry overrides `backend` for layers of the matching kind; kinds not
listed fall back to `backend` (or automatic selection). A selected backend
that is invalid for that kind raises at startup."""
flash_attn_version: Literal[2, 3, 4] | None = None
"""Force vllm to use a specific flash-attention version (2, 3, or 4).
Only valid when using the flash-attention backend."""
@@ -120,3 +132,29 @@ class AttentionConfig:
if isinstance(value, str):
return MLAPrefillBackendEnum[value.upper()]
return value
@field_validator("backend_per_kind", mode="before")
@classmethod
def validate_backend_per_kind_before(cls, value: Any) -> Any:
"""Parse the `backend_per_kind` map from strings.
Keys must be valid `KVCacheSpecKind` values; values are parsed like
`backend` (enum name, case-insensitive).
"""
from vllm.v1.kv_cache_interface import KVCacheSpecKind
if not isinstance(value, dict):
return value
valid_kinds = {kind.value for kind in KVCacheSpecKind}
parsed: dict[str, AttentionBackendEnum] = {}
for kind, backend in value.items():
if kind not in valid_kinds:
raise ValueError(
f"Unknown KV cache group kind '{kind}' in "
f"backend_per_kind. Valid kinds are: "
f"{', '.join(sorted(valid_kinds))}."
)
if isinstance(backend, str):
backend = AttentionBackendEnum[backend.upper()]
parsed[kind] = backend
return parsed
+59 -3
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import cache
from typing import NamedTuple, cast, get_args
from typing import TYPE_CHECKING, NamedTuple, cast, get_args
import torch
@@ -15,6 +15,9 @@ from vllm.v1.attention.backends.registry import (
MambaAttentionBackendEnum,
)
if TYPE_CHECKING:
from vllm.v1.kv_cache_interface import KVCacheSpecKind
logger = init_logger(__name__)
@@ -53,6 +56,46 @@ class AttentionSelectorConfig(NamedTuple):
)
def get_attn_spec_kind(
use_mla: bool,
has_sliding_window: bool,
attn_type: str,
) -> "KVCacheSpecKind":
"""Derive the KV-cache group kind a layer belongs to from its signals.
Mirrors ``get_kv_cache_spec_kind`` (which derives the kind from the
produced ``KVCacheSpec``) so users can target groups by kind when
setting ``AttentionConfig.backend_per_kind``.
``SINK_FULL_ATTENTION`` is intentionally not derived here: it is produced
only by the ``StaticSinkAttention`` layer, whereas a plain ``Attention``
layer with attention sinks (e.g. gpt-oss) still yields a
``FullAttentionSpec``/``SlidingWindowSpec``. Sinks therefore do not change
the kind.
Args:
use_mla: Whether the layer uses multi-head latent attention.
has_sliding_window: Whether the layer applies a sliding window.
attn_type: The layer's ``AttentionType``.
Returns:
The ``KVCacheSpecKind`` the layer maps to.
"""
from vllm.v1.kv_cache_interface import KVCacheSpecKind
if attn_type == AttentionType.ENCODER_ONLY:
return KVCacheSpecKind.ENCODER_ONLY_ATTENTION
if attn_type == AttentionType.ENCODER_DECODER:
return KVCacheSpecKind.CROSS_ATTENTION
if use_mla:
if has_sliding_window:
return KVCacheSpecKind.SLIDING_WINDOW_MLA
return KVCacheSpecKind.MLA_ATTENTION
if has_sliding_window:
return KVCacheSpecKind.SLIDING_WINDOW
return KVCacheSpecKind.FULL_ATTENTION
def get_attn_backend(
head_size: int,
dtype: torch.dtype,
@@ -91,6 +134,7 @@ def get_attn_backend(
kv_transfer_config is not None and kv_transfer_config.is_kv_transfer_instance
)
attn_type = attn_type or AttentionType.DECODER
attn_selector_config = AttentionSelectorConfig(
head_size=head_size,
dtype=dtype,
@@ -101,15 +145,27 @@ def get_attn_backend(
use_sparse=use_sparse,
use_mm_prefix=use_mm_prefix,
use_per_head_quant_scales=use_per_head_quant_scales,
attn_type=attn_type or AttentionType.DECODER,
attn_type=attn_type,
has_sliding_window=has_sliding_window,
use_non_causal=vllm_config.attention_config.use_non_causal,
use_batch_invariant=envs.VLLM_BATCH_INVARIANT,
use_kv_connector=use_kv_connector,
)
# A per-KV-group override (keyed by KVCacheSpecKind) takes precedence over
# the global backend; kinds not present in the map fall back to it.
attention_config = vllm_config.attention_config
backend = attention_config.backend
if attention_config.backend_per_kind:
kind = get_attn_spec_kind(
use_mla=use_mla,
has_sliding_window=has_sliding_window,
attn_type=attn_type,
)
backend = attention_config.backend_per_kind.get(kind.value, backend)
return _cached_get_attn_backend(
backend=vllm_config.attention_config.backend,
backend=backend,
attn_selector_config=attn_selector_config,
num_heads=num_heads,
)