[Mini-vLLM] SM86-only cut: models, backends, Rust, tests
- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries - Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels - Remove inc/quark quant loaders; keep compressed-tensors and Marlin - Drop the Rust frontend, pooling entrypoints, and idle test suites - Rebuild kernels for sm_80;sm_86 and strip the extensions - Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,104 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Differential test for the AITER MLA uniform-MTP padding decision.
|
||||
|
||||
`_uniform_padded_mtp_qo_len` decides whether a full-CUDA-graph decode batch may
|
||||
synthesize dummy query rows. It used to reach that decision through eight tensor
|
||||
dispatches -- sum/item, boolean-mask index, all, eq, nonzero, item, any -- on a
|
||||
CPU tensor holding one entry per request. It now reads the tensor out once and
|
||||
decides on Python ints.
|
||||
|
||||
That rewrite also **reordered** the checks: the `num_decode_tokens <= sum(...)`
|
||||
early-out moved below the divisibility and `uniform_qo_len <= 1` guards. Every
|
||||
one of those paths returns 0, so the result should be unchanged -- but "should
|
||||
be" is exactly the sort of claim worth checking exhaustively, so both
|
||||
implementations are carried here and compared over the whole small input space.
|
||||
|
||||
Pure host arithmetic; no GPU required.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
|
||||
|
||||
|
||||
def _reference(qo_len: torch.Tensor, max_qo_len: int, num_decode_tokens: int) -> int:
|
||||
"""The pre-#58381 implementation, verbatim."""
|
||||
num_reqs = qo_len.numel()
|
||||
if num_reqs == 0 or num_decode_tokens <= 0:
|
||||
return 0
|
||||
if num_decode_tokens <= int(qo_len.sum().item()):
|
||||
return 0
|
||||
if num_decode_tokens % num_reqs != 0:
|
||||
return 0
|
||||
|
||||
uniform_qo_len = num_decode_tokens // num_reqs
|
||||
if uniform_qo_len <= 1:
|
||||
return 0
|
||||
|
||||
positive_qo_len = qo_len[qo_len > 0]
|
||||
if positive_qo_len.numel() == qo_len.numel():
|
||||
return 0
|
||||
if positive_qo_len.numel() > 0:
|
||||
if max_qo_len != uniform_qo_len:
|
||||
return 0
|
||||
if not torch.all(positive_qo_len == uniform_qo_len):
|
||||
return 0
|
||||
|
||||
zero_positions = torch.nonzero(qo_len == 0, as_tuple=False).flatten()
|
||||
if zero_positions.numel() > 0:
|
||||
first_zero = int(zero_positions[0].item())
|
||||
if torch.any(qo_len[first_zero:] > 0):
|
||||
return 0
|
||||
|
||||
return uniform_qo_len
|
||||
|
||||
|
||||
_ACTUAL = AiterMLAMetadataBuilder._uniform_padded_mtp_qo_len
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_reqs", [1, 2, 3, 4])
|
||||
def test_matches_reference_exhaustively(num_reqs):
|
||||
"""Every qo_len vector x decode-token count x max_qo_len in a small space."""
|
||||
checked = 0
|
||||
for lens in itertools.product(range(0, 4), repeat=num_reqs):
|
||||
qo = torch.tensor(lens, dtype=torch.int32)
|
||||
for num_decode_tokens in range(0, 13):
|
||||
for max_qo_len in range(0, 5):
|
||||
got = _ACTUAL(qo, max_qo_len, num_decode_tokens)
|
||||
want = _reference(qo, max_qo_len, num_decode_tokens)
|
||||
assert got == want, (
|
||||
f"lens={lens} num_decode_tokens={num_decode_tokens} "
|
||||
f"max_qo_len={max_qo_len}: got {got}, reference {want}"
|
||||
)
|
||||
checked += 1
|
||||
assert checked > 0
|
||||
|
||||
|
||||
def test_empty_batch():
|
||||
assert _ACTUAL(torch.zeros(0, dtype=torch.int32), 4, 8) == 0
|
||||
assert _reference(torch.zeros(0, dtype=torch.int32), 4, 8) == 0
|
||||
|
||||
|
||||
def test_the_padded_mtp_case_that_should_succeed():
|
||||
"""A live prefix at the uniform width, then zero-padded dummies."""
|
||||
qo = torch.tensor([4, 4, 0, 0], dtype=torch.int32)
|
||||
# 4 requests x 4 tokens = 16 captured, 8 live -> dummies are synthesizable.
|
||||
assert _ACTUAL(qo, 4, 16) == 4
|
||||
assert _reference(qo, 4, 16) == 4
|
||||
|
||||
|
||||
def test_positive_after_zero_is_rejected():
|
||||
"""A live request after a padding hole breaks the contiguous-prefix layout."""
|
||||
qo = torch.tensor([4, 0, 4, 0], dtype=torch.int32)
|
||||
assert _ACTUAL(qo, 4, 16) == 0
|
||||
assert _reference(qo, 4, 16) == 0
|
||||
|
||||
|
||||
def test_ragged_live_lengths_are_rejected():
|
||||
qo = torch.tensor([4, 2, 0, 0], dtype=torch.int32)
|
||||
assert _ACTUAL(qo, 4, 16) == 0
|
||||
assert _reference(qo, 4, 16) == 0
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,195 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for mamba attention backend selectors."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.mamba.abstract import MambaBase
|
||||
from vllm.model_executor.layers.mamba.linear.minimax_linear_attn import (
|
||||
MiniMaxText01LinearAttention,
|
||||
)
|
||||
from vllm.model_executor.layers.mamba.mamba_mixer import MambaMixer
|
||||
from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateShapeCalculator
|
||||
from vllm.model_executor.layers.mamba.short_conv import ShortConv
|
||||
from vllm.model_executor.models.falcon_h1 import FalconH1ForCausalLM
|
||||
from vllm.model_executor.models.granitemoehybrid import GraniteMoeHybridForCausalLM
|
||||
from vllm.model_executor.models.zamba2 import Zamba2ForCausalLM
|
||||
from vllm.v1.attention.backends.linear_attn import LinearAttentionBackend
|
||||
from vllm.v1.attention.backends.mamba1_attn import Mamba1AttentionBackend
|
||||
from vllm.v1.attention.backends.mamba2_attn import Mamba2AttentionBackend
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionBackend
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("use_replayssm", "expected_blocks"), [(False, 3), (True, 0)])
|
||||
def test_replayssm_does_not_reserve_speculative_state_blocks(
|
||||
use_replayssm, expected_blocks
|
||||
):
|
||||
layer = SimpleNamespace(
|
||||
get_state_shape=lambda: ((2,),),
|
||||
get_state_dtype=lambda: (torch.float32,),
|
||||
mamba_type=MambaAttentionBackendEnum.MAMBA2,
|
||||
is_kv_cache_tp_replicated=False,
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
mamba_block_size=1,
|
||||
mamba_page_size_padded=None,
|
||||
mamba_cache_mode="none",
|
||||
use_replayssm=use_replayssm,
|
||||
),
|
||||
num_speculative_tokens=3,
|
||||
)
|
||||
|
||||
spec = MambaBase.get_kv_cache_spec(layer, vllm_config)
|
||||
|
||||
assert spec is not None
|
||||
assert spec.num_speculative_blocks == expected_blocks
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_cls", [FalconH1ForCausalLM, GraniteMoeHybridForCausalLM, Zamba2ForCausalLM]
|
||||
)
|
||||
def test_mamba2_config_state_shape_includes_speculative_tokens(model_cls):
|
||||
"""The config-time shape sizes the padded Mamba page, so it must match
|
||||
MambaMixer2.get_state_shape, whose conv state grows with spec tokens."""
|
||||
hf_config = SimpleNamespace(
|
||||
hidden_size=128,
|
||||
mamba_expand=2,
|
||||
mamba_d_ssm=None,
|
||||
mamba_n_groups=1,
|
||||
mamba_ngroups=1,
|
||||
mamba_n_heads=8,
|
||||
n_mamba_heads=8,
|
||||
mamba_d_head=32,
|
||||
mamba_headdim=32,
|
||||
mamba_d_state=16,
|
||||
mamba_d_conv=4,
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(hf_config=hf_config),
|
||||
parallel_config=SimpleNamespace(tensor_parallel_size=1),
|
||||
num_speculative_tokens=2,
|
||||
)
|
||||
|
||||
assert model_cls.get_mamba_state_shape_from_config(
|
||||
vllm_config
|
||||
) == MambaStateShapeCalculator.mamba2_state_shape(
|
||||
tp_world_size=1,
|
||||
intermediate_size=256,
|
||||
n_groups=1,
|
||||
num_heads=8,
|
||||
head_dim=32,
|
||||
state_size=16,
|
||||
conv_kernel=4,
|
||||
num_spec=2,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layer_class, init_kwargs, expected_backend, expected_mamba_type",
|
||||
[
|
||||
(
|
||||
MambaMixer,
|
||||
dict(
|
||||
hidden_size=128,
|
||||
ssm_state_size=16,
|
||||
conv_kernel_size=4,
|
||||
intermediate_size=256,
|
||||
time_step_rank=8,
|
||||
use_conv_bias=True,
|
||||
use_bias=False,
|
||||
use_rms_norm=True,
|
||||
),
|
||||
Mamba1AttentionBackend,
|
||||
MambaAttentionBackendEnum.MAMBA1,
|
||||
),
|
||||
(
|
||||
MambaMixer2,
|
||||
dict(
|
||||
hidden_size=128,
|
||||
ssm_state_size=16,
|
||||
conv_kernel_size=4,
|
||||
intermediate_size=256,
|
||||
use_conv_bias=True,
|
||||
use_bias=False,
|
||||
n_groups=1,
|
||||
num_heads=8,
|
||||
head_dim=32,
|
||||
),
|
||||
Mamba2AttentionBackend,
|
||||
MambaAttentionBackendEnum.MAMBA2,
|
||||
),
|
||||
(
|
||||
MiniMaxText01LinearAttention,
|
||||
dict(
|
||||
config=SimpleNamespace(
|
||||
hidden_size=256,
|
||||
num_attention_heads=8,
|
||||
head_dim=32,
|
||||
num_hidden_layers=12,
|
||||
block=64,
|
||||
),
|
||||
prefix="layers.0.self_attn",
|
||||
),
|
||||
LinearAttentionBackend,
|
||||
MambaAttentionBackendEnum.LINEAR,
|
||||
),
|
||||
(
|
||||
ShortConv,
|
||||
dict(
|
||||
config=SimpleNamespace(conv_L_cache=32, conv_bias=True),
|
||||
dim=128,
|
||||
layer_idx=0,
|
||||
),
|
||||
ShortConvAttentionBackend,
|
||||
MambaAttentionBackendEnum.SHORT_CONV,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_mamba_layers_get_attn_backend(
|
||||
default_vllm_config,
|
||||
dist_init,
|
||||
layer_class,
|
||||
init_kwargs,
|
||||
expected_backend,
|
||||
expected_mamba_type,
|
||||
):
|
||||
"""Test that Mamba-like layers return the correct attention backend."""
|
||||
if layer_class is MiniMaxText01LinearAttention:
|
||||
init_kwargs["vllm_config"] = default_vllm_config
|
||||
layer = layer_class(**init_kwargs)
|
||||
|
||||
backend_class = layer.get_attn_backend()
|
||||
assert backend_class is expected_backend
|
||||
assert layer.mamba_type == expected_mamba_type
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layer_class,expected_backend,expected_mamba_type",
|
||||
[
|
||||
(MambaMixer, Mamba1AttentionBackend, MambaAttentionBackendEnum.MAMBA1),
|
||||
(MambaMixer2, Mamba2AttentionBackend, MambaAttentionBackendEnum.MAMBA2),
|
||||
(
|
||||
MiniMaxText01LinearAttention,
|
||||
LinearAttentionBackend,
|
||||
MambaAttentionBackendEnum.LINEAR,
|
||||
),
|
||||
(ShortConv, ShortConvAttentionBackend, MambaAttentionBackendEnum.SHORT_CONV),
|
||||
],
|
||||
)
|
||||
def test_mamba_layers_have_unified_interface(
|
||||
layer_class, expected_backend, expected_mamba_type
|
||||
):
|
||||
"""Test that all Mamba layers have the unified get_attn_backend
|
||||
interface."""
|
||||
assert hasattr(layer_class, "get_attn_backend"), (
|
||||
f"{layer_class.__name__} should have get_attn_backend method"
|
||||
)
|
||||
assert hasattr(layer_class, "mamba_type"), (
|
||||
f"{layer_class.__name__} should have mamba_type property"
|
||||
)
|
||||
@@ -1,360 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.test_attention_backends import (
|
||||
BATCH_SPECS,
|
||||
_test_backend_correctness,
|
||||
)
|
||||
from tests.v1.attention.utils import BatchSpec
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.utils.b12x import get_b12x_paged_attention
|
||||
from vllm.v1.attention.backends import b12x
|
||||
from vllm.v1.attention.backends.b12x import (
|
||||
B12xPagedAttentionBackend,
|
||||
B12xPagedAttentionImpl,
|
||||
_kv_page_size,
|
||||
_max_page_table_width,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheLayout
|
||||
|
||||
|
||||
def _require_b12x_paged_attention() -> None:
|
||||
capability = current_platform.get_device_capability()
|
||||
if (
|
||||
not current_platform.is_cuda()
|
||||
or capability is None
|
||||
or not B12xPagedAttentionBackend.supports_compute_capability(capability)
|
||||
):
|
||||
pytest.skip("b12x paged attention requires SM120 or SM121.")
|
||||
|
||||
paged_attention = get_b12x_paged_attention()
|
||||
if paged_attention is None or not paged_attention.is_supported():
|
||||
pytest.skip("b12x paged attention is not available.")
|
||||
|
||||
|
||||
def _causal_mask(
|
||||
b: torch.Tensor,
|
||||
h: torch.Tensor,
|
||||
q_idx: torch.Tensor,
|
||||
kv_idx: torch.Tensor,
|
||||
*,
|
||||
context_len: int,
|
||||
):
|
||||
return q_idx + context_len >= kv_idx
|
||||
|
||||
|
||||
def _causal_sliding_window_mask(
|
||||
b: torch.Tensor,
|
||||
h: torch.Tensor,
|
||||
q_idx: torch.Tensor,
|
||||
kv_idx: torch.Tensor,
|
||||
*,
|
||||
context_len: int,
|
||||
sliding_window: int,
|
||||
):
|
||||
causal_mask = q_idx + context_len >= kv_idx
|
||||
window_mask = q_idx + context_len - kv_idx < sliding_window
|
||||
return causal_mask & window_mask
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dtype", "kv_cache_dtype", "paged_attention", "expected_reason"),
|
||||
[
|
||||
pytest.param(
|
||||
torch.float16,
|
||||
"fp8_e4m3",
|
||||
None,
|
||||
"b12x currently requires bfloat16 queries",
|
||||
id="query-dtype",
|
||||
),
|
||||
pytest.param(
|
||||
torch.bfloat16,
|
||||
"float16",
|
||||
None,
|
||||
"b12x does not support float16 KV cache",
|
||||
id="kv-cache-dtype",
|
||||
),
|
||||
pytest.param(
|
||||
torch.bfloat16,
|
||||
"auto",
|
||||
None,
|
||||
"Install the b12x backend with `pip install vllm[b12x]`",
|
||||
id="package-not-installed",
|
||||
),
|
||||
pytest.param(
|
||||
torch.bfloat16,
|
||||
"auto",
|
||||
SimpleNamespace(is_supported=lambda: False),
|
||||
"b12x paged attention is not supported on the current device",
|
||||
id="device-api",
|
||||
),
|
||||
pytest.param(
|
||||
torch.bfloat16,
|
||||
"auto",
|
||||
SimpleNamespace(is_supported=lambda: True),
|
||||
None,
|
||||
id="supported",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_b12x_attention_config_support(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: str,
|
||||
paged_attention,
|
||||
expected_reason: str | None,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
b12x,
|
||||
"get_b12x_paged_attention",
|
||||
lambda: paged_attention,
|
||||
)
|
||||
|
||||
reason = B12xPagedAttentionBackend.supports_combination(
|
||||
head_size=128,
|
||||
dtype=dtype,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
block_size=128,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_mm_prefix=False,
|
||||
device_capability=DeviceCapability(12, 0),
|
||||
)
|
||||
|
||||
assert reason == expected_reason
|
||||
|
||||
|
||||
def test_b12x_attention_uses_two_plane_nhd_cache() -> None:
|
||||
spec = B12xPagedAttentionBackend.customize_spec(
|
||||
FullAttentionSpec(
|
||||
block_size=128,
|
||||
num_kv_heads=4,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
)
|
||||
|
||||
assert spec.num_head_slots == 2
|
||||
assert spec.state_content_bytes == 4 * 128 * 2
|
||||
assert B12xPagedAttentionBackend.supported_kv_cache_layouts() == (
|
||||
KVCacheLayout.LBHNC,
|
||||
KVCacheLayout.BLHNC,
|
||||
)
|
||||
assert B12xPagedAttentionBackend.supports_block_size(128)
|
||||
assert not B12xPagedAttentionBackend.supports_block_size(32)
|
||||
|
||||
|
||||
def test_b12x_attention_hybrid_cache_capacity_includes_expansion() -> None:
|
||||
assert _max_page_table_width(4096, 128, 4096, False) == 32
|
||||
assert _max_page_table_width(4096, 128, 4096, True) == 64
|
||||
|
||||
|
||||
def test_b12x_attention_runtime_page_size_comes_from_cache() -> None:
|
||||
key_cache = torch.empty((3, 64, 4, 128), device="meta")
|
||||
value_cache = torch.empty_like(key_cache)
|
||||
|
||||
assert _kv_page_size(key_cache, value_cache) == 64
|
||||
with pytest.raises(ValueError, match="matching K/V page sizes"):
|
||||
_kv_page_size(key_cache, torch.empty((3, 128, 4, 128), device="meta"))
|
||||
|
||||
|
||||
def test_b12x_attention_lazily_prepares_decode_bucket(monkeypatch) -> None:
|
||||
impl = object.__new__(B12xPagedAttentionImpl)
|
||||
plan = SimpleNamespace(layout=SimpleNamespace(nbytes=96))
|
||||
created: list[tuple[int, int]] = []
|
||||
|
||||
def create_plan(page_size: int, batch_size: int) -> SimpleNamespace:
|
||||
created.append((page_size, batch_size))
|
||||
return plan
|
||||
|
||||
impl._decode_plans = {}
|
||||
impl._create_decode_plan = create_plan
|
||||
impl._scratch_nbytes = 128
|
||||
impl._extend_plans = {}
|
||||
impl._verify_q_per_req = 0
|
||||
metadata = SimpleNamespace(max_query_len=1)
|
||||
monkeypatch.setattr(b12x, "_capture_alloc_forbidden", lambda: False)
|
||||
|
||||
assert impl._select_plan(metadata, 7, 7, 7, 64) is plan
|
||||
assert impl._select_plan(metadata, 7, 7, 7, 64) is plan
|
||||
assert created == [(64, 7)]
|
||||
|
||||
|
||||
def test_b12x_attention_fp8_descales_follow_request_batch() -> None:
|
||||
impl = object.__new__(B12xPagedAttentionImpl)
|
||||
impl.kv_cache_dtype = "fp8_e4m3"
|
||||
layer = SimpleNamespace(
|
||||
_k_scale=torch.tensor(2.0),
|
||||
_v_scale=torch.tensor([3.0, 4.0, 5.0]),
|
||||
)
|
||||
|
||||
k_descale, v_descale = impl._prepare_fp8_descales(
|
||||
layer, num_reqs=2, device=torch.device("cpu")
|
||||
)
|
||||
|
||||
torch.testing.assert_close(k_descale, torch.tensor([2.0, 2.0]))
|
||||
torch.testing.assert_close(v_descale, torch.tensor([3.0, 4.0]))
|
||||
assert k_descale.stride() == (0,)
|
||||
assert v_descale.stride() == (1,)
|
||||
|
||||
|
||||
def test_b12x_attention_sinks_refresh_in_place_after_reload() -> None:
|
||||
impl = object.__new__(B12xPagedAttentionImpl)
|
||||
source = torch.tensor([1.0, 2.0], dtype=torch.bfloat16)
|
||||
impl._sinks_source = source
|
||||
impl.sinks = None
|
||||
|
||||
impl.process_weights_after_loading(torch.bfloat16)
|
||||
assert impl.sinks is not None
|
||||
sinks_ptr = impl.sinks.data_ptr()
|
||||
source.copy_(torch.tensor([3.0, 4.0], dtype=torch.bfloat16))
|
||||
impl.process_weights_after_loading(torch.bfloat16)
|
||||
|
||||
assert impl.sinks.data_ptr() == sinks_ptr
|
||||
torch.testing.assert_close(impl.sinks, source.float())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_spec_name",
|
||||
["small_decode", "small_prefill", "mixed_small", "medium_decode"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("kv_cache_dtype", "model_dtype"),
|
||||
[
|
||||
("auto", None),
|
||||
("bfloat16", torch.bfloat16),
|
||||
("fp8_e4m3", torch.bfloat16),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("block_size", [64, 128])
|
||||
def test_b12x_causal_backend_correctness(
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
batch_spec_name: str,
|
||||
kv_cache_dtype: str,
|
||||
model_dtype: torch.dtype | None,
|
||||
block_size: int,
|
||||
) -> None:
|
||||
"""b12x causal paged attention matches the shared SDPA reference."""
|
||||
_require_b12x_paged_attention()
|
||||
batch_spec = BATCH_SPECS[batch_spec_name]
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
"Qwen/Qwen3-0.6B",
|
||||
[AttentionBackendEnum.B12X],
|
||||
_causal_mask,
|
||||
block_size=block_size,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
model_dtype=model_dtype,
|
||||
max_num_seqs=batch_spec.batch_size,
|
||||
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_spec",
|
||||
[
|
||||
pytest.param(BatchSpec(seq_lens=[2080, 2200], query_lens=[1, 1]), id="decode"),
|
||||
pytest.param(BatchSpec(seq_lens=[2080, 2200], query_lens=[8, 8]), id="prefill"),
|
||||
],
|
||||
)
|
||||
def test_b12x_causal_sliding_window(
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
batch_spec: BatchSpec,
|
||||
) -> None:
|
||||
"""b12x causal sliding-window attention matches the shared reference."""
|
||||
_require_b12x_paged_attention()
|
||||
|
||||
model = "microsoft/Phi-tiny-MoE-instruct"
|
||||
sliding_window = ModelConfig(
|
||||
model=model, max_model_len=max(batch_spec.seq_lens)
|
||||
).get_sliding_window()
|
||||
assert sliding_window is not None
|
||||
mask = partial(_causal_sliding_window_mask, sliding_window=sliding_window)
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
model,
|
||||
[AttentionBackendEnum.B12X],
|
||||
mask,
|
||||
block_size=64,
|
||||
atol=3e-2,
|
||||
rtol=3e-2,
|
||||
max_num_seqs=batch_spec.batch_size,
|
||||
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
|
||||
)
|
||||
|
||||
|
||||
def test_b12x_attention_sinks(
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
) -> None:
|
||||
"""b12x attention sinks match the explicit sink reference."""
|
||||
_require_b12x_paged_attention()
|
||||
batch_spec = BATCH_SPECS["small_prefill"]
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
"Qwen/Qwen3-0.6B",
|
||||
[AttentionBackendEnum.B12X],
|
||||
_causal_mask,
|
||||
block_size=64,
|
||||
atol=3e-2,
|
||||
rtol=3e-2,
|
||||
use_sinks=True,
|
||||
max_num_seqs=batch_spec.batch_size,
|
||||
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
|
||||
)
|
||||
|
||||
|
||||
def test_b12x_decode_cuda_graph_replay(
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
) -> None:
|
||||
"""b12x decode output remains correct after CUDA graph replay."""
|
||||
_require_b12x_paged_attention()
|
||||
batch_spec = BATCH_SPECS["small_decode"]
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
"Qwen/Qwen3-0.6B",
|
||||
[AttentionBackendEnum.B12X],
|
||||
_causal_mask,
|
||||
block_size=64,
|
||||
use_cuda_graph=True,
|
||||
max_num_seqs=batch_spec.batch_size,
|
||||
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
|
||||
)
|
||||
|
||||
|
||||
def test_b12x_speculative_verification_uses_cuda_graph_plan(
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
) -> None:
|
||||
"""Exercise the verifier plan rather than the general extend plan."""
|
||||
_require_b12x_paged_attention()
|
||||
batch_spec = BatchSpec(seq_lens=[32, 40], query_lens=[4, 4])
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
"Qwen/Qwen3-0.6B",
|
||||
[AttentionBackendEnum.B12X],
|
||||
_causal_mask,
|
||||
block_size=128,
|
||||
num_speculative_tokens=3,
|
||||
use_cuda_graph=True,
|
||||
max_num_seqs=batch_spec.batch_size,
|
||||
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
|
||||
)
|
||||
@@ -1,140 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for attention configuration and per-KV-group backend selection."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.config.attention import AttentionConfig, HiSparseConfig
|
||||
from vllm.model_executor.layers.attention.attention import (
|
||||
_largest_kernel_block_within,
|
||||
)
|
||||
from vllm.v1.attention.backend import AttentionType, MultipleOf
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.selector import get_attn_spec_kind
|
||||
from vllm.v1.hisparse.runtime import ResolvedHiSparseConfig
|
||||
from vllm.v1.kv_cache_interface import KVCacheSpecKind
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"supported_sizes,expected",
|
||||
[
|
||||
([MultipleOf(16)], 1536),
|
||||
([16, 32], 32),
|
||||
([2048], 2048),
|
||||
([MultipleOf(2048)], 2048),
|
||||
],
|
||||
)
|
||||
def test_largest_kernel_block_within(supported_sizes, expected):
|
||||
class Backend:
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None):
|
||||
return supported_sizes
|
||||
|
||||
assert _largest_kernel_block_within(Backend, 1024, 1024 * 1536, 2048) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"signals,expected",
|
||||
[
|
||||
(dict(use_mla=False, has_sliding_window=False), "full"),
|
||||
(dict(use_mla=True, has_sliding_window=False), "mla"),
|
||||
(dict(use_mla=True, has_sliding_window=True), "sw_mla"),
|
||||
(dict(use_mla=False, has_sliding_window=True), "sw"),
|
||||
],
|
||||
)
|
||||
def test_get_attn_spec_kind_decoder(signals, expected):
|
||||
kind_by_name = {
|
||||
"full": KVCacheSpecKind.FULL_ATTENTION,
|
||||
"mla": KVCacheSpecKind.MLA_ATTENTION,
|
||||
"sw_mla": KVCacheSpecKind.SLIDING_WINDOW_MLA,
|
||||
"sw": KVCacheSpecKind.SLIDING_WINDOW,
|
||||
}
|
||||
kind = get_attn_spec_kind(attn_type=AttentionType.DECODER, **signals)
|
||||
assert kind is kind_by_name[expected]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"attn_type,expected",
|
||||
[
|
||||
(AttentionType.ENCODER_ONLY, KVCacheSpecKind.ENCODER_ONLY_ATTENTION),
|
||||
(AttentionType.ENCODER_DECODER, KVCacheSpecKind.CROSS_ATTENTION),
|
||||
],
|
||||
)
|
||||
def test_get_attn_spec_kind_attn_type(attn_type, expected):
|
||||
kind = get_attn_spec_kind(
|
||||
use_mla=False,
|
||||
has_sliding_window=False,
|
||||
attn_type=attn_type,
|
||||
)
|
||||
assert kind is expected
|
||||
|
||||
|
||||
def test_backend_per_kind_parses_strings():
|
||||
cfg = AttentionConfig(
|
||||
backend_per_kind={
|
||||
"mla_attention": "FLASHINFER_MLA",
|
||||
"sliding_window_mla": "triton_mla", # case-insensitive
|
||||
}
|
||||
)
|
||||
assert cfg.backend_per_kind["mla_attention"] is AttentionBackendEnum.FLASHINFER_MLA
|
||||
assert cfg.backend_per_kind["sliding_window_mla"] is AttentionBackendEnum.TRITON_MLA
|
||||
|
||||
|
||||
def test_backend_per_kind_rejects_unknown_kind():
|
||||
with pytest.raises(ValueError, match="Unknown KV cache group kind"):
|
||||
AttentionConfig(backend_per_kind={"not_a_kind": "TRITON_MLA"})
|
||||
|
||||
|
||||
def test_backend_per_kind_defaults_empty():
|
||||
assert AttentionConfig().backend_per_kind == {}
|
||||
|
||||
|
||||
def test_hisparse_device_buffer_size_boundaries():
|
||||
vllm_config = SimpleNamespace(
|
||||
attention_config=AttentionConfig(hisparse_config=HiSparseConfig()),
|
||||
speculative_config=None,
|
||||
)
|
||||
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
assert resolved is not None
|
||||
assert resolved.device_buffer_size == 256
|
||||
|
||||
vllm_config.attention_config.hisparse_config = HiSparseConfig(
|
||||
device_buffer_size=127
|
||||
)
|
||||
with pytest.raises(ValueError, match="expected at least 128"):
|
||||
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
|
||||
vllm_config.attention_config.hisparse_config = HiSparseConfig(
|
||||
device_buffer_size=32768
|
||||
)
|
||||
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
assert resolved is not None
|
||||
assert resolved.device_buffer_size == 32768
|
||||
|
||||
vllm_config.attention_config.hisparse_config = HiSparseConfig(
|
||||
device_buffer_size=32769
|
||||
)
|
||||
with pytest.raises(ValueError, match="int16 slot-index limit"):
|
||||
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
|
||||
|
||||
def test_hisparse_device_buffer_covers_speculative_window():
|
||||
vllm_config = SimpleNamespace(
|
||||
attention_config=AttentionConfig(hisparse_config=HiSparseConfig()),
|
||||
speculative_config=SimpleNamespace(
|
||||
num_speculative_tokens=3,
|
||||
parallel_drafting=False,
|
||||
),
|
||||
)
|
||||
|
||||
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
assert resolved is not None
|
||||
assert resolved.device_buffer_size == 5 * 128
|
||||
|
||||
vllm_config.attention_config.hisparse_config = HiSparseConfig(
|
||||
device_buffer_size=4 * 128 - 1
|
||||
)
|
||||
with pytest.raises(ValueError, match="expected at least 512"):
|
||||
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
|
||||
@@ -1,316 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Smoke tests for the CPU MLA backend.
|
||||
|
||||
Two levels of coverage are provided:
|
||||
|
||||
* :func:`test_kv_cache_cpu_write` checks that the kv-cache write logic
|
||||
inlined in the CPU MLA backend writes the latent KV cache in the same
|
||||
layout the CPU decode kernel expects. This runs without downloading
|
||||
any model weights and is safe for CI.
|
||||
* :func:`test_cpu_mla_backend_smoke` exercises the full end-to-end path
|
||||
(LLM engine, model construction, prefill + decode) against a shrunk
|
||||
DeepSeek-V2-Lite with `hf_overrides`. It uses `dummy` weights so the
|
||||
outputs are not meaningful, only shape / plumbing correctness is
|
||||
asserted. Marked `cpu_model` so it is skipped on non-CPU CI.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.mla.prefill.cpu_sdpa import (
|
||||
CPUSDPAMLAPrefillBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import (
|
||||
get_mla_prefill_backend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.zen_cpu_sdpa import (
|
||||
ZenCPUSDPAMLAPrefillBackend,
|
||||
)
|
||||
|
||||
|
||||
def _reference_ragged_attention(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
q_cu_seq_lens: torch.Tensor,
|
||||
kv_cu_seq_lens: torch.Tensor,
|
||||
*,
|
||||
scale: float,
|
||||
causal: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
outputs: list[torch.Tensor] = []
|
||||
lses: list[torch.Tensor] = []
|
||||
num_reqs = q_cu_seq_lens.numel() - 1
|
||||
for req_idx in range(num_reqs):
|
||||
q_start = int(q_cu_seq_lens[req_idx])
|
||||
q_end = int(q_cu_seq_lens[req_idx + 1])
|
||||
kv_start = int(kv_cu_seq_lens[req_idx])
|
||||
kv_end = int(kv_cu_seq_lens[req_idx + 1])
|
||||
|
||||
q_r = q[q_start:q_end].transpose(0, 1).float()
|
||||
k_r = k[kv_start:kv_end].transpose(0, 1).float()
|
||||
v_r = v[kv_start:kv_end].transpose(0, 1).float()
|
||||
|
||||
scores = torch.matmul(q_r, k_r.transpose(-2, -1)) * scale
|
||||
if causal:
|
||||
causal_mask = torch.ones(
|
||||
(q_end - q_start, kv_end - kv_start),
|
||||
dtype=torch.bool,
|
||||
device=scores.device,
|
||||
).triu(1)
|
||||
scores.masked_fill_(causal_mask.unsqueeze(0), float("-inf"))
|
||||
|
||||
probs = torch.softmax(scores, dim=-1)
|
||||
outputs.append(torch.matmul(probs, v_r).transpose(0, 1).to(v.dtype))
|
||||
lses.append(torch.logsumexp(scores, dim=-1))
|
||||
|
||||
return torch.cat(outputs, dim=0), torch.cat(lses, dim=1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
def test_kv_cache_cpu_write() -> None:
|
||||
kv_lora_rank = 512
|
||||
pe_dim = 64
|
||||
block_size = 16
|
||||
num_blocks = 4
|
||||
num_tokens = 8
|
||||
dtype = torch.float32
|
||||
|
||||
kv_c = torch.randn(num_tokens, kv_lora_rank, dtype=dtype)
|
||||
k_pe = torch.randn(num_tokens, pe_dim, dtype=dtype)
|
||||
kv_cache = torch.zeros(num_blocks, block_size, kv_lora_rank + pe_dim, dtype=dtype)
|
||||
slot_mapping = torch.arange(num_tokens, dtype=torch.long)
|
||||
# Mark the last slot as padding to make sure we honour negative slots.
|
||||
slot_mapping[-1] = -1
|
||||
|
||||
flat = kv_cache.view(-1, kv_lora_rank + pe_dim)
|
||||
slots = slot_mapping.to(torch.long)
|
||||
valid_mask = slots >= 0
|
||||
if not valid_mask.all().item():
|
||||
slots = slots[valid_mask]
|
||||
kv_c = kv_c[valid_mask]
|
||||
k_pe = k_pe[valid_mask]
|
||||
target_dtype = flat.dtype
|
||||
flat[slots, :kv_lora_rank] = kv_c.to(target_dtype)
|
||||
flat[slots, kv_lora_rank:] = k_pe.to(target_dtype)
|
||||
|
||||
flat = kv_cache.view(-1, kv_lora_rank + pe_dim)
|
||||
for i in range(num_tokens - 1):
|
||||
assert torch.equal(flat[i, :kv_lora_rank], kv_c[i])
|
||||
assert torch.equal(flat[i, kv_lora_rank:], k_pe[i])
|
||||
# The padding slot must remain untouched.
|
||||
assert torch.all(flat[num_tokens - 1] == 0)
|
||||
|
||||
|
||||
@pytest.mark.cpu_model
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
def test_cpu_mla_backend_smoke(tmp_path) -> None:
|
||||
# Shrink the architecture aggressively so the test is CI-friendly.
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
hf_overrides = {
|
||||
"num_hidden_layers": 2,
|
||||
"n_routed_experts": 4,
|
||||
"first_k_dense_replace": 0,
|
||||
"num_experts_per_tok": 2,
|
||||
}
|
||||
llm = LLM(
|
||||
model="deepseek-ai/DeepSeek-V2-Lite",
|
||||
skip_tokenizer_init=True,
|
||||
trust_remote_code=True,
|
||||
load_format="dummy",
|
||||
enforce_eager=True,
|
||||
max_model_len=128,
|
||||
max_num_seqs=2,
|
||||
block_size=16,
|
||||
gpu_memory_utilization=0.25,
|
||||
hf_overrides=hf_overrides,
|
||||
kv_transfer_config={
|
||||
"kv_connector": "ExampleConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {
|
||||
"shared_storage_path": str(tmp_path),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
sampling_params = SamplingParams(max_tokens=4, temperature=0.0)
|
||||
outputs = llm.generate([[1, 2, 3, 4], [5, 6, 7]], sampling_params, use_tqdm=False)
|
||||
assert len(outputs) == 2
|
||||
for output in outputs:
|
||||
# `dummy` weights do not produce meaningful text, but the number
|
||||
# of generated tokens must match what we asked for.
|
||||
assert len(output.outputs[0].token_ids) == 4
|
||||
|
||||
prefix_hit_prompt = [1] * 20
|
||||
outputs = llm.generate([prefix_hit_prompt], sampling_params, use_tqdm=False)
|
||||
assert len(outputs[0].outputs[0].token_ids) == 4
|
||||
assert llm.reset_prefix_cache(reset_connector=False)
|
||||
|
||||
# ExampleConnector persists KV externally at block granularity. With a
|
||||
# 20-token prompt and block_size=16, the second run reloads 16 cached
|
||||
# tokens and forces the 4-token suffix through MLA prefill with context.
|
||||
outputs = llm.generate([prefix_hit_prompt], sampling_params, use_tqdm=False)
|
||||
assert len(outputs[0].outputs[0].token_ids) == 4
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
def test_cpu_mla_prefill_backend_selected() -> None:
|
||||
# On CPU (no device capability) the MLA prefill backend must be the
|
||||
# SDPA-based CPU backend, not flash-attn which is unavailable on CPU.
|
||||
# Accelerator-specific subclasses (e.g. the zentorch-backed Zen CPU
|
||||
# backend) are also valid selections.
|
||||
backend_cls = get_mla_prefill_backend(None)
|
||||
assert issubclass(backend_cls, CPUSDPAMLAPrefillBackend)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
def test_cpu_mla_prefill_new_tokens() -> None:
|
||||
# The SDPA prefill must exactly match a reference causal attention over
|
||||
# the ragged (varlen) q/k/v layout, with per-request padding handled.
|
||||
backend = CPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=0,
|
||||
v_head_dim=16,
|
||||
vllm_config=None,
|
||||
)
|
||||
|
||||
class _PrefillMeta:
|
||||
query_start_loc = torch.tensor([0, 3, 6], dtype=torch.int32)
|
||||
|
||||
backend.prepare_metadata(_PrefillMeta())
|
||||
q = torch.randn(6, 4, 16, dtype=torch.bfloat16)
|
||||
k = torch.randn(6, 4, 16, dtype=torch.bfloat16)
|
||||
v = torch.randn(6, 4, 16, dtype=torch.bfloat16)
|
||||
out = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=False)
|
||||
ref, _ = _reference_ragged_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
_PrefillMeta.query_start_loc,
|
||||
_PrefillMeta.query_start_loc,
|
||||
scale=0.25,
|
||||
causal=True,
|
||||
)
|
||||
assert out.float().allclose(ref.float(), atol=2e-2)
|
||||
assert out.shape == (6, 4, 16)
|
||||
|
||||
out_lse, lse = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
|
||||
ref_out, ref_lse = _reference_ragged_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
_PrefillMeta.query_start_loc,
|
||||
_PrefillMeta.query_start_loc,
|
||||
scale=0.25,
|
||||
causal=True,
|
||||
)
|
||||
assert out_lse.float().allclose(ref_out.float(), atol=2e-2)
|
||||
assert lse.float().allclose(ref_lse.float(), atol=2e-2)
|
||||
assert lse.shape == (4, 6)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
def test_cpu_mla_prefill_context_chunk() -> None:
|
||||
backend = CPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=0,
|
||||
v_head_dim=16,
|
||||
vllm_config=None,
|
||||
)
|
||||
|
||||
class _PrefillMeta:
|
||||
query_start_loc = torch.tensor([0, 5], dtype=torch.int32)
|
||||
|
||||
class _Chunk:
|
||||
query_start_loc = torch.tensor([0, 2, 5], dtype=torch.int32)
|
||||
cu_seq_lens = torch.tensor([0, 3, 7], dtype=torch.int32)
|
||||
|
||||
backend.prepare_metadata(_PrefillMeta())
|
||||
q = torch.randn(5, 4, 16, dtype=torch.bfloat16)
|
||||
k = torch.randn(7, 4, 16, dtype=torch.bfloat16)
|
||||
v = torch.randn(7, 4, 16, dtype=torch.bfloat16)
|
||||
|
||||
out, lse = backend.run_prefill_context_chunk(_Chunk(), q, k, v)
|
||||
ref_out, ref_lse = _reference_ragged_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
_Chunk.query_start_loc,
|
||||
_Chunk.cu_seq_lens,
|
||||
scale=0.25,
|
||||
causal=False,
|
||||
)
|
||||
assert out.float().allclose(ref_out.float(), atol=2e-2)
|
||||
assert lse.float().allclose(ref_lse.float(), atol=2e-2)
|
||||
assert out.shape == (5, 4, 16)
|
||||
assert lse.shape == (4, 5)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
@pytest.mark.skipif(
|
||||
not ZenCPUSDPAMLAPrefillBackend.is_available(),
|
||||
reason="requires a Zen CPU with the zentorch_sdpa op registered",
|
||||
)
|
||||
def test_zen_cpu_mla_prefill_new_tokens() -> None:
|
||||
# Runs the zentorch kernel itself. The head dims are deliberately
|
||||
# asymmetric (v_head_dim < qk_head_dim, as in real MLA) so that the V
|
||||
# padding and output slicing are exercised; the generic-CPU cases above
|
||||
# use equal dims and never reach that code.
|
||||
qk_head_dim = 24
|
||||
v_head_dim = 16
|
||||
backend = ZenCPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=None,
|
||||
)
|
||||
|
||||
class _PrefillMeta:
|
||||
query_start_loc = torch.tensor([0, 3, 6], dtype=torch.int32)
|
||||
|
||||
backend.prepare_metadata(_PrefillMeta())
|
||||
q = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
|
||||
k = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
|
||||
v = torch.randn(6, 4, v_head_dim, dtype=torch.bfloat16)
|
||||
|
||||
out = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=False)
|
||||
ref, _ = _reference_ragged_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
_PrefillMeta.query_start_loc,
|
||||
_PrefillMeta.query_start_loc,
|
||||
scale=0.25,
|
||||
causal=True,
|
||||
)
|
||||
assert out.shape == (6, 4, v_head_dim)
|
||||
assert out.float().allclose(ref.float(), atol=2e-2)
|
||||
|
||||
# zentorch_sdpa does not return a usable LSE, so that path must fall back
|
||||
# to the fp32 reference and match the generic backend exactly.
|
||||
generic = CPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=None,
|
||||
)
|
||||
generic.prepare_metadata(_PrefillMeta())
|
||||
zen_out, zen_lse = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
|
||||
gen_out, gen_lse = generic.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
|
||||
assert torch.equal(zen_out, gen_out)
|
||||
assert torch.equal(zen_lse, gen_lse)
|
||||
@@ -1,284 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.deepseek_v4.amd.rocm import (
|
||||
DeepseekV4ROCMAiterMLASparseMetadataBuilder,
|
||||
DeepseekV4ROCMAiterSparseSWAMetadataBuilder,
|
||||
)
|
||||
from vllm.models.deepseek_v41.amd import rocm as v41_rocm
|
||||
from vllm.models.deepseek_v41.amd.rocm import (
|
||||
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backend import AttentionCGSupport
|
||||
from vllm.v1.attention.backends.mla import indexer
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
DeepseekV4IndexerBackend,
|
||||
DeepseekV32IndexerMetadataBuilder,
|
||||
DeepseekV41IndexerBackend,
|
||||
)
|
||||
|
||||
|
||||
def _make_indexer_config(*, architecture: str, adaptive: bool):
|
||||
return SimpleNamespace(
|
||||
model_config=SimpleNamespace(architectures=[architecture]),
|
||||
num_speculative_tokens=1,
|
||||
speculative_config=SimpleNamespace(enable_adaptive_verification=adaptive),
|
||||
)
|
||||
|
||||
|
||||
def _mock_rocm_platform(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# Platform predicates are mutually exclusive in production. Override both
|
||||
# so these ROCm policy tests do not inherit CUDA capabilities from the CI
|
||||
# host running them.
|
||||
monkeypatch.setattr(indexer.current_platform, "is_cuda", lambda: False)
|
||||
monkeypatch.setattr(indexer.current_platform, "is_rocm", lambda: True)
|
||||
|
||||
|
||||
def _make_indexer_builder(*, adaptive: bool, capacity: int = 12):
|
||||
builder = DeepseekV32IndexerMetadataBuilder.__new__(
|
||||
DeepseekV32IndexerMetadataBuilder
|
||||
)
|
||||
builder.vllm_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(enable_adaptive_verification=adaptive)
|
||||
)
|
||||
builder.supports_varlen = False
|
||||
builder.decode_seq_lens_buffer = torch.zeros(capacity, dtype=torch.int32)
|
||||
builder.expanded_block_table_buffer = torch.zeros((capacity, 2), dtype=torch.int32)
|
||||
builder.decode_lens_buffer = torch.zeros(capacity, dtype=torch.int32)
|
||||
builder.arange_buffer = torch.arange(capacity, dtype=torch.int32)
|
||||
return builder
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_rocm_adaptive_builders_support_varlen_full_graphs():
|
||||
adaptive_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(enable_adaptive_verification=True)
|
||||
)
|
||||
fixed_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(enable_adaptive_verification=False)
|
||||
)
|
||||
|
||||
for builder_cls in (
|
||||
DeepseekV4ROCMAiterMLASparseMetadataBuilder,
|
||||
DeepseekV4ROCMAiterSparseSWAMetadataBuilder,
|
||||
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
|
||||
v41_rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder,
|
||||
):
|
||||
assert (
|
||||
builder_cls.get_cudagraph_support(adaptive_config, SimpleNamespace())
|
||||
== AttentionCGSupport.ALWAYS
|
||||
)
|
||||
assert (
|
||||
builder_cls.get_cudagraph_support(fixed_config, SimpleNamespace())
|
||||
== AttentionCGSupport.UNIFORM_BATCH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
("architecture", "backend_cls"),
|
||||
[
|
||||
("DeepseekV4ForCausalLM", DeepseekV4IndexerBackend),
|
||||
("DeepseekV41ForCausalLM", DeepseekV41IndexerBackend),
|
||||
],
|
||||
)
|
||||
def test_deepseek_rocm_adaptive_indexer_support(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
architecture: str,
|
||||
backend_cls: type[DeepseekV4IndexerBackend],
|
||||
):
|
||||
_mock_rocm_platform(monkeypatch)
|
||||
adaptive_config = _make_indexer_config(architecture=architecture, adaptive=True)
|
||||
fixed_config = _make_indexer_config(architecture=architecture, adaptive=False)
|
||||
|
||||
assert backend_cls.supports_device_cpu_query_lens_mismatch()
|
||||
assert indexer._rocm_supports_flattened_device_query_lens(adaptive_config)
|
||||
assert backend_cls.get_builder_cls() is DeepseekV32IndexerMetadataBuilder
|
||||
assert indexer._use_flattening(adaptive_config)
|
||||
assert (
|
||||
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
|
||||
adaptive_config, SimpleNamespace()
|
||||
)
|
||||
== AttentionCGSupport.ALWAYS
|
||||
)
|
||||
assert not indexer._use_flattening(fixed_config)
|
||||
assert (
|
||||
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
|
||||
fixed_config, SimpleNamespace()
|
||||
)
|
||||
== AttentionCGSupport.UNIFORM_BATCH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v41_rocm_fixed_k_path_is_unchanged(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
_mock_rocm_platform(monkeypatch)
|
||||
fixed_config = _make_indexer_config(
|
||||
architecture="DeepseekV41ForCausalLM", adaptive=False
|
||||
)
|
||||
|
||||
for builder_cls in (
|
||||
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
|
||||
v41_rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder,
|
||||
):
|
||||
assert (
|
||||
builder_cls.get_cudagraph_support(fixed_config, SimpleNamespace())
|
||||
== AttentionCGSupport.UNIFORM_BATCH
|
||||
)
|
||||
|
||||
assert not indexer._use_flattening(fixed_config)
|
||||
assert (
|
||||
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
|
||||
fixed_config, SimpleNamespace()
|
||||
)
|
||||
== AttentionCGSupport.UNIFORM_BATCH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
"architecture",
|
||||
["DeepseekV32ForCausalLM", "GlmMoeDsaForCausalLM"],
|
||||
)
|
||||
def test_rocm_adaptive_indexer_flattening_rejects_other_architectures(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
architecture: str,
|
||||
):
|
||||
_mock_rocm_platform(monkeypatch)
|
||||
adaptive_config = _make_indexer_config(architecture=architecture, adaptive=True)
|
||||
|
||||
assert not indexer._rocm_supports_flattened_device_query_lens(adaptive_config)
|
||||
assert not indexer._use_flattening(adaptive_config)
|
||||
assert (
|
||||
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
|
||||
adaptive_config, SimpleNamespace()
|
||||
)
|
||||
== AttentionCGSupport.UNIFORM_BATCH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_rocm_adaptive_indexer_preserves_single_request_uniform_path(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
builder = _make_indexer_builder(adaptive=True, capacity=8)
|
||||
|
||||
class FakeUniformKernel:
|
||||
called = False
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
seq_lens,
|
||||
decode_seq_lens,
|
||||
block_table,
|
||||
expanded_block_table,
|
||||
decode_lens,
|
||||
num_decode_tokens,
|
||||
max_decode_len,
|
||||
):
|
||||
self.called = True
|
||||
assert num_decode_tokens == 4
|
||||
assert block_table.stride(0) == expanded_block_table.stride(0) == 2
|
||||
decode_seq_lens[:max_decode_len] = torch.arange(
|
||||
seq_lens[0] - max_decode_len + 1,
|
||||
seq_lens[0] + 1,
|
||||
dtype=torch.int32,
|
||||
)
|
||||
expanded_block_table[:max_decode_len] = block_table[0]
|
||||
decode_lens[:max_decode_len] = 1
|
||||
|
||||
fake_kernel = FakeUniformKernel()
|
||||
monkeypatch.setattr(indexer, "_PREPARE_UNIFORM_DECODE_KERNEL", fake_kernel)
|
||||
|
||||
seq_lens, block_table, decode_lens, batch_size, requires_padding = (
|
||||
builder._prepare_decode_tensors(
|
||||
seq_lens=torch.tensor([10], dtype=torch.int32),
|
||||
block_table=torch.tensor([[1, 2]], dtype=torch.int32),
|
||||
decode_lens=torch.tensor([4], dtype=torch.int32),
|
||||
decode_lens_cpu=torch.tensor([4], dtype=torch.int32),
|
||||
query_start_loc=torch.tensor([0], dtype=torch.int32),
|
||||
num_decodes=1,
|
||||
num_decode_tokens=4,
|
||||
use_native=False,
|
||||
next_n=8,
|
||||
max_decode_len=4,
|
||||
)
|
||||
)
|
||||
|
||||
assert fake_kernel.called
|
||||
torch.testing.assert_close(seq_lens, torch.tensor([7, 8, 9, 10], dtype=torch.int32))
|
||||
torch.testing.assert_close(
|
||||
block_table,
|
||||
torch.tensor([[1, 2], [1, 2], [1, 2], [1, 2]], dtype=torch.int32),
|
||||
)
|
||||
torch.testing.assert_close(decode_lens, torch.ones(4, dtype=torch.int32))
|
||||
assert batch_size == 4
|
||||
assert not requires_padding
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_rocm_adaptive_indexer_replays_changed_allocations_with_stable_buffers():
|
||||
builder = _make_indexer_builder(adaptive=True)
|
||||
buffer_ptrs = (
|
||||
builder.decode_seq_lens_buffer.data_ptr(),
|
||||
builder.expanded_block_table_buffer.data_ptr(),
|
||||
builder.decode_lens_buffer.data_ptr(),
|
||||
)
|
||||
block_table = torch.tensor([[1, 2], [3, 4], [5, 6]], dtype=torch.int32)
|
||||
decode_lens_cpu = torch.tensor([4, 4, 0], dtype=torch.int32)
|
||||
|
||||
first = builder._prepare_decode_tensors(
|
||||
seq_lens=torch.tensor([20, 20, 0], dtype=torch.int32),
|
||||
block_table=block_table,
|
||||
decode_lens=torch.tensor([7, 1, 0], dtype=torch.int32),
|
||||
decode_lens_cpu=decode_lens_cpu,
|
||||
query_start_loc=torch.tensor([0, 7, 8], dtype=torch.int32),
|
||||
num_decodes=3,
|
||||
num_decode_tokens=10,
|
||||
use_native=False,
|
||||
next_n=8,
|
||||
max_decode_len=4,
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
first[0],
|
||||
torch.tensor([14, 15, 16, 17, 18, 19, 20, 20, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
first[1][:, 0],
|
||||
torch.tensor([1, 1, 1, 1, 1, 1, 1, 3, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
|
||||
second = builder._prepare_decode_tensors(
|
||||
seq_lens=torch.tensor([20, 20, 0], dtype=torch.int32),
|
||||
block_table=block_table,
|
||||
decode_lens=torch.tensor([1, 7, 0], dtype=torch.int32),
|
||||
decode_lens_cpu=decode_lens_cpu,
|
||||
query_start_loc=torch.tensor([0, 1, 8], dtype=torch.int32),
|
||||
num_decodes=3,
|
||||
num_decode_tokens=10,
|
||||
use_native=False,
|
||||
next_n=8,
|
||||
max_decode_len=4,
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
second[0],
|
||||
torch.tensor([20, 14, 15, 16, 17, 18, 19, 20, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
second[1][:, 0],
|
||||
torch.tensor([1, 3, 3, 3, 3, 3, 3, 3, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
torch.testing.assert_close(second[2], torch.ones(10, dtype=torch.int32))
|
||||
assert second[3:] == (10, False)
|
||||
assert buffer_ptrs == (
|
||||
builder.decode_seq_lens_buffer.data_ptr(),
|
||||
builder.expanded_block_table_buffer.data_ptr(),
|
||||
builder.decode_lens_buffer.data_ptr(),
|
||||
)
|
||||
@@ -1,885 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for DeepSeek-V4 in-image bidirectional SWA visibility (vision variant).
|
||||
|
||||
The reference semantics are a torch port of the official
|
||||
``get_image_visible`` / ``get_window_topk_idxs_visible``: inside an image span
|
||||
[span_start, span_end] (inclusive), a token at ``pos`` sees
|
||||
``min(pos - span_start, max_image_tokens - 1)`` extra tokens to the left and
|
||||
``min(span_end - pos, max_image_tokens)`` to the right; the window then starts
|
||||
at ``max(pos - (window - 1) - max(left - (window - 1), 0), 0)`` and ends at
|
||||
``pos + right`` (inclusive).
|
||||
"""
|
||||
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import DeepseekV4Config
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
from vllm.models.deepseek_v4.common.ops.cache_utils import (
|
||||
build_flashinfer_mixed_sparse_indices,
|
||||
combine_topk_swa_indices,
|
||||
)
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import (
|
||||
DeepseekSparseSWAMetadataBuilder,
|
||||
_compute_image_visibility_kernel,
|
||||
_compute_swa_indices_and_lens_kernel,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import SlidingWindowMLASpec
|
||||
|
||||
WINDOW = 8
|
||||
MAX_IMG = 6
|
||||
WIDTH = WINDOW + MAX_IMG
|
||||
BLOCK_SIZE = 64
|
||||
|
||||
|
||||
def ref_left_right(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
spans_per_req: list[list[tuple[int, int]]],
|
||||
max_image_tokens: int,
|
||||
) -> tuple[list[int], list[int]]:
|
||||
"""Per-token (left, right) for the flattened decode-first token stream."""
|
||||
lefts: list[int] = []
|
||||
rights: list[int] = []
|
||||
for seq_len, query_len, spans in zip(seq_lens, query_lens, spans_per_req):
|
||||
prefix_len = seq_len - query_len
|
||||
for i in range(query_len):
|
||||
pos = prefix_len + i
|
||||
left = right = 0
|
||||
for span_start, span_end in spans:
|
||||
if span_start <= pos <= span_end:
|
||||
left = min(pos - span_start, max_image_tokens - 1)
|
||||
right = min(span_end - pos, max_image_tokens)
|
||||
lefts.append(left)
|
||||
rights.append(right)
|
||||
return lefts, rights
|
||||
|
||||
|
||||
def ref_swa_bounds(
|
||||
pos: int, window: int, left: int, right: int, replay_start: int = 0
|
||||
) -> tuple[int, int]:
|
||||
"""Reference [start, end) window bounds for one query token. Under SWA
|
||||
bounded replay no window KV exists below ``replay_start``."""
|
||||
left_add = max(left - (window - 1), 0)
|
||||
start = max(pos - (window - 1) - left_add, 0, replay_start)
|
||||
return start, pos + right + 1
|
||||
|
||||
|
||||
def make_batch(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
device: torch.device,
|
||||
):
|
||||
"""Build the kernel inputs for a decode-first batch."""
|
||||
num_reqs = len(seq_lens)
|
||||
query_start_loc = torch.zeros(num_reqs + 1, dtype=torch.int32, device=device)
|
||||
query_start_loc[1:] = torch.tensor(
|
||||
query_lens, dtype=torch.int32, device=device
|
||||
).cumsum(0)
|
||||
num_tokens = int(query_start_loc[-1])
|
||||
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
|
||||
token_to_req = torch.repeat_interleave(
|
||||
torch.arange(num_reqs, dtype=torch.int32, device=device),
|
||||
torch.tensor(query_lens, dtype=torch.int32, device=device),
|
||||
)
|
||||
max_blocks = (max(seq_lens) + BLOCK_SIZE - 1) // BLOCK_SIZE
|
||||
block_table = torch.arange(
|
||||
num_reqs * max_blocks, dtype=torch.int32, device=device
|
||||
).view(num_reqs, max_blocks)
|
||||
slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
|
||||
return query_start_loc, seq_lens_t, token_to_req, slot_mapping, block_table
|
||||
|
||||
|
||||
def ref_swa_slot_rows(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
spans_per_req: list[list[tuple[int, int]]],
|
||||
block_table: torch.Tensor,
|
||||
window: int,
|
||||
max_image_tokens: int,
|
||||
width: int,
|
||||
replay_starts: list[int] | None = None,
|
||||
) -> tuple[list[list[int]], list[int]]:
|
||||
"""Reference paged slot-id rows and lens for every token in the batch."""
|
||||
block_table_cpu = block_table.cpu()
|
||||
lefts, rights = ref_left_right(
|
||||
seq_lens, query_lens, spans_per_req, max_image_tokens
|
||||
)
|
||||
replay_starts = replay_starts or [0] * len(seq_lens)
|
||||
rows: list[list[int]] = []
|
||||
lens: list[int] = []
|
||||
token = 0
|
||||
for req, (seq_len, query_len) in enumerate(zip(seq_lens, query_lens)):
|
||||
prefix_len = seq_len - query_len
|
||||
for i in range(query_len):
|
||||
pos = prefix_len + i
|
||||
start, end = ref_swa_bounds(
|
||||
pos, window, lefts[token], rights[token], replay_starts[req]
|
||||
)
|
||||
row = []
|
||||
for p in range(start, end):
|
||||
blk = int(block_table_cpu[req, p // BLOCK_SIZE])
|
||||
row.append(blk * BLOCK_SIZE + p % BLOCK_SIZE)
|
||||
lens.append(len(row))
|
||||
row.extend([-1] * (width - len(row)))
|
||||
rows.append(row)
|
||||
token += 1
|
||||
return rows, lens
|
||||
|
||||
|
||||
def run_swa_kernel(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
spans_per_req: list[list[tuple[int, int]]],
|
||||
window: int = WINDOW,
|
||||
max_image_tokens: int = MAX_IMG,
|
||||
with_image: bool = True,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
device = torch.device("cuda")
|
||||
query_start_loc, seq_lens_t, token_to_req, slot_mapping, block_table = make_batch(
|
||||
seq_lens, query_lens, device
|
||||
)
|
||||
num_tokens = int(query_start_loc[-1])
|
||||
width = window + (max_image_tokens if with_image else 0)
|
||||
swa_indices = torch.zeros(num_tokens, 1, width, dtype=torch.int32, device=device)
|
||||
swa_lens = torch.zeros(num_tokens, dtype=torch.int32, device=device)
|
||||
is_valid = slot_mapping >= 0
|
||||
replay_start_t = torch.zeros(len(seq_lens), dtype=torch.int32, device=device)
|
||||
|
||||
if with_image:
|
||||
lefts, rights = ref_left_right(
|
||||
seq_lens, query_lens, spans_per_req, max_image_tokens
|
||||
)
|
||||
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
|
||||
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
|
||||
else:
|
||||
left_t = right_t = swa_lens # unused dummies
|
||||
|
||||
_compute_swa_indices_and_lens_kernel[(num_tokens,)](
|
||||
swa_indices,
|
||||
swa_indices.stride(0),
|
||||
swa_lens,
|
||||
window,
|
||||
width,
|
||||
left_t,
|
||||
right_t,
|
||||
query_start_loc,
|
||||
seq_lens_t,
|
||||
token_to_req,
|
||||
is_valid,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
BLOCK_SIZE,
|
||||
replay_start_t,
|
||||
token_offset=0,
|
||||
HAS_IMAGE=with_image,
|
||||
TRITON_BLOCK_SIZE=1024,
|
||||
)
|
||||
return swa_indices[:, 0], swa_lens
|
||||
|
||||
|
||||
# seq_lens, query_lens, spans per request (positions are prompt-absolute,
|
||||
# inclusive on both ends, matching the reference's sentinel-bracketed spans).
|
||||
class _Case(TypedDict):
|
||||
seq_lens: list[int]
|
||||
query_lens: list[int]
|
||||
spans: list[list[tuple[int, int]]]
|
||||
|
||||
|
||||
CASES: list[_Case] = [
|
||||
# two image spans in one request, one pure-text request
|
||||
{
|
||||
"seq_lens": [30, 12],
|
||||
"query_lens": [30, 12],
|
||||
"spans": [[(4, 12), (20, 24)], []],
|
||||
},
|
||||
# span larger than max_image_tokens, straddling the window boundary
|
||||
{
|
||||
"seq_lens": [26],
|
||||
"query_lens": [26],
|
||||
"spans": [[(2, 17)]],
|
||||
},
|
||||
# chunked prefill: span fully inside the second chunk's query
|
||||
{
|
||||
"seq_lens": [40, 9],
|
||||
"query_lens": [16, 9],
|
||||
"spans": [[(30, 38)], []],
|
||||
},
|
||||
# span ending exactly at the prompt end; tiny request
|
||||
{
|
||||
"seq_lens": [7, 15],
|
||||
"query_lens": [7, 15],
|
||||
"spans": [[(0, 6)], [(10, 14)]],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("case", CASES)
|
||||
def test_swa_indices_kernel_with_image_spans(case):
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
case["seq_lens"],
|
||||
case["query_lens"],
|
||||
case["spans"],
|
||||
make_batch(case["seq_lens"], case["query_lens"], torch.device("cuda"))[4],
|
||||
WINDOW,
|
||||
MAX_IMG,
|
||||
WIDTH,
|
||||
)
|
||||
indices, actual_lens = run_swa_kernel(
|
||||
case["seq_lens"], case["query_lens"], case["spans"], with_image=True
|
||||
)
|
||||
assert actual_lens.cpu().tolist() == lens
|
||||
assert indices.cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("case", CASES)
|
||||
def test_swa_indices_kernel_without_image_unchanged(case):
|
||||
"""HAS_IMAGE=False must reproduce the plain causal sliding window."""
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
case["seq_lens"],
|
||||
case["query_lens"],
|
||||
[[] for _ in case["seq_lens"]],
|
||||
make_batch(case["seq_lens"], case["query_lens"], torch.device("cuda"))[4],
|
||||
WINDOW,
|
||||
MAX_IMG,
|
||||
WINDOW,
|
||||
)
|
||||
indices, actual_lens = run_swa_kernel(
|
||||
case["seq_lens"], case["query_lens"], case["spans"], with_image=False
|
||||
)
|
||||
assert indices.shape[-1] == WINDOW
|
||||
assert actual_lens.cpu().tolist() == lens
|
||||
assert indices.cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_image_visibility_kernel():
|
||||
"""The builder's visibility kernel must match get_image_visible."""
|
||||
device = torch.device("cuda")
|
||||
seq_lens = [30, 12]
|
||||
query_lens = [30, 12]
|
||||
spans = [[(4, 12), (20, 24)], []]
|
||||
query_start_loc, seq_lens_t, token_to_req, _, _ = make_batch(
|
||||
seq_lens, query_lens, device
|
||||
)
|
||||
num_tokens = int(query_start_loc[-1])
|
||||
|
||||
# CSR span layout: request -> contiguous [start, end) span list.
|
||||
indptr = [0, 2, 2]
|
||||
starts = [4, 20]
|
||||
ends = [12, 24]
|
||||
left = torch.zeros(num_tokens, dtype=torch.int32, device=device)
|
||||
right = torch.zeros(num_tokens, dtype=torch.int32, device=device)
|
||||
_compute_image_visibility_kernel[(num_tokens,)](
|
||||
left,
|
||||
right,
|
||||
torch.tensor(indptr, dtype=torch.int32, device=device),
|
||||
torch.tensor(starts, dtype=torch.int32, device=device),
|
||||
torch.tensor(ends, dtype=torch.int32, device=device),
|
||||
query_start_loc,
|
||||
seq_lens_t,
|
||||
token_to_req,
|
||||
MAX_IMG,
|
||||
token_offset=0,
|
||||
)
|
||||
ref_left, ref_right = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
|
||||
assert left.cpu().tolist() == ref_left
|
||||
assert right.cpu().tolist() == ref_right
|
||||
|
||||
|
||||
def combine_case(
|
||||
compress_ratio: int,
|
||||
topk: int,
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
spans: list[list[tuple[int, int]]],
|
||||
with_image: bool,
|
||||
replay_starts: list[int] | None = None,
|
||||
combine_fn=combine_topk_swa_indices,
|
||||
in_range_topk: bool = False,
|
||||
):
|
||||
"""Run combine_topk_swa_indices and return (indices, lens, expected).
|
||||
|
||||
``in_range_topk`` draws top-k indices below N, for combiners that drop
|
||||
out-of-range ones.
|
||||
"""
|
||||
device = torch.device("cuda")
|
||||
num_reqs = len(seq_lens)
|
||||
replay_starts = replay_starts or [0] * num_reqs
|
||||
query_start_loc = torch.zeros(num_reqs + 1, dtype=torch.int32, device=device)
|
||||
query_start_loc[1:] = torch.tensor(
|
||||
query_lens, dtype=torch.int32, device=device
|
||||
).cumsum(0)
|
||||
num_tokens = int(query_start_loc[-1])
|
||||
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
|
||||
# The builder's gather covers only the context above the replay start.
|
||||
gather_lens = torch.tensor(
|
||||
[
|
||||
q + min(max(s - q - r, 0), WINDOW - 1)
|
||||
for s, q, r in zip(seq_lens, query_lens, replay_starts)
|
||||
],
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
)
|
||||
N = (max(seq_lens) + compress_ratio - 1) // compress_ratio
|
||||
M = N + int(gather_lens.max()) + 8
|
||||
gen = torch.Generator(device="cpu").manual_seed(0)
|
||||
topk_indices = torch.randint(
|
||||
0,
|
||||
N if in_range_topk else 4096,
|
||||
(num_tokens, max(topk, 1)),
|
||||
generator=gen,
|
||||
dtype=torch.int32,
|
||||
).to(device)
|
||||
topk_indices = topk_indices[:, : max(topk, 1)]
|
||||
|
||||
if with_image:
|
||||
lefts, rights = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
|
||||
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
|
||||
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
|
||||
else:
|
||||
left_t = right_t = None
|
||||
|
||||
# V4.1's combine has no image windows (causal SWA only).
|
||||
has_image = "left_visible" in inspect.signature(combine_fn).parameters
|
||||
image_kwargs = (
|
||||
dict(left_visible=left_t, right_visible=right_t, max_image_tokens=MAX_IMG)
|
||||
if has_image
|
||||
else {}
|
||||
)
|
||||
combined_indices, combined_lens = combine_fn(
|
||||
topk_indices,
|
||||
query_start_loc,
|
||||
seq_lens_t,
|
||||
gather_lens,
|
||||
WINDOW,
|
||||
compress_ratio,
|
||||
topk,
|
||||
M,
|
||||
N,
|
||||
**image_kwargs,
|
||||
)
|
||||
|
||||
# Reference rows.
|
||||
lefts, rights = ref_left_right(
|
||||
seq_lens,
|
||||
query_lens,
|
||||
spans if with_image else [[] for _ in seq_lens],
|
||||
MAX_IMG,
|
||||
)
|
||||
topk_cpu = topk_indices.cpu()
|
||||
width = WINDOW + (MAX_IMG if has_image else 0)
|
||||
combined_topk = (topk + width + 127) // 128 * 128
|
||||
rows = []
|
||||
lens = []
|
||||
token = 0
|
||||
for b, (seq_len, query_len) in enumerate(zip(seq_lens, query_lens)):
|
||||
prefix_len = seq_len - query_len
|
||||
gather_start = seq_len - int(gather_lens[b])
|
||||
for i in range(query_len):
|
||||
pos = prefix_len + i
|
||||
topk_len = min((pos + 1) // compress_ratio, topk)
|
||||
start, end = ref_swa_bounds(pos, WINDOW, lefts[token], rights[token])
|
||||
# The window never reaches below the gathered buffer.
|
||||
start = max(start, gather_start)
|
||||
swa_len = end - start
|
||||
row = [-1] * combined_topk
|
||||
for j in range(topk_len):
|
||||
row[j] = int(topk_cpu[token, j]) + M * b
|
||||
for j in range(swa_len):
|
||||
row[topk_len + j] = M * b + N + start + j - gather_start
|
||||
rows.append(row)
|
||||
lens.append(topk_len + swa_len)
|
||||
token += 1
|
||||
return combined_indices, combined_lens, rows, lens
|
||||
|
||||
|
||||
COMBINE_CASES = [
|
||||
dict(compress_ratio=1, topk=0), # SWA-only layer
|
||||
dict(compress_ratio=4, topk=16), # C4A layer
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("cfg", COMBINE_CASES)
|
||||
def test_combine_topk_swa_with_image_spans(cfg):
|
||||
case = CASES[0]
|
||||
indices, lens, rows, exp_lens = combine_case(
|
||||
cfg["compress_ratio"],
|
||||
cfg["topk"],
|
||||
case["seq_lens"],
|
||||
case["query_lens"],
|
||||
case["spans"],
|
||||
with_image=True,
|
||||
)
|
||||
assert lens.cpu().tolist() == exp_lens
|
||||
assert indices.cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("cfg", COMBINE_CASES)
|
||||
@pytest.mark.parametrize("query_len", [24, 20])
|
||||
def test_v41_combine_topk_swa_stops_at_replay_start(cfg, query_len):
|
||||
"""SWA bounded replay: the gathered buffer starts at replay_start, so the
|
||||
window never indexes below it."""
|
||||
from vllm.models.deepseek_v41.common.ops.cache_utils import (
|
||||
combine_topk_swa_indices as combine_v41,
|
||||
)
|
||||
|
||||
# Request 0 replays from 16: a 24-token chunk starts there, a 20-token
|
||||
# chunk leaves only 4 context tokens above it (fewer than the window).
|
||||
indices, lens, rows, exp_lens = combine_case(
|
||||
cfg["compress_ratio"],
|
||||
cfg["topk"],
|
||||
seq_lens=[40, 12],
|
||||
query_lens=[query_len, 12],
|
||||
spans=[[], []],
|
||||
with_image=False,
|
||||
replay_starts=[16, 0],
|
||||
combine_fn=combine_v41,
|
||||
in_range_topk=True,
|
||||
)
|
||||
assert lens.cpu().tolist() == exp_lens
|
||||
assert indices.cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("cfg", COMBINE_CASES)
|
||||
def test_combine_topk_swa_without_image_unchanged(cfg):
|
||||
"""left_visible=None must reproduce the plain causal combined indices."""
|
||||
case = CASES[0]
|
||||
indices, lens, rows, exp_lens = combine_case(
|
||||
cfg["compress_ratio"],
|
||||
cfg["topk"],
|
||||
case["seq_lens"],
|
||||
case["query_lens"],
|
||||
case["spans"],
|
||||
with_image=False,
|
||||
)
|
||||
assert lens.cpu().tolist() == exp_lens
|
||||
assert indices.cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_flashinfer_mixed_sparse_indices_with_image_spans():
|
||||
device = torch.device("cuda")
|
||||
# 1 decode token (req 0) + two prefill requests (reqs 1, 2).
|
||||
seq_lens = [20, 30, 9]
|
||||
query_lens = [1, 30, 9]
|
||||
spans = [[], [(4, 12)], [(0, 6)]]
|
||||
query_start_loc = torch.tensor([0, 1, 31, 40], dtype=torch.int32, device=device)
|
||||
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
|
||||
token_to_req = torch.tensor(
|
||||
[0] + [1] * 30 + [2] * 9, dtype=torch.int32, device=device
|
||||
)
|
||||
block_table = torch.arange(3, dtype=torch.int32, device=device).view(3, 1)
|
||||
decode_swa = torch.tensor(
|
||||
[[100, 101, 102, 103, 104, 105, 106, 107]], dtype=torch.int32, device=device
|
||||
)
|
||||
prefill_topk = torch.zeros(39, 0, dtype=torch.int32, device=device)
|
||||
|
||||
lefts, rights = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
|
||||
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
|
||||
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
|
||||
|
||||
sparse_indices, sparse_lens = build_flashinfer_mixed_sparse_indices(
|
||||
decode_swa_indices=decode_swa,
|
||||
decode_compressed_indices=None,
|
||||
decode_compressed_topk_lens=None,
|
||||
prefill_topk_indices=prefill_topk,
|
||||
query_start_loc=query_start_loc,
|
||||
seq_lens=seq_lens_t,
|
||||
token_to_req_indices=token_to_req,
|
||||
swa_block_table=block_table,
|
||||
swa_block_size=BLOCK_SIZE,
|
||||
compressed_block_table=None,
|
||||
compressed_block_size=BLOCK_SIZE,
|
||||
window_size=WINDOW,
|
||||
compress_ratio=1,
|
||||
topk=0,
|
||||
prefill_left_visible=left_t,
|
||||
prefill_right_visible=right_t,
|
||||
max_image_tokens=MAX_IMG,
|
||||
)
|
||||
|
||||
swa_total = WINDOW + MAX_IMG
|
||||
assert sparse_indices.shape == (40, swa_total)
|
||||
assert sparse_lens.cpu().tolist() == [swa_total] * 40
|
||||
# Decode row: slots copied, image-extension columns padded with -1.
|
||||
decode_row = sparse_indices[0].cpu().tolist()
|
||||
assert decode_row[:WINDOW] == list(range(100, 108))
|
||||
assert decode_row[WINDOW:] == [-1] * MAX_IMG
|
||||
# Prefill rows: paged slot ids over the widened window.
|
||||
exp_rows, _ = ref_swa_slot_rows(
|
||||
seq_lens, query_lens, spans, block_table, WINDOW, MAX_IMG, swa_total
|
||||
)
|
||||
actual = sparse_indices[1:].cpu().tolist()
|
||||
assert actual == exp_rows[1:]
|
||||
|
||||
|
||||
def make_builder(
|
||||
vision: bool,
|
||||
window: int = WINDOW,
|
||||
max_image_tokens: int = MAX_IMG,
|
||||
max_num_batched_tokens: int = 64,
|
||||
model_name: str = "Qwen/Qwen3-0.6B",
|
||||
builder_cls: type[
|
||||
DeepseekSparseSWAMetadataBuilder
|
||||
] = DeepseekSparseSWAMetadataBuilder,
|
||||
deepseek_v4_config: bool = True,
|
||||
bounded_replay: bool = False,
|
||||
) -> DeepseekSparseSWAMetadataBuilder:
|
||||
vision_fields = dict(vision_n_layers=2, vision_max_n_token=max_image_tokens)
|
||||
vllm_config = create_vllm_config(
|
||||
model_name=model_name,
|
||||
max_model_len=4096,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
max_num_seqs=8,
|
||||
hf_config_override={"sliding_window": window}
|
||||
| (vision_fields if vision and not deepseek_v4_config else {}),
|
||||
)
|
||||
if vision and deepseek_v4_config:
|
||||
# Only V4 configs widen the SWA window in-kernel over image spans
|
||||
vllm_config.model_config.hf_config = DeepseekV4Config(
|
||||
num_hidden_layers=1,
|
||||
layer_types=["sliding_attention"],
|
||||
sliding_window=window,
|
||||
**vision_fields,
|
||||
)
|
||||
spec = SlidingWindowMLASpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=1,
|
||||
head_size=512,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=window,
|
||||
cache_dtype_str="auto",
|
||||
model_version="deepseek_v4",
|
||||
bounded_replay=bounded_replay,
|
||||
)
|
||||
return builder_cls(
|
||||
kv_cache_spec=spec,
|
||||
layer_names=["layer0"],
|
||||
vllm_config=vllm_config,
|
||||
device=torch.device("cuda"),
|
||||
)
|
||||
|
||||
|
||||
def build_metadata(
|
||||
builder: DeepseekSparseSWAMetadataBuilder,
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
mm_req_doc_ranges: dict[int, list[tuple[int, int]]] | None,
|
||||
replay_starts: list[int] | None = None,
|
||||
):
|
||||
device = torch.device("cuda")
|
||||
query_start_loc, seq_lens_t, _, slot_mapping, block_table = make_batch(
|
||||
seq_lens, query_lens, device
|
||||
)
|
||||
replay_start = (
|
||||
None
|
||||
if replay_starts is None
|
||||
else torch.tensor(replay_starts, dtype=torch.int32, device=device)
|
||||
)
|
||||
return builder.build(
|
||||
0,
|
||||
CommonAttentionMetadata(
|
||||
query_start_loc=query_start_loc,
|
||||
query_start_loc_cpu=query_start_loc.cpu(),
|
||||
seq_lens=seq_lens_t,
|
||||
seq_lens_cpu_upper_bound=seq_lens_t.cpu(),
|
||||
num_reqs=len(seq_lens),
|
||||
num_actual_tokens=int(query_start_loc[-1]),
|
||||
max_query_len=max(query_lens),
|
||||
max_seq_len=max(seq_lens),
|
||||
block_table_tensor=block_table,
|
||||
slot_mapping=slot_mapping,
|
||||
causal=True,
|
||||
mm_req_doc_ranges=mm_req_doc_ranges,
|
||||
),
|
||||
replay_start=replay_start,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_builder_in_image_visibility():
|
||||
seq_lens = [30, 12]
|
||||
query_lens = [30, 12]
|
||||
spans = [[(4, 12), (20, 24)], []]
|
||||
builder = make_builder(vision=True)
|
||||
md = build_metadata(builder, seq_lens, query_lens, {0: spans[0], 1: spans[1]})
|
||||
assert md.num_prefills == 2
|
||||
assert md.num_decode_tokens == 0
|
||||
assert md.prefill_swa_indices.shape[-1] == WIDTH
|
||||
assert md.prefill_left_visible is not None
|
||||
assert md.prefill_right_visible is not None
|
||||
|
||||
ref_left, ref_right = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
|
||||
assert md.prefill_left_visible.cpu().tolist() == ref_left
|
||||
assert md.prefill_right_visible.cpu().tolist() == ref_right
|
||||
|
||||
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
seq_lens, query_lens, spans, block_table, WINDOW, MAX_IMG, WIDTH
|
||||
)
|
||||
assert md.prefill_swa_lens.cpu().tolist() == lens
|
||||
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_builder_no_image_spans_fast_path():
|
||||
"""Vision model, image-free batch: no visibility tensors, plain window."""
|
||||
seq_lens = [30, 12]
|
||||
query_lens = [30, 12]
|
||||
builder = make_builder(vision=True)
|
||||
md = build_metadata(builder, seq_lens, query_lens, {0: [], 1: []})
|
||||
assert md.prefill_left_visible is None
|
||||
assert md.prefill_right_visible is None
|
||||
|
||||
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
seq_lens, query_lens, [[], []], block_table, WINDOW, MAX_IMG, WIDTH
|
||||
)
|
||||
assert md.prefill_swa_lens.cpu().tolist() == lens
|
||||
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_builder_text_model_unchanged():
|
||||
"""Text-only model: buffers stay window-sized and spans are ignored."""
|
||||
seq_lens = [30, 12]
|
||||
query_lens = [30, 12]
|
||||
builder = make_builder(vision=False)
|
||||
assert builder.max_image_tokens == 0
|
||||
md = build_metadata(builder, seq_lens, query_lens, None)
|
||||
assert md.prefill_swa_indices.shape[-1] == WINDOW
|
||||
assert md.prefill_left_visible is None
|
||||
|
||||
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
seq_lens, query_lens, [[], []], block_table, WINDOW, MAX_IMG, WINDOW
|
||||
)
|
||||
assert md.prefill_swa_lens.cpu().tolist() == lens
|
||||
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("compress_ratio", [0, 1, 2])
|
||||
@pytest.mark.parametrize("query_len", [100, 4000])
|
||||
def test_v41_image_prefill_uses_causal_swa(compress_ratio, query_len):
|
||||
"""V4.1 image tokens use the same causal SWA as text, including in chunks."""
|
||||
from vllm.models.deepseek_v41.common.ops.cache_utils import (
|
||||
combine_topk_swa_indices as combine_v41,
|
||||
)
|
||||
from vllm.models.deepseek_v41.sparse_mla import DeepseekV41SparseSWAMetadataBuilder
|
||||
|
||||
seq_len, window, max_image_tokens = 4000, 128, 2048
|
||||
spans = [(1900, 3947)]
|
||||
builder = make_builder(
|
||||
True,
|
||||
window,
|
||||
max_image_tokens,
|
||||
query_len,
|
||||
builder_cls=DeepseekV41SparseSWAMetadataBuilder,
|
||||
deepseek_v4_config=False,
|
||||
)
|
||||
assert builder.max_image_tokens == 0
|
||||
md = build_metadata(builder, [seq_len], [query_len], {0: spans})
|
||||
assert md.prefill_left_visible is None
|
||||
assert md.prefill_right_visible is None
|
||||
assert md.prefill_swa_indices.shape[-1] == window
|
||||
plan = md.get_prefill_chunk_plan(
|
||||
compress_ratio, prefill_chunk_size=4, has_compressed=compress_ratio > 0
|
||||
)
|
||||
[(start, end, n, m)] = plan
|
||||
gather_len = int(md.prefill_gather_lens[0])
|
||||
assert (start, end, m - n) == (0, 1, gather_len)
|
||||
assert gather_len == query_len + min(seq_len - query_len, window - 1)
|
||||
indices, lens = combine_v41(
|
||||
torch.empty(query_len, 0, dtype=torch.int32, device="cuda"),
|
||||
md.query_start_loc,
|
||||
md.prefill_seq_lens,
|
||||
md.prefill_gather_lens,
|
||||
window,
|
||||
compress_ratio,
|
||||
0,
|
||||
m,
|
||||
n,
|
||||
)
|
||||
indices, lens = indices.cpu(), lens.cpu().tolist()
|
||||
paged_indices = md.prefill_swa_indices.cpu()
|
||||
paged_lens = md.prefill_swa_lens.cpu().tolist()
|
||||
for token, pos in enumerate(range(seq_len - query_len, seq_len)):
|
||||
lo, hi = max(0, pos - window + 1), pos + 1
|
||||
row = indices[token, : lens[token]]
|
||||
assert lens[token] == hi - lo
|
||||
assert torch.all((row >= n) & (row < m))
|
||||
absolute_keys = row - n + seq_len - gather_len
|
||||
assert absolute_keys.tolist() == list(range(lo, hi))
|
||||
assert paged_lens[token] == hi - lo
|
||||
assert paged_indices[token, 0, : hi - lo].tolist() == list(range(lo, hi))
|
||||
|
||||
|
||||
# SWA bounded replay: every prefill index path clamps the window at replay_start.
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_builder_replay_start_bounds_prefill_window_and_gather():
|
||||
"""Paged-direct prefill indices stop at replay_start and the FlashMLA
|
||||
gather only covers the context the request may see."""
|
||||
seq_lens = [40, 12, 30]
|
||||
query_lens = [24, 12, 10]
|
||||
replay_starts = [12, 0, 0]
|
||||
builder = make_builder(vision=False)
|
||||
md = build_metadata(builder, seq_lens, query_lens, None, replay_starts)
|
||||
assert md.replay_start is not None
|
||||
assert md.replay_start.cpu().tolist() == replay_starts
|
||||
|
||||
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
|
||||
rows, lens = ref_swa_slot_rows(
|
||||
seq_lens,
|
||||
query_lens,
|
||||
[[], [], []],
|
||||
block_table,
|
||||
WINDOW,
|
||||
MAX_IMG,
|
||||
WINDOW,
|
||||
replay_starts=replay_starts,
|
||||
)
|
||||
assert md.prefill_swa_lens.cpu().tolist() == lens
|
||||
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
|
||||
# Request 0: the first replayed row (pos 16) sees [12, 16]; its last row
|
||||
# (pos 39) is a full window above the replay start and sees all of it.
|
||||
assert md.prefill_swa_lens[0].item() == 16 - 12 + 1
|
||||
assert md.prefill_swa_lens[23].item() == WINDOW
|
||||
# gather_len = query_len + min(prefix_len - replay_start, WINDOW - 1).
|
||||
assert md.prefill_gather_lens.cpu().tolist() == [
|
||||
24 + min(16 - 12, WINDOW - 1),
|
||||
12,
|
||||
10 + min(20, WINDOW - 1),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_builder_replaying_group_builds_without_replay_start():
|
||||
"""Graph captures build without model-specific kwargs: a replaying group's
|
||||
metadata then bounds nothing."""
|
||||
builder = make_builder(vision=False, bounded_replay=True)
|
||||
md = build_metadata(builder, [40, 12], [24, 12], None)
|
||||
assert not md.replay_start.any()
|
||||
assert md.prefill_swa_lens[0].item() == WINDOW
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_v41_flashinfer_mixed_sparse_indices_respect_replay_start():
|
||||
from vllm.models.deepseek_v41.common.ops.cache_utils import (
|
||||
build_flashinfer_mixed_sparse_indices as build_v41,
|
||||
)
|
||||
|
||||
device = torch.device("cuda")
|
||||
# 1 decode token (req 0) + two prefill requests; req 1 resumes at 16.
|
||||
seq_lens = [20, 40, 9]
|
||||
query_lens = [1, 24, 9]
|
||||
replay_starts = [0, 16, 0]
|
||||
query_start_loc = torch.tensor([0, 1, 25, 34], dtype=torch.int32, device=device)
|
||||
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
|
||||
token_to_req = torch.tensor(
|
||||
[0] + [1] * 24 + [2] * 9, dtype=torch.int32, device=device
|
||||
)
|
||||
block_table = torch.arange(3, dtype=torch.int32, device=device).view(3, 1)
|
||||
kwargs = dict(
|
||||
decode_swa_indices=torch.zeros((1, WINDOW), dtype=torch.int32, device=device),
|
||||
decode_compressed_indices=None,
|
||||
decode_compressed_topk_lens=None,
|
||||
prefill_topk_indices=torch.empty((33, 0), dtype=torch.int32, device=device),
|
||||
query_start_loc=query_start_loc,
|
||||
seq_lens=seq_lens_t,
|
||||
token_to_req_indices=token_to_req,
|
||||
swa_block_table=block_table,
|
||||
swa_block_size=BLOCK_SIZE,
|
||||
compressed_block_table=None,
|
||||
compressed_block_size=BLOCK_SIZE,
|
||||
window_size=WINDOW,
|
||||
compress_ratio=1,
|
||||
topk=0,
|
||||
)
|
||||
plain, _ = build_v41(
|
||||
replay_start=torch.zeros(3, dtype=torch.int32, device=device), **kwargs
|
||||
)
|
||||
bounded, _ = build_v41(
|
||||
replay_start=torch.tensor(replay_starts, dtype=torch.int32, device=device),
|
||||
**kwargs,
|
||||
)
|
||||
rows, _ = ref_swa_slot_rows(
|
||||
seq_lens,
|
||||
query_lens,
|
||||
[[], [], []],
|
||||
block_table,
|
||||
WINDOW,
|
||||
MAX_IMG,
|
||||
WINDOW,
|
||||
replay_starts=replay_starts,
|
||||
)
|
||||
# Decode row is copied through; prefill rows follow the bounded window.
|
||||
assert bounded[0].cpu().tolist() == plain[0].cpu().tolist()
|
||||
assert bounded[1:].cpu().tolist() == rows[1:]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_dspark_noncausal_draft_decode_update_matches_build():
|
||||
"""A DSpark draft graph refreshes its non-causal SWA metadata in place
|
||||
instead of rebuilding it, so the refresh must match a fresh build."""
|
||||
from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
get_dspark_swa_index_width,
|
||||
)
|
||||
|
||||
num_spec = 4
|
||||
query_lens = [num_spec] * 3
|
||||
|
||||
def make_dspark_builder():
|
||||
builder = make_builder(vision=False)
|
||||
builder.is_dspark = True
|
||||
builder.noncausal_index_width = get_dspark_swa_index_width(WINDOW, num_spec)
|
||||
builder.decode_threshold = num_spec
|
||||
return builder
|
||||
|
||||
def common_metadata(seq_lens):
|
||||
query_start_loc, seq_lens_t, _, slot_mapping, block_table = make_batch(
|
||||
seq_lens, query_lens, torch.device("cuda")
|
||||
)
|
||||
return CommonAttentionMetadata(
|
||||
query_start_loc=query_start_loc,
|
||||
query_start_loc_cpu=query_start_loc.cpu(),
|
||||
seq_lens=seq_lens_t,
|
||||
seq_lens_cpu_upper_bound=seq_lens_t.cpu(),
|
||||
num_reqs=len(seq_lens),
|
||||
num_actual_tokens=int(query_start_loc[-1]),
|
||||
max_query_len=num_spec,
|
||||
max_seq_len=max(seq_lens),
|
||||
block_table_tensor=block_table,
|
||||
slot_mapping=slot_mapping,
|
||||
causal=False,
|
||||
)
|
||||
|
||||
captured_seq_lens = [6, 40, 130]
|
||||
replay_seq_lens = [130, 9, 90]
|
||||
builder = make_dspark_builder()
|
||||
captured = common_metadata(captured_seq_lens)
|
||||
md = builder.build(0, captured)
|
||||
replay = common_metadata(replay_seq_lens)
|
||||
expected = make_dspark_builder().build(0, replay)
|
||||
|
||||
# A replay sees new inputs through the same device buffers.
|
||||
captured.seq_lens.copy_(replay.seq_lens)
|
||||
captured.block_table_tensor.copy_(replay.block_table_tensor)
|
||||
builder.update_draft_decode_metadata(md)
|
||||
|
||||
assert md.decode_swa_width == builder.noncausal_index_width
|
||||
torch.testing.assert_close(md.decode_swa_lens, expected.decode_swa_lens)
|
||||
torch.testing.assert_close(md.decode_swa_indices, expected.decode_swa_indices)
|
||||
@@ -1,771 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Correctness tests for DSpark non-causal sliding-window MLA via sparse indices.
|
||||
|
||||
DSpark drafts a block of N tokens whose attention is NON-CAUSAL within the block:
|
||||
every block token attends to the sliding window of context AND to all block
|
||||
tokens (including ones at later positions than itself).
|
||||
|
||||
We can implement this using the existing sparse-MLA pathway by expanding the window size
|
||||
to include the rest of the block tokens: instead of setting topk indices to the 127
|
||||
previous tokens, we expand it to the next power of 2 (256) and include up to
|
||||
swa_size + block_size - 1 topk indices, so that each query attends to the rest. The
|
||||
remaining slots are filled with padding.
|
||||
|
||||
The sparse-MLA decode kernels (FlashMLA on SM90/SM100, FlashInfer TRTLLM on
|
||||
SM100/SM120) are index-driven: each query attends over exactly the slots in its
|
||||
index list, with no causal mask (see ``flash_mla_with_kvcache(..., indices=...)``
|
||||
and ``_forward_decode``'s "attend only by generated indices"). The existing
|
||||
``test_sparse_mla_backends`` suite already validates arbitrary index lists, but
|
||||
only ones whose entries are <= the query's own position. This test suite specifically
|
||||
ensures correctness of the non-causal attention case.
|
||||
|
||||
This reuses the harness/helpers of ``test_sparse_mla_backends.py`` (same model
|
||||
shapes, fp8_ds_mla round-trip, mock indexer, MockSparseMLAAttentionLayer); only
|
||||
the index construction differs.
|
||||
"""
|
||||
|
||||
import math
|
||||
from types import MethodType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.test_mla_backends import (
|
||||
BatchSpec,
|
||||
MockSparseMLAAttentionLayer,
|
||||
create_and_prepopulate_kv_cache,
|
||||
)
|
||||
from tests.v1.attention.test_sparse_mla_backends import (
|
||||
_quantize_dequantize_fp8_ds_mla,
|
||||
)
|
||||
from tests.v1.attention.utils import (
|
||||
create_common_attn_metadata,
|
||||
create_standard_kv_cache_spec,
|
||||
create_vllm_config,
|
||||
)
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(
|
||||
"DSpark non-causal sparse MLA tests currently only support CUDA.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseTRTLLMBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.flashmla_sparse import FlashMLASparseBackend
|
||||
from vllm.v1.attention.ops import flashmla
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
# (window, block_size, topk_width). topk_width must be a multiple of the kernel's
|
||||
# B_TOPK (= padded query-head count, 64 or 128); we use 128-multiples to cover
|
||||
# both. The "wide" case needs window + block > 128 -> width must grow past 128.
|
||||
_DSPARK_CONFIGS = {
|
||||
"small_block": (8, 4, 128),
|
||||
"full_window_block": (128, 5, 256),
|
||||
}
|
||||
|
||||
|
||||
def _build_dspark_noncausal_indices(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
window: int,
|
||||
topk_width: int,
|
||||
device: torch.device,
|
||||
) -> torch.Tensor:
|
||||
"""Per-token sparse indices for the DSpark non-causal block.
|
||||
|
||||
For a request with context length ``ctx`` and a query block of ``q_len``
|
||||
tokens (block positions ``ctx .. ctx+q_len-1``), EVERY block query attends to
|
||||
the same set: the trailing ``window`` context positions plus all block
|
||||
positions, i.e. the contiguous range ``[max(ctx-window,0) .. ctx+q_len-1]``.
|
||||
This is non-causal: an early block query's list contains later block tokens
|
||||
(future-pointing). The list is padded to ``topk_width`` with ``-1``.
|
||||
"""
|
||||
total_query_tokens = sum(query_lens)
|
||||
sparse_indices = torch.full(
|
||||
(total_query_tokens, topk_width), -1, dtype=torch.int32, device=device
|
||||
)
|
||||
gt = 0
|
||||
for s_len, q_len in zip(seq_lens, query_lens):
|
||||
ctx_len = s_len - q_len
|
||||
lo = max(ctx_len - window, 0)
|
||||
hi = ctx_len + q_len # exclusive: window context + the full block
|
||||
idx_list = torch.arange(lo, hi, dtype=torch.int32, device=device)
|
||||
n = idx_list.numel()
|
||||
assert n <= topk_width, (
|
||||
f"index list ({n}) exceeds aligned topk width ({topk_width})"
|
||||
)
|
||||
for _ in range(q_len):
|
||||
sparse_indices[gt, :n] = idx_list
|
||||
gt += 1
|
||||
return sparse_indices
|
||||
|
||||
|
||||
def _run_sparse_backend_vs_sdpa(
|
||||
backend_cls,
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
sparse_indices: torch.Tensor,
|
||||
kv_cache_dtype: str,
|
||||
block_size: int,
|
||||
num_heads: int,
|
||||
device: torch.device,
|
||||
force_future_dominance: bool = False,
|
||||
qk_nope_head_dim: int = 128,
|
||||
v_head_dim: int = 128,
|
||||
stale_cpu_query_lens: list[int] | None = None,
|
||||
capture_graph: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Run a sparse-MLA backend with the given per-token indices and compute a
|
||||
dense per-token SDPA reference over the SAME indices.
|
||||
|
||||
Mirrors ``test_sparse_mla_backends.test_sparse_backend_decode_correctness``
|
||||
but with externally-supplied (non-causal) ``sparse_indices``.
|
||||
|
||||
``num_heads`` selects the kernel's B_TOPK (= padded q-head count): 128 -> 128,
|
||||
64 -> 64. The aligned widths (128/256) are multiples of both, so num_heads=64
|
||||
exercises the head64 decode path that the SM100 alignment assert guards.
|
||||
|
||||
``force_future_dominance`` scales the LAST block token's latent KV so it
|
||||
dominates the softmax for every query that attends to it. With random data the
|
||||
few future block tokens carry negligible attention mass (especially with a wide
|
||||
window), so causal and non-causal outputs coincide; this knob makes the
|
||||
future-token contribution provably large for the differentiation test. It is
|
||||
OFF for the correctness test (which needs sensitivity to all tokens).
|
||||
|
||||
Returns (backend_output, noncausal_reference, causal_reference). The causal
|
||||
reference restricts each query to indices <= its own absolute position.
|
||||
"""
|
||||
batch_spec = BatchSpec(seq_lens=seq_lens, query_lens=query_lens)
|
||||
topk_tokens = sparse_indices.shape[1]
|
||||
dtype = torch.bfloat16
|
||||
use_fp8_ds_mla_quantization = kv_cache_dtype == "fp8_ds_mla"
|
||||
|
||||
kv_lora_rank = 512
|
||||
qk_rope_head_dim = 64
|
||||
head_size = kv_lora_rank + qk_rope_head_dim
|
||||
|
||||
max_seqlen = max(seq_lens)
|
||||
total_cache_tokens = sum(seq_lens)
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name="deepseek-ai/DeepSeek-V2-Lite-Chat",
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=max_seqlen,
|
||||
num_gpu_blocks=max(2048, cdiv(total_cache_tokens, block_size) + 1),
|
||||
block_size=block_size,
|
||||
hf_config_override={
|
||||
"index_topk": topk_tokens,
|
||||
"attn_module_list_cfg": [{"topk_tokens": topk_tokens}],
|
||||
},
|
||||
)
|
||||
model_config = vllm_config.model_config
|
||||
model_config.hf_text_config = SimpleNamespace(
|
||||
index_topk=topk_tokens,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
model_type="deepseek_v2",
|
||||
)
|
||||
del model_config.hf_config.index_topk # Composite configs only nest this field.
|
||||
model_config.dtype = dtype
|
||||
model_config.get_num_attention_heads = MethodType(
|
||||
lambda self, parallel_config: num_heads, model_config
|
||||
)
|
||||
model_config.get_num_kv_heads = MethodType(
|
||||
lambda self, parallel_config: 1, model_config
|
||||
)
|
||||
model_config.get_head_size = MethodType(lambda self: head_size, model_config)
|
||||
model_config.get_sliding_window = MethodType(lambda self: None, model_config)
|
||||
|
||||
kv_cache_spec = create_standard_kv_cache_spec(vllm_config)
|
||||
|
||||
torch.manual_seed(0)
|
||||
scale = 1.0 / math.sqrt(head_size)
|
||||
|
||||
# Shared MLA projection weights, used by both reference and backend.
|
||||
W_UK = torch.rand(
|
||||
kv_lora_rank, num_heads, qk_nope_head_dim, dtype=dtype, device=device
|
||||
)
|
||||
W_UV = torch.rand(kv_lora_rank, num_heads, v_head_dim, dtype=dtype, device=device)
|
||||
|
||||
all_q_vllm, all_kv_c_vllm, all_k_pe_vllm = [], [], []
|
||||
kv_c_contexts, k_pe_contexts = [], []
|
||||
reference_outputs = []
|
||||
# Causal counterpart of the reference: same index lists, but each query is
|
||||
# restricted to indices <= its own absolute position (drops future-pointing
|
||||
# block tokens). Used to prove the non-causal result is genuinely different.
|
||||
causal_reference_outputs = []
|
||||
|
||||
kv_cache_scale = torch.tensor(1.0, dtype=torch.float32, device=device)
|
||||
global_token_idx = 0
|
||||
|
||||
for s_len, q_len in zip(seq_lens, query_lens):
|
||||
ctx_len = s_len - q_len
|
||||
|
||||
q_c = torch.rand(
|
||||
q_len,
|
||||
num_heads,
|
||||
qk_nope_head_dim + qk_rope_head_dim,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
)
|
||||
kv_c_full = torch.rand(s_len, kv_lora_rank, dtype=dtype, device=device)
|
||||
k_pe_full = torch.rand(s_len, 1, qk_rope_head_dim, dtype=dtype, device=device)
|
||||
|
||||
if force_future_dominance:
|
||||
# Scale the last block token's latent KV so its key/value dominate the
|
||||
# softmax for any query attending to it. 4x in the latent dot makes its
|
||||
# pre-softmax score exceed the others by a wide margin, so non-causal
|
||||
# queries (which include it) diverge sharply from causal ones (which,
|
||||
# for all but the last query, exclude it). Applied before quantization
|
||||
# so cache and reference stay consistent.
|
||||
kv_c_full[s_len - 1] = kv_c_full[s_len - 1] * 4.0 + 2.0
|
||||
|
||||
if use_fp8_ds_mla_quantization:
|
||||
is_sm100 = torch.cuda.get_device_capability()[0] >= 10
|
||||
kv_c_full, k_pe_squeezed = _quantize_dequantize_fp8_ds_mla(
|
||||
kv_c_full,
|
||||
k_pe_full.squeeze(1),
|
||||
block_size=block_size,
|
||||
scale=kv_cache_scale,
|
||||
simulate_sm100_e8m0_scales=is_sm100,
|
||||
)
|
||||
k_pe_full = k_pe_squeezed.unsqueeze(1)
|
||||
|
||||
q_nope, q_pe = q_c.split([qk_nope_head_dim, qk_rope_head_dim], dim=-1)
|
||||
ql_nope = torch.einsum("qnh,lnh->qnl", q_nope, W_UK)
|
||||
q_mqa = torch.cat([ql_nope, q_pe], dim=-1)
|
||||
|
||||
k_mqa = torch.cat([kv_c_full, k_pe_full.squeeze(1)], dim=-1)
|
||||
v_mqa = kv_c_full
|
||||
|
||||
# Per-token sparse SDPA reference over the supplied (non-causal) indices.
|
||||
def _sparse_sdpa(idx_tensor, q_tok, k_mqa=k_mqa, v_mqa=v_mqa):
|
||||
k_sparse = k_mqa[idx_tensor].unsqueeze(1).expand(-1, num_heads, -1)
|
||||
v_sparse = v_mqa[idx_tensor].unsqueeze(1).expand(-1, num_heads, -1)
|
||||
out = torch.nn.functional.scaled_dot_product_attention(
|
||||
q_tok.unsqueeze(0).transpose(1, 2),
|
||||
k_sparse.unsqueeze(0).transpose(1, 2),
|
||||
v_sparse.unsqueeze(0).transpose(1, 2),
|
||||
scale=scale,
|
||||
)
|
||||
out = out.transpose(1, 2).squeeze(0)
|
||||
out = torch.einsum("qnl,lnv->qnv", out, W_UV)
|
||||
return out.flatten(start_dim=-2)
|
||||
|
||||
for q_idx in range(q_len):
|
||||
tok_sparse_idx = sparse_indices[global_token_idx]
|
||||
valid_indices = tok_sparse_idx[tok_sparse_idx >= 0].long()
|
||||
|
||||
q_tok = q_mqa[q_idx : q_idx + 1]
|
||||
reference_outputs.append(_sparse_sdpa(valid_indices, q_tok))
|
||||
|
||||
# Causal: drop indices pointing past this query's own position.
|
||||
abs_pos = ctx_len + q_idx
|
||||
causal_indices = valid_indices[valid_indices <= abs_pos]
|
||||
causal_reference_outputs.append(_sparse_sdpa(causal_indices, q_tok))
|
||||
global_token_idx += 1
|
||||
|
||||
all_q_vllm.append(q_c)
|
||||
all_kv_c_vllm.append(kv_c_full[ctx_len:])
|
||||
all_k_pe_vllm.append(k_pe_full[ctx_len:])
|
||||
kv_c_contexts.append(kv_c_full[: ctx_len + 1])
|
||||
k_pe_contexts.append(k_pe_full[: ctx_len + 1])
|
||||
|
||||
query_vllm = torch.cat(all_q_vllm, dim=0)
|
||||
kv_c_vllm = torch.cat(all_kv_c_vllm, dim=0)
|
||||
k_pe_vllm = torch.cat(all_k_pe_vllm, dim=0)
|
||||
sdpa_reference = torch.cat(reference_outputs, dim=0)
|
||||
causal_reference = torch.cat(causal_reference_outputs, dim=0)
|
||||
|
||||
vllm_config.cache_config.cache_dtype = kv_cache_dtype
|
||||
vllm_config.model_config.hf_text_config.index_topk = topk_tokens
|
||||
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch_spec, block_size, device, arange_block_indices=True
|
||||
)
|
||||
if stale_cpu_query_lens is not None:
|
||||
# Adaptive verification updates only device boundaries; the stale CPU
|
||||
# copy proves token_to_req_indices consumes the device layout.
|
||||
assert len(stale_cpu_query_lens) == len(query_lens)
|
||||
cpu_query_start_loc = [0]
|
||||
for query_len in stale_cpu_query_lens:
|
||||
cpu_query_start_loc.append(cpu_query_start_loc[-1] + query_len)
|
||||
common_attn_metadata.query_start_loc_cpu = torch.tensor(
|
||||
cpu_query_start_loc, dtype=torch.int32
|
||||
)
|
||||
kv_cache = create_and_prepopulate_kv_cache(
|
||||
kv_c_contexts=kv_c_contexts,
|
||||
k_pe_contexts=k_pe_contexts,
|
||||
block_size=block_size,
|
||||
head_size=head_size,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
num_blocks=vllm_config.cache_config.num_gpu_blocks,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
randomize_blocks=False,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
scale=kv_cache_scale,
|
||||
)
|
||||
|
||||
# The sparse builder clones the layer's dense-MHA prefill backend from
|
||||
# static_forward_context; register a mock layer carrying one.
|
||||
from vllm.v1.attention.backends.mla.prefill import get_mla_prefill_backend
|
||||
|
||||
prefill_backend = get_mla_prefill_backend(vllm_config)(
|
||||
num_heads=num_heads,
|
||||
scale=scale,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
vllm_config.compilation_config.static_forward_context["placeholder"] = (
|
||||
SimpleNamespace(prefill_backend=prefill_backend)
|
||||
)
|
||||
|
||||
builder = backend_cls.get_builder_cls()(
|
||||
kv_cache_spec, ["placeholder"], vllm_config, device
|
||||
)
|
||||
metadata = builder.build(
|
||||
common_prefix_len=0, common_attn_metadata=common_attn_metadata
|
||||
)
|
||||
|
||||
mock_indexer = SimpleNamespace(topk_indices_buffer=sparse_indices)
|
||||
|
||||
kv_b_proj_weight = torch.cat([W_UK, W_UV], dim=-1).view(
|
||||
kv_lora_rank, num_heads * (qk_nope_head_dim + v_head_dim)
|
||||
)
|
||||
mock_kv_b_proj = ColumnParallelLinear(
|
||||
input_size=kv_lora_rank,
|
||||
output_size=num_heads * (qk_nope_head_dim + v_head_dim),
|
||||
bias=False,
|
||||
).to(device=device, dtype=dtype)
|
||||
mock_kv_b_proj.weight = torch.nn.Parameter(kv_b_proj_weight.T.contiguous())
|
||||
|
||||
with set_current_vllm_config(vllm_config):
|
||||
impl = backend_cls.get_impl_cls()(
|
||||
num_heads=num_heads,
|
||||
head_size=head_size,
|
||||
scale=scale,
|
||||
num_kv_heads=1,
|
||||
alibi_slopes=None,
|
||||
sliding_window=None,
|
||||
kv_cache_dtype=vllm_config.cache_config.cache_dtype,
|
||||
logits_soft_cap=None,
|
||||
attn_type="decoder",
|
||||
kv_sharing_target_layer_name=None,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
qk_head_dim=qk_nope_head_dim + qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
kv_b_proj=mock_kv_b_proj,
|
||||
indexer=mock_indexer,
|
||||
)
|
||||
impl.process_weights_after_loading(dtype)
|
||||
mock_layer = MockSparseMLAAttentionLayer(
|
||||
impl=impl,
|
||||
num_heads=num_heads,
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
kv_lora_rank=kv_lora_rank,
|
||||
device=device,
|
||||
W_UK=W_UK,
|
||||
W_UV=W_UV,
|
||||
q_scale=1.0,
|
||||
k_scale=1.0,
|
||||
)
|
||||
|
||||
out_buffer = torch.empty(
|
||||
metadata.num_actual_tokens, num_heads * v_head_dim, dtype=dtype, device=device
|
||||
)
|
||||
with torch.inference_mode():
|
||||
impl.record_logical_topk_ready()
|
||||
backend_output = mock_layer.forward_impl(
|
||||
query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer
|
||||
)
|
||||
if capture_graph:
|
||||
device_boundaries = common_attn_metadata.query_start_loc.clone()
|
||||
common_attn_metadata.query_start_loc.copy_(
|
||||
common_attn_metadata.query_start_loc_cpu
|
||||
)
|
||||
metadata = builder.build(0, common_attn_metadata)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
impl.record_logical_topk_ready()
|
||||
backend_output = mock_layer.forward_impl(
|
||||
query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer
|
||||
)
|
||||
common_attn_metadata.query_start_loc.copy_(device_boundaries)
|
||||
builder.build(0, common_attn_metadata)
|
||||
graph.replay()
|
||||
return backend_output, sdpa_reference, causal_reference
|
||||
|
||||
|
||||
def _skip_if_backend_unavailable(backend_cls, kv_cache_dtype: str, block_size: int):
|
||||
if kv_cache_dtype not in backend_cls.supported_kv_cache_dtypes:
|
||||
pytest.skip(f"{backend_cls.get_name()} does not support {kv_cache_dtype}")
|
||||
if (
|
||||
backend_cls is FlashMLASparseBackend
|
||||
and kv_cache_dtype.startswith("fp8")
|
||||
and kv_cache_dtype != "fp8_ds_mla"
|
||||
):
|
||||
pytest.skip("FlashMLA Sparse fp8 only supports fp8_ds_mla kv-cache dtype")
|
||||
if not backend_cls.supports_block_size(block_size):
|
||||
pytest.skip(
|
||||
f"{backend_cls.get_name()} does not support block_size={block_size}"
|
||||
)
|
||||
if backend_cls is FlashMLASparseBackend:
|
||||
ok, reason = flashmla.is_flashmla_sparse_supported()
|
||||
if not ok:
|
||||
pytest.skip(reason)
|
||||
elif backend_cls is FlashInferMLASparseTRTLLMBackend:
|
||||
cap = current_platform.get_device_capability()
|
||||
if cap is None or not backend_cls.supports_compute_capability(cap):
|
||||
pytest.skip("FlashInferMLASparseTRTLLMBackend requires SM 10.x capability")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query_lens", [[1, 7, 3, 5], [1, 7, 8, 0]])
|
||||
def test_flashinfer_sparse_mla_adaptive_varlen_graph_matches_sdpa(
|
||||
default_vllm_config,
|
||||
dist_init,
|
||||
workspace_init,
|
||||
query_lens,
|
||||
):
|
||||
"""Replay uses device boundaries, including empty padding, despite stale CPU."""
|
||||
backend_cls = FlashInferMLASparseTRTLLMBackend
|
||||
_skip_if_backend_unavailable(backend_cls, "fp8", 64)
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
seq_lens = [257, 270, 265, 276]
|
||||
sparse_indices = _build_dspark_noncausal_indices(
|
||||
seq_lens,
|
||||
query_lens,
|
||||
window=128,
|
||||
topk_width=256,
|
||||
device=device,
|
||||
)
|
||||
|
||||
backend_output, sdpa_reference, _ = _run_sparse_backend_vs_sdpa(
|
||||
backend_cls,
|
||||
seq_lens,
|
||||
query_lens,
|
||||
sparse_indices,
|
||||
"fp8",
|
||||
64,
|
||||
16,
|
||||
device,
|
||||
qk_nope_head_dim=192,
|
||||
v_head_dim=256,
|
||||
stale_cpu_query_lens=[4, 4, 4, 4],
|
||||
capture_graph=True,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(
|
||||
backend_output,
|
||||
sdpa_reference,
|
||||
rtol=0.065,
|
||||
atol=0.05,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_cls",
|
||||
[FlashMLASparseBackend, FlashInferMLASparseTRTLLMBackend],
|
||||
ids=["FlashMLA", "FlashInferTRTLLM"],
|
||||
)
|
||||
@pytest.mark.parametrize("config_name", list(_DSPARK_CONFIGS.keys()))
|
||||
# Per backend, the skip logic routes fp8 to the supported flavor: FlashMLA tests
|
||||
# auto + fp8_ds_mla (and skips per-tensor "fp8", which it aliases to ds_mla);
|
||||
# FlashInfer TRTLLM tests auto + per-tensor "fp8" (and skips fp8_ds_mla, which it
|
||||
# does not implement). So both backends get a bf16 case and an fp8 case.
|
||||
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_ds_mla", "fp8"])
|
||||
@pytest.mark.parametrize("block_size", [64])
|
||||
# h_q=128 -> B_TOPK=128; h_q=64 -> B_TOPK=64 (covers the head64 decode path the
|
||||
# SM100 alignment assert specifically guards). Aligned widths (128/256) satisfy both.
|
||||
@pytest.mark.parametrize("num_heads", [128, 64], ids=["h128", "h64"])
|
||||
def test_dspark_noncausal_sparse_mla_matches_sdpa(
|
||||
default_vllm_config,
|
||||
dist_init,
|
||||
workspace_init,
|
||||
backend_cls,
|
||||
config_name,
|
||||
kv_cache_dtype,
|
||||
block_size,
|
||||
num_heads,
|
||||
):
|
||||
"""Non-causal (window ∪ block, future-pointing) per-token indices must match
|
||||
a dense SDPA reference over the same indices, for both sparse-MLA backends."""
|
||||
_skip_if_backend_unavailable(backend_cls, kv_cache_dtype, block_size)
|
||||
|
||||
window, block, topk_width = _DSPARK_CONFIGS[config_name]
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
# Decode-style batch: each request has `block` query tokens and enough
|
||||
# context for a full sliding window.
|
||||
seq_lens = [window + block + 123, window + block + 50]
|
||||
query_lens = [block, block]
|
||||
|
||||
sparse_indices = _build_dspark_noncausal_indices(
|
||||
seq_lens, query_lens, window, topk_width, device
|
||||
)
|
||||
|
||||
# Sanity: the construction must actually be non-causal (an early block query
|
||||
# must reference a later block position than itself).
|
||||
ctx0 = seq_lens[0] - query_lens[0]
|
||||
first_query_valid = sparse_indices[0][sparse_indices[0] >= 0]
|
||||
assert int(first_query_valid.max()) >= ctx0 + query_lens[0] - 1, (
|
||||
"expected the first block query to attend to a future block token"
|
||||
)
|
||||
|
||||
backend_output, sdpa_reference, _ = _run_sparse_backend_vs_sdpa(
|
||||
backend_cls,
|
||||
seq_lens,
|
||||
query_lens,
|
||||
sparse_indices,
|
||||
kv_cache_dtype,
|
||||
block_size,
|
||||
num_heads,
|
||||
device,
|
||||
)
|
||||
|
||||
assert backend_output.shape == sdpa_reference.shape
|
||||
assert backend_output.dtype == sdpa_reference.dtype
|
||||
assert torch.isfinite(backend_output).all()
|
||||
if kv_cache_dtype.startswith("fp8"):
|
||||
rtol, atol = 0.065, 0.05
|
||||
else:
|
||||
rtol, atol = 0.01, 0.01
|
||||
torch.testing.assert_close(backend_output, sdpa_reference, rtol=rtol, atol=atol)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_cls",
|
||||
[FlashMLASparseBackend, FlashInferMLASparseTRTLLMBackend],
|
||||
ids=["FlashMLA", "FlashInferTRTLLM"],
|
||||
)
|
||||
@pytest.mark.parametrize("config_name", list(_DSPARK_CONFIGS.keys()))
|
||||
@pytest.mark.parametrize("block_size", [64])
|
||||
def test_dspark_noncausal_differs_from_causal(
|
||||
default_vllm_config,
|
||||
dist_init,
|
||||
workspace_init,
|
||||
backend_cls,
|
||||
config_name,
|
||||
block_size,
|
||||
):
|
||||
"""Differentiation guard: prove the backend genuinely attends to the
|
||||
future-pointing indices (not silently applying a causal mask, and not merely
|
||||
coinciding with a causal result because future tokens carry little weight).
|
||||
|
||||
With random data the few future block tokens are a negligible fraction of the
|
||||
attended set (especially with a wide window), so causal and non-causal outputs
|
||||
are numerically indistinguishable -- that is correct physics, not a backend
|
||||
bug. To make the check meaningful we use ``force_future_dominance`` so the last
|
||||
block token dominates the softmax: the backend must then match the non-causal
|
||||
reference and diverge sharply from the causal one. bf16 (``auto``) suffices;
|
||||
the property is dtype-independent and fp8 correctness is covered above.
|
||||
"""
|
||||
_skip_if_backend_unavailable(backend_cls, "auto", block_size)
|
||||
|
||||
window, block, topk_width = _DSPARK_CONFIGS[config_name]
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
seq_lens = [window + block + 123, window + block + 50]
|
||||
query_lens = [block, block]
|
||||
|
||||
sparse_indices = _build_dspark_noncausal_indices(
|
||||
seq_lens, query_lens, window, topk_width, device
|
||||
)
|
||||
|
||||
backend_output, sdpa_reference, causal_reference = _run_sparse_backend_vs_sdpa(
|
||||
backend_cls,
|
||||
seq_lens,
|
||||
query_lens,
|
||||
sparse_indices,
|
||||
"auto",
|
||||
block_size,
|
||||
128,
|
||||
device,
|
||||
force_future_dominance=True,
|
||||
)
|
||||
|
||||
# The two references must be clearly distinguishable for the check to mean
|
||||
# anything (dominance guarantees this).
|
||||
ref_gap = (sdpa_reference - causal_reference).abs().max().item()
|
||||
assert ref_gap > 0.1, (
|
||||
f"non-causal and causal references are too close (gap={ref_gap}); "
|
||||
"force_future_dominance did not create a separable scenario"
|
||||
)
|
||||
|
||||
# Backend must track the NON-causal reference, not the causal one.
|
||||
torch.testing.assert_close(backend_output, sdpa_reference, rtol=0.01, atol=0.01)
|
||||
causal_err = (backend_output - causal_reference).abs().max().item()
|
||||
assert causal_err > 0.1, (
|
||||
f"non-causal backend output matches the causal reference "
|
||||
f"(max abs diff={causal_err}); future-pointing indices are not attended to"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("context_len", [20, 128, 900])
|
||||
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float8_e4m3fn])
|
||||
@pytest.mark.parametrize("num_heads", [16, 64])
|
||||
def test_dsv41_flashinfer_dspark_window_matches_reference(
|
||||
context_len, dtype, num_heads, monkeypatch
|
||||
):
|
||||
"""Draft queries see the full block without treating padded slots as keys."""
|
||||
if not current_platform.is_device_capability_family(100):
|
||||
pytest.skip("DSV4 TRTLLM sparse attention requires SM100")
|
||||
from vllm.models.deepseek_v41.nvidia.flashinfer_sparse import (
|
||||
DeepseekSparseSWAFlashInferMetadataBuilder,
|
||||
DeepseekV4FlashInferMLAAttention,
|
||||
)
|
||||
from vllm.models.deepseek_v41.sparse_mla import (
|
||||
DeepseekV41SparseSWAMetadataBuilder,
|
||||
)
|
||||
|
||||
torch.manual_seed(123)
|
||||
device = "cuda"
|
||||
query_lens = [5, 3]
|
||||
context_lens = [context_len, context_len + 137]
|
||||
num_real_tokens, num_tokens, head_dim = 8, 9, 512
|
||||
cache = torch.randn(32, 128, head_dim, device=device, dtype=torch.bfloat16).to(
|
||||
dtype
|
||||
)
|
||||
query = torch.randn(
|
||||
num_tokens, num_heads, head_dim, device=device, dtype=torch.bfloat16
|
||||
).to(dtype)
|
||||
indices = torch.full((num_tokens, 256), -1, device=device, dtype=torch.int32)
|
||||
visible_indices = []
|
||||
visible_lens = []
|
||||
for req, (context, query_len) in enumerate(zip(context_lens, query_lens)):
|
||||
visible = (
|
||||
torch.arange(max(context - 128, 0), context + query_len, device=device)
|
||||
+ req * 16 * 128
|
||||
)
|
||||
visible_indices.extend([visible] * query_len)
|
||||
visible_lens.extend([visible.numel()] * query_len)
|
||||
for token, visible in enumerate(visible_indices):
|
||||
indices[token, : visible.numel()] = visible.to(torch.int32)
|
||||
query_start_loc = torch.tensor([0, 5, 8, 9], dtype=torch.int32)
|
||||
metadata = SimpleNamespace(
|
||||
num_decodes=3,
|
||||
num_prefills=0,
|
||||
num_decode_tokens=num_tokens,
|
||||
num_prefill_tokens=0,
|
||||
seq_lens=torch.tensor(
|
||||
[context_lens[0] + 5, context_lens[1] + 3, 1],
|
||||
device=device,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
query_start_loc=query_start_loc.to(device),
|
||||
query_start_loc_cpu=query_start_loc,
|
||||
token_to_req_indices=torch.tensor(
|
||||
[0] * 5 + [1] * 3 + [2], device=device, dtype=torch.int32
|
||||
),
|
||||
decode_swa_indices=indices,
|
||||
decode_swa_width=256,
|
||||
decode_swa_lens=torch.tensor(
|
||||
visible_lens + [0], device=device, dtype=torch.int32
|
||||
),
|
||||
block_table=torch.arange(48, device=device, dtype=torch.int32).view(3, -1),
|
||||
block_size=128,
|
||||
replay_start=torch.zeros(3, device=device, dtype=torch.int32),
|
||||
flashinfer_sparse_index_cache={},
|
||||
max_decode_query_len=5,
|
||||
)
|
||||
|
||||
# Exercise FlashInfer preparation without constructing a model/config.
|
||||
def init_parent(builder):
|
||||
builder._max_tokens = num_tokens
|
||||
builder.device = device
|
||||
builder.window_size = 128
|
||||
|
||||
monkeypatch.setattr(DeepseekV41SparseSWAMetadataBuilder, "__init__", init_parent)
|
||||
monkeypatch.setattr(
|
||||
DeepseekV41SparseSWAMetadataBuilder,
|
||||
"build",
|
||||
lambda *args: metadata,
|
||||
)
|
||||
builder = DeepseekSparseSWAFlashInferMetadataBuilder()
|
||||
common_metadata = SimpleNamespace(causal=False)
|
||||
builder.build(0, common_metadata)
|
||||
prepared = (
|
||||
metadata.flashinfer_decode_topk_lens,
|
||||
metadata.flashinfer_decode_seq_lens,
|
||||
)
|
||||
attention = SimpleNamespace(
|
||||
kv_cache_torch_dtype=dtype,
|
||||
window_size=128,
|
||||
compress_ratio=0,
|
||||
topk_indices_buffer=torch.empty(
|
||||
num_tokens, 0, device=device, dtype=torch.int32
|
||||
),
|
||||
scale=1 / math.sqrt(head_dim),
|
||||
_flashinfer_fp8_bmm1_scale=1 / math.sqrt(head_dim),
|
||||
_flashinfer_fp8_bmm2_scale=1.0,
|
||||
attn_sink=None,
|
||||
)
|
||||
attention._build_sparse_index_metadata = MethodType(
|
||||
DeepseekV4FlashInferMLAAttention._build_sparse_index_metadata, attention
|
||||
)
|
||||
output = torch.empty_like(query, dtype=torch.bfloat16)
|
||||
|
||||
def forward():
|
||||
metadata.flashinfer_sparse_index_cache.clear()
|
||||
DeepseekV4FlashInferMLAAttention._forward(
|
||||
attention, query, None, cache, metadata, None, True, output
|
||||
)
|
||||
|
||||
def check_output():
|
||||
references = []
|
||||
for token, visible in enumerate(visible_indices):
|
||||
keys = cache.flatten(0, 1)[visible].float()
|
||||
weights = torch.softmax(
|
||||
query[token].float() @ keys.T / math.sqrt(head_dim), -1
|
||||
)
|
||||
references.append(weights @ keys)
|
||||
atol = 0.01 if dtype == torch.bfloat16 else 0.05
|
||||
torch.testing.assert_close(
|
||||
output[:num_real_tokens].float(),
|
||||
torch.stack(references),
|
||||
atol=atol,
|
||||
rtol=0.05,
|
||||
)
|
||||
|
||||
forward()
|
||||
check_output()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
forward()
|
||||
# Replay must consume the current inputs, including KV written since capture.
|
||||
query.copy_(torch.randn_like(query, dtype=torch.bfloat16).to(dtype))
|
||||
cache.copy_(torch.randn_like(cache, dtype=torch.bfloat16).to(dtype))
|
||||
# A new step changes visibility as well as Q/KV, without recapturing.
|
||||
metadata.seq_lens.sub_(1)
|
||||
metadata.decode_swa_lens[:num_real_tokens].sub_(1)
|
||||
for token, visible in enumerate(visible_indices):
|
||||
indices[token, visible.numel() - 1] = -1
|
||||
visible_indices[token] = visible[:-1]
|
||||
builder.build(0, common_metadata)
|
||||
assert metadata.flashinfer_decode_topk_lens.data_ptr() == prepared[0].data_ptr()
|
||||
assert metadata.flashinfer_decode_seq_lens.data_ptr() == prepared[1].data_ptr()
|
||||
torch.testing.assert_close(prepared[0], metadata.decode_swa_lens.clamp_min(128))
|
||||
torch.testing.assert_close(
|
||||
prepared[1], metadata.seq_lens[metadata.token_to_req_indices.long()]
|
||||
)
|
||||
graph.replay()
|
||||
check_output()
|
||||
@@ -1,162 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Equivalence tests for the AITER MLA page-index expansion kernel.
|
||||
|
||||
`_expand_page_indices_kernel` turns a block table into the per-token flat page
|
||||
indices the AITER MLA decode kernel consumes (it always runs with page_size=1
|
||||
internally, so `kv_buffer` is flattened and each token needs its own index).
|
||||
|
||||
The kernel was parallelised over token chunks as well as requests; at
|
||||
concurrency 1 the previous `(num_reqs,)` grid put a single workgroup in a serial
|
||||
loop over the whole sequence. These tests pin the result to a straightforward
|
||||
PyTorch expansion so the parallelisation cannot change what is produced.
|
||||
|
||||
Both block-table strides are passed by the caller, so a non-contiguous view is
|
||||
covered explicitly rather than assumed away.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
_expand_page_indices_kernel,
|
||||
)
|
||||
|
||||
|
||||
def _reference(block_table, cu_num_tokens, kernel_block_size, out_len, device):
|
||||
"""Per-token flat index, written the obvious way."""
|
||||
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
|
||||
num_reqs = cu_num_tokens.numel() - 1
|
||||
for r in range(num_reqs):
|
||||
start = int(cu_num_tokens[r])
|
||||
end = int(cu_num_tokens[r + 1])
|
||||
n = end - start
|
||||
if n <= 0:
|
||||
continue
|
||||
tok = torch.arange(n, device=device)
|
||||
blk = tok // kernel_block_size
|
||||
off = tok % kernel_block_size
|
||||
out[start:end] = block_table[r, blk].to(torch.int64) * kernel_block_size + off
|
||||
return out
|
||||
|
||||
|
||||
def _run(block_table, cu_num_tokens, kernel_block_size, out_len, device):
|
||||
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
|
||||
num_reqs = cu_num_tokens.numel() - 1
|
||||
max_tokens_per_req = block_table.shape[1] * kernel_block_size
|
||||
num_chunks = max(1, -(-max_tokens_per_req // 1024))
|
||||
_expand_page_indices_kernel[(num_reqs, num_chunks)](
|
||||
out,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
block_table.stride(1),
|
||||
cu_num_tokens,
|
||||
cu_num_tokens[1:] - cu_num_tokens[:-1],
|
||||
KERNEL_BLOCK_SIZE=kernel_block_size,
|
||||
BLOCK_SIZE=1024,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _make(seq_lens, kernel_block_size, device, noncontig=False):
|
||||
num_reqs = len(seq_lens)
|
||||
max_blocks = (
|
||||
max(1, max((s + kernel_block_size - 1) // kernel_block_size for s in seq_lens))
|
||||
+ 2
|
||||
)
|
||||
width = max_blocks * 2 if noncontig else max_blocks
|
||||
torch.manual_seed(0)
|
||||
bt = torch.randint(0, 10_000, (num_reqs, width), dtype=torch.int64, device=device)
|
||||
if noncontig:
|
||||
bt = bt[:, ::2]
|
||||
assert not bt.is_contiguous()
|
||||
cu = torch.zeros(num_reqs + 1, dtype=torch.int64, device=device)
|
||||
cu[1:] = torch.tensor(seq_lens, dtype=torch.int64, device=device).cumsum(0)
|
||||
return bt, cu, int(cu[-1])
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens", [[1], [128], [4096], [1, 1], [4096, 7], [37, 4096, 1], [1024] * 8]
|
||||
)
|
||||
@pytest.mark.parametrize("kernel_block_size", [1, 16, 64])
|
||||
def test_matches_reference(seq_lens, kernel_block_size):
|
||||
bt, cu, total = _make(seq_lens, kernel_block_size, "cuda")
|
||||
got = _run(bt, cu, kernel_block_size, total, "cuda")
|
||||
want = _reference(bt, cu, kernel_block_size, total, "cuda")
|
||||
torch.testing.assert_close(got, want, atol=0, rtol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
|
||||
@pytest.mark.parametrize("kernel_block_size", [1, 16])
|
||||
def test_non_contiguous_block_table(kernel_block_size):
|
||||
"""Column stride != 1 must be honoured, not assumed away."""
|
||||
bt, cu, total = _make([4096, 37], kernel_block_size, "cuda", noncontig=True)
|
||||
got = _run(bt, cu, kernel_block_size, total, "cuda")
|
||||
want = _reference(bt, cu, kernel_block_size, total, "cuda")
|
||||
torch.testing.assert_close(got, want, atol=0, rtol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
|
||||
def test_ragged_batch_leaves_other_rows_untouched():
|
||||
"""A short request must not have its tail written by a longer one's chunks."""
|
||||
kbs = 16
|
||||
bt, cu, total = _make([4096, 1, 512], kbs, "cuda")
|
||||
out = torch.full((total + 8,), -999, dtype=torch.int64, device="cuda")
|
||||
num_chunks = max(1, -(-(bt.shape[1] * kbs) // 1024))
|
||||
_expand_page_indices_kernel[(3, num_chunks)](
|
||||
out,
|
||||
bt,
|
||||
bt.stride(0),
|
||||
bt.stride(1),
|
||||
cu,
|
||||
cu[1:] - cu[:-1],
|
||||
KERNEL_BLOCK_SIZE=kbs,
|
||||
BLOCK_SIZE=1024,
|
||||
)
|
||||
want = _reference(bt, cu, kbs, total, "cuda")
|
||||
torch.testing.assert_close(out[:total], want, atol=0, rtol=0)
|
||||
# The slack past the last request must be untouched.
|
||||
assert torch.all(out[total:] == -999)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
|
||||
def test_zero_length_request_writes_nothing():
|
||||
"""A zero-token request in a padded batch must produce no stores."""
|
||||
kbs = 16
|
||||
bt, cu, total = _make([256, 0, 128], kbs, "cuda")
|
||||
got = _run(bt, cu, kbs, total, "cuda")
|
||||
want = _reference(bt, cu, kbs, total, "cuda")
|
||||
torch.testing.assert_close(got, want, atol=0, rtol=0)
|
||||
assert int(cu[2] - cu[1]) == 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
|
||||
def test_over_provisioned_chunks_do_not_change_result():
|
||||
"""Extra chunks must be inert.
|
||||
|
||||
Each program covers `chunk_idx * BLOCK_SIZE + [0, BLOCK_SIZE)`, so the grid
|
||||
has to span the request: 8192 tokens need at least ceil(8192/1024) == 8
|
||||
chunks, and fewer would simply leave the tail unwritten. The caller sizes
|
||||
the grid from `block_table.shape[1] * kernel_block_size`, an upper bound
|
||||
over the batch, so in a ragged batch most requests get more chunks than
|
||||
they need. That over-provisioning is the case worth pinning: the surplus
|
||||
programs must return early and change nothing.
|
||||
"""
|
||||
kbs = 1
|
||||
bt, cu, total = _make([8192], kbs, "cuda")
|
||||
ref = _reference(bt, cu, kbs, total, "cuda")
|
||||
required = -(-total // 1024)
|
||||
for num_chunks in (required, required * 2, required * 8):
|
||||
out = torch.full((total,), -1, dtype=torch.int64, device="cuda")
|
||||
_expand_page_indices_kernel[(1, num_chunks)](
|
||||
out,
|
||||
bt,
|
||||
bt.stride(0),
|
||||
bt.stride(1),
|
||||
cu,
|
||||
cu[1:] - cu[:-1],
|
||||
KERNEL_BLOCK_SIZE=kbs,
|
||||
BLOCK_SIZE=1024,
|
||||
)
|
||||
torch.testing.assert_close(out, ref, atol=0, rtol=0)
|
||||
@@ -1,80 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlashInfer GQA builder: reorder threshold under DCP with spec decode."""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip("FlashInfer backend requires a CUDA platform.", allow_module_level=True)
|
||||
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
from vllm.config import SpeculativeConfig, set_current_vllm_config
|
||||
from vllm.v1.attention.backend import AttentionCGSupport
|
||||
from vllm.v1.attention.backends import flashinfer as flashinfer_backend
|
||||
from vllm.v1.attention.backends.flashinfer import (
|
||||
FlashInferDecodeKernel,
|
||||
FlashInferMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import PerLayerParameters
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
|
||||
|
||||
def test_flashinfer_gqa_dcp_spec_decode_clamps_reorder_threshold(monkeypatch):
|
||||
"""trtllm-gen decode receives no cp_rank/global-seq-len information, so its
|
||||
end-aligned causal mask is wrong for q_len > 1 over the DCP-interleaved
|
||||
local KV shard. The builder must keep reorder_batch_threshold at 1 under
|
||||
DCP so spec queries take the (DCP-aware) prefill path instead.
|
||||
"""
|
||||
vllm_config = create_vllm_config(max_model_len=1024)
|
||||
vllm_config.parallel_config.decode_context_parallel_size = 2
|
||||
vllm_config.speculative_config = SpeculativeConfig(
|
||||
method="ngram", num_speculative_tokens=3
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
flashinfer_backend, "can_use_trtllm_attention", lambda *args, **kwargs: True
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
FlashInferMetadataBuilder,
|
||||
"_get_flashinfer_trtllm_api_decode_kernel",
|
||||
staticmethod(lambda: FlashInferDecodeKernel.TRTLLM_GEN),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
flashinfer_backend,
|
||||
"get_per_layer_parameters",
|
||||
lambda *args, **kwargs: {
|
||||
"layer.0": PerLayerParameters(
|
||||
window_left=-1, logits_soft_cap=None, sm_scale=0.1, has_sinks=False
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
kv_cache_spec = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=vllm_config.model_config.get_num_kv_heads(
|
||||
vllm_config.parallel_config
|
||||
),
|
||||
head_size=vllm_config.model_config.get_head_size(),
|
||||
dtype=vllm_config.model_config.dtype,
|
||||
)
|
||||
with set_current_vllm_config(vllm_config):
|
||||
builder = FlashInferMetadataBuilder(
|
||||
kv_cache_spec,
|
||||
["layer.0"],
|
||||
vllm_config,
|
||||
torch.device("cpu"),
|
||||
)
|
||||
|
||||
# Guard against passing vacuously with the kernel disabled.
|
||||
assert (
|
||||
builder.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.TRTLLM_GEN
|
||||
)
|
||||
assert builder.reorder_batch_threshold == 1
|
||||
assert (
|
||||
FlashInferMetadataBuilder.get_cudagraph_support(vllm_config, kv_cache_spec)
|
||||
== AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
|
||||
)
|
||||
@@ -1,179 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import MethodType
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
requires_flashinfer_mla = pytest.mark.skipif(
|
||||
not current_platform.has_device_capability(100),
|
||||
reason="FlashInfer MLA requires compute capability 10 or above.",
|
||||
)
|
||||
|
||||
|
||||
def test_mla_dcp_gathered_query_reserves_backend_head_storage():
|
||||
from vllm.v1.attention.ops.dcp import reserve_query_head_storage
|
||||
|
||||
query = torch.randn(3, 24, 576, dtype=torch.bfloat16)
|
||||
|
||||
padded = reserve_query_head_storage(query, 128)
|
||||
|
||||
assert padded.shape == query.shape
|
||||
assert padded.stride() == query.stride()
|
||||
assert padded.untyped_storage().nbytes() >= 3 * 128 * 576 * 2
|
||||
assert torch.equal(padded, query)
|
||||
|
||||
|
||||
@requires_flashinfer_mla
|
||||
def test_flashinfer_mla_selects_backend_for_gathered_heads():
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla import (
|
||||
_select_mla_decode_backend,
|
||||
)
|
||||
|
||||
assert _select_mla_decode_backend(6) is None
|
||||
assert _select_mla_decode_backend(24) == "cute-dsl"
|
||||
|
||||
|
||||
@requires_flashinfer_mla
|
||||
def test_flashinfer_mla_forward_uses_gathered_head_count(monkeypatch):
|
||||
import vllm.v1.attention.backends.mla.flashinfer_mla as flashinfer_mla
|
||||
|
||||
impl = MagicMock()
|
||||
impl.bmm1_scale = 1.0
|
||||
impl.bmm2_scale = 1.0
|
||||
impl.need_to_return_lse_for_decode = True
|
||||
impl.dcp_world_size = 1
|
||||
impl.dcp_rank = 0
|
||||
impl.cp_kv_cache_interleave_size = 1
|
||||
impl.num_heads = 6
|
||||
impl.qk_nope_head_dim = 128
|
||||
impl.kv_lora_rank = 512
|
||||
impl.qk_rope_head_dim = 64
|
||||
impl.kv_cache_dtype = "auto"
|
||||
|
||||
attn_metadata = MagicMock()
|
||||
attn_metadata.causal = True
|
||||
attn_metadata.num_decode_tokens = 2
|
||||
attn_metadata.num_decodes = 2
|
||||
attn_metadata.max_seq_len = 1
|
||||
attn_metadata.decode.block_table = torch.zeros(2, 1, dtype=torch.int32)
|
||||
attn_metadata.decode.seq_lens = torch.ones(2, dtype=torch.int32)
|
||||
attn_metadata.decode.max_query_len = 1
|
||||
|
||||
query = torch.ones(2, 24, 576, dtype=torch.bfloat16)
|
||||
kv_cache = torch.ones(1, 128, 576, dtype=torch.bfloat16)
|
||||
kernel = MagicMock(
|
||||
return_value=(
|
||||
torch.ones(2, 1, 24, 512, dtype=torch.bfloat16),
|
||||
torch.ones(2, 24, dtype=torch.float32),
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(flashinfer_mla, "_get_workspace_buffer", MagicMock())
|
||||
monkeypatch.setattr(flashinfer_mla, "trtllm_batch_decode_with_kv_cache_mla", kernel)
|
||||
layer = MagicMock()
|
||||
|
||||
output, lse = flashinfer_mla.FlashInferMLAImpl.forward_mqa(
|
||||
impl, query, kv_cache, attn_metadata, layer
|
||||
)
|
||||
|
||||
assert kernel.call_args.kwargs["backend"] == "cute-dsl"
|
||||
assert output.shape == (2, 24, 512)
|
||||
assert lse is not None and lse.shape == (2, 24)
|
||||
|
||||
|
||||
@requires_flashinfer_mla
|
||||
@pytest.mark.parametrize("causal", [True, False], ids=["causal", "noncausal"])
|
||||
def test_flashinfer_mla_forward_uses_native_dcp_api(monkeypatch, causal):
|
||||
import vllm.v1.attention.backends.mla.flashinfer_mla as flashinfer_mla
|
||||
|
||||
impl = MagicMock()
|
||||
impl.bmm1_scale = 1.0
|
||||
impl.bmm2_scale = 1.0
|
||||
impl.need_to_return_lse_for_decode = True
|
||||
impl.num_heads = 6
|
||||
impl.qk_nope_head_dim = 128
|
||||
impl.kv_lora_rank = 512
|
||||
impl.qk_rope_head_dim = 64
|
||||
impl.kv_cache_dtype = "auto"
|
||||
impl.dcp_world_size = 8
|
||||
impl.dcp_rank = 3
|
||||
impl.cp_kv_cache_interleave_size = 1
|
||||
impl._flattened_decode_metadata = MethodType(
|
||||
flashinfer_mla.FlashInferMLAImpl._flattened_decode_metadata, impl
|
||||
)
|
||||
|
||||
num_reqs, query_len = 2, 3
|
||||
num_tokens = num_reqs * query_len
|
||||
block_table = torch.tensor([[10], [20]], dtype=torch.int32)
|
||||
seq_lens = torch.tensor([4, 5], dtype=torch.int32)
|
||||
global_causal_seq_lens = torch.tensor([31, 35], dtype=torch.int32)
|
||||
attn_metadata = MagicMock()
|
||||
attn_metadata.causal = causal
|
||||
attn_metadata.num_decode_tokens = num_tokens
|
||||
attn_metadata.num_decodes = num_reqs
|
||||
attn_metadata.max_seq_len = 9
|
||||
attn_metadata.decode.block_table = block_table
|
||||
attn_metadata.decode.seq_lens = seq_lens
|
||||
attn_metadata.decode.dcp_tot_seq_lens = global_causal_seq_lens
|
||||
attn_metadata.decode.max_query_len = query_len
|
||||
attn_metadata.decode.query_start_loc = torch.arange(
|
||||
0, num_tokens + 1, query_len, dtype=torch.int32
|
||||
)
|
||||
attn_metadata.decode.query_len = 0
|
||||
|
||||
query = torch.ones(num_tokens, 24, 576, dtype=torch.bfloat16)
|
||||
kv_cache = torch.ones(2, 128, 576, dtype=torch.bfloat16)
|
||||
kernel_batch = num_reqs if causal else num_tokens
|
||||
kernel_query_len = query_len if causal else 1
|
||||
kernel = MagicMock(
|
||||
return_value=(
|
||||
torch.ones(
|
||||
kernel_batch,
|
||||
kernel_query_len,
|
||||
24,
|
||||
512,
|
||||
dtype=torch.bfloat16,
|
||||
),
|
||||
torch.ones(
|
||||
kernel_batch,
|
||||
kernel_query_len,
|
||||
24,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(flashinfer_mla, "_get_workspace_buffer", MagicMock())
|
||||
monkeypatch.setattr(flashinfer_mla, "trtllm_batch_decode_with_kv_cache_mla", kernel)
|
||||
|
||||
output, lse = flashinfer_mla.FlashInferMLAImpl.forward_mqa(
|
||||
impl, query, kv_cache, attn_metadata, MagicMock()
|
||||
)
|
||||
|
||||
call = kernel.call_args.kwargs
|
||||
assert call["query"].shape == (kernel_batch, kernel_query_len, 24, 576)
|
||||
expected_block_table = (
|
||||
block_table if causal else block_table.repeat_interleave(query_len, dim=0)
|
||||
)
|
||||
expected_seq_lens = seq_lens if causal else seq_lens.repeat_interleave(query_len)
|
||||
expected_global_seq_lens = (
|
||||
global_causal_seq_lens
|
||||
if causal
|
||||
else global_causal_seq_lens.repeat_interleave(query_len)
|
||||
)
|
||||
torch.testing.assert_close(call["block_tables"], expected_block_table)
|
||||
torch.testing.assert_close(call["seq_lens"], expected_seq_lens)
|
||||
assert call["backend"] == "cute-dsl"
|
||||
assert call["enable_dcp"] is True
|
||||
assert call["cp_world"] == 8
|
||||
assert call["cp_rank"] == 3
|
||||
torch.testing.assert_close(
|
||||
call["causal_seqlens_kv_global"], expected_global_seq_lens
|
||||
)
|
||||
assert "multi_ctas_kv_counter_buffer" not in call
|
||||
assert flashinfer_mla.FlashInferMLAImpl.lse_base_on_e
|
||||
assert output.shape == (num_tokens, 24, 512)
|
||||
assert lse is not None and lse.shape == (num_tokens, 24)
|
||||
@@ -1,563 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for the FlashInfer SM90 sparse MLA backend wiring and index packing.
|
||||
|
||||
The FlashInfer wrapper and top-k conversion are replaced by CPU recorders;
|
||||
the tests pin the contract between the impl and the kernel API: page_size=1
|
||||
varlen rows, reserved-buffer refresh, plan parameters (dims, NoPE/rope scale,
|
||||
causality), ckv/kpe cache splitting, and the backend's model-shape gates.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
# isort: off
|
||||
import vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90 as sm90_mod
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90 import (
|
||||
FlashInferMLASparseSM90Backend,
|
||||
FlashInferMLASparseSM90Builder,
|
||||
FlashInferMLASparseSM90Impl,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
# isort: on
|
||||
|
||||
BLOCK_SIZE = 64
|
||||
HEAD = 512
|
||||
TOPK = 128 # triton convert requires width % 128 == 0
|
||||
|
||||
|
||||
def ref_convert(req_id, block_table, token_indices, BLOCK_SIZE=64, **kw):
|
||||
out = torch.full_like(token_indices, -1)
|
||||
counts = torch.zeros(token_indices.shape[0], dtype=torch.int32)
|
||||
for t in range(token_indices.shape[0]):
|
||||
vals = []
|
||||
for j in range(token_indices.shape[1]):
|
||||
pos = int(token_indices[t, j])
|
||||
if pos == -1:
|
||||
continue
|
||||
blk = int(block_table[int(req_id[t]), pos // BLOCK_SIZE])
|
||||
if blk < 0:
|
||||
continue
|
||||
vals.append(blk * kw["BLOCK_STRIDE_ROWS"] + pos % BLOCK_SIZE)
|
||||
out[t, : len(vals)] = torch.tensor(vals, dtype=out.dtype)
|
||||
counts[t] = len(vals)
|
||||
return out, counts
|
||||
|
||||
|
||||
class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.plan_args = None
|
||||
self.run_args = None
|
||||
self._plan_info: Any = None
|
||||
self._planned_backend: Any = None
|
||||
|
||||
def plan(self, *args, **kwargs):
|
||||
self.plan_args = (args, kwargs)
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
q_nope, q_pe, ckv, kpe = args
|
||||
self.run_args = (q_nope, q_pe, ckv, kpe, kwargs)
|
||||
return torch.zeros(
|
||||
q_nope.shape[0], q_nope.shape[1], ckv.shape[-1], dtype=torch.bfloat16
|
||||
)
|
||||
|
||||
|
||||
class FakeState:
|
||||
def __init__(self, width, max_tokens=64):
|
||||
self.kv_indices = torch.zeros(max_tokens * width, dtype=torch.int32)
|
||||
self.kv_len_arr = torch.zeros(max_tokens, dtype=torch.int32)
|
||||
self.kv_indptr = torch.zeros(max_tokens + 1, dtype=torch.int32)
|
||||
self.wrapper = FakeWrapper()
|
||||
self.plan_calls = []
|
||||
self.index_topk = 2048
|
||||
self.index_kpool = 4
|
||||
self.max_valid = 2051
|
||||
|
||||
def plan(self, num_tokens, kv_lens, cam, req_id_per_token):
|
||||
self.plan_calls.append((num_tokens, kv_lens))
|
||||
|
||||
def pack_indices(self, slots):
|
||||
for row in range(slots.shape[0]):
|
||||
start, end = self.kv_indptr[row : row + 2].tolist()
|
||||
self.kv_indices[start:end] = slots[row, : end - start].clamp(min=0)
|
||||
|
||||
|
||||
def make_impl(qk_rope, kv_dtype="fp8_e4m3", num_heads=2, topk_width=TOPK):
|
||||
impl = object.__new__(FlashInferMLASparseSM90Impl)
|
||||
impl.num_heads = num_heads
|
||||
impl.head_size = HEAD + qk_rope
|
||||
impl.scale = (HEAD + qk_rope) ** -0.5
|
||||
impl.kv_lora_rank = HEAD
|
||||
impl.qk_rope_head_dim = qk_rope
|
||||
impl.kv_cache_dtype = kv_dtype
|
||||
impl.use_fp8_kv_cache = kv_dtype in ("fp8", "fp8_e4m3")
|
||||
rows = 4
|
||||
impl.topk_indices_buffer = torch.full((rows, topk_width), -1, dtype=torch.int32)
|
||||
return impl, rows
|
||||
|
||||
|
||||
def make_batch(rows, topk_rows, own_blocks):
|
||||
req_id = torch.tensor([0] * rows, dtype=torch.int32)
|
||||
block_table = torch.zeros(1, 16, dtype=torch.int32)
|
||||
block_table[:, 0] = own_blocks[0]
|
||||
topk = torch.full((rows, TOPK), -1, dtype=torch.int32)
|
||||
for t, row in enumerate(topk_rows):
|
||||
topk[t, : len(row)] = torch.tensor(row, dtype=torch.int32)
|
||||
return SimpleNamespace(
|
||||
req_id_per_token=req_id, block_table=block_table, block_size=BLOCK_SIZE
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("qk_rope,kv_dtype", [(0, "fp8_e4m3"), (64, "auto")])
|
||||
def test_forward_wiring(monkeypatch, qk_rope, kv_dtype):
|
||||
impl, rows = make_impl(qk_rope, kv_dtype)
|
||||
state = FakeState(TOPK)
|
||||
monkeypatch.setattr(
|
||||
sm90_mod, "triton_convert_req_index_to_global_index", ref_convert
|
||||
)
|
||||
|
||||
# req with context 10 < topk: 8 valid + -1 padding.
|
||||
topk_rows = [
|
||||
[7, 3, 1, 9, 0, 2, 5, 8] + [-1] * (TOPK - 8),
|
||||
[4, 0, 2, 3, 1] + [-1] * (TOPK - 5),
|
||||
[6, 5, 4] + [-1] * (TOPK - 3),
|
||||
[2] + [-1] * (TOPK - 1),
|
||||
]
|
||||
impl.topk_indices_buffer.copy_(torch.tensor(topk_rows, dtype=torch.int32))
|
||||
state.kv_indptr[1:5] = torch.tensor([8, 13, 16, 17], dtype=torch.int32)
|
||||
state.kv_indptr[5:] = 17
|
||||
meta = make_batch(rows, topk_rows, [3])
|
||||
meta.state = state
|
||||
q_nope = torch.randn(rows, impl.num_heads, HEAD)
|
||||
q_rope = torch.randn(rows, impl.num_heads, qk_rope)
|
||||
dtype = torch.uint8 if impl.use_fp8_kv_cache else torch.bfloat16
|
||||
cache = torch.zeros(8, 2, BLOCK_SIZE, impl.head_size, dtype=dtype)[:, 0]
|
||||
|
||||
out, lse = impl.forward_mqa(
|
||||
(q_nope, q_rope), cache, meta, SimpleNamespace(_k_scale_float=0.5)
|
||||
)
|
||||
assert lse is None and out.shape == (rows, impl.num_heads, HEAD)
|
||||
|
||||
# Reserved buffers carry this step's slots; lengths are NOT refreshed
|
||||
# here (the builder plans them host-side before capture/replay).
|
||||
ref_slots, ref_counts = ref_convert(
|
||||
meta.req_id_per_token,
|
||||
meta.block_table,
|
||||
impl.topk_indices_buffer,
|
||||
BLOCK_STRIDE_ROWS=2 * BLOCK_SIZE,
|
||||
)
|
||||
offset = 0
|
||||
for t in range(rows):
|
||||
k = int(ref_counts[t])
|
||||
assert (
|
||||
state.kv_indices[offset : offset + k].tolist() == ref_slots[t, :k].tolist()
|
||||
)
|
||||
offset += k
|
||||
assert state.plan_calls == []
|
||||
|
||||
assert state.wrapper.run_args is not None
|
||||
q_pe, ckv, kpe, kwargs = state.wrapper.run_args[1:]
|
||||
assert q_pe.shape == (rows, impl.num_heads, qk_rope)
|
||||
assert ckv.shape == ((8 - 1) * 2 * BLOCK_SIZE + BLOCK_SIZE, 1, HEAD)
|
||||
assert kpe.shape[-1] == qk_rope
|
||||
if impl.use_fp8_kv_cache:
|
||||
assert kwargs["ckv_scale"] == 0.5 and kwargs["kpe_scale"] == 1.0
|
||||
else:
|
||||
assert kwargs == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_mha", [False, True])
|
||||
@pytest.mark.parametrize("num_decodes", [0, 1])
|
||||
def test_builder_plans_only_rows_dispatched_to_mqa(monkeypatch, use_mha, num_decodes):
|
||||
"""MHA prefill rows must not make the MQA kernel read beyond its query."""
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
builder._adaptive_verification = False
|
||||
builder.state = FakeState(TOPK)
|
||||
builder._attention_layer = SimpleNamespace(_use_sparse_mha=lambda _: use_mha)
|
||||
metadata = object.__new__(sm90_mod.FlashInferMLASparseSM90Metadata)
|
||||
metadata.state = None
|
||||
metadata.req_id_per_token = None
|
||||
metadata.num_prefills = 1
|
||||
metadata.num_decode_tokens = num_decodes
|
||||
monkeypatch.setattr(
|
||||
sm90_mod.FlashInferMLASparseMetadataBuilder,
|
||||
"build",
|
||||
lambda *_args, **_kwargs: metadata,
|
||||
)
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=num_decodes + 1,
|
||||
query_start_loc_cpu=torch.tensor(
|
||||
[0, 1, 6] if num_decodes else [0, 5], dtype=torch.int32
|
||||
),
|
||||
seq_lens_cpu_upper_bound=torch.tensor(
|
||||
[1402, 5] if num_decodes else [5], dtype=torch.int32
|
||||
),
|
||||
positions=None,
|
||||
)
|
||||
|
||||
result = builder.build(0, cam)
|
||||
|
||||
assert result.state is builder.state
|
||||
expected_lens = [1402] if num_decodes else []
|
||||
if not use_mha:
|
||||
expected_lens += [1, 2, 3, 4, 5]
|
||||
assert builder.state.plan_calls[0][0] == len(expected_lens)
|
||||
assert builder.state.plan_calls[0][1].tolist() == expected_lens
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_dtype", [torch.bfloat16, torch.float8_e4m3fn])
|
||||
def test_plan_uses_state_params(monkeypatch, kv_dtype):
|
||||
"""The NoPE/rope dims and scale live on the builder state, not the layer.
|
||||
|
||||
Without a device batch layout plan() takes exact per-row KV lengths and
|
||||
rebuilds the schedule on every call; the indptrs are always full-size
|
||||
with zero-query padding rows past num_tokens. An fp8 cache plans as
|
||||
float8_e4m3fn.
|
||||
"""
|
||||
wrapper = FakeWrapper()
|
||||
plan_info = [0] * sm90_mod._PLAN_INFO_LEN
|
||||
plan_info[sm90_mod._PI_KV_INDPTR] = 64 * 4
|
||||
wrapper._plan_info = torch.tensor(plan_info)
|
||||
wrapper._planned_backend = SimpleNamespace(
|
||||
_int_workspace_buffer=torch.zeros(64, dtype=torch.int32)
|
||||
)
|
||||
state = sm90_mod._SM90State.__new__(sm90_mod._SM90State)
|
||||
state.device = torch.device("cpu")
|
||||
state.wrapper = wrapper
|
||||
state.num_heads = 4
|
||||
state.kv_dtype = kv_dtype
|
||||
state.kv_lora_rank = HEAD
|
||||
state.qk_rope_head_dim = 64
|
||||
state.sm_scale = 576**-0.5
|
||||
state.max_tokens = 4
|
||||
state.topk_width = TOPK
|
||||
state.kv_indices = torch.zeros(4 * TOPK)
|
||||
state._arange_cpu = torch.arange(5, dtype=torch.int32)
|
||||
state._qo_cpu = torch.empty(5, dtype=torch.int32)
|
||||
state._kv_cpu = torch.empty(5, dtype=torch.int32)
|
||||
state._lens_cpu = torch.full((4,), TOPK, dtype=torch.int32)
|
||||
state._saved_kv_end = torch.empty(0, dtype=torch.int32)
|
||||
|
||||
state.plan(3, torch.tensor([2, 5, 7], dtype=torch.int32), None, None)
|
||||
assert wrapper.plan_args is not None
|
||||
args, kwargs = wrapper.plan_args
|
||||
(qo, kv, indices, kv_len, heads, ckv, kpe, page, causal, scale) = args
|
||||
assert qo.tolist() == [0, 1, 2, 3, 3] # clamp: rows past 3 have no queries
|
||||
assert kv.tolist() == [0, 2, 7, 14, 14]
|
||||
assert kv_len.tolist() == [2, 5, 7, 0]
|
||||
assert (heads, ckv, kpe, page, causal) == (4, HEAD, 64, 1, False)
|
||||
assert scale == 576**-0.5
|
||||
assert kwargs["q_data_type"] == torch.bfloat16
|
||||
assert kwargs["kv_data_type"] == kv_dtype
|
||||
|
||||
# Replanning a smaller batch must clear the previous rows' lengths.
|
||||
state.plan(1, torch.tensor([TOPK], dtype=torch.int32), None, None)
|
||||
assert state._kv_cpu.tolist() == [0, TOPK, TOPK, TOPK, TOPK]
|
||||
assert state._lens_cpu.tolist() == [TOPK, 0, 0, 0]
|
||||
state.plan(0, torch.empty(0, dtype=torch.int32), None, None)
|
||||
assert state._kv_cpu.tolist() == [0, 0, 0, 0, 0]
|
||||
assert state._lens_cpu.tolist() == [0, 0, 0, 0]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA")
|
||||
@pytest.mark.parametrize("width", [128, 2048, 2176])
|
||||
def test_pack_indices_replays_with_updated_offsets(width):
|
||||
"""Graph replay packs exact prefixes after row lengths and slots change."""
|
||||
state = sm90_mod._SM90State.__new__(sm90_mod._SM90State)
|
||||
state.kv_indptr = torch.zeros(5, dtype=torch.int32, device="cuda")
|
||||
state.kv_indices = torch.full((4 * width,), -99, dtype=torch.int32, device="cuda")
|
||||
# Exercise a contiguous view with an unaligned starting address.
|
||||
slots = torch.arange(4 * width + 1, dtype=torch.int32, device="cuda")[1:]
|
||||
slots = slots.view(4, width)
|
||||
state.kv_indptr.copy_(torch.tensor([0, 1, 4, 4, 4]))
|
||||
state.pack_indices(slots)
|
||||
torch.accelerator.synchronize()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
state.pack_indices(slots)
|
||||
|
||||
for lengths in ([1, 3, 0, 0], [width, 0, 17, width - 1], [0, 0, 0, 0]):
|
||||
offsets = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()])
|
||||
state.kv_indptr.copy_(offsets)
|
||||
state.kv_indices.fill_(-99)
|
||||
slots.add_(1)
|
||||
graph.replay()
|
||||
expected = torch.cat(
|
||||
[slots[row, :length] for row, length in enumerate(lengths)]
|
||||
)
|
||||
torch.testing.assert_close(state.kv_indices[: expected.numel()], expected)
|
||||
assert (state.kv_indices[expected.numel() :] == -99).all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("adaptive", [False, True])
|
||||
def test_kv_lens_host_formula(adaptive):
|
||||
"""Per-row host lengths: context == position + 1; capped at
|
||||
index_topk + trailing-pool remainder past the sparse threshold.
|
||||
|
||||
Exact (synced) without a host upper bound; with one, a sync-free bound
|
||||
capped at the largest valid count, which the plan clamps on device.
|
||||
"""
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
builder.state = FakeState(TOPK)
|
||||
builder._adaptive_verification = adaptive
|
||||
seq_lens = torch.tensor([100, 9, 3000], dtype=torch.int32)
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=3,
|
||||
query_start_loc_cpu=torch.tensor([0, 5, 7, 10], dtype=torch.int32),
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
)
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 10 and exact
|
||||
# req0: positions 95..99 -> ctx 96..100 (all <= 2048: full context)
|
||||
# req1: positions 7,8 -> ctx 8,9
|
||||
# req2: positions 2997..2999 -> ctx 2998..3000 (> 2048: topk + ctx%4)
|
||||
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2050, 2051, 2048]
|
||||
|
||||
cam.seq_lens_cpu_upper_bound = seq_lens
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 10 and not exact
|
||||
if adaptive:
|
||||
# Host query split may differ from the device one: batch-wide bound.
|
||||
assert lens.tolist() == [2051] * 10
|
||||
else:
|
||||
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2051, 2051, 2051]
|
||||
|
||||
|
||||
def test_kv_lens_host_empty():
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=0,
|
||||
query_start_loc_cpu=torch.tensor([0], dtype=torch.int32),
|
||||
seq_lens=torch.zeros(0, dtype=torch.int32),
|
||||
)
|
||||
num_rows, lens, _ = builder._kv_lens_host(cam)
|
||||
assert num_rows == 0 and lens.numel() == 0
|
||||
|
||||
|
||||
_NO_KPOOL = object()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"spec_dtype,expected_kv_dtype",
|
||||
[
|
||||
(torch.bfloat16, torch.bfloat16),
|
||||
(torch.uint8, torch.float8_e4m3fn),
|
||||
],
|
||||
ids=["bf16", "fp8"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"index_kpool,prefill_lens",
|
||||
[
|
||||
(4, [2048, 2049, 2050, 2051]),
|
||||
(None, [2048] * 4),
|
||||
(_NO_KPOOL, [2048] * 4),
|
||||
],
|
||||
ids=["kpool4", "kpool_none", "no_kpool_attr"],
|
||||
)
|
||||
def test_builder_kpool_from_model_config(
|
||||
monkeypatch, index_kpool, prefill_lens, spec_dtype, expected_kv_dtype
|
||||
):
|
||||
"""The builder took kpool from the KV cache spec, whose tokens_per_state is
|
||||
1, so the tail pool was never read. The state plans the cache's logical
|
||||
dtype: uint8 fp8 storage becomes float8_e4m3fn."""
|
||||
monkeypatch.setattr(
|
||||
sm90_mod.FlashInferMLASparseMetadataBuilder,
|
||||
"__init__",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
class _RecordingState:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.kv_dtype = args[2]
|
||||
self.index_topk = kwargs["index_topk"]
|
||||
self.index_kpool = kwargs["index_kpool"]
|
||||
|
||||
monkeypatch.setattr(sm90_mod, "_SM90State", _RecordingState)
|
||||
impl, _ = make_impl(64)
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=BLOCK_SIZE, num_kv_heads=1, head_size=576, dtype=spec_dtype
|
||||
)
|
||||
assert spec.tokens_per_state == 1
|
||||
hf_config = SimpleNamespace(index_topk=2048)
|
||||
if index_kpool is not _NO_KPOOL:
|
||||
hf_config.index_kpool = index_kpool
|
||||
vllm_config = SimpleNamespace(
|
||||
compilation_config=SimpleNamespace(
|
||||
static_forward_context={"attn": SimpleNamespace(impl=impl)}
|
||||
),
|
||||
scheduler_config=SimpleNamespace(
|
||||
max_num_batched_tokens=64, async_scheduling=False
|
||||
),
|
||||
model_config=SimpleNamespace(hf_text_config=hf_config),
|
||||
speculative_config=None,
|
||||
)
|
||||
builder = FlashInferMLASparseSM90Builder(
|
||||
spec, ["attn"], vllm_config, torch.device("cpu")
|
||||
)
|
||||
assert builder.state.kv_dtype == expected_kv_dtype
|
||||
# req0: prefill chunk ending at context 42295; req1: context <= topk.
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=2,
|
||||
query_start_loc_cpu=torch.tensor([0, 4, 6], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([42295, 100], dtype=torch.int32),
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
)
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 6 and exact
|
||||
assert lens.tolist() == prefill_lens + [99, 100]
|
||||
|
||||
|
||||
def _sm90_flashinfer_available():
|
||||
return (
|
||||
torch.cuda.is_available()
|
||||
and torch.cuda.get_device_capability()[0] == 9
|
||||
and sm90_mod.has_flashinfer_sm90_nope_mla()
|
||||
)
|
||||
|
||||
|
||||
SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH = 16, 2048, 4, 2176
|
||||
|
||||
|
||||
def _real_state(rows):
|
||||
return sm90_mod._SM90State(
|
||||
torch.device("cuda"),
|
||||
SM90_HEADS,
|
||||
torch.bfloat16,
|
||||
rows,
|
||||
SM90_WIDTH,
|
||||
HEAD,
|
||||
0,
|
||||
HEAD**-0.5,
|
||||
SM90_TOPK,
|
||||
SM90_KPOOL,
|
||||
)
|
||||
|
||||
|
||||
def _clamp_batch(num_reqs, q_per_req, lo, hi, topk, kpool, width):
|
||||
"""Random batch: per-row contexts, device layout, and top-k slots."""
|
||||
last = torch.randint(lo + q_per_req, hi, (num_reqs,))
|
||||
ctx = (last[:, None] + torch.arange(1 - q_per_req, 1)).reshape(-1)
|
||||
valid = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
|
||||
cam = SimpleNamespace(
|
||||
seq_lens=last.to(torch.int32).cuda(),
|
||||
query_start_loc=(torch.arange(num_reqs + 1) * q_per_req).to(torch.int32).cuda(),
|
||||
)
|
||||
req_id = torch.arange(num_reqs, dtype=torch.int32).repeat_interleave(q_per_req)
|
||||
slots = torch.randint(0, 1 << 16, (ctx.numel(), width), dtype=torch.int32)
|
||||
slots[torch.arange(width) >= valid[:, None]] = -1
|
||||
return ctx, valid.to(torch.int32), cam, req_id.cuda(), slots.cuda()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"num_reqs,q_per_req,lo,hi",
|
||||
[
|
||||
(64, 1, 1, 3000),
|
||||
(16, 6, 2030, 2070), # MTP-style rows straddling index_topk
|
||||
(4096, 1, 1, 3000), # clamp spans several program blocks
|
||||
],
|
||||
)
|
||||
def test_upper_bound_plan_matches_exact(num_reqs, q_per_req, lo, hi):
|
||||
"""Sync-free planning from optimistic host bounds (async spec decode)
|
||||
must match exact planning: the device clamp trims every work item back
|
||||
to its row's valid count, so no -1 slot is read."""
|
||||
torch.manual_seed(0)
|
||||
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
|
||||
ctx, valid, cam, req_id, slots = _clamp_batch(
|
||||
num_reqs, q_per_req, lo, hi, topk, kpool, width
|
||||
)
|
||||
rows = ctx.numel()
|
||||
|
||||
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
q_pe = q.new_empty(rows, heads, 0)
|
||||
|
||||
def run(state):
|
||||
state.pack_indices(slots)
|
||||
return state.wrapper.run(q, q_pe, kv, kv[..., :0])
|
||||
|
||||
exact = _real_state(rows)
|
||||
exact.plan(rows, valid, None, None)
|
||||
ub = _real_state(rows)
|
||||
host_bound = torch.clamp(ctx + torch.randint(0, 7, (rows,)), max=ub.max_valid)
|
||||
ub.plan(rows, host_bound, cam, req_id)
|
||||
out = run(ub)
|
||||
assert not out.isnan().any()
|
||||
torch.testing.assert_close(out, run(exact), atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
|
||||
)
|
||||
def test_upper_bound_plan_reused_across_steps(monkeypatch):
|
||||
"""Growing contexts (draft/decode steps) reuse the padded plan and only
|
||||
re-clamp on device, matching an exact replan every step."""
|
||||
torch.manual_seed(0)
|
||||
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
|
||||
rows = 48
|
||||
ctx, _, _, req_id, _ = _clamp_batch(rows, 1, 1, 3000, topk, kpool, width)
|
||||
|
||||
exact, ub = _real_state(rows), _real_state(rows)
|
||||
replans: list[int] = []
|
||||
plan_fn = ub._plan
|
||||
|
||||
def counting_plan(num_tokens, kv_lens):
|
||||
replans.append(num_tokens)
|
||||
plan_fn(num_tokens, kv_lens)
|
||||
|
||||
monkeypatch.setattr(ub, "_plan", counting_plan)
|
||||
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
for step in range(5):
|
||||
step_ctx = ctx + step
|
||||
valid = torch.where(step_ctx <= topk, step_ctx, topk + step_ctx % kpool)
|
||||
slots = torch.randint(0, 1 << 16, (rows, width), dtype=torch.int32)
|
||||
slots[torch.arange(width) >= valid[:, None]] = -1
|
||||
slots = slots.cuda()
|
||||
cam = SimpleNamespace(
|
||||
seq_lens=step_ctx.to(torch.int32).cuda(),
|
||||
query_start_loc=torch.arange(rows + 1, dtype=torch.int32).cuda(),
|
||||
)
|
||||
num_plans = len(replans)
|
||||
ub.plan(rows, torch.clamp(step_ctx + 5, max=ub.max_valid), cam, req_id)
|
||||
assert len(replans) - num_plans == (1 if step == 0 else 0)
|
||||
exact.plan(rows, valid.to(torch.int32), None, None)
|
||||
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
outs = []
|
||||
for state in (ub, exact):
|
||||
state.pack_indices(slots)
|
||||
outs.append(state.wrapper.run(q, q[..., :0], kv, kv[..., :0]))
|
||||
torch.testing.assert_close(outs[0], outs[1], atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
def test_supports_combination_gates(monkeypatch, default_vllm_config):
|
||||
monkeypatch.setattr(sm90_mod, "has_flashinfer_sm90_nope_mla", lambda: True)
|
||||
call = lambda **kw: FlashInferMLASparseSM90Backend.supports_combination(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="fp8_e4m3",
|
||||
block_size=64,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
device_capability=SimpleNamespace(major=9),
|
||||
**kw,
|
||||
)
|
||||
assert call() is None # no model config: only the feature gate applies
|
||||
|
||||
import vllm.config as cfg
|
||||
|
||||
monkeypatch.setattr(
|
||||
cfg,
|
||||
"get_current_vllm_config",
|
||||
lambda: SimpleNamespace(model_config=None),
|
||||
)
|
||||
assert call() is None
|
||||
monkeypatch.setattr(sm90_mod, "has_flashinfer_sm90_nope_mla", lambda: False)
|
||||
assert "requires FlashInfer" in (call() or "")
|
||||
@@ -1,94 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Behavior checks for FlashInfer SM120 sparse MLA backend selection."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.models.deepseek_v4.nvidia.flashinfer_sparse import (
|
||||
_required_sm120_sparse_topk,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.utils import flashinfer as fi_utils
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseSM120Backend,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
|
||||
def _fake_vllm_config(model_type: str) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
hf_text_config=SimpleNamespace(model_type=model_type, index_topk=2048),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_sm120_backend_uses_dedicated_backend_name() -> None:
|
||||
assert FlashInferMLASparseSM120Backend.get_name() == "FLASHINFER_MLA_SPARSE_SM120"
|
||||
assert (
|
||||
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM120.get_class()
|
||||
is FlashInferMLASparseSM120Backend
|
||||
)
|
||||
|
||||
|
||||
def test_sm120_backend_uses_sparse_mqa_for_prefill() -> None:
|
||||
impl_cls = FlashInferMLASparseSM120Backend.get_impl_cls()
|
||||
|
||||
assert impl_cls.is_sparse
|
||||
assert not impl_cls.supports_dense_mha_prefill
|
||||
|
||||
|
||||
def test_v32_glm_sm120_backend_accepts_glm_block_size(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(fi_utils, "has_flashinfer_sparse_mla_sm120", lambda: True)
|
||||
|
||||
with set_current_vllm_config(_fake_vllm_config("glm4_moe")):
|
||||
invalid_reasons = FlashInferMLASparseSM120Backend.validate_configuration(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="fp8",
|
||||
block_size=256,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
use_per_head_quant_scales=False,
|
||||
device_capability=DeviceCapability(12, 0),
|
||||
attn_type="decoder",
|
||||
)
|
||||
|
||||
assert invalid_reasons == []
|
||||
|
||||
|
||||
def test_sm120_dsv4_capability_checks_exact_dispatch_shape(monkeypatch) -> None:
|
||||
fake_module = SimpleNamespace(
|
||||
_DECODE_DSV4_DISPATCH=frozenset({(32, 128), (32, 192)})
|
||||
)
|
||||
monkeypatch.setattr(fi_utils, "has_flashinfer_sparse_mla_sm120", lambda: True)
|
||||
monkeypatch.setattr(fi_utils, "_get_submodule", lambda _name: fake_module)
|
||||
fi_utils.has_flashinfer_sparse_mla_sm120_config.cache_clear()
|
||||
|
||||
assert fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 128)
|
||||
assert fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 192)
|
||||
assert not fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 256)
|
||||
assert not fi_utils.has_flashinfer_sparse_mla_sm120_config(16, 192)
|
||||
|
||||
fi_utils.has_flashinfer_sparse_mla_sm120_config.cache_clear()
|
||||
|
||||
|
||||
def test_sm120_dsv4_required_topk_tracks_dspark_width() -> None:
|
||||
causal = SimpleNamespace(
|
||||
attention_config=SimpleNamespace(use_non_causal=False),
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=5),
|
||||
)
|
||||
dspark = SimpleNamespace(
|
||||
attention_config=SimpleNamespace(use_non_causal=True),
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=5),
|
||||
)
|
||||
|
||||
assert _required_sm120_sparse_topk(causal, 128) == 128
|
||||
assert _required_sm120_sparse_topk(dspark, 128) == 192
|
||||
@@ -1,166 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU-only tests for FlashInfer sparse MLA backend constraints."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
_DEFAULT_WORKSPACE_BUFFER_SIZE,
|
||||
FlashInferMLASparseTRTLLMBackend,
|
||||
_required_workspace_bytes,
|
||||
compute_trtllm_sparse_mla_workspace_bytes,
|
||||
)
|
||||
|
||||
# Reporter config from vllm#50781: GLM-5.2 (64 q heads), TP=8, DCP=8,
|
||||
# max_num_batched_tokens=16384, FlashInfer 0.6.14.
|
||||
_REPORTER_HEADS_PER_RANK = 64 // 8
|
||||
_REPORTER_DCP = 8
|
||||
_REPORTER_MAX_TOKENS = 16384
|
||||
# From the reported crash: trtllm-gen requested exactly this many bytes for
|
||||
# trtllm_gen_softmax_workspace after an 8 MiB counter carve had left
|
||||
# 404,750,336 of the 413,138,944-byte default buffer.
|
||||
_REPORTER_OBSERVED_SOFTMAX_BYTES = 1_611_661_312
|
||||
_REPORTER_OBSERVED_PRECARVE_BYTES = 8_388_608
|
||||
|
||||
|
||||
def test_reporter_softmax_carve_is_reproduced_byte_exactly():
|
||||
# The crashing step scheduled 12288 tokens (a single 12K-token request);
|
||||
# the softmax slab formula must reproduce the kernel's request exactly:
|
||||
# 8 * (8 heads/rank * 8 dcp) * 12288 tokens * 256 + 1 MiB guard.
|
||||
softmax_bytes = compute_trtllm_sparse_mla_workspace_bytes(
|
||||
base_workspace_bytes=0,
|
||||
dcp_world_size=_REPORTER_DCP,
|
||||
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
|
||||
max_num_batched_tokens=12288,
|
||||
)
|
||||
assert softmax_bytes == _REPORTER_OBSERVED_SOFTMAX_BYTES
|
||||
|
||||
|
||||
def test_reporter_config_covers_observed_overflow():
|
||||
computed = compute_trtllm_sparse_mla_workspace_bytes(
|
||||
base_workspace_bytes=_DEFAULT_WORKSPACE_BUFFER_SIZE,
|
||||
dcp_world_size=_REPORTER_DCP,
|
||||
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
|
||||
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
|
||||
)
|
||||
assert computed >= (
|
||||
_REPORTER_OBSERVED_SOFTMAX_BYTES + _REPORTER_OBSERVED_PRECARVE_BYTES
|
||||
)
|
||||
|
||||
|
||||
def test_non_dcp_size_is_unchanged():
|
||||
computed = compute_trtllm_sparse_mla_workspace_bytes(
|
||||
base_workspace_bytes=_DEFAULT_WORKSPACE_BUFFER_SIZE,
|
||||
dcp_world_size=1,
|
||||
num_heads_per_rank=128,
|
||||
max_num_batched_tokens=65536,
|
||||
)
|
||||
assert computed == _DEFAULT_WORKSPACE_BUFFER_SIZE
|
||||
|
||||
|
||||
def test_combined_pcp_dcp_rejects_flashinfer_sparse():
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=4,
|
||||
decode_context_parallel_size=4,
|
||||
),
|
||||
model_config=None,
|
||||
)
|
||||
with patch("vllm.config.get_current_vllm_config", return_value=config):
|
||||
reason = FlashInferMLASparseTRTLLMBackend.supports_combination(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="fp8",
|
||||
block_size=64,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
device_capability=SimpleNamespace(major=10),
|
||||
)
|
||||
|
||||
assert reason is not None
|
||||
assert "use FLASHMLA_SPARSE" in reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pcp_size,dcp_size", [(4, 1), (1, 4)])
|
||||
def test_single_context_parallel_mode_allows_flashinfer_sparse(
|
||||
pcp_size: int, dcp_size: int
|
||||
):
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=pcp_size,
|
||||
decode_context_parallel_size=dcp_size,
|
||||
),
|
||||
model_config=None,
|
||||
)
|
||||
with patch("vllm.config.get_current_vllm_config", return_value=config):
|
||||
reason = FlashInferMLASparseTRTLLMBackend.supports_combination(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="fp8",
|
||||
block_size=64,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
device_capability=SimpleNamespace(major=10),
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
|
||||
|
||||
def test_default_constant_matches_envs_default(monkeypatch):
|
||||
from vllm import envs
|
||||
|
||||
monkeypatch.delenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", raising=False)
|
||||
assert _DEFAULT_WORKSPACE_BUFFER_SIZE == envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
|
||||
|
||||
|
||||
def test_env_unset_returns_computed(monkeypatch):
|
||||
monkeypatch.delenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", raising=False)
|
||||
required = _required_workspace_bytes(
|
||||
dcp_world_size=_REPORTER_DCP,
|
||||
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
|
||||
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
|
||||
)
|
||||
assert required == compute_trtllm_sparse_mla_workspace_bytes(
|
||||
_DEFAULT_WORKSPACE_BUFFER_SIZE,
|
||||
_REPORTER_DCP,
|
||||
_REPORTER_HEADS_PER_RANK,
|
||||
_REPORTER_MAX_TOKENS,
|
||||
)
|
||||
|
||||
|
||||
def test_env_override_below_computed_is_respected_with_warning(monkeypatch):
|
||||
override = 100 * 1024 * 1024
|
||||
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", str(override))
|
||||
with patch(
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse.logger"
|
||||
) as mock_logger:
|
||||
required = _required_workspace_bytes(
|
||||
dcp_world_size=_REPORTER_DCP,
|
||||
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
|
||||
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
|
||||
)
|
||||
assert required == override
|
||||
mock_logger.warning_once.assert_called_once()
|
||||
|
||||
|
||||
def test_env_override_above_computed_is_respected_without_warning(monkeypatch):
|
||||
override = 8 * 1024 * 1024 * 1024
|
||||
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", str(override))
|
||||
with patch(
|
||||
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse.logger"
|
||||
) as mock_logger:
|
||||
required = _required_workspace_bytes(
|
||||
dcp_world_size=_REPORTER_DCP,
|
||||
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
|
||||
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
|
||||
)
|
||||
assert required == override
|
||||
mock_logger.warning_once.assert_not_called()
|
||||
@@ -1,312 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU tests for the FlashMLA sparse backend NoPE-512 (GLM5Next) gates.
|
||||
|
||||
GLM5Next is rope-free MLA: qk_nope_head_dim=256, qk_rope_head_dim=0,
|
||||
v_head_dim=256, kv_lora_rank=512 -> head_size 512. These tests pin the
|
||||
selection contract only (no GPU required):
|
||||
|
||||
* ``get_supported_head_sizes`` advertises 512 so the backend is a candidate;
|
||||
* ``supports_combination`` admits 512 only for rope-free models on SM90, with
|
||||
a bf16 cache or an fp8_ds_mla cache (zero RoPE slot), and rejects
|
||||
everything else;
|
||||
* adding 512 must NOT reorder the SM100 priority list for bf16, which is why
|
||||
the bf16 arm is restricted to SM90.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.flashmla_sparse import (
|
||||
QUANTIZED_DS_MLA_CACHE_FORMATS,
|
||||
FlashMLASparseBackend,
|
||||
_fp8_kv_pages,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheTensor,
|
||||
KVQuantMode,
|
||||
MLAAttentionSpec,
|
||||
)
|
||||
from vllm.v1.worker.utils import (
|
||||
AttentionGroup,
|
||||
allocate_kv_cache,
|
||||
prepare_kernel_block_sizes,
|
||||
select_common_block_size,
|
||||
)
|
||||
|
||||
SM90 = DeviceCapability(major=9, minor=0)
|
||||
SM100 = DeviceCapability(major=10, minor=0)
|
||||
|
||||
BF16_CACHE_DTYPES = (None, "auto", "bfloat16", "float16")
|
||||
NOPE_SM90_CACHE_DTYPES = (*BF16_CACHE_DTYPES, "fp8_ds_mla")
|
||||
|
||||
|
||||
def _supports_combination(head_size, kv_cache_dtype, capability):
|
||||
return FlashMLASparseBackend.supports_combination(
|
||||
head_size,
|
||||
torch.bfloat16,
|
||||
kv_cache_dtype,
|
||||
64,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
device_capability=capability,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rope_free_model(monkeypatch):
|
||||
"""Patch get_current_vllm_config so the model looks like GLM5Next NoPE."""
|
||||
import vllm.config as cfg
|
||||
|
||||
monkeypatch.setattr(
|
||||
cfg,
|
||||
"get_current_vllm_config",
|
||||
lambda: SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
hf_text_config=SimpleNamespace(qk_rope_head_dim=0)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rope_carrying_model(monkeypatch):
|
||||
"""Patch get_current_vllm_config with a rope-carrying (576-style) model."""
|
||||
import vllm.config as cfg
|
||||
|
||||
monkeypatch.setattr(
|
||||
cfg,
|
||||
"get_current_vllm_config",
|
||||
lambda: SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
hf_text_config=SimpleNamespace(qk_rope_head_dim=64)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_supported_head_sizes_include_512():
|
||||
assert FlashMLASparseBackend.get_supported_head_sizes() == [576, 512]
|
||||
|
||||
|
||||
def test_flashmla_bf16_nope_accepts_packed_manager_blocks():
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1152,
|
||||
num_kv_heads=1,
|
||||
head_size=512,
|
||||
dtype=torch.bfloat16,
|
||||
cache_dtype_str="bfloat16",
|
||||
block_stride_alignment=1024,
|
||||
)
|
||||
num_blocks = 2
|
||||
layers = ["layer.0", "layer.1"]
|
||||
page_size = spec.page_size_bytes
|
||||
config = KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=num_blocks * len(layers) * page_size,
|
||||
layers=layers,
|
||||
layer_stride=page_size,
|
||||
block_stride=len(layers) * page_size,
|
||||
)
|
||||
],
|
||||
kv_cache_groups=[KVCacheGroupSpec(layers, spec)],
|
||||
)
|
||||
groups = [[AttentionGroup(FlashMLASparseBackend, layers, spec, 0)]]
|
||||
|
||||
kernel_block_sizes = prepare_kernel_block_sizes(config, groups)
|
||||
caches = allocate_kv_cache(
|
||||
config,
|
||||
torch.device("cpu"),
|
||||
KVCacheLayout.BLHNC,
|
||||
kernel_block_sizes,
|
||||
)
|
||||
|
||||
assert kernel_block_sizes == [1152]
|
||||
assert caches["layer.0"].shape == (num_blocks, 1, 1152, 512)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sm100", [False, True])
|
||||
def test_flashmla_quantized_cache_kernel_pages(monkeypatch, sm100):
|
||||
"""Quantized blocks are read as 64-token pages; SM100 only row-aligns them
|
||||
(TMA) and keeps 64-token blocks."""
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"is_device_capability_family",
|
||||
lambda family, device_id=0: sm100 and family == 100,
|
||||
)
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1152,
|
||||
num_kv_heads=1,
|
||||
head_size=576,
|
||||
dtype=torch.float8_e4m3fn,
|
||||
cache_dtype_str="fp8_ds_mla",
|
||||
kv_quant_mode=KVQuantMode.FP8_PER_TENSOR,
|
||||
state_content_bytes=656,
|
||||
)
|
||||
|
||||
kernel_block_size = 64 if sm100 else 1152
|
||||
assert (
|
||||
select_common_block_size(1152, [FlashMLASparseBackend], [spec])
|
||||
== kernel_block_size
|
||||
)
|
||||
|
||||
|
||||
def test_fp8_kv_pages_address_packed_blocks():
|
||||
"""Token t of block b is row b * block_stride_rows + t of the 64-row pages;
|
||||
64-token blocks are passed through."""
|
||||
row, block_size, stride_rows = 656, 128, 192
|
||||
backing = torch.arange(3 * stride_rows).repeat_interleave(row)
|
||||
cache = backing.view(3, stride_rows, row)[:, :block_size]
|
||||
|
||||
pages, block_stride_rows = _fp8_kv_pages(cache, block_size)
|
||||
assert block_stride_rows == stride_rows
|
||||
assert pages.shape[1:] == (64, row)
|
||||
slot = 2 * block_stride_rows + 100
|
||||
assert torch.equal(pages[slot // 64, slot % 64], cache[2, 100])
|
||||
|
||||
pages, block_stride_rows = _fp8_kv_pages(cache[:, :64], 64)
|
||||
assert block_stride_rows is None
|
||||
assert torch.equal(pages, cache[:, :64])
|
||||
|
||||
|
||||
def test_quantized_ds_mla_formats_are_the_envelope_set():
|
||||
assert frozenset({"fp8_ds_mla", "nvfp4_ds_mla"}) == QUANTIZED_DS_MLA_CACHE_FORMATS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
|
||||
def test_nope_512_sm90_rope_free_accepted(kv_cache_dtype, rope_free_model):
|
||||
assert _supports_combination(512, kv_cache_dtype, SM90) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
|
||||
def test_nope_512_sm90_rope_carrying_rejected(kv_cache_dtype, rope_carrying_model):
|
||||
reason = _supports_combination(512, kv_cache_dtype, SM90)
|
||||
assert reason is not None and "rope-free" in reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
|
||||
def test_nope_512_sm100_rejected(kv_cache_dtype, rope_free_model):
|
||||
# The SM90 restriction is what keeps the SM100 priority order unchanged.
|
||||
reason = _supports_combination(512, kv_cache_dtype, SM100)
|
||||
assert reason is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", ("fp8", "fp8_e4m3", "nvfp4_ds_mla"))
|
||||
def test_nope_512_other_quantized_rejected(kv_cache_dtype, rope_free_model):
|
||||
reason = _supports_combination(512, kv_cache_dtype, SM90)
|
||||
assert reason is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capability", [SM90, SM100], ids=["sm90", "sm100"])
|
||||
@pytest.mark.parametrize(
|
||||
"kv_cache_dtype",
|
||||
("auto", "bfloat16", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"),
|
||||
)
|
||||
def test_576_unchanged_for_all_dtypes(kv_cache_dtype, capability):
|
||||
# DeepSeek 576 must be untouched by the NoPE-512 gates, except for the
|
||||
# pre-existing SM100-only nvfp4 rule.
|
||||
reason = _supports_combination(576, kv_cache_dtype, capability)
|
||||
if kv_cache_dtype == "nvfp4_ds_mla" and capability.major != 10:
|
||||
assert reason is not None and "SM100" in reason
|
||||
else:
|
||||
assert reason is None, reason
|
||||
|
||||
|
||||
def _sparse_order(kv_cache_dtype, head_size, num_heads=32, capability=SM100):
|
||||
try:
|
||||
from vllm.platforms.cuda import _get_backend_priorities
|
||||
except ImportError as e: # pragma: no cover - depends on host
|
||||
pytest.skip(f"CUDA platform unavailable on this host: {e}")
|
||||
|
||||
priorities = _get_backend_priorities(
|
||||
use_mla=True,
|
||||
device_capability=capability,
|
||||
num_heads=num_heads,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
head_size=head_size,
|
||||
)
|
||||
sparse = {
|
||||
"FLASH_ATTN_MLA_SPARSE",
|
||||
"FLASH_ATTN_MLA_SPARSE_FA4",
|
||||
"FLASHMLA_SPARSE",
|
||||
"FLASHINFER_MLA_SPARSE",
|
||||
"FLASHINFER_MLA_SPARSE_SM90",
|
||||
}
|
||||
return [b.name for b in priorities if b.name in sparse]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_heads", [32, 64], ids=["tp2", "tp1"])
|
||||
def test_sm100_bf16_512_priority_unchanged(num_heads):
|
||||
"""Adding head_size 512 must not reorder the SM100 bf16 sparse list.
|
||||
|
||||
On SM100 with >16 heads the hardcoded bf16 order is
|
||||
[FLASHMLA_SPARSE, FLASHINFER_MLA_SPARSE] (FlashMLA first). head_size 512
|
||||
must leave this untouched (identical to the 576 order); the guard that
|
||||
keeps bf16-512 from *serving* through FlashMLA on SM100 lives in
|
||||
supports_combination (gated to SM90), tested separately.
|
||||
"""
|
||||
order512 = _sparse_order("auto", 512, num_heads=num_heads)
|
||||
order576 = _sparse_order("auto", 576, num_heads=num_heads)
|
||||
assert order512 == order576, order512
|
||||
assert order512[0] == "FLASHMLA_SPARSE", order512
|
||||
|
||||
|
||||
def test_sm100_576_priority_unchanged():
|
||||
order = _sparse_order("auto", 576, num_heads=32)
|
||||
assert order[0] == "FLASHMLA_SPARSE", order
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA backends")
|
||||
def test_sm90_nope_fp8_ds_mla_resolves_to_flashmla():
|
||||
"""The sparse backends ranked ahead of FLASHMLA_SPARSE for SM90 NoPE-512
|
||||
reject fp8_ds_mla, so the auto-selector lands on FlashMLA."""
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
order = _sparse_order("fp8_ds_mla", 512, num_heads=64, capability=SM90)
|
||||
for name in order[: order.index("FLASHMLA_SPARSE")]:
|
||||
backend_cls = AttentionBackendEnum[name].get_class()
|
||||
assert not backend_cls.supports_kv_cache_dtype("fp8_ds_mla"), name
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA backends")
|
||||
def test_sm100_576_bf16_low_heads_falls_back_from_fa4(monkeypatch):
|
||||
"""With FA4 unusable, low-head bf16 selection lands on FlashInfer."""
|
||||
import vllm.v1.attention.backends.mla.flashattn_mla_sparse as fa4_sparse
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
monkeypatch.setattr(fa4_sparse, "_fa4_cute_mla_available", lambda: "no FA4")
|
||||
|
||||
def reasons(name):
|
||||
backend_cls = AttentionBackendEnum[name].get_class()
|
||||
return backend_cls.validate_configuration(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=64,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
use_mm_prefix=False,
|
||||
use_per_head_quant_scales=False,
|
||||
device_capability=SM100,
|
||||
attn_type="decoder",
|
||||
)
|
||||
|
||||
order = _sparse_order("auto", 576, num_heads=16)
|
||||
with set_current_vllm_config(VllmConfig()):
|
||||
# The selector takes the first candidate with no rejection reasons.
|
||||
selected = next(name for name in order if not reasons(name))
|
||||
assert order[0] == "FLASH_ATTN_MLA_SPARSE_FA4", order
|
||||
assert selected == "FLASHINFER_MLA_SPARSE"
|
||||
@@ -1,40 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""GLM-5.3-Flash indexer kernel block sizes are DeepGEMM pool pages."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.mla import indexer
|
||||
from vllm.v1.attention.backends.mla.indexer import Glm5NextIndexerBackend
|
||||
|
||||
KPOOL = 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rocm,sm120,expected",
|
||||
[
|
||||
(False, False, [KPOOL * 32, KPOOL * 64]),
|
||||
# SM120 DeepGEMM takes only 64-entry pages for the fp8 cache.
|
||||
(False, True, [KPOOL * 64]),
|
||||
# ROCm's AITER paged-MQA logits take the same pool pages.
|
||||
(True, False, [KPOOL * 32, KPOOL * 64]),
|
||||
],
|
||||
)
|
||||
def test_glm5next_indexer_kernel_block_sizes(monkeypatch, rocm, sm120, expected):
|
||||
monkeypatch.setattr(current_platform, "is_rocm", lambda: rocm)
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"is_device_capability_family",
|
||||
lambda family: sm120 and family == 120,
|
||||
)
|
||||
model_config = SimpleNamespace(hf_text_config=SimpleNamespace(index_kpool=KPOOL))
|
||||
config = SimpleNamespace(model_config=model_config)
|
||||
monkeypatch.setattr(indexer, "get_current_vllm_config", lambda: config)
|
||||
|
||||
spec = SimpleNamespace(tokens_per_state=KPOOL)
|
||||
assert Glm5NextIndexerBackend.get_supported_kernel_block_sizes(spec) == expected
|
||||
# Platform block-size selection queries without a spec.
|
||||
assert Glm5NextIndexerBackend.get_supported_kernel_block_sizes() == expected
|
||||
@@ -1,131 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Attention metadata geometry must come from the builder's own group."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.cpu_attn import (
|
||||
CPUAttentionBackendImpl,
|
||||
CPUAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadataBuilder
|
||||
|
||||
requires_cpu = pytest.mark.skipif(
|
||||
not current_platform.is_cpu(), reason="CPU attention backend"
|
||||
)
|
||||
|
||||
# Laguna's shape: 48 query heads model-wide, 64 on its sliding layers, both
|
||||
# against 8 KV heads.
|
||||
MODEL_WIDE_NUM_HEADS = 48
|
||||
NUM_KV_HEADS = 8
|
||||
|
||||
|
||||
def _layers(layer_num_heads: list[int]):
|
||||
"""Stand-in attention layers, one per head count, as one attention group."""
|
||||
return {
|
||||
f"layer_{i}": SimpleNamespace(
|
||||
impl=MagicMock(
|
||||
spec=CPUAttentionBackendImpl,
|
||||
num_heads=num_heads,
|
||||
sliding_window=None,
|
||||
)
|
||||
)
|
||||
for i, num_heads in enumerate(layer_num_heads)
|
||||
}
|
||||
|
||||
|
||||
def _build(layer_num_heads: list[int]) -> CPUAttentionMetadataBuilder:
|
||||
layers = _layers(layer_num_heads)
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.model_config.dtype = torch.bfloat16
|
||||
vllm_config.model_config.get_num_attention_heads.return_value = MODEL_WIDE_NUM_HEADS
|
||||
vllm_config.cache_config.cache_dtype = "auto"
|
||||
kv_cache_spec = SimpleNamespace(
|
||||
num_kv_heads=NUM_KV_HEADS, head_size=64, block_size=16
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"vllm.v1.attention.backends.utils.get_layers_from_vllm_config",
|
||||
return_value=layers,
|
||||
),
|
||||
patch(
|
||||
"vllm.v1.attention.backends.cpu_attn.get_layers_from_vllm_config",
|
||||
return_value=layers,
|
||||
),
|
||||
):
|
||||
return CPUAttentionMetadataBuilder(
|
||||
kv_cache_spec=kv_cache_spec,
|
||||
layer_names=list(layers),
|
||||
vllm_config=vllm_config,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
|
||||
|
||||
@requires_cpu
|
||||
@pytest.mark.parametrize("group_num_heads", [MODEL_WIDE_NUM_HEADS, 64, 16])
|
||||
def test_num_heads_comes_from_the_group(group_num_heads):
|
||||
"""The group's own count wins, even when it is not the model-wide one."""
|
||||
builder = _build([group_num_heads, group_num_heads])
|
||||
assert builder.num_heads == group_num_heads
|
||||
|
||||
|
||||
@requires_cpu
|
||||
def test_mixed_head_counts_in_one_group_are_rejected():
|
||||
"""Grouping guarantees uniformity; a mixed group means that broke."""
|
||||
with pytest.raises(AssertionError, match="share num_heads"):
|
||||
_build([MODEL_WIDE_NUM_HEADS, 64])
|
||||
|
||||
|
||||
def test_flash_attention_geometry_comes_from_the_group():
|
||||
"""FA3 must use group geometry for layers without an ``impl`` wrapper."""
|
||||
layers = {f"layer_{i}": SimpleNamespace(num_heads=16) for i in range(2)}
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.model_config.get_num_attention_heads.return_value = MODEL_WIDE_NUM_HEADS
|
||||
vllm_config.model_config.get_num_kv_heads.return_value = NUM_KV_HEADS
|
||||
vllm_config.model_config.get_head_size.return_value = 128
|
||||
vllm_config.model_config.rswa_window = None
|
||||
vllm_config.model_config.is_mm_prefix_lm = False
|
||||
vllm_config.parallel_config.cp_kv_cache_interleave_size = 1
|
||||
vllm_config.compilation_config.cudagraph_mode.has_full_cudagraphs.return_value = (
|
||||
False
|
||||
)
|
||||
vllm_config.compilation_config.max_cudagraph_capture_size = None
|
||||
kv_cache_spec = SimpleNamespace(
|
||||
block_size=16,
|
||||
num_kv_heads=2,
|
||||
head_size=64,
|
||||
dtype=torch.bfloat16,
|
||||
dcp_sharded=True,
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"vllm.v1.attention.backends.utils.get_layers_from_vllm_config",
|
||||
return_value=layers,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.parallel_state.get_dcp_group",
|
||||
side_effect=AssertionError,
|
||||
),
|
||||
patch(
|
||||
"vllm.v1.attention.backends.flash_attn.get_flash_attn_version",
|
||||
return_value=3,
|
||||
),
|
||||
):
|
||||
builder = FlashAttentionMetadataBuilder(
|
||||
kv_cache_spec=kv_cache_spec,
|
||||
layer_names=list(layers),
|
||||
vllm_config=vllm_config,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
|
||||
assert builder.aot_schedule
|
||||
assert builder.num_heads_q == 16
|
||||
assert builder.num_heads_kv == 2
|
||||
assert builder.headdim == 64
|
||||
@@ -1,48 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""A KV cache group may hold both windowed and global layers — e.g. Gemma-3 with
|
||||
the hybrid KV cache manager disabled, where the sliding-window layers are
|
||||
promoted to full-attention *storage* and merged into one group whose spec still
|
||||
records the window. Backends must take the window from the layers, never from
|
||||
that group spec, or the global layers get windowed too and silently lose access
|
||||
to everything older than the window.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.v1.attention.backends.cpu_attn import (
|
||||
CPUAttentionBackendImpl,
|
||||
CPUAttentionMetadataBuilder,
|
||||
)
|
||||
|
||||
|
||||
def _layers(layer_windows: list[int]):
|
||||
"""Stand-in attention layers, one per window, as one KV cache group."""
|
||||
return {
|
||||
f"layer_{i}": SimpleNamespace(
|
||||
impl=MagicMock(spec=CPUAttentionBackendImpl, sliding_window=window)
|
||||
)
|
||||
for i, window in enumerate(layer_windows)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layer_windows,expected",
|
||||
[
|
||||
([512, 512], 512), # uniform sliding window -> shared by the group
|
||||
([-1, -1], -1), # all global -> no window
|
||||
([512, -1], -1), # mixed -> the group cannot assume either window
|
||||
],
|
||||
)
|
||||
def test_cpu_group_sliding_window(layer_windows, expected):
|
||||
layers = _layers(layer_windows)
|
||||
builder = SimpleNamespace(vllm_config=None, layer_names=list(layers))
|
||||
with patch(
|
||||
"vllm.v1.attention.backends.cpu_attn.get_layers_from_vllm_config",
|
||||
return_value=layers,
|
||||
):
|
||||
window = CPUAttentionMetadataBuilder._group_sliding_window(builder)
|
||||
assert window == expected
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,665 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
from vllm.model_executor.layers.attention.sparse_mla_attention import (
|
||||
SparseMLACommonMetadataBuilder,
|
||||
)
|
||||
from vllm.models.deepseek_v4.sparse_mla import DeepseekV4SparseMLABackend
|
||||
from vllm.models.deepseek_v41.sparse_mla import (
|
||||
DeepseekV4SparseMLABackend as DeepseekV41SparseMLABackend,
|
||||
)
|
||||
from vllm.utils.deep_gemm import mqa_logits_use_mx_scales
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla import indexer as indexer_module
|
||||
from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
CompressedSlotMappingKernel,
|
||||
get_compressed_slot_mapping,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
BuildPrefillChunkMetadataKernel,
|
||||
DeepseekV4IndexerBackend,
|
||||
DeepSeekV32IndexerDecodeMetadata,
|
||||
DeepseekV32IndexerMetadata,
|
||||
DeepseekV32IndexerMetadataBuilder,
|
||||
DeepseekV41IndexerBackend,
|
||||
get_max_prefill_buffer_size,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
ConvertReqIndexToGlobalIndexKernel,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
MLAAttentionSpec,
|
||||
compute_layer_kv_cache_shape_bytes,
|
||||
)
|
||||
from vllm.v1.worker.block_table import get_block_table_width
|
||||
from vllm.v1.worker.utils import select_common_block_size
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("query_lens", [[1], [6] * 16, [0, 2, 6, 0, 4], [0, 0, 0]])
|
||||
@pytest.mark.parametrize("padding", [0, 17])
|
||||
def test_fused_indexer_decode_metadata(query_lens, padding):
|
||||
"""Flatten device query boundaries and clear graph padding on every replay."""
|
||||
from vllm.v1.attention.ops.metadata import _indexer_decode_metadata_kernel
|
||||
|
||||
device = "cuda"
|
||||
lengths = torch.tensor(query_lens, device=device, dtype=torch.int32)
|
||||
qsl = torch.cat(
|
||||
[torch.zeros(1, device=device, dtype=torch.int32), lengths.cumsum(0).int()]
|
||||
)
|
||||
reqs = len(query_lens)
|
||||
n = sum(query_lens)
|
||||
tokens = n + padding
|
||||
capacity = max(tokens, reqs) + 31
|
||||
seq = lengths + 4096
|
||||
# Exercise block-table row padding and masked columns.
|
||||
bt = torch.arange(reqs * 74, device=device, dtype=torch.int32).view(reqs, 74)[
|
||||
:, :65
|
||||
]
|
||||
out_bt = torch.full((capacity, 69), -99, device=device, dtype=torch.int32)
|
||||
outputs = [
|
||||
torch.full((capacity,), -99, device=device, dtype=torch.int32) for _ in range(4)
|
||||
]
|
||||
out_seq, out_lens, indices, per_req = outputs
|
||||
grid = max(reqs, tokens + (capacity - tokens + 255) // 256)
|
||||
_indexer_decode_metadata_kernel[(grid,)](
|
||||
qsl,
|
||||
seq,
|
||||
bt,
|
||||
out_seq,
|
||||
out_bt,
|
||||
out_lens,
|
||||
indices,
|
||||
per_req,
|
||||
reqs,
|
||||
tokens,
|
||||
capacity,
|
||||
bt.stride(0),
|
||||
out_bt.stride(0),
|
||||
BLOCK_COLS=bt.shape[1],
|
||||
num_warps=4,
|
||||
)
|
||||
expected_req = torch.repeat_interleave(torch.arange(reqs, device=device), lengths)
|
||||
expected_seq = torch.cat(
|
||||
[torch.arange(4097, 4097 + q, device=device) for q in query_lens]
|
||||
)
|
||||
torch.testing.assert_close(out_seq[:n], expected_seq.int(), rtol=0, atol=0)
|
||||
assert torch.count_nonzero(out_seq[n:]) == 0
|
||||
torch.testing.assert_close(out_bt[:n, :65], bt[expected_req], rtol=0, atol=0)
|
||||
assert torch.count_nonzero(out_bt[n:tokens, :65]) == 0
|
||||
torch.testing.assert_close(indices[:n], expected_req.int(), rtol=0, atol=0)
|
||||
torch.testing.assert_close(
|
||||
indices[n:tokens],
|
||||
torch.arange(reqs, reqs + padding, device=device, dtype=torch.int32),
|
||||
)
|
||||
assert torch.all(out_lens[:tokens] == 1)
|
||||
torch.testing.assert_close(per_req[:reqs], lengths)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_indexer_draft_decode_metadata_update_is_capture_safe():
|
||||
if not indexer_module.has_deep_gemm():
|
||||
pytest.skip("requires DeepGEMM")
|
||||
device = torch.device("cuda")
|
||||
num_reqs = 3
|
||||
seq_lens = torch.tensor([17, 33, 65], dtype=torch.int32, device=device)
|
||||
decode_seq_lens = torch.zeros((num_reqs, 1), dtype=torch.int32, device=device)
|
||||
block_table = torch.arange(num_reqs * 4, dtype=torch.int32, device=device).view(
|
||||
num_reqs, 4
|
||||
)
|
||||
num_sms = torch.cuda.get_device_properties(device).multi_processor_count
|
||||
# SM100's paged MQA logits only take varlen rows.
|
||||
indices = (
|
||||
torch.arange(num_reqs, dtype=torch.int32, device=device)
|
||||
if mqa_logits_use_mx_scales()
|
||||
else None
|
||||
)
|
||||
schedule_metadata = indexer_module.get_paged_mqa_logits_metadata(
|
||||
torch.div(seq_lens, 16, rounding_mode="floor").unsqueeze(1),
|
||||
64,
|
||||
num_sms,
|
||||
indices=indices,
|
||||
).clone()
|
||||
|
||||
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
|
||||
builder.dcp_world_size = 1
|
||||
builder.compress_ratio = 16
|
||||
builder.num_sms = num_sms
|
||||
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
|
||||
builder.kv_cache_spec = SimpleNamespace(num_states=64)
|
||||
metadata = DeepseekV32IndexerMetadata(
|
||||
seq_lens=seq_lens,
|
||||
max_seq_len=128,
|
||||
slot_mapping=torch.zeros(num_reqs, dtype=torch.int64, device=device),
|
||||
num_decodes=num_reqs,
|
||||
num_decode_tokens=num_reqs,
|
||||
num_prefills=0,
|
||||
num_prefill_tokens=0,
|
||||
decode=DeepSeekV32IndexerDecodeMetadata(
|
||||
block_table=block_table,
|
||||
seq_lens=decode_seq_lens,
|
||||
decode_lens=torch.zeros(num_reqs, dtype=torch.int32, device=device),
|
||||
requires_padding=False,
|
||||
schedule_metadata=schedule_metadata,
|
||||
indices=indices,
|
||||
),
|
||||
block_table=block_table,
|
||||
)
|
||||
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
seq_lens.copy_(torch.tensor([32, 48, 80], dtype=torch.int32, device=device))
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected_decode_seq_lens = torch.div(seq_lens, 16, rounding_mode="floor")
|
||||
torch.testing.assert_close(decode_seq_lens.flatten(), expected_decode_seq_lens)
|
||||
torch.testing.assert_close(
|
||||
schedule_metadata,
|
||||
indexer_module.get_paged_mqa_logits_metadata(
|
||||
expected_decode_seq_lens.unsqueeze(1), 64, num_sms, indices=indices
|
||||
),
|
||||
)
|
||||
assert metadata.decode is not None
|
||||
assert torch.all(metadata.decode.decode_lens == 1)
|
||||
expected_slot_mapping = block_table[:, 0].to(torch.int64) * 64 + torch.tensor(
|
||||
[1, 2, 4], dtype=torch.int64, device=device
|
||||
)
|
||||
torch.testing.assert_close(metadata.slot_mapping, expected_slot_mapping)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("compress_ratio", [1, 4])
|
||||
def test_indexer_draft_decode_refresh_follows_new_batch(monkeypatch, compress_ratio):
|
||||
"""Without a prior build(), the refresh must not keep the last batch's state."""
|
||||
monkeypatch.setattr(indexer_module, "has_deep_gemm", lambda: False)
|
||||
device = torch.device("cuda")
|
||||
num_reqs, width = 3, 8
|
||||
|
||||
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
|
||||
builder.dcp_world_size = 1
|
||||
builder.compress_ratio = compress_ratio
|
||||
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
|
||||
builder.kv_cache_spec = SimpleNamespace(block_size=64, num_states=64)
|
||||
|
||||
def stale(*shape: int) -> torch.Tensor:
|
||||
return torch.full(shape, -7, dtype=torch.int32, device=device)
|
||||
|
||||
decode = DeepSeekV32IndexerDecodeMetadata(
|
||||
block_table=stale(num_reqs, width),
|
||||
seq_lens=stale(num_reqs, 1),
|
||||
decode_lens=stale(num_reqs),
|
||||
requires_padding=False,
|
||||
schedule_metadata=stale(1),
|
||||
indices=stale(num_reqs),
|
||||
per_req_decode_lens=stale(num_reqs),
|
||||
)
|
||||
request_block_table = torch.randint(
|
||||
0, 1000, (num_reqs, width), dtype=torch.int32, device=device
|
||||
)
|
||||
seq_lens = torch.tensor([17, 33, 65], dtype=torch.int32, device=device)
|
||||
metadata = DeepseekV32IndexerMetadata(
|
||||
seq_lens=seq_lens,
|
||||
max_seq_len=128,
|
||||
slot_mapping=torch.zeros(num_reqs, dtype=torch.int64, device=device),
|
||||
num_decodes=num_reqs,
|
||||
num_decode_tokens=num_reqs,
|
||||
num_prefills=0,
|
||||
num_prefill_tokens=0,
|
||||
decode=decode,
|
||||
block_table=request_block_table,
|
||||
)
|
||||
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
torch.testing.assert_close(decode.block_table, request_block_table)
|
||||
torch.testing.assert_close(decode.indices, builder.arange_buffer[:num_reqs])
|
||||
assert torch.all(decode.per_req_decode_lens == 1)
|
||||
assert torch.all(decode.decode_lens == 1)
|
||||
expected_seq_lens = torch.div(seq_lens, compress_ratio, rounding_mode="floor")
|
||||
torch.testing.assert_close(decode.seq_lens.flatten(), expected_seq_lens)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize(
|
||||
"query_lens", [[1], [0, 257, 1, 0, 3], [6] * 64, [2, 6, 4, 0], [0, 0, 0]]
|
||||
)
|
||||
@pytest.mark.parametrize("use_sparse_mla_builder", [False, True])
|
||||
def test_device_token_request_mapping(query_lens, use_sparse_mla_builder):
|
||||
"""Graph replay follows device boundaries even when CPU lengths are stale."""
|
||||
lengths = torch.tensor(query_lens, device="cuda", dtype=torch.int32)
|
||||
qsl = torch.cat(
|
||||
[torch.zeros(1, device="cuda", dtype=torch.int32), lengths.cumsum(0).int()]
|
||||
)
|
||||
n = sum(query_lens)
|
||||
output = torch.full((n + 7,), -99, device="cuda", dtype=torch.int32)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=qsl,
|
||||
query_start_loc_cpu=qsl.cpu(),
|
||||
seq_lens=lengths,
|
||||
num_reqs=len(query_lens),
|
||||
num_actual_tokens=output.numel(),
|
||||
max_query_len=max(query_lens),
|
||||
max_seq_len=max(query_lens),
|
||||
block_table_tensor=torch.empty(
|
||||
(len(query_lens), 1), device="cuda", dtype=torch.int32
|
||||
),
|
||||
slot_mapping=torch.full((n + 7,), -1, device="cuda", dtype=torch.int64),
|
||||
)
|
||||
|
||||
def build_mapping():
|
||||
if use_sparse_mla_builder:
|
||||
builder = SimpleNamespace(req_id_per_token_buffer=output)
|
||||
return SparseMLACommonMetadataBuilder._build_req_id_per_token(
|
||||
builder, common
|
||||
)
|
||||
return common.token_to_req_indices(output)
|
||||
|
||||
result = build_mapping()
|
||||
assert result.data_ptr() == output.data_ptr()
|
||||
expected = torch.repeat_interleave(
|
||||
torch.arange(len(query_lens), device="cuda", dtype=torch.int32), lengths
|
||||
)
|
||||
torch.testing.assert_close(output[:n], expected)
|
||||
assert torch.count_nonzero(output[n:]) == 0
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
common._token_to_req_indices_cache = None
|
||||
with torch.cuda.graph(graph):
|
||||
build_mapping()
|
||||
reversed_lens = lengths.flip(0)
|
||||
qsl[1:].copy_(reversed_lens.cumsum(0))
|
||||
graph.replay()
|
||||
expected = torch.repeat_interleave(
|
||||
torch.arange(len(query_lens), device="cuda", dtype=torch.int32), reversed_lens
|
||||
)
|
||||
torch.testing.assert_close(output[:n], expected)
|
||||
assert torch.count_nonzero(output[n:]) == 0
|
||||
|
||||
|
||||
def test_indexer_shares_uncompressed_block_size_with_deepseek_v4_mla():
|
||||
"""Packed MLA/indexer groups must retain 64 compressed rows per page."""
|
||||
kernel_block_size = select_common_block_size(
|
||||
256, [DeepseekV4SparseMLABackend, DeepseekV4IndexerBackend]
|
||||
)
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=132,
|
||||
dtype=torch.uint8,
|
||||
tokens_per_state=4,
|
||||
)
|
||||
assert compute_layer_kv_cache_shape_bytes(spec, 2, kernel_block_size) == (
|
||||
2,
|
||||
1,
|
||||
64,
|
||||
132,
|
||||
)
|
||||
|
||||
|
||||
def test_indexer_preserves_deepseek_v41_mla_block_size():
|
||||
"""V4.1 retains its smaller pages independently of V4's C4 indexer."""
|
||||
block_size = DeepseekV41SparseMLABackend.get_supported_kernel_block_sizes()[0]
|
||||
assert isinstance(block_size, int)
|
||||
assert (
|
||||
select_common_block_size(
|
||||
block_size, [DeepseekV41SparseMLABackend, DeepseekV41IndexerBackend]
|
||||
)
|
||||
== block_size
|
||||
)
|
||||
|
||||
|
||||
def test_indexer_warmup_normalizes_zero_compress_ratios():
|
||||
config = SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(max_num_batched_tokens=8),
|
||||
model_config=SimpleNamespace(
|
||||
hf_text_config=SimpleNamespace(
|
||||
compress_ratios=[0, 0, 4, 128, 0], index_kpool=32
|
||||
)
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=1,
|
||||
prefill_context_parallel_size=1,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
),
|
||||
)
|
||||
|
||||
keys = BuildPrefillChunkMetadataKernel().get_warmup_keys(config)
|
||||
|
||||
assert {key.compress_ratio for key in keys} == {1, 4, 32, 128}
|
||||
assert {(key.query_slice_start, key.query_slice_stop) for key in keys} == {
|
||||
(query_slice_start, query_slice_stop)
|
||||
for query_slice_start in (1, 2, 16)
|
||||
for query_slice_stop in (1, 2, 16)
|
||||
}
|
||||
|
||||
|
||||
def test_indexer_warmup_includes_pcp_normalized_dcp_key(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.attention.backends.mla.indexer.get_dcp_group",
|
||||
lambda: SimpleNamespace(rank_in_group=2),
|
||||
)
|
||||
config = SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(max_num_batched_tokens=8),
|
||||
model_config=SimpleNamespace(
|
||||
hf_text_config=SimpleNamespace(compress_ratios=[32], index_kpool=32)
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=4,
|
||||
prefill_context_parallel_size=4,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
),
|
||||
)
|
||||
|
||||
keys = BuildPrefillChunkMetadataKernel().get_warmup_keys(config)
|
||||
|
||||
# Triton's compile key normalizes generic i32 values to 2 and divisible
|
||||
# i32 values (including zero) to 16.
|
||||
assert {(key.dcp_rank, key.dcp_world) for key in keys} == {(2, 2), (16, 1)}
|
||||
assert {
|
||||
(
|
||||
key.input_variant.is_aligned("uncompressed_seq_lens"),
|
||||
key.input_variant.is_aligned("cu_compressed_seq_lens"),
|
||||
)
|
||||
for key in keys
|
||||
} == {(False, False), (False, True), (True, False), (True, True)}
|
||||
|
||||
|
||||
def test_compressed_slot_mapping_warmup_includes_index_kpool():
|
||||
config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(block_size=256),
|
||||
model_config=SimpleNamespace(hf_text_config=SimpleNamespace(index_kpool=32)),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=1, cp_kv_cache_interleave_size=1
|
||||
),
|
||||
)
|
||||
|
||||
keys = CompressedSlotMappingKernel().get_warmup_keys(config)
|
||||
assert {(key.compress_ratio, key.block_size) for key in keys} == {(32, 2)}
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_compressed_slot_mapping_inherits_padded_token_slots():
|
||||
"""A token whose own slot is padded (SWA bounded replay) closes no
|
||||
compressed state either."""
|
||||
device = torch.device("cuda")
|
||||
query_start_loc = torch.tensor([0, 8], dtype=torch.int32, device=device)
|
||||
seq_lens = torch.tensor([8], dtype=torch.int32, device=device)
|
||||
block_table = torch.tensor([[3]], dtype=torch.int32, device=device)
|
||||
slot_mapping = torch.arange(8, dtype=torch.int64, device=device)
|
||||
slot_mapping[:4] = -1
|
||||
compressed = get_compressed_slot_mapping(
|
||||
8,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
block_table,
|
||||
block_size=4,
|
||||
compress_ratio=2,
|
||||
)
|
||||
assert compressed.tolist() == [-1, -1, -1, -1, -1, 3 * 4 + 2, -1, 3 * 4 + 3]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_compressed_slot_mapping_dcp_uses_rank_local_state_positions():
|
||||
"""Under DCP each rank writes only the states it owns, at the state's
|
||||
rank-local position."""
|
||||
device = torch.device("cuda")
|
||||
dcp, interleave, ratio, block_size = 2, 4, 2, 4
|
||||
num_tokens = 32
|
||||
query_start_loc = torch.tensor([0, num_tokens], dtype=torch.int32, device=device)
|
||||
seq_lens = torch.tensor([num_tokens], dtype=torch.int32, device=device)
|
||||
block_table = torch.tensor([[5, 7]], dtype=torch.int32, device=device)
|
||||
pos = torch.arange(num_tokens)
|
||||
for rank in range(dcp):
|
||||
owned = (pos // interleave) % dcp == rank
|
||||
slot_mapping = torch.where(owned, 0, -1).to(torch.int64).to(device)
|
||||
compressed = get_compressed_slot_mapping(
|
||||
num_tokens,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
block_table,
|
||||
block_size=block_size,
|
||||
compress_ratio=ratio,
|
||||
dcp_world_size=dcp,
|
||||
cp_interleave=interleave,
|
||||
)
|
||||
local_pos = pos // (interleave * dcp) * interleave + pos % interleave
|
||||
state = local_pos // ratio
|
||||
expected = torch.where(
|
||||
owned & ((pos + 1) % ratio == 0),
|
||||
block_table[0].cpu()[state // block_size] * block_size + state % block_size,
|
||||
-1,
|
||||
)
|
||||
assert compressed.tolist() == expected.tolist()
|
||||
|
||||
|
||||
def test_index_conversion_warmup_uses_physical_block_stride():
|
||||
config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(block_size=64),
|
||||
model_config=SimpleNamespace(
|
||||
max_model_len=1024,
|
||||
hf_text_config=SimpleNamespace(index_topk=2048),
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=1,
|
||||
prefill_context_parallel_size=1,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
),
|
||||
)
|
||||
|
||||
keys = ConvertReqIndexToGlobalIndexKernel().get_warmup_keys(
|
||||
config,
|
||||
block_stride_rows=4096,
|
||||
)
|
||||
assert {key.block_stride_rows for key in keys} == {4096}
|
||||
|
||||
|
||||
def test_zero_token_pcp_rank_participates_in_compressed_mapping_gather(monkeypatch):
|
||||
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
|
||||
builder.compress_ratio = 4
|
||||
builder.use_pcp = True
|
||||
builder.pcp_world_size = 4
|
||||
builder.pcp_rank = 0
|
||||
builder.dcp_world_size = 1
|
||||
builder.cp_kv_cache_interleave_size = 1
|
||||
builder.kv_cache_spec = SimpleNamespace(block_size=64, num_states=64)
|
||||
builder.compressed_slot_mapping_buffer = torch.zeros(8, dtype=torch.int64)
|
||||
|
||||
def fake_get_compressed_slot_mapping(
|
||||
num_tokens,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
block_table,
|
||||
block_size,
|
||||
compress_ratio,
|
||||
out,
|
||||
dcp_world_size,
|
||||
cp_interleave,
|
||||
):
|
||||
assert num_tokens == 0
|
||||
assert dcp_world_size == 1
|
||||
assert block_size == 64
|
||||
assert compress_ratio == 4
|
||||
out.fill_(-1)
|
||||
return out[:num_tokens]
|
||||
|
||||
gathered_slot_mapping = torch.tensor([123, -1, -1, -1], dtype=torch.int64)
|
||||
|
||||
class FakePCPGroup:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def all_gather(self, tensor, dim=0):
|
||||
self.calls += 1
|
||||
assert dim == 0
|
||||
torch.testing.assert_close(tensor, torch.tensor([-1]))
|
||||
return gathered_slot_mapping
|
||||
|
||||
fake_pcp_group = FakePCPGroup()
|
||||
monkeypatch.setattr(
|
||||
indexer_module,
|
||||
"get_compressed_slot_mapping",
|
||||
fake_get_compressed_slot_mapping,
|
||||
)
|
||||
monkeypatch.setattr(indexer_module, "get_pcp_group", lambda: fake_pcp_group)
|
||||
|
||||
query_start_loc = torch.tensor([0, 0], dtype=torch.int32)
|
||||
seq_lens = torch.tensor([16], dtype=torch.int32)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=query_start_loc,
|
||||
query_start_loc_cpu=query_start_loc,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_cpu_upper_bound=seq_lens,
|
||||
num_reqs=1,
|
||||
num_actual_tokens=0,
|
||||
max_query_len=0,
|
||||
max_seq_len=16,
|
||||
block_table_tensor=torch.tensor([[0]], dtype=torch.int32),
|
||||
slot_mapping=torch.tensor([11, 22, 33, 44], dtype=torch.int64),
|
||||
causal=True,
|
||||
)
|
||||
|
||||
metadata = builder.build(common_prefix_len=0, common_attn_metadata=common)
|
||||
|
||||
assert fake_pcp_group.calls == 1
|
||||
assert metadata.num_decodes == 0
|
||||
assert metadata.num_decode_tokens == 0
|
||||
assert metadata.num_prefills == 0
|
||||
assert metadata.num_prefill_tokens == 0
|
||||
torch.testing.assert_close(metadata.slot_mapping, gathered_slot_mapping)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_indexer_builder_deepseek_v4_compressed_slot_mapping_uses_num_states():
|
||||
"""Regression test: DeepseekV4 compression path must compute slot_mapping from
|
||||
compressed positions, not reuse the uncompressed common metadata mapping.
|
||||
"""
|
||||
device = torch.device("cuda")
|
||||
|
||||
# num_states = block_size // tokens_per_state = 256 // 4 = 64
|
||||
kv_cache_spec = MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
)
|
||||
vllm_config = create_vllm_config(max_model_len=1024)
|
||||
max_num_blocks = kv_cache_spec.max_num_blocks_per_req(vllm_config, 1024)
|
||||
block_table_width = get_block_table_width(max_num_blocks, kv_cache_spec.block_size)
|
||||
builder = DeepseekV32IndexerMetadataBuilder(
|
||||
kv_cache_spec=kv_cache_spec,
|
||||
layer_names=["dummy"],
|
||||
vllm_config=vllm_config,
|
||||
device=device,
|
||||
block_table_width=block_table_width,
|
||||
)
|
||||
|
||||
# Construct a single request where:
|
||||
# - num_computed = 240 (=> compressed_pos_start = 60)
|
||||
# - query_len = 40 (=> num_groups = 10)
|
||||
# => compressed positions are 60..69 which cross the storage block boundary at 64.
|
||||
query_start_loc = torch.tensor([0, 40], dtype=torch.int32, device=device)
|
||||
query_start_loc_cpu = query_start_loc.cpu()
|
||||
seq_lens = torch.tensor([280], dtype=torch.int32, device=device) # 240 + 40
|
||||
|
||||
# Two blocks: compressed positions 0..63 map to block 5, 64..127 map to block 7.
|
||||
block_table_tensor = torch.tensor([[5, 7]], dtype=torch.int32, device=device)
|
||||
|
||||
# Dummy uncompressed slot mapping (length == uncompressed num_actual_tokens).
|
||||
slot_mapping = torch.full((40,), -123, dtype=torch.int64, device=device)
|
||||
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=query_start_loc,
|
||||
query_start_loc_cpu=query_start_loc_cpu,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_cpu_upper_bound=seq_lens.cpu(),
|
||||
num_reqs=1,
|
||||
num_actual_tokens=40,
|
||||
max_query_len=40,
|
||||
max_seq_len=280,
|
||||
block_table_tensor=block_table_tensor,
|
||||
slot_mapping=slot_mapping,
|
||||
causal=True,
|
||||
)
|
||||
|
||||
md = builder.build(common_prefix_len=0, common_attn_metadata=common)
|
||||
|
||||
# The compressed slot_mapping retains the original uncompressed size (40).
|
||||
# Only every compress_ratio-th position gets a valid slot; the rest are -1.
|
||||
assert md.slot_mapping.numel() == 40
|
||||
valid_slots = md.slot_mapping[md.slot_mapping >= 0]
|
||||
assert valid_slots.numel() == 10 # 40 tokens / compress_ratio 4
|
||||
|
||||
storage_bs = kv_cache_spec.num_states # 64
|
||||
# Compressed positions 60..63 land in block 5, positions 64..69 in block 7.
|
||||
expected = torch.tensor(
|
||||
[
|
||||
5 * storage_bs + 60,
|
||||
5 * storage_bs + 61,
|
||||
5 * storage_bs + 62,
|
||||
5 * storage_bs + 63,
|
||||
]
|
||||
+ [
|
||||
7 * storage_bs + 0,
|
||||
7 * storage_bs + 1,
|
||||
7 * storage_bs + 2,
|
||||
7 * storage_bs + 3,
|
||||
7 * storage_bs + 4,
|
||||
7 * storage_bs + 5,
|
||||
],
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
torch.testing.assert_close(valid_slots, expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("compress_ratio", [1, 4])
|
||||
def test_indexer_prefill_budget_matches_compressed_workspace(compress_ratio):
|
||||
"""The chunker budget is in compressed rows, like the K-gather workspace."""
|
||||
max_model_len = 1024
|
||||
kv_cache_spec = MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=compress_ratio,
|
||||
)
|
||||
vllm_config = create_vllm_config(max_model_len=max_model_len)
|
||||
max_num_blocks = kv_cache_spec.max_num_blocks_per_req(vllm_config, max_model_len)
|
||||
block_table_width = get_block_table_width(max_num_blocks, kv_cache_spec.block_size)
|
||||
builder = DeepseekV32IndexerMetadataBuilder(
|
||||
kv_cache_spec=kv_cache_spec,
|
||||
layer_names=["dummy"],
|
||||
vllm_config=vllm_config,
|
||||
device=torch.device("cpu"),
|
||||
block_table_width=block_table_width,
|
||||
)
|
||||
|
||||
workspace_rows = get_max_prefill_buffer_size(vllm_config) // compress_ratio
|
||||
assert builder.max_prefill_buffer_size == workspace_rows
|
||||
|
||||
# Overflows the workspace unless the chunker splits.
|
||||
num_reqs = 3 * (workspace_rows // (max_model_len // compress_ratio)) + 1
|
||||
compressed_seq_lens = torch.full((num_reqs,), max_model_len // compress_ratio)
|
||||
query_lens = torch.ones(num_reqs, dtype=torch.int64)
|
||||
chunks = builder._split_indexer_prefill_chunks(
|
||||
compressed_seq_lens,
|
||||
query_lens,
|
||||
builder.max_prefill_buffer_size,
|
||||
max_logits_bytes=10**15,
|
||||
)
|
||||
assert len(chunks) > 1
|
||||
for req_slice, _ in chunks:
|
||||
assert int(compressed_seq_lens[req_slice].sum()) <= workspace_rows
|
||||
@@ -1,75 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Which next_n the DSA indexer decode path may hand to DeepGEMM unflattened.
|
||||
|
||||
Getting this wrong is not a slow path but a crash: `fp8_fp4_paged_mqa_logits`
|
||||
asserts both that the architecture implements the requested `next_n` and that
|
||||
the schedule metadata was sized for the matching slot count.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import _paged_mqa_logits_schedule_slots
|
||||
from vllm.v1.attention.backends.mla import indexer
|
||||
|
||||
NUM_SMS = 114 # H100 PCIe
|
||||
|
||||
|
||||
def _set_arch(monkeypatch, family: int, *, cuda: bool = True, deep_gemm: bool = True):
|
||||
monkeypatch.setattr(current_platform, "is_cuda", lambda: cuda)
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"is_device_capability_family",
|
||||
lambda capability, device_id=0: capability // 10 == family,
|
||||
)
|
||||
monkeypatch.setattr(indexer, "has_deep_gemm", lambda: deep_gemm)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"family,expected_native",
|
||||
[
|
||||
# SM90 gained next_n=4 (MTP=3) via 2-CTA multicast, but never 3.
|
||||
(9, {1, 2, 4}),
|
||||
# SM100 schedules any next_n with multi-atom tiles.
|
||||
(10, {1, 2, 3, 4, 5, 8}),
|
||||
# SM120 advertises multi-atom too but is unvalidated on hardware, so
|
||||
# it stays on the conservative gate. Loosen it only with measurements.
|
||||
(12, {1, 2}),
|
||||
],
|
||||
)
|
||||
def test_native_decode_gate_per_architecture(monkeypatch, family, expected_native):
|
||||
_set_arch(monkeypatch, family)
|
||||
for next_n in (1, 2, 3, 4, 5, 8):
|
||||
assert indexer._supports_native_decode(next_n) == (next_n in expected_native), (
|
||||
f"family={family} next_n={next_n}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cuda,deep_gemm", [(False, True), (True, False), (False, False)]
|
||||
)
|
||||
def test_native_decode_gate_without_deepgemm(monkeypatch, cuda, deep_gemm):
|
||||
"""Without the DeepGEMM kernels only the shapes every backend handles."""
|
||||
_set_arch(monkeypatch, 9, cuda=cuda, deep_gemm=deep_gemm)
|
||||
assert [indexer._supports_native_decode(n) for n in (1, 2, 3, 4)] == [
|
||||
True,
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
]
|
||||
|
||||
|
||||
def test_sm90_next_n_4_halves_the_schedule_slots(monkeypatch):
|
||||
"""SM90 next_n=4 runs one scheduler task per 2-CTA cluster, not per SM."""
|
||||
_set_arch(monkeypatch, 9)
|
||||
assert _paged_mqa_logits_schedule_slots(NUM_SMS, 4) == NUM_SMS // 2
|
||||
for next_n in (1, 2, 3):
|
||||
assert _paged_mqa_logits_schedule_slots(NUM_SMS, next_n) == NUM_SMS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("family", [10, 12])
|
||||
def test_multicast_is_sm90_only(monkeypatch, family):
|
||||
_set_arch(monkeypatch, family)
|
||||
for next_n in (1, 2, 3, 4):
|
||||
assert _paged_mqa_logits_schedule_slots(NUM_SMS, next_n) == NUM_SMS
|
||||
@@ -1,241 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""TP query-row sharding of the DSA indexer prefill (see PrefillRowShard):
|
||||
each rank scores a contiguous slice; the group exchanges int32s per row."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.model_executor.layers.sparse_attn_indexer as sparse_indexer
|
||||
import vllm.v1.attention.backends.mla.indexer as indexer
|
||||
from vllm.config import AttentionConfig, CUDAGraphMode
|
||||
from vllm.model_executor.layers.sparse_attn_indexer import PrefillRowShard
|
||||
|
||||
MIN_ROWS = AttentionConfig().indexer_tp_shard_min_rows
|
||||
|
||||
|
||||
def _chunk(start: int, end: int) -> SimpleNamespace:
|
||||
"""Chunk over rows [start, end); bounds derive from the global row."""
|
||||
n = end - start
|
||||
return SimpleNamespace(
|
||||
token_start=start,
|
||||
token_end=end,
|
||||
cu_seqlen_ks=torch.zeros(n, dtype=torch.int32),
|
||||
cu_seqlen_ke=((torch.arange(n) * 7 + start) % 65).int(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("world", [2, 3, 8])
|
||||
def test_shard_narrowing_covers_every_row_once(world: int) -> None:
|
||||
"""Narrowed windows tile the prefill rows exactly once, carry the causal
|
||||
bounds of those global rows, and skip chunks foreign to this rank."""
|
||||
decode, rows = 5, 997
|
||||
edges = [decode, decode + 330, decode + 337, decode + rows]
|
||||
chunks = [_chunk(lo, hi) for lo, hi in zip(edges, edges[1:])]
|
||||
sizes = [rows // world + int(r < rows % world) for r in range(world)]
|
||||
covered = []
|
||||
for rank in range(world):
|
||||
shard = PrefillRowShard(decode, sizes, rank)
|
||||
for chunk in chunks:
|
||||
window = shard.narrow(chunk)
|
||||
if window is None:
|
||||
continue
|
||||
start, end, ks, ke = window
|
||||
lo, hi = start - chunk.token_start, end - chunk.token_start
|
||||
torch.testing.assert_close(ks, chunk.cu_seqlen_ks[lo:hi])
|
||||
torch.testing.assert_close(ke, chunk.cu_seqlen_ke[lo:hi])
|
||||
covered.append((start, end))
|
||||
covered.sort()
|
||||
# Windows must be disjoint, contiguous and exactly cover the prefill rows.
|
||||
assert [s for s, _ in covered] == [decode, *[e for _, e in covered][:-1]]
|
||||
assert covered[-1][1] == decode + rows
|
||||
|
||||
|
||||
def test_shard_exchange_reassembles_rows_only(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Gathered indices land only on real prefill rows: leading decode rows
|
||||
and trailing CUDA-graph padding stay untouched, and the full k-pool
|
||||
width (tail columns included) is exchanged."""
|
||||
decode, pad, topk, kpool = 5, 3, 8, 4
|
||||
width = topk + kpool - 1
|
||||
sizes = [17, 9, 21]
|
||||
buffer = torch.full((decode + sum(sizes) + pad, width), -7, dtype=torch.int32)
|
||||
gathered = torch.arange(sum(sizes) * width, dtype=torch.int32).reshape(-1, width)
|
||||
calls = []
|
||||
|
||||
def fake_group():
|
||||
def all_gatherv(local, dim, sizes):
|
||||
calls.append((local, sizes))
|
||||
return gathered
|
||||
|
||||
return SimpleNamespace(all_gatherv=all_gatherv)
|
||||
|
||||
monkeypatch.setattr(sparse_indexer, "get_tp_group", fake_group)
|
||||
for rank in range(len(sizes)):
|
||||
PrefillRowShard(decode, sizes, rank).exchange_topk(buffer, width)
|
||||
assert calls[0][1] == sizes and calls[0][0].is_contiguous()
|
||||
torch.testing.assert_close(buffer[decode : decode + sum(sizes)], gathered)
|
||||
assert torch.all(buffer[:decode] == -7), "decode rows stay outside"
|
||||
assert torch.all(buffer[decode + sum(sizes) :] == -7), "padding untouched"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tp_size", [2, 4, 8])
|
||||
def test_balanced_row_shard_partitions_and_declines(tp_size: int) -> None:
|
||||
"""The split covers every row once with >= 1 row per rank and declines
|
||||
below the activation floor (or on a single rank)."""
|
||||
n = MIN_ROWS
|
||||
shapes = [
|
||||
([4 * n], [4 * n]), # fresh prompt: the full causal cost ramp
|
||||
# uneven requests at different context depths
|
||||
([2 * n, 7, 4 * n, n // 3 + 5], [2 * n, 9007, 4 * n + 500, n // 3 + 60005]),
|
||||
]
|
||||
ratio = 4
|
||||
for query_lens, seq_lens in shapes:
|
||||
sizes = indexer.balanced_prefill_row_shard(
|
||||
torch.tensor(seq_lens, dtype=torch.int32),
|
||||
torch.tensor(query_lens, dtype=torch.int32),
|
||||
ratio,
|
||||
tp_size,
|
||||
n,
|
||||
)
|
||||
assert sizes is not None and len(sizes) == tp_size
|
||||
assert sum(sizes) == sum(query_lens) and min(sizes) >= 1
|
||||
lens = torch.tensor([n - 1], dtype=torch.int32)
|
||||
assert indexer.balanced_prefill_row_shard(lens, lens, ratio, tp_size, n) is None
|
||||
assert indexer.balanced_prefill_row_shard(lens, lens, ratio, 1, n) is None
|
||||
|
||||
|
||||
def test_row_shard_threshold_is_total_not_per_rank() -> None:
|
||||
"""The activation floor counts TOTAL rows regardless of tp_size: a
|
||||
per-rank floor would need 128K rows at TP8, i.e. an unschedulable
|
||||
--max-num-batched-tokens of 128K on 80 GB Hopper nodes."""
|
||||
lens = torch.tensor([MIN_ROWS], dtype=torch.int32)
|
||||
for tp_size in (2, 4, 8):
|
||||
sizes = indexer.balanced_prefill_row_shard(lens, lens, 4, tp_size, MIN_ROWS)
|
||||
assert sizes is not None
|
||||
|
||||
|
||||
def test_tp2_old_per_rank_window_stays_replicated() -> None:
|
||||
"""32K-64K total rows engaged on TP2 under the old per-rank floor
|
||||
(16K rows/rank); the total floor now keeps them replicated — the
|
||||
all_gatherv latency term is largest at small tp."""
|
||||
window = torch.tensor([3 * MIN_ROWS // 4], dtype=torch.int32)
|
||||
assert indexer.balanced_prefill_row_shard(window, window, 4, 2, MIN_ROWS) is None
|
||||
|
||||
|
||||
def test_row_shard_floor_is_at_least_tp_size() -> None:
|
||||
"""A floor below tp_size still leaves every rank at least one row."""
|
||||
lens = torch.tensor([8], dtype=torch.int32)
|
||||
assert indexer.balanced_prefill_row_shard(lens, lens, 4, 8, 1) is not None
|
||||
assert indexer.balanced_prefill_row_shard(lens - 1, lens - 1, 4, 8, 1) is None
|
||||
|
||||
|
||||
def test_row_sharding_gate_rejects_unsupported_configurations(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The gate is the whole safety envelope; nothing else guards the exchange."""
|
||||
monkeypatch.setattr(indexer.current_platform, "is_cuda", lambda: True)
|
||||
|
||||
def supported(**kwargs):
|
||||
mode = kwargs.pop("cudagraph_mode", CUDAGraphMode.PIECEWISE)
|
||||
cfg = SimpleNamespace(compilation_config=SimpleNamespace(cudagraph_mode=mode))
|
||||
args = {"dcp_world_size": 1, "use_pcp": False, "tp_size": 4, **kwargs}
|
||||
return indexer.tp_prefill_row_sharding_supported(cfg, **args)
|
||||
|
||||
assert supported()
|
||||
for bad in ({"tp_size": 1}, {"dcp_world_size": 2}, {"use_pcp": True}):
|
||||
assert not supported(**bad)
|
||||
for name in (
|
||||
"VLLM_DISABLE_PYNCCL",
|
||||
"VLLM_USE_NCCL_SYMM_MEM",
|
||||
"VLLM_BATCH_INVARIANT",
|
||||
):
|
||||
with monkeypatch.context() as m:
|
||||
m.setattr(indexer.envs, name, True)
|
||||
assert not supported()
|
||||
# FULL captures mixed batches whole, so the exchange must stay out.
|
||||
assert not supported(cudagraph_mode=CUDAGraphMode.FULL)
|
||||
assert supported(cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE)
|
||||
|
||||
|
||||
def test_profiling_run_reserves_exchange_transient(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The dummy run returns before the exchange executes, so its all_gatherv
|
||||
output plus staging copy must be reserved up front when row sharding is
|
||||
active -- and only then."""
|
||||
rows, topk = 128, 8
|
||||
buffer = torch.empty((rows, topk), dtype=torch.int32)
|
||||
peak = 2 * rows * topk * buffer.element_size()
|
||||
specs = (((1,), torch.uint8), ((1,), torch.uint8))
|
||||
numels: list[int] = []
|
||||
real_empty = torch.empty
|
||||
|
||||
def recording_empty(*args, **kwargs):
|
||||
out = real_empty(*args, **kwargs)
|
||||
numels.append(out.numel())
|
||||
return out
|
||||
|
||||
def run_dummy(tp_world: int) -> None:
|
||||
numels.clear()
|
||||
with monkeypatch.context() as m:
|
||||
m.setattr(torch, "empty", recording_empty)
|
||||
m.setattr(
|
||||
sparse_indexer,
|
||||
"get_forward_context",
|
||||
lambda: SimpleNamespace(attn_metadata=None),
|
||||
)
|
||||
m.setattr(sparse_indexer, "_gather_workspace_shapes", lambda *a: specs)
|
||||
m.setattr(
|
||||
sparse_indexer,
|
||||
"current_workspace_manager",
|
||||
lambda: SimpleNamespace(get_simultaneous=lambda *s: None),
|
||||
)
|
||||
m.setattr(
|
||||
sparse_indexer,
|
||||
"get_tp_group",
|
||||
lambda: SimpleNamespace(world_size=tp_world),
|
||||
)
|
||||
m.setattr(
|
||||
sparse_indexer,
|
||||
"get_current_vllm_config_or_none",
|
||||
lambda: SimpleNamespace(
|
||||
compilation_config=SimpleNamespace(
|
||||
cudagraph_mode=CUDAGraphMode.PIECEWISE
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=1,
|
||||
prefill_context_parallel_size=1,
|
||||
),
|
||||
),
|
||||
)
|
||||
m.setattr(sparse_indexer.envs, "VLLM_SPARSE_INDEXER_MAX_LOGITS_MB", 1)
|
||||
m.setattr(indexer.current_platform, "is_cuda", lambda: True)
|
||||
sparse_indexer.sparse_attn_indexer(
|
||||
hidden_states=torch.empty(4, 4),
|
||||
k_cache_prefix="k",
|
||||
kv_cache=torch.empty(4, 4),
|
||||
q_quant=torch.empty(4, 4),
|
||||
q_scale=None,
|
||||
k=None,
|
||||
weights=torch.empty(4),
|
||||
quant_block_size=128,
|
||||
scale_fmt=None,
|
||||
topk_tokens=topk,
|
||||
head_dim=64,
|
||||
max_model_len=1024,
|
||||
total_seq_lens=512,
|
||||
topk_indices_buffer=buffer,
|
||||
skip_k_cache_insert=True,
|
||||
use_pcp=False,
|
||||
pcp_shard_decode_requests=False,
|
||||
dense_mha_metadata_layer_name="",
|
||||
)
|
||||
|
||||
run_dummy(tp_world=2)
|
||||
assert peak in numels
|
||||
run_dummy(tp_world=1)
|
||||
assert peak not in numels
|
||||
@@ -1,121 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU tests for the kpool indexer's kernel block selection."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.models.glm5next.common.attention import Glm5NextIndexerCache
|
||||
from vllm.v1.attention.backend import AttentionBackend, MultipleOf
|
||||
from vllm.v1.attention.backends.mla import indexer as indexer_mod
|
||||
from vllm.v1.attention.backends.mla.indexer import Glm5NextIndexerBackend
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
from vllm.v1.worker.utils import prepare_kernel_block_sizes, select_common_block_size
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
# ``index_kpool`` of zai-org/GLM-5.3-Flash: one indexer state pools 4
|
||||
# compressed states (hence a kernel block is page * 4 tokens).
|
||||
INDEX_KPOOL = 4
|
||||
|
||||
# The hybrid KDA/mamba manager floors at TP8..TP1; 640 is the geometry of the
|
||||
# original report ("the 640-token block table").
|
||||
TP_FLOOR_MANAGER_BLOCKS = [640, 1152, 2176, 4352]
|
||||
|
||||
|
||||
def _mock_rocm_platform(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# Platform predicates are mutually exclusive in production. Override both
|
||||
# so these ROCm policy tests do not inherit CUDA capabilities from the CI
|
||||
# host running them (same approach as test_deepseek_v4_rocm_adaptive).
|
||||
monkeypatch.setattr(indexer_mod.current_platform, "is_cuda", lambda: False)
|
||||
monkeypatch.setattr(indexer_mod.current_platform, "is_rocm", lambda: True)
|
||||
|
||||
|
||||
def _kpool_storage_spec(manager_block: int) -> MLAAttentionSpec:
|
||||
"""Real Glm5NextIndexerCache spec for the given cache block size."""
|
||||
with set_current_vllm_config(VllmConfig()):
|
||||
cache = Glm5NextIndexerCache(
|
||||
head_dim=128,
|
||||
dtype=torch.bfloat16,
|
||||
prefix="model.layers.0.indexer.k_cache_probe",
|
||||
cache_config=SimpleNamespace(block_size=manager_block),
|
||||
index_kpool=INDEX_KPOOL,
|
||||
)
|
||||
spec = cache.get_kv_cache_spec(VllmConfig())
|
||||
assert isinstance(spec, MLAAttentionSpec)
|
||||
return spec
|
||||
|
||||
|
||||
def _prepare(
|
||||
spec: MLAAttentionSpec, backends: list[type[AttentionBackend]]
|
||||
) -> list[int]:
|
||||
kv_cache_config = SimpleNamespace(
|
||||
kv_cache_groups=[SimpleNamespace(kv_cache_spec=spec, layer_names=[])],
|
||||
kv_cache_tensors=[],
|
||||
)
|
||||
attn_groups = [
|
||||
[SimpleNamespace(backend=backend, kv_cache_spec=spec) for backend in backends]
|
||||
]
|
||||
return prepare_kernel_block_sizes(kv_cache_config, attn_groups)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manager_block", TP_FLOOR_MANAGER_BLOCKS)
|
||||
def test_kpool_group_maps_pool_pages(
|
||||
monkeypatch: pytest.MonkeyPatch, manager_block: int
|
||||
):
|
||||
"""The bug: on ROCm, kpool groups must get 128/256 - not the 640-4352
|
||||
manager block - as their kernel block size.
|
||||
|
||||
Manager-granular selection is what made the block table address manager
|
||||
blocks while the kpool writer and the index-cache gather read pool pages,
|
||||
aliasing every cache column past the request's row.
|
||||
"""
|
||||
_mock_rocm_platform(monkeypatch)
|
||||
spec = _kpool_storage_spec(manager_block)
|
||||
expected = 256 if manager_block % 256 == 0 else 128
|
||||
|
||||
# The kpool group's AttentionGroup selects its kernel block this way.
|
||||
selected = [
|
||||
select_common_block_size(manager_block, [Glm5NextIndexerBackend], [spec])
|
||||
]
|
||||
assert selected == [expected]
|
||||
assert selected != [manager_block]
|
||||
# The hybrid block-table split stays integral.
|
||||
assert manager_block % selected[0] == 0
|
||||
|
||||
|
||||
def test_prepare_uses_the_backend_vote():
|
||||
"""Unpacked groups take `select_common_block_size`'s answer."""
|
||||
|
||||
class Fixed64Backend:
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None):
|
||||
return [64]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FIXED64"
|
||||
|
||||
plain_spec = MLAAttentionSpec(
|
||||
block_size=640,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
assert _prepare(plain_spec, [Fixed64Backend]) == [64]
|
||||
|
||||
# ...and with backends that accept the manager block, the manager wins,
|
||||
# exactly as on main.
|
||||
class AcceptAllBackend:
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes(kv_cache_spec=None):
|
||||
return [MultipleOf(1)]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "ACCEPTALL"
|
||||
|
||||
assert _prepare(plain_spec, [AcceptAllBackend]) == [640]
|
||||
@@ -1,510 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU tests for the kpool tail slot mapping (no GPU required).
|
||||
|
||||
The kpool tail cache is a 1-block-per-request circular ring addressed by
|
||||
``pos % kpool`` (``CircularBufferSpec`` / ``CircularBufferManager``: exactly one block
|
||||
allocated per request, never grown, so only column 0 of its block table is
|
||||
ever written; the rest stays zero-initialized).
|
||||
|
||||
The generic per-group slot kernel cannot express that layout: it maps
|
||||
``pos -> bt[req][pos // bs] * bs + pos % bs`` (``_compute_slot_mappings_kernel``
|
||||
in vllm/v1/worker/gpu/block_table.py), so every token at ``pos >= kpool``
|
||||
reads a zero column and collapses onto physical tail block 0. All concurrent
|
||||
requests then share one ``kpool``-slot ring and corrupt each other's pool
|
||||
compression.
|
||||
|
||||
These tests pin that defect's arithmetic, verify the circular replacement
|
||||
(``compute_kpool_tail_slot_mapping``), and mirror the tail kernels' index
|
||||
math to show cross-request pollution before the fix and isolation after.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.models.glm5next.common.attention import Glm5NextTailCache
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
KpoolTailBackend,
|
||||
KpoolTailMetadataBuilder,
|
||||
compute_kpool_tail_slot_mapping,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import CircularBufferSpec, compute_layout_strides
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
KPOOL = 4
|
||||
|
||||
|
||||
def test_tail_backend_layout_matches_kernel_pointer_arithmetic():
|
||||
(layout,) = KpoolTailBackend.supported_kv_cache_layouts()
|
||||
spec = CircularBufferSpec(
|
||||
block_size=KPOOL,
|
||||
num_kv_heads=2,
|
||||
head_size=128,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
strides = compute_layout_strides(spec, num_blocks=8, num_layers=3, layout=layout)
|
||||
_, _, head_stride, state_stride, content_stride = strides
|
||||
|
||||
assert layout is KVCacheLayout.BLHNC
|
||||
assert head_stride == KPOOL * 128 * torch.bfloat16.itemsize
|
||||
assert state_stride == 128 * torch.bfloat16.itemsize
|
||||
assert content_stride == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"num_speculative_tokens, ring", [(0, 4), (1, 8), (4, 8), (7, 16), (13, 32)]
|
||||
)
|
||||
def test_tail_ring_divides_the_attention_block(num_speculative_tokens, ring):
|
||||
"""With 7 draft tokens the ring was 12 slots. 12 does not divide the
|
||||
640-token KDA attention block, so the scheduler block grew to their lcm
|
||||
and prefix-cache hits were cut down to multiples of 1920."""
|
||||
with set_current_vllm_config(VllmConfig()):
|
||||
cache = Glm5NextTailCache(
|
||||
head_dim=128,
|
||||
dtype=torch.bfloat16,
|
||||
prefix="tail",
|
||||
cache_config=SimpleNamespace(block_size=640),
|
||||
index_kpool=KPOOL,
|
||||
)
|
||||
spec = cache.get_kv_cache_spec(
|
||||
SimpleNamespace(num_speculative_tokens=num_speculative_tokens)
|
||||
)
|
||||
|
||||
assert isinstance(spec, CircularBufferSpec) and spec.block_size == ring
|
||||
assert ring >= KPOOL + num_speculative_tokens
|
||||
assert 640 % ring == 0
|
||||
|
||||
|
||||
def make_tail_block_table(own_blocks, width=64):
|
||||
"""Tail-group block table as BlockTables produces it: column 0 holds the
|
||||
request's single CircularBufferManager block, the remaining columns are never
|
||||
written and stay zero."""
|
||||
bt = torch.zeros(len(own_blocks), width, dtype=torch.int32)
|
||||
bt[:, 0] = torch.tensor(own_blocks, dtype=torch.int32)
|
||||
return bt
|
||||
|
||||
|
||||
def legacy_generic_tail_slots(block_table, query_start_loc, positions):
|
||||
"""Reference of the generic ``_compute_slot_mappings_kernel`` arithmetic
|
||||
(block_table.py:305-313) applied to the tail group's table."""
|
||||
slots = []
|
||||
for req in range(block_table.shape[0]):
|
||||
for i in range(query_start_loc[req], query_start_loc[req + 1]):
|
||||
pos = int(positions[i])
|
||||
block_number = int(block_table[req, pos // KPOOL])
|
||||
slots.append(block_number * KPOOL + pos % KPOOL)
|
||||
return torch.tensor(slots, dtype=torch.int64)
|
||||
|
||||
|
||||
def circular_tail_slots(
|
||||
slot_mapping, block_table, query_start_loc, positions, num_actual, num_reqs
|
||||
):
|
||||
return compute_kpool_tail_slot_mapping(
|
||||
slot_mapping,
|
||||
block_table,
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_actual,
|
||||
num_reqs,
|
||||
KPOOL,
|
||||
)
|
||||
|
||||
|
||||
def make_batch(per_req_positions, padded_len=None):
|
||||
positions = torch.cat(
|
||||
[torch.tensor(p, dtype=torch.int64) for p in per_req_positions]
|
||||
)
|
||||
num_actual = positions.numel()
|
||||
num_reqs = len(per_req_positions)
|
||||
lens = [len(p) for p in per_req_positions]
|
||||
qsl = torch.zeros(num_reqs + 1, dtype=torch.int64)
|
||||
torch.cumsum(torch.tensor(lens, dtype=torch.int64), 0, out=qsl[1:])
|
||||
if padded_len is None:
|
||||
padded_len = num_actual
|
||||
slot_mapping = torch.full((padded_len,), -1, dtype=torch.int64)
|
||||
return positions, qsl, slot_mapping, num_actual, num_reqs
|
||||
|
||||
|
||||
def test_legacy_generic_mapping_collapses_onto_block_zero():
|
||||
"""The bug: with the manager's 1-column block table, the generic kernel
|
||||
maps every pos >= kpool onto tail block 0, and distinct requests collide."""
|
||||
own_blocks = [5, 9]
|
||||
per_req = [list(range(10)), list(range(12))] # prompts of len 10 and 12
|
||||
positions, qsl, _, num_actual, num_reqs = make_batch(per_req)
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
|
||||
legacy = legacy_generic_tail_slots(bt, qsl, positions)
|
||||
|
||||
# Every token at pos >= kpool resolves to block 0, not the request's own.
|
||||
off = 0
|
||||
for req, prompt in enumerate(per_req):
|
||||
req_slots = legacy[off : off + len(prompt)]
|
||||
for pos in range(len(prompt)):
|
||||
slot = int(req_slots[pos])
|
||||
if pos >= KPOOL:
|
||||
assert slot // KPOOL == 0, (
|
||||
f"expected collapse onto block 0 at pos {pos}"
|
||||
)
|
||||
assert slot // KPOOL != own_blocks[req]
|
||||
off += len(prompt)
|
||||
|
||||
# The two requests share ring slots -> cross-request pollution.
|
||||
a_slots = set(legacy[: len(per_req[0])].tolist())
|
||||
b_slots = set(legacy[len(per_req[0]) :].tolist())
|
||||
assert a_slots & b_slots, "legacy mapping must collide across requests"
|
||||
|
||||
|
||||
def test_circular_mapping_isolates_requests():
|
||||
"""The fix: every token lands in its own request's block at pos % kpool,
|
||||
and no slot is ever shared by two different requests (slots do recur
|
||||
within a request every kpool positions -- that is the circular design)."""
|
||||
own_blocks = [5, 9]
|
||||
per_req = [list(range(10)), list(range(12))]
|
||||
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
|
||||
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
|
||||
|
||||
off = 0
|
||||
per_req_slots = []
|
||||
for req, prompt in enumerate(per_req):
|
||||
req_slots = set()
|
||||
for pos in range(len(prompt)):
|
||||
slot = int(out[off + pos])
|
||||
assert slot // KPOOL == own_blocks[req], (
|
||||
f"req {req} pos {pos} left its tail block"
|
||||
)
|
||||
assert slot % KPOOL == pos % KPOOL
|
||||
req_slots.add(slot)
|
||||
per_req_slots.append(req_slots)
|
||||
off += len(prompt)
|
||||
assert not per_req_slots[0] & per_req_slots[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prompt_len", [1, 2, 3, 4])
|
||||
def test_circular_mapping_matches_generic_for_short_requests(prompt_len):
|
||||
"""For pos < kpool the generic kernel already picks the own block, so the
|
||||
two mappings agree while every position fits the request's first block
|
||||
(single-request behavior is unchanged)."""
|
||||
own_blocks = [7]
|
||||
per_req = [list(range(prompt_len))]
|
||||
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
|
||||
legacy = legacy_generic_tail_slots(bt, qsl, positions)
|
||||
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
|
||||
assert torch.equal(out, legacy)
|
||||
|
||||
|
||||
def test_circular_mapping_preserves_padding_and_empty_batch():
|
||||
# The last request is a padding request on the null block, which owns no
|
||||
# tail block and must never be written.
|
||||
own_blocks = [5, 9, 0]
|
||||
per_req = [list(range(10)), list(range(12)), [0, 1]]
|
||||
padded_len = sum(len(p) for p in per_req) + 8
|
||||
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(
|
||||
per_req, padded_len=padded_len
|
||||
)
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
|
||||
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
|
||||
assert out.shape == slot_mapping.shape
|
||||
pad_start = int(qsl[-2])
|
||||
assert torch.equal(out[pad_start:], torch.full_like(out[pad_start:], -1))
|
||||
|
||||
empty = circular_tail_slots(slot_mapping, bt, qsl, positions[:0], 0, num_reqs)
|
||||
assert torch.equal(empty, slot_mapping)
|
||||
|
||||
|
||||
def make_common_metadata(per_req_positions, own_blocks, with_positions=True):
|
||||
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(
|
||||
per_req_positions, padded_len=sum(len(p) for p in per_req_positions) + 4
|
||||
)
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
seq_lens = torch.tensor(
|
||||
[max(p) + 1 if p else 1 for p in per_req_positions], dtype=torch.int64
|
||||
)
|
||||
return CommonAttentionMetadata(
|
||||
query_start_loc=qsl,
|
||||
query_start_loc_cpu=qsl.clone(),
|
||||
seq_lens=seq_lens,
|
||||
num_reqs=num_reqs,
|
||||
num_actual_tokens=num_actual,
|
||||
max_query_len=max((len(p) for p in per_req_positions), default=1),
|
||||
max_seq_len=int(seq_lens.max()) if num_reqs else 1,
|
||||
block_table_tensor=bt,
|
||||
slot_mapping=slot_mapping,
|
||||
positions=positions if with_positions else None,
|
||||
)
|
||||
|
||||
|
||||
def make_tail_builder(block_size=KPOOL, max_num_batched_tokens=128):
|
||||
builder = object.__new__(KpoolTailMetadataBuilder)
|
||||
builder.kv_cache_spec = SimpleNamespace(block_size=block_size)
|
||||
builder.slot_mapping_buffer = torch.empty(max_num_batched_tokens, dtype=torch.int64)
|
||||
return builder
|
||||
|
||||
|
||||
def test_builder_build_uses_circular_mapping():
|
||||
per_req = [list(range(10)), list(range(12))]
|
||||
own_blocks = [5, 9]
|
||||
cam = make_common_metadata(per_req, own_blocks)
|
||||
meta = KpoolTailMetadataBuilder.build(make_tail_builder(), 0, cam)
|
||||
|
||||
out = meta.slot_mapping
|
||||
off = 0
|
||||
for req, prompt in enumerate(per_req):
|
||||
for pos in range(len(prompt)):
|
||||
slot = int(out[off + pos])
|
||||
assert slot // KPOOL == own_blocks[req]
|
||||
assert slot % KPOOL == pos % KPOOL
|
||||
off += len(prompt)
|
||||
# Padding tail of the buffer keeps the -1 sentinel.
|
||||
assert torch.equal(
|
||||
out[cam.num_actual_tokens :], torch.full_like(out[cam.num_actual_tokens :], -1)
|
||||
)
|
||||
|
||||
|
||||
def test_builder_build_falls_back_without_positions():
|
||||
"""Capture / dummy builds without positions keep the generic mapping."""
|
||||
per_req = [list(range(10))]
|
||||
cam = make_common_metadata(per_req, [5], with_positions=False)
|
||||
meta = KpoolTailMetadataBuilder.build(make_tail_builder(), 0, cam)
|
||||
assert meta.slot_mapping is cam.slot_mapping
|
||||
|
||||
|
||||
def test_builder_updates_draft_mapping():
|
||||
builder = make_tail_builder()
|
||||
cam = make_common_metadata([[15], [16]], [5, 9])
|
||||
meta = KpoolTailMetadataBuilder.build(builder, 0, cam)
|
||||
assert cam.positions is not None
|
||||
cam.positions.add_(1)
|
||||
builder.update_draft_decode_metadata(meta)
|
||||
assert meta.slot_mapping[:2].tolist() == [5 * KPOOL, 9 * KPOOL + 1]
|
||||
|
||||
|
||||
def test_builder_reuses_slot_mapping_storage():
|
||||
builder = make_tail_builder()
|
||||
first = make_common_metadata([list(range(10))], [5])
|
||||
first_meta = KpoolTailMetadataBuilder.build(builder, 0, first)
|
||||
data_ptr = first_meta.slot_mapping.data_ptr()
|
||||
|
||||
second = make_common_metadata([list(range(12))], [9])
|
||||
second_meta = KpoolTailMetadataBuilder.build(builder, 0, second)
|
||||
|
||||
assert second_meta.slot_mapping.data_ptr() == data_ptr
|
||||
assert second_meta.slot_mapping[:12].tolist() == [
|
||||
9 * KPOOL + pos % KPOOL for pos in range(12)
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Index-level mirror of the tail kernels: seed / stash / pool completion
|
||||
# (addressing replicated from kpool_compress.py's Triton kernels).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TailRingMirror:
|
||||
"""Mirror of the tail-ring addressing in _kpool_tail_seed_kernel and
|
||||
_kpool_decode_update_batched_kernel."""
|
||||
|
||||
def __init__(self, num_blocks, kpool=KPOOL, ring=None):
|
||||
self.kpool = kpool
|
||||
self.ring = ring or kpool
|
||||
self.k = torch.full((num_blocks, self.ring, 3), float("nan"))
|
||||
self.s = torch.full((num_blocks, self.ring, 3), float("nan"))
|
||||
|
||||
def stash(self, tail_slot, pos, k, s):
|
||||
blk, off = tail_slot // self.ring, pos % self.ring
|
||||
self.k[blk, off] = k
|
||||
self.s[blk, off] = s
|
||||
|
||||
seed = stash # the seed kernel writes with the same addressing
|
||||
|
||||
def complete(self, tail_slot, pos, k, s):
|
||||
blk = tail_slot // self.ring
|
||||
start = pos - (self.kpool - 1)
|
||||
kk = torch.stack(
|
||||
[self.k[blk, (start + i) % self.ring] for i in range(self.kpool)]
|
||||
)
|
||||
ss = torch.stack(
|
||||
[self.s[blk, (start + i) % self.ring] for i in range(self.kpool)]
|
||||
)
|
||||
kk[-1], ss[-1] = k, s # is_current for the completing token
|
||||
w = torch.softmax(ss, dim=0)
|
||||
return (kk * w).sum(0)
|
||||
|
||||
|
||||
def token_kv(req, pos):
|
||||
k = torch.tensor([pos + 100.0 * req, pos + 0.5, 2.0 * pos + 0.25])
|
||||
s = torch.tensor([0.1 * (pos + 1) + req, 0.2 * pos, 0.05 * pos])
|
||||
return k, s
|
||||
|
||||
|
||||
def tail_slot_for(mapping, req, pos, own_block):
|
||||
if mapping == "legacy":
|
||||
bt_val = own_block if pos < KPOOL else 0
|
||||
return bt_val * KPOOL + pos % KPOOL
|
||||
return own_block * KPOOL + pos % KPOOL
|
||||
|
||||
|
||||
def run_scenario(mapping, interleave):
|
||||
"""Requests A (block 5, prompt len 9) and B (block 9, prompt len 11)
|
||||
decode concurrently; returns A's boundary pool [8, 9, 10, 11]."""
|
||||
ring = TailRingMirror(num_blocks=16)
|
||||
blocks = {"A": 5, "B": 9}
|
||||
prompts = {"A": 9, "B": 11}
|
||||
|
||||
def slot(req, pos):
|
||||
return tail_slot_for(mapping, 0 if req == "A" else 1, pos, blocks[req])
|
||||
|
||||
# Prefill: seed each request's trailing incomplete pool.
|
||||
for req, L in prompts.items():
|
||||
for pos in range(L - (L % KPOOL or KPOOL), L):
|
||||
if pos < 0:
|
||||
continue
|
||||
ring.stash(slot(req, pos), pos, *token_kv(0 if req == "A" else 1, pos))
|
||||
|
||||
# Decode: A emits pos 9, 10, 11; B emits 11, 12, 13. `interleave`
|
||||
# processes B before A within a step, which is exactly what concurrent
|
||||
# Triton programs do when they share tail block 0.
|
||||
order = ["B", "A"] if interleave else ["A", "B"]
|
||||
decode = {"A": [9, 10, 11], "B": [11, 12, 13]}
|
||||
result = None
|
||||
for step in range(3):
|
||||
for req in order:
|
||||
pos = decode[req][step]
|
||||
k, s = token_kv(0 if req == "A" else 1, pos)
|
||||
if pos % KPOOL == KPOOL - 1:
|
||||
pool = ring.complete(slot(req, pos), pos, k, s)
|
||||
if req == "A":
|
||||
result = pool
|
||||
ring.stash(slot(req, pos), pos, k, s)
|
||||
return result
|
||||
|
||||
|
||||
def test_interleaved_decode_pollution_legacy_vs_circular():
|
||||
"""Ground truth: request A decoding alone (its ring used exclusively)."""
|
||||
torch.manual_seed(0)
|
||||
ground_truth = run_scenario("circular", interleave=False)
|
||||
|
||||
legacy = run_scenario("legacy", interleave=True)
|
||||
circular = run_scenario("circular", interleave=True)
|
||||
|
||||
# The old mapping lets request B's tokens into A's ring: A's boundary
|
||||
# pool is compressed from 2 of B's tokens -> wrong.
|
||||
assert not torch.allclose(legacy, ground_truth), (
|
||||
f"legacy mapping unexpectedly clean: {legacy} vs {ground_truth}"
|
||||
)
|
||||
|
||||
# The circular mapping keeps the rings isolated under interleaving.
|
||||
torch.testing.assert_close(circular, ground_truth)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
|
||||
@pytest.mark.parametrize(
|
||||
"per_req,own_blocks,num_actual,padded_len",
|
||||
[
|
||||
([list(range(10)), list(range(12))], [5, 6], 22, 22),
|
||||
([list(range(10)), list(range(12))], [5, 6], 22, 30),
|
||||
([[3, 4], [0], [7, 8, 9]], [5, 0, 7], 6, 8),
|
||||
([[5]], [5], 1, 1),
|
||||
([[0], [0]], [0, 0], 2, 4), # dummy run: every row on the null block
|
||||
],
|
||||
)
|
||||
def test_triton_mapping_matches_cpu(per_req, own_blocks, num_actual, padded_len):
|
||||
"""The CUDA (Triton) path must match the CPU torch reference, including
|
||||
tokens between the last request boundary and num_actual_tokens (mapped to
|
||||
the last request), untouched padding beyond num_actual, and PAD for
|
||||
requests on the null block."""
|
||||
ring_size = 2 * KPOOL
|
||||
positions, qsl, slot_mapping, _, num_reqs = make_batch(
|
||||
per_req, padded_len=padded_len
|
||||
)
|
||||
# Replace the all--1 placeholder slots with sentinel values to check the
|
||||
# padding range is copied through untouched.
|
||||
slot_mapping = torch.arange(padded_len, dtype=torch.int64) + 1000
|
||||
bt = make_tail_block_table(own_blocks)
|
||||
|
||||
ref = compute_kpool_tail_slot_mapping(
|
||||
slot_mapping, bt, qsl, positions, num_actual, num_reqs, ring_size
|
||||
)
|
||||
got = compute_kpool_tail_slot_mapping(
|
||||
slot_mapping.cuda(),
|
||||
bt.cuda(),
|
||||
qsl.cuda().to(torch.int32),
|
||||
positions.cuda(),
|
||||
num_actual,
|
||||
num_reqs,
|
||||
ring_size,
|
||||
)
|
||||
torch.testing.assert_close(got.cpu(), ref)
|
||||
for req, blk in enumerate(own_blocks):
|
||||
if blk == 0:
|
||||
assert (got[int(qsl[req]) : int(qsl[req + 1])] == -1).all()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
|
||||
def test_triton_mapping_reads_strided_block_table():
|
||||
"""The kernel must address the block table through its real stride(0),
|
||||
not a dense assumption (the #57477 class of bug): a tail block table that
|
||||
is a column view of a wider allocation must still read column 0."""
|
||||
per_req = [list(range(10)), list(range(12))]
|
||||
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
|
||||
own_blocks = [11, 22]
|
||||
wide = torch.zeros(num_reqs, 8, dtype=torch.int32)
|
||||
bt = wide[:, 1:4] # non-contiguous view, stride(0) == 8
|
||||
bt[:, 0] = torch.tensor(own_blocks, dtype=torch.int32)
|
||||
|
||||
ref = circular_tail_slots(
|
||||
slot_mapping, bt.contiguous(), qsl, positions, num_actual, num_reqs
|
||||
)
|
||||
got = circular_tail_slots(
|
||||
slot_mapping.cuda(),
|
||||
bt.cuda(),
|
||||
qsl.cuda().to(torch.int32),
|
||||
positions.cuda(),
|
||||
num_actual,
|
||||
num_reqs,
|
||||
)
|
||||
torch.testing.assert_close(got.cpu(), ref)
|
||||
for req, blk in enumerate(own_blocks):
|
||||
start, end = int(qsl[req]), int(qsl[req + 1])
|
||||
assert (got[start:end] // KPOOL == blk).all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ring_pools", [1, 2])
|
||||
def test_rejected_completing_draft_needs_ring_slots(ring_pools):
|
||||
"""With a one-pool ring, the drafts behind a rejected pool-completing draft
|
||||
overwrote the pool's earlier keys, so its redo compressed wrong keys."""
|
||||
ring_size = ring_pools * KPOOL
|
||||
truth = TailRingMirror(num_blocks=2, ring=ring_size)
|
||||
ring = TailRingMirror(num_blocks=2, ring=ring_size)
|
||||
block = 1
|
||||
|
||||
def slot(pos):
|
||||
return block * ring_size + pos % ring_size
|
||||
|
||||
for pos in range(4, 7):
|
||||
truth.stash(slot(pos), pos, *token_kv(0, pos))
|
||||
ring.stash(slot(pos), pos, *token_kv(0, pos))
|
||||
expected = truth.complete(slot(7), 7, *token_kv(0, 7))
|
||||
|
||||
# Draft 7 completes the pool and is rejected. With a one-pool ring, drafts
|
||||
# 8..10 overwrite the slots of positions 4..6, which are read by the redo
|
||||
# of 7.
|
||||
for pos in range(7, 11):
|
||||
k, s = token_kv(9, pos) # draft values
|
||||
if pos % KPOOL == KPOOL - 1:
|
||||
ring.complete(slot(pos), pos, k, s)
|
||||
ring.stash(slot(pos), pos, k, s)
|
||||
redo = ring.complete(slot(7), 7, *token_kv(0, 7))
|
||||
if ring_pools == 1:
|
||||
assert not torch.allclose(redo, expected)
|
||||
else:
|
||||
torch.testing.assert_close(redo, expected)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,355 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Per-request scheduling of MLA chunked-context prefill.
|
||||
|
||||
These cover the metadata contract `_compute_prefill_context` relies on: every
|
||||
context row is gathered exactly once, no chunk exceeds the workspace, and a
|
||||
chunk never covers a prefill without context (which is why the partial no
|
||||
longer needs an empty-span masking pass).
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.utils.gpu_sync_debug as gsd
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
build_mla_chunked_context_metadata,
|
||||
init_mla_context_partial,
|
||||
reorg_kvcache,
|
||||
)
|
||||
from vllm.model_executor.layers.attention.sparse_mla_attention import (
|
||||
SparseMLACommonMetadataBuilder,
|
||||
)
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
|
||||
|
||||
def build_chunked_context(
|
||||
context_lens: list[int],
|
||||
query_lens: list[int],
|
||||
workspace_size: int,
|
||||
block_size: int = BLOCK_SIZE,
|
||||
dcp_world_size: int = 1,
|
||||
dcp_local_block_size: int = 1,
|
||||
):
|
||||
query_start_loc = torch.zeros(len(query_lens) + 1, dtype=torch.int32)
|
||||
query_start_loc[1:] = torch.tensor(query_lens, dtype=torch.int32).cumsum(0)
|
||||
workspace_rows = workspace_size + workspace_size // dcp_world_size
|
||||
return build_mla_chunked_context_metadata(
|
||||
context_lens_cpu=torch.tensor(context_lens, dtype=torch.int32),
|
||||
prefill_query_start_loc_cpu=query_start_loc,
|
||||
chunked_prefill_workspace=torch.empty((workspace_rows, 1)),
|
||||
chunked_prefill_workspace_size=workspace_size,
|
||||
block_size=block_size,
|
||||
align_chunk_to_block=True,
|
||||
device=torch.device("cpu"),
|
||||
dcp_world_size=dcp_world_size,
|
||||
dcp_local_block_size=dcp_local_block_size,
|
||||
dcp_virtual_block_size=dcp_local_block_size * dcp_world_size,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_sparse_context_lengths_do_not_force_gpu_sync(monkeypatch):
|
||||
"""Sparse MLA must pin computed context lengths before the H2D copy."""
|
||||
builder = SimpleNamespace(
|
||||
_context_lens_cpu=torch.empty(2, dtype=torch.int32, pin_memory=True),
|
||||
chunked_prefill_workspace=torch.empty((2048, 1)),
|
||||
chunked_prefill_workspace_size=1024,
|
||||
kv_cache_spec=SimpleNamespace(block_size=BLOCK_SIZE),
|
||||
device=torch.device("cuda"),
|
||||
dcp_world_size=1,
|
||||
dcp_local_block_size=1,
|
||||
dcp_virtual_block_size=1,
|
||||
dcp_manager=None,
|
||||
)
|
||||
common_metadata = SimpleNamespace(
|
||||
seq_lens_cpu_upper_bound=torch.tensor([17, 2052, 324], dtype=torch.int32),
|
||||
query_start_loc_cpu=torch.tensor([0, 1, 5, 9], dtype=torch.int32),
|
||||
)
|
||||
monkeypatch.setattr(gsd, "_SYNC_CHECK_MODE", "error")
|
||||
monkeypatch.setattr(gsd, "_sync_check_enabled", True)
|
||||
gsd._install_copy_checkers()
|
||||
metadata = gsd.with_gpu_sync_check(
|
||||
SparseMLACommonMetadataBuilder._build_chunked_context_fields
|
||||
)(
|
||||
builder,
|
||||
common_metadata,
|
||||
num_decodes=1,
|
||||
num_prefills=2,
|
||||
prefill_query_lens_cpu=torch.tensor([4, 4], dtype=torch.int32),
|
||||
)
|
||||
assert metadata is not None
|
||||
assert metadata.context_lens.device.type == "cuda"
|
||||
assert metadata.context_lens.tolist() == [2048, 320]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"context_lens,workspace_size",
|
||||
[
|
||||
# Heterogeneous batch: the long request must not shrink the chunk the
|
||||
# short ones share.
|
||||
([960, 16, 16, 16, 16, 16, 16, 16], 1024),
|
||||
# A single request that does not fit is split on its own.
|
||||
([2048, 320], 1024),
|
||||
# Every request needs its own chunk.
|
||||
([1024, 1024, 1024], 1024),
|
||||
# Unaligned tails.
|
||||
([37, 1000, 5], 1024),
|
||||
# A zero-context request between active requests must not become an
|
||||
# empty TRTLLM ragged-attention row.
|
||||
([4, 0, 2], 1024),
|
||||
([1], 1024),
|
||||
],
|
||||
)
|
||||
def test_chunks_gather_every_context_row_exactly_once(context_lens, workspace_size):
|
||||
"""Chunks tile the batch's context without gaps, overlap, or overflow.
|
||||
|
||||
This is the invariant the whole schedule rests on: attention over a chunk
|
||||
only sees the rows that chunk gathered, so a row counted twice or dropped
|
||||
silently corrupts the context partial.
|
||||
"""
|
||||
query_lens = [4] * len(context_lens)
|
||||
metadata = build_chunked_context(context_lens, query_lens, workspace_size)
|
||||
assert metadata is not None
|
||||
assert metadata.context_lens.tolist() == context_lens
|
||||
|
||||
gathered: dict[int, list[tuple[int, int]]] = {}
|
||||
previous_request_start = -1
|
||||
for chunk in metadata.chunks:
|
||||
assert chunk.all_rows_active
|
||||
assert chunk.num_context_tokens <= workspace_size
|
||||
assert chunk.num_context_tokens == int(chunk.cu_seq_lens[-1])
|
||||
assert chunk.token_to_seq.shape[0] == chunk.num_context_tokens
|
||||
# Chunks are emitted in request order, which is what lets the partial
|
||||
# treat only a chunk's first request as a continuation.
|
||||
assert chunk.request_slice.start >= previous_request_start
|
||||
previous_request_start = chunk.request_slice.start
|
||||
|
||||
starts = chunk.starts.tolist()
|
||||
seq_lens = chunk.seq_lens.tolist()
|
||||
assert len(starts) == len(seq_lens) == chunk.num_requests
|
||||
for offset, (start, length) in enumerate(zip(starts, seq_lens)):
|
||||
assert length > 0, "a chunk must not cover an empty context span"
|
||||
gathered.setdefault(chunk.request_slice.start + offset, []).append(
|
||||
(start, length)
|
||||
)
|
||||
|
||||
expected = {i: length for i, length in enumerate(context_lens) if length > 0}
|
||||
assert gathered.keys() == expected.keys()
|
||||
for request, spans in gathered.items():
|
||||
cursor = 0
|
||||
for start, length in spans:
|
||||
assert start == cursor
|
||||
cursor += length
|
||||
assert cursor == expected[request]
|
||||
|
||||
|
||||
def test_continuation_is_confined_to_a_chunks_first_request():
|
||||
"""Only a chunk's first request may continue an earlier chunk.
|
||||
|
||||
`accumulate_mla_context_chunk` merges the continuation token slice and
|
||||
writes the rest, so a chunk that continues a request other than its first,
|
||||
or reports the wrong boundary, folds the partial into the wrong tokens.
|
||||
"""
|
||||
context_lens = [2048, 32, 32]
|
||||
query_lens = [3, 5, 7]
|
||||
metadata = build_chunked_context(context_lens, query_lens, 1024)
|
||||
assert metadata is not None
|
||||
query_start_loc = [0, 3, 8, 15]
|
||||
|
||||
assert [chunk.is_continuation for chunk in metadata.chunks] == [
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
]
|
||||
for chunk in metadata.chunks:
|
||||
starts = chunk.starts.tolist()
|
||||
assert chunk.is_continuation == (starts[0] > 0)
|
||||
# Requests after the first always start at the beginning of their
|
||||
# context, so they can only ever be initialized, never merged.
|
||||
assert all(start == 0 for start in starts[1:])
|
||||
request_start = chunk.request_slice.start
|
||||
request_end = chunk.request_slice.stop
|
||||
assert chunk.continuation_token_end == query_start_loc[request_start + 1]
|
||||
assert chunk.token_slice == slice(
|
||||
query_start_loc[request_start], query_start_loc[request_end]
|
||||
)
|
||||
assert chunk.query_start_loc.tolist() == [
|
||||
offset - chunk.token_slice.start
|
||||
for offset in query_start_loc[request_start : request_end + 1]
|
||||
]
|
||||
|
||||
|
||||
def test_tail_splitting_minimizes_chunks():
|
||||
"""A tail request may fill one chunk and continue at the next chunk's head.
|
||||
|
||||
Without tail splitting these contexts need three chunks. Splitting on the
|
||||
block boundary reduces that to the workspace lower bound of two.
|
||||
"""
|
||||
metadata = build_chunked_context([768, 512, 512], [3, 5, 7], 1024)
|
||||
assert metadata is not None
|
||||
|
||||
assert len(metadata.chunks) == 2
|
||||
first, second = metadata.chunks
|
||||
assert first.starts.tolist() == [0, 0]
|
||||
assert first.seq_lens.tolist() == [768, 256]
|
||||
assert not first.is_continuation
|
||||
|
||||
assert second.starts.tolist() == [256, 0]
|
||||
assert second.seq_lens.tolist() == [256, 512]
|
||||
assert second.is_continuation
|
||||
|
||||
|
||||
def test_prefills_without_context_are_skipped_and_neutralized():
|
||||
"""Context-free prefills get neutral partials instead of chunk work.
|
||||
|
||||
If the full-query partial leaves either an internal or trailing gap
|
||||
uninitialized, the final merge combines the suffix with undefined scratch.
|
||||
"""
|
||||
metadata = build_chunked_context([64, 0, 64, 0], [4, 4, 4, 4], 1024)
|
||||
assert metadata is not None
|
||||
|
||||
covered = {
|
||||
request
|
||||
for chunk in metadata.chunks
|
||||
for request in range(chunk.request_slice.start, chunk.request_slice.stop)
|
||||
}
|
||||
assert covered == {0, 2}
|
||||
assert metadata.empty_token_slices == [slice(4, 8), slice(12, 16)]
|
||||
|
||||
output, output_lse = init_mla_context_partial(
|
||||
metadata,
|
||||
attn_output=torch.empty(4, 2, 3),
|
||||
attn_softmax_lse=torch.empty(2, 4),
|
||||
num_tokens=16,
|
||||
)
|
||||
assert output.shape == (16, 2, 3)
|
||||
assert output_lse.shape == (2, 16)
|
||||
for token_slice in metadata.empty_token_slices:
|
||||
assert not torch.count_nonzero(output[token_slice])
|
||||
assert torch.isneginf(output_lse[:, token_slice]).all()
|
||||
|
||||
|
||||
def test_no_context_needs_no_chunks():
|
||||
assert build_chunked_context([0, 0], [4, 4], 1024) is None
|
||||
|
||||
|
||||
def test_dcp_chunks_fit_the_per_rank_row_budget():
|
||||
"""Under DCP each rank gathers its own shard, so the budget is 1/world.
|
||||
|
||||
The local starts and lengths must tile the rank's padded context the same
|
||||
way the global ones tile the real context, since `reorg_kvcache` unpads
|
||||
using them.
|
||||
"""
|
||||
dcp_world_size, interleave, workspace_size = 2, 64, 1024
|
||||
context_lens = [3000, 200, 200]
|
||||
metadata = build_chunked_context(
|
||||
context_lens,
|
||||
[4] * len(context_lens),
|
||||
workspace_size,
|
||||
block_size=128,
|
||||
dcp_world_size=dcp_world_size,
|
||||
dcp_local_block_size=interleave,
|
||||
)
|
||||
assert metadata is not None
|
||||
assert metadata.context_lens.tolist() == context_lens
|
||||
virtual_block_size = interleave * dcp_world_size
|
||||
|
||||
local_cursor: dict[int, int] = {}
|
||||
for chunk in metadata.chunks:
|
||||
assert chunk.num_local_context_tokens <= workspace_size // dcp_world_size
|
||||
assert chunk.local_starts == chunk.starts.tolist()
|
||||
assert chunk.padded_local_cu_seq_lens.tolist() == [0] + list(
|
||||
torch.tensor(chunk.padded_local_seq_lens).cumsum(0)
|
||||
)
|
||||
assert (
|
||||
chunk.padded_local_token_to_seq.shape[0] == chunk.num_local_context_tokens
|
||||
)
|
||||
for offset, (start, length) in enumerate(
|
||||
zip(chunk.local_starts, chunk.padded_local_seq_lens)
|
||||
):
|
||||
request = chunk.request_slice.start + offset
|
||||
assert start == local_cursor.get(request, 0)
|
||||
local_cursor[request] = start + length
|
||||
|
||||
for request, length in enumerate(context_lens):
|
||||
padded_local = -(-length // virtual_block_size) * interleave
|
||||
assert local_cursor[request] == padded_local
|
||||
|
||||
|
||||
def test_dcp_reorg_uses_each_chunks_local_starts():
|
||||
"""Reorganization drops DCP padding at each request's own chunk offset."""
|
||||
dcp_world_size, interleave, workspace_size = 2, 64, 1024
|
||||
metadata = build_chunked_context(
|
||||
[3000, 200, 200],
|
||||
[4, 4, 4],
|
||||
workspace_size,
|
||||
block_size=128,
|
||||
dcp_world_size=dcp_world_size,
|
||||
dcp_local_block_size=interleave,
|
||||
)
|
||||
assert metadata is not None
|
||||
|
||||
for chunk in metadata.chunks:
|
||||
assert chunk.padded_local_seq_lens is not None
|
||||
assert chunk.local_context_lens_allranks is not None
|
||||
assert chunk.local_starts is not None
|
||||
|
||||
toks = chunk.num_local_context_tokens
|
||||
rank_buffers = [torch.full((toks, 1, 1), -1) for _ in range(dcp_world_size)]
|
||||
expected = []
|
||||
src_token_idx = 0
|
||||
for request, (padded_len, local_lens, local_start) in enumerate(
|
||||
zip(
|
||||
chunk.padded_local_seq_lens,
|
||||
chunk.local_context_lens_allranks,
|
||||
chunk.local_starts,
|
||||
)
|
||||
):
|
||||
for rank, local_len in enumerate(local_lens):
|
||||
actual_len = min(max(0, local_len - local_start), padded_len)
|
||||
values = (
|
||||
request * 100_000
|
||||
+ rank * 10_000
|
||||
+ torch.arange(local_start, local_start + actual_len)
|
||||
).view(-1, 1, 1)
|
||||
rank_buffers[rank][src_token_idx : src_token_idx + actual_len] = values
|
||||
expected.append(values)
|
||||
src_token_idx += padded_len
|
||||
|
||||
allgathered = torch.cat(rank_buffers)
|
||||
reorganized, _ = reorg_kvcache(
|
||||
allgathered,
|
||||
allgathered,
|
||||
padded_local_chunk_seq_lens_lst=chunk.padded_local_seq_lens,
|
||||
local_context_lens_allranks=chunk.local_context_lens_allranks,
|
||||
local_starts=chunk.local_starts,
|
||||
sum_seq_len=chunk.num_context_tokens,
|
||||
max_seq_len=chunk.max_seq_len,
|
||||
toks=toks,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(reorganized, torch.cat(expected))
|
||||
|
||||
|
||||
def test_chunked_context_metadata_owns_context_lengths():
|
||||
"""Reusing CPU scratch must not overwrite an earlier batch's context lengths."""
|
||||
context_lens = torch.tensor([16, 32], dtype=torch.int32)
|
||||
metadata = build_mla_chunked_context_metadata(
|
||||
context_lens_cpu=context_lens,
|
||||
prefill_query_start_loc_cpu=torch.tensor([0, 4, 8], dtype=torch.int32),
|
||||
chunked_prefill_workspace=torch.empty((64, 1)),
|
||||
chunked_prefill_workspace_size=64,
|
||||
block_size=BLOCK_SIZE,
|
||||
align_chunk_to_block=True,
|
||||
device=torch.device("cpu"),
|
||||
dcp_world_size=1,
|
||||
dcp_local_block_size=1,
|
||||
dcp_virtual_block_size=1,
|
||||
)
|
||||
context_lens.zero_()
|
||||
assert metadata is not None
|
||||
assert metadata.context_lens.tolist() == [16, 32]
|
||||
@@ -1,260 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonMetadata,
|
||||
MLACommonMetadataBuilder,
|
||||
QueryLenSupport,
|
||||
)
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
|
||||
|
||||
class _NonCausalMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
|
||||
supports_non_causal_multi_token_decode = True
|
||||
|
||||
|
||||
class _CausalOnlyMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
|
||||
pass
|
||||
|
||||
|
||||
class _DraftMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
|
||||
"""Triton-like: non-causal decode is supported, DCP draft decode is not."""
|
||||
|
||||
supports_non_causal_multi_token_decode = True
|
||||
|
||||
|
||||
class _DcpCapableMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
|
||||
supports_non_causal_multi_token_decode = True
|
||||
supports_non_causal_multi_token_dcp = True
|
||||
|
||||
|
||||
def _metadata(
|
||||
query_start_loc: list[int],
|
||||
num_tokens: int | None = None,
|
||||
causal: bool = False,
|
||||
) -> CommonAttentionMetadata:
|
||||
num_reqs = len(query_start_loc) - 1
|
||||
num_tokens = query_start_loc[-1] if num_tokens is None else num_tokens
|
||||
return CommonAttentionMetadata(
|
||||
query_start_loc=torch.tensor(query_start_loc, dtype=torch.int32),
|
||||
query_start_loc_cpu=torch.tensor(query_start_loc, dtype=torch.int32),
|
||||
seq_lens=torch.arange(1, num_reqs + 1, dtype=torch.int32) * 100 + 8,
|
||||
num_reqs=num_reqs,
|
||||
num_actual_tokens=num_tokens,
|
||||
max_query_len=max(
|
||||
end - start for start, end in zip(query_start_loc, query_start_loc[1:])
|
||||
),
|
||||
max_seq_len=num_reqs * 100 + 8,
|
||||
block_table_tensor=torch.arange(num_reqs * 3, dtype=torch.int32).view(
|
||||
num_reqs, 3
|
||||
),
|
||||
slot_mapping=torch.arange(num_tokens),
|
||||
causal=causal,
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
)
|
||||
|
||||
|
||||
def _builder(marked: bool = True) -> _NonCausalMLAMetadataBuilder:
|
||||
builder = object.__new__(_NonCausalMLAMetadataBuilder)
|
||||
builder.device = torch.device("cpu")
|
||||
builder.reorder_batch_threshold = 1
|
||||
builder.query_len_support = QueryLenSupport.SINGLE_ONLY
|
||||
builder.non_causal_multi_token_decode = marked
|
||||
builder.dcp_world_size = 1
|
||||
builder.use_pcp = False
|
||||
builder.metadata_cls = MLACommonMetadata
|
||||
builder.model_config = SimpleNamespace(
|
||||
dtype=torch.bfloat16, get_head_size=lambda: 576
|
||||
)
|
||||
return builder
|
||||
|
||||
|
||||
def _mla_layer(*, non_causal: bool = False) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
non_causal_multi_token_decode=non_causal,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=512,
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
prefill_backend=SimpleNamespace(clone=lambda: None),
|
||||
)
|
||||
|
||||
|
||||
def _merged_mla_spec() -> MLAAttentionSpec:
|
||||
return MLAAttentionSpec(
|
||||
block_size=64,
|
||||
num_kv_heads=1,
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
non_causal_multi_token_decode=True,
|
||||
)
|
||||
|
||||
|
||||
def _dspark_dcp_vllm_config(
|
||||
static_forward_context: dict[str, SimpleNamespace],
|
||||
) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
method="dspark", num_speculative_tokens=None
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=2,
|
||||
prefill_context_parallel_size=1,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
),
|
||||
compilation_config=SimpleNamespace(
|
||||
static_forward_context=static_forward_context
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.bfloat16,
|
||||
max_model_len=128,
|
||||
get_num_attention_heads=lambda _parallel_config: 16,
|
||||
),
|
||||
cache_config=SimpleNamespace(cache_dtype="auto", block_size=64),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=1),
|
||||
attention_config=SimpleNamespace(use_prefill_query_quantization=False),
|
||||
)
|
||||
|
||||
|
||||
def test_group_capability_keeps_runtime_causality_per_step():
|
||||
builder = _builder()
|
||||
|
||||
target_metadata = builder.build(0, _metadata([0, 1, 2], causal=True))
|
||||
assert (
|
||||
target_metadata.num_decodes,
|
||||
target_metadata.num_decode_tokens,
|
||||
target_metadata.num_prefills,
|
||||
target_metadata.causal,
|
||||
) == (2, 2, 0, True)
|
||||
|
||||
common_metadata = _metadata([0, 8, 16])
|
||||
metadata = builder.build(0, common_metadata)
|
||||
|
||||
assert metadata.num_decodes == 2
|
||||
assert metadata.num_decode_tokens == 16
|
||||
assert metadata.num_prefills == 0
|
||||
assert metadata.prefill is None
|
||||
assert metadata.decode is not None
|
||||
assert metadata.decode.block_table.shape == (2, 3)
|
||||
assert metadata.decode.seq_lens.shape == (2,)
|
||||
assert torch.equal(metadata.decode.block_table, common_metadata.block_table_tensor)
|
||||
assert torch.equal(metadata.decode.seq_lens, common_metadata.seq_lens)
|
||||
assert not metadata.causal
|
||||
|
||||
|
||||
def test_noncausal_support_is_explicit_and_uniform():
|
||||
with pytest.raises(ValueError, match="explicitly supported"):
|
||||
_builder(marked=False).build(0, _metadata([0, 8, 16]))
|
||||
with pytest.raises(ValueError, match="uniform query block"):
|
||||
_builder().build(0, _metadata([0, 3, 8]))
|
||||
|
||||
|
||||
def test_noncausal_block_allows_trailing_cudagraph_padding():
|
||||
common_metadata = _metadata([0, 8, 16, 16], num_tokens=24)
|
||||
common_metadata.seq_lens[-1] = 0
|
||||
|
||||
metadata = _builder().build(0, common_metadata)
|
||||
|
||||
assert metadata.num_decodes == 3
|
||||
assert metadata.num_decode_tokens == 24
|
||||
assert metadata.decode is not None
|
||||
assert metadata.decode.seq_lens.tolist() == [108, 208, 0]
|
||||
|
||||
|
||||
def test_noncausal_block_rejects_non_trailing_padding():
|
||||
with pytest.raises(ValueError, match="uniform query block"):
|
||||
_builder().build(0, _metadata([0, 8, 8, 16], num_tokens=24))
|
||||
|
||||
|
||||
def test_noncausal_decode_metadata_keeps_live_request_buffers():
|
||||
common_metadata = _metadata([0, 8, 16])
|
||||
metadata = _builder().build(0, common_metadata)
|
||||
|
||||
assert metadata.decode is not None
|
||||
assert metadata.decode.seq_lens.data_ptr() == common_metadata.seq_lens.data_ptr()
|
||||
assert (
|
||||
metadata.decode.block_table.data_ptr()
|
||||
== common_metadata.block_table_tensor.data_ptr()
|
||||
)
|
||||
|
||||
|
||||
def test_mla_cache_marker_is_promoted_to_group_capability():
|
||||
kwargs = {
|
||||
"block_size": 64,
|
||||
"num_kv_heads": 1,
|
||||
"head_size": 576,
|
||||
"dtype": torch.bfloat16,
|
||||
}
|
||||
marked = MLAAttentionSpec(**kwargs, non_causal_multi_token_decode=True)
|
||||
unmarked = MLAAttentionSpec(**kwargs)
|
||||
|
||||
assert MLAAttentionSpec.merge([marked, marked]).non_causal_multi_token_decode
|
||||
assert not MLAAttentionSpec.merge(
|
||||
[unmarked, unmarked]
|
||||
).non_causal_multi_token_decode
|
||||
assert MLAAttentionSpec.merge([unmarked, marked]).non_causal_multi_token_decode
|
||||
|
||||
|
||||
def test_builder_scopes_noncausal_capability_to_its_layers():
|
||||
merged_spec = _merged_mla_spec()
|
||||
static_forward_context = {
|
||||
"target": _mla_layer(non_causal=False),
|
||||
"draft": _mla_layer(non_causal=True),
|
||||
# Indexer and compressor caches share an MLA group but predate the flag.
|
||||
"indexer": SimpleNamespace(),
|
||||
}
|
||||
vllm_config = _dspark_dcp_vllm_config(static_forward_context)
|
||||
device = torch.device("cpu")
|
||||
|
||||
def _flag(layer_names: list[str]) -> bool:
|
||||
return _DcpCapableMLAMetadataBuilder(
|
||||
merged_spec,
|
||||
layer_names,
|
||||
vllm_config,
|
||||
device,
|
||||
supports_dcp_with_varlen=True,
|
||||
).non_causal_multi_token_decode
|
||||
|
||||
assert not _flag(["target"])
|
||||
assert _flag(["draft"])
|
||||
assert _flag(["target", "draft"])
|
||||
assert not _flag(["target", "indexer"])
|
||||
|
||||
|
||||
def test_merged_group_spec_does_not_mark_a_target_only_builder():
|
||||
# Both builders receive the same merged spec; only the draft layer is
|
||||
# non-causal. Constructing through __init__ would still fail DCP
|
||||
# validation if the builder read the group flag.
|
||||
merged_spec = _merged_mla_spec()
|
||||
static_forward_context = {
|
||||
"target": _mla_layer(non_causal=False),
|
||||
"draft": _mla_layer(non_causal=True),
|
||||
}
|
||||
vllm_config = _dspark_dcp_vllm_config(static_forward_context)
|
||||
device = torch.device("cpu")
|
||||
assert merged_spec.non_causal_multi_token_decode
|
||||
|
||||
target = _CausalOnlyMLAMetadataBuilder(
|
||||
merged_spec,
|
||||
["target"],
|
||||
vllm_config,
|
||||
device,
|
||||
supports_dcp_with_varlen=True,
|
||||
)
|
||||
assert not target.non_causal_multi_token_decode
|
||||
|
||||
with pytest.raises(ValueError, match="non-causal draft"):
|
||||
_DraftMLAMetadataBuilder(
|
||||
merged_spec,
|
||||
["draft"],
|
||||
vllm_config,
|
||||
device,
|
||||
supports_dcp_with_varlen=True,
|
||||
)
|
||||
@@ -1,240 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for MLA prefill backend fused-quant-output support.
|
||||
|
||||
Covers two things:
|
||||
* `MLAPrefillBackend.supports_quant_output`, the capability gate that decides
|
||||
whether the prefill kernel writes quantized output directly (FA4 native
|
||||
fused FP8, see flash-attention#135) instead of the post-quant path.
|
||||
* The numerical equivalence of that fused FP8 write versus the bf16-attention
|
||||
+ standalone static-FP8-quant path it replaces (GPU-only, SM100/SM110).
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8Dynamic128Sym,
|
||||
kFp8StaticTensorSym,
|
||||
kNvfp4Dynamic,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
from vllm.v1.attention.backends.mla.prefill.flash_attn import (
|
||||
FlashAttnPrefillBackend,
|
||||
)
|
||||
|
||||
_FA_MODULE = "vllm.v1.attention.backends.mla.prefill.flash_attn"
|
||||
|
||||
|
||||
class _DummyPrefillBackend(MLAPrefillBackend):
|
||||
"""Concrete backend that does NOT override supports_quant_output."""
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "DUMMY"
|
||||
|
||||
def run_prefill_new_tokens(self, *args, **kwargs): # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def run_prefill_context_chunk(self, *args, **kwargs): # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"quant_key", [kFp8StaticTensorSym, kFp8Dynamic128Sym, kNvfp4Dynamic, None]
|
||||
)
|
||||
def test_base_backend_never_supports_quant_output(quant_key):
|
||||
"""The base default opts every backend out unless it overrides."""
|
||||
backend = object.__new__(_DummyPrefillBackend)
|
||||
assert backend.supports_quant_output(quant_key) is False
|
||||
|
||||
|
||||
def _make_fa_backend(version: int | None, is_vllm_fa: bool):
|
||||
"""Build a FlashAttnPrefillBackend without running its heavy __init__."""
|
||||
backend = object.__new__(FlashAttnPrefillBackend)
|
||||
backend.vllm_flash_attn_version = version
|
||||
backend._is_vllm_fa = is_vllm_fa
|
||||
return backend
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "is_vllm_fa", "dc_major", "quant_key", "expected"),
|
||||
[
|
||||
# FA4 + vLLM-FA + Blackwell SM100/SM110 + static FP8 -> fused.
|
||||
(4, True, 10, kFp8StaticTensorSym, True),
|
||||
(4, True, 11, kFp8StaticTensorSym, True),
|
||||
# Wrong compute capability (SM90 / SM120) -> not supported (#135).
|
||||
(4, True, 9, kFp8StaticTensorSym, False),
|
||||
(4, True, 12, kFp8StaticTensorSym, False),
|
||||
# Not FA4.
|
||||
(3, True, 10, kFp8StaticTensorSym, False),
|
||||
(2, True, 10, kFp8StaticTensorSym, False),
|
||||
(None, True, 10, kFp8StaticTensorSym, False),
|
||||
# Upstream (ROCm) flash-attn, not vLLM-FA.
|
||||
(4, False, 10, kFp8StaticTensorSym, False),
|
||||
# Quant keys not wired through FA4 yet.
|
||||
(4, True, 10, kFp8Dynamic128Sym, False),
|
||||
(4, True, 10, kNvfp4Dynamic, False),
|
||||
],
|
||||
)
|
||||
def test_flash_attn_supports_quant_output(
|
||||
version, is_vllm_fa, dc_major, quant_key, expected
|
||||
):
|
||||
backend = _make_fa_backend(version, is_vllm_fa)
|
||||
with patch(f"{_FA_MODULE}.current_platform") as plat:
|
||||
plat.get_device_capability.return_value = DeviceCapability(
|
||||
major=dc_major, minor=0
|
||||
)
|
||||
assert backend.supports_quant_output(quant_key) is expected
|
||||
|
||||
|
||||
def test_flash_attn_supports_quant_output_unknown_device():
|
||||
"""A None device capability (e.g. capability probe failed) is safe."""
|
||||
backend = _make_fa_backend(version=4, is_vllm_fa=True)
|
||||
with patch(f"{_FA_MODULE}.current_platform") as plat:
|
||||
plat.get_device_capability.return_value = None
|
||||
assert backend.supports_quant_output(kFp8StaticTensorSym) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "enable_jit_warmup", "expected_calls"),
|
||||
[(4, True, 1), (4, False, 0), (3, True, 0)],
|
||||
)
|
||||
def test_flash_attn_registers_warmup_only_for_fa4(
|
||||
version: int,
|
||||
enable_jit_warmup: bool,
|
||||
expected_calls: int,
|
||||
):
|
||||
vllm_config = SimpleNamespace(
|
||||
kernel_config=SimpleNamespace(enable_jit_warmup=enable_jit_warmup)
|
||||
)
|
||||
with (
|
||||
patch(f"{_FA_MODULE}.flash_attn_varlen_func"),
|
||||
patch(f"{_FA_MODULE}.get_flash_attn_version", return_value=version),
|
||||
patch(f"{_FA_MODULE}._FA4_MLA_PREFILL_KERNEL.register_warmup") as register,
|
||||
patch(f"{_FA_MODULE}.current_platform") as platform,
|
||||
):
|
||||
platform.get_device_capability.return_value = DeviceCapability(10, 0)
|
||||
FlashAttnPrefillBackend(
|
||||
num_heads=16,
|
||||
scale=1.0,
|
||||
kv_lora_rank=512,
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
assert register.call_count == expected_calls
|
||||
|
||||
|
||||
def test_flash_attn_prefill_backend_signature_accepts_fused_kwargs():
|
||||
"""run_prefill_new_tokens must accept out/output_scale so the direct
|
||||
(non-**kwargs) call in forward_mha type- and runtime-checks."""
|
||||
import inspect
|
||||
|
||||
params = inspect.signature(
|
||||
FlashAttnPrefillBackend.run_prefill_new_tokens
|
||||
).parameters
|
||||
assert "out" in params
|
||||
assert "output_scale" in params
|
||||
# The base contract must expose them too (Liskov / direct call site).
|
||||
base_params = inspect.signature(MLAPrefillBackend.run_prefill_new_tokens).parameters
|
||||
assert "out" in base_params
|
||||
assert "output_scale" in base_params
|
||||
|
||||
|
||||
def test_mla_impl_forward_mha_accepts_output_scale():
|
||||
"""The abstract MLA impl forward_mha must carry output_scale so every
|
||||
override (and the unconditional forward_impl call) stays compatible."""
|
||||
import inspect
|
||||
|
||||
from vllm.v1.attention.backend import MLAAttentionImpl
|
||||
|
||||
params = inspect.signature(MLAAttentionImpl.forward_mha).parameters
|
||||
assert "output_scale" in params
|
||||
assert params["output_scale"].default is None
|
||||
|
||||
|
||||
def _fused_fp8_skip_reason() -> str | None:
|
||||
"""FA4 fused FP8 output needs a real Blackwell SM100/SM110 GPU."""
|
||||
if not torch.cuda.is_available():
|
||||
return "requires CUDA"
|
||||
major = torch.cuda.get_device_capability()[0]
|
||||
if major not in (10, 11):
|
||||
return f"FA4 fused FP8 output requires SM100/SM110, got SM{major}x"
|
||||
return None
|
||||
|
||||
|
||||
_FUSED_FP8_SKIP = _fused_fp8_skip_reason()
|
||||
|
||||
|
||||
@pytest.mark.skipif(_FUSED_FP8_SKIP is not None, reason=_FUSED_FP8_SKIP or "")
|
||||
def test_fa4_fused_fp8_output_matches_post_quant(default_vllm_config):
|
||||
"""FA4's fused FP8 write (output_scale, flash-attention#135) must match the
|
||||
bf16-attention + standalone static-FP8-quant path it replaces, since
|
||||
production uses the same output_scale for both."""
|
||||
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.vllm_flash_attn import flash_attn_varlen_func
|
||||
|
||||
torch.manual_seed(0)
|
||||
device = torch.device("cuda")
|
||||
fp8_dtype = current_platform.fp8_dtype()
|
||||
|
||||
# MLA prefill head dims (post kv_b_proj): q/k = qk_nope(128)+qk_rope(64),
|
||||
# v = v_head_dim(128); DeepSeek-V2-Lite has 16 query heads.
|
||||
num_heads, qk_head_dim, v_head_dim, seqlen = 16, 192, 128, 512
|
||||
cu_seqlens = torch.tensor([0, seqlen], dtype=torch.int32, device=device)
|
||||
q = torch.randn(seqlen, num_heads, qk_head_dim, dtype=torch.bfloat16, device=device)
|
||||
k = torch.randn(seqlen, num_heads, qk_head_dim, dtype=torch.bfloat16, device=device)
|
||||
v = torch.randn(seqlen, num_heads, v_head_dim, dtype=torch.bfloat16, device=device)
|
||||
|
||||
fa_kwargs = dict(
|
||||
cu_seqlens_q=cu_seqlens,
|
||||
cu_seqlens_k=cu_seqlens,
|
||||
max_seqlen_q=seqlen,
|
||||
max_seqlen_k=seqlen,
|
||||
causal=True,
|
||||
fa_version=4,
|
||||
)
|
||||
|
||||
# Reference: bf16 attention, then standalone static per-tensor FP8 quant.
|
||||
out_bf16 = flash_attn_varlen_func(q=q, k=k, v=v, **fa_kwargs)
|
||||
out_2d = out_bf16.reshape(seqlen, num_heads * v_head_dim)
|
||||
# Scale the amax near e4m3 max so the check uses the representable range.
|
||||
finfo = torch.finfo(fp8_dtype)
|
||||
scale = (out_2d.abs().max() / finfo.max).to(torch.float32).reshape(1)
|
||||
quant_op = QuantFP8(static=True, group_shape=GroupShape.PER_TENSOR)
|
||||
ref_fp8, _ = quant_op(out_2d, scale)
|
||||
|
||||
# Feature: FA4 writes e4m3 into the (tokens, heads*dim) buffer directly.
|
||||
fused_fp8 = torch.empty(
|
||||
seqlen, num_heads * v_head_dim, dtype=fp8_dtype, device=device
|
||||
)
|
||||
flash_attn_varlen_func(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
out=fused_fp8.view(seqlen, num_heads, v_head_dim),
|
||||
output_scale=scale,
|
||||
**fa_kwargs,
|
||||
)
|
||||
|
||||
# Non-degenerate (catches a no-op / all-zero write).
|
||||
assert torch.isfinite(fused_fp8.float()).all()
|
||||
assert fused_fp8.float().abs().any()
|
||||
|
||||
# e4m3 has 3 mantissa bits, so allow ~1 mantissa step of rounding slack.
|
||||
ref = ref_fp8.float() * scale
|
||||
got = fused_fp8.float() * scale
|
||||
torch.testing.assert_close(got, ref, rtol=0.125, atol=float(scale) * 2)
|
||||
|
||||
# ...and most elements land in the exact same fp8 bucket.
|
||||
exact = (fused_fp8.view(torch.uint8) == ref_fp8.view(torch.uint8)).float().mean()
|
||||
assert exact > 0.9, f"only {exact:.1%} of fused FP8 outputs matched the baseline"
|
||||
@@ -1,274 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for MLA prefill backend registry."""
|
||||
|
||||
import gc
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
from vllm.v1.attention.backends.mla.prefill.flashinfer import FlashInferPrefillBackend
|
||||
from vllm.v1.attention.backends.mla.prefill.registry import (
|
||||
MLAPrefillBackendEnum,
|
||||
register_mla_prefill_backend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.trtllm_ragged import (
|
||||
TrtllmRaggedPrefillBackend,
|
||||
)
|
||||
from vllm.v1.worker.workspace import (
|
||||
current_workspace_manager,
|
||||
init_workspace_manager,
|
||||
reset_workspace_manager,
|
||||
)
|
||||
|
||||
|
||||
class CustomMLAPrefillBackend(MLAPrefillBackend):
|
||||
"""Mock custom MLA prefill backend for testing."""
|
||||
|
||||
supported_dtypes = [torch.bfloat16, torch.float16]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "CUSTOM"
|
||||
|
||||
def run_prefill_new_tokens(self, q, k, v, return_softmax_lse):
|
||||
raise NotImplementedError
|
||||
|
||||
def run_prefill_context_chunk(self, chunk, q, k, v, out=None):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def test_prefill_backend_clone_has_isolated_metadata():
|
||||
backend = CustomMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.5,
|
||||
kv_lora_rank=8,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=32,
|
||||
vllm_config=object(),
|
||||
)
|
||||
|
||||
clone = backend.clone()
|
||||
|
||||
assert isinstance(clone, CustomMLAPrefillBackend)
|
||||
assert clone is not backend
|
||||
assert clone.num_heads == backend.num_heads
|
||||
assert clone.scale == backend.scale
|
||||
backend._prefill_metadata = object()
|
||||
clone._prefill_metadata = object()
|
||||
assert clone._prefill_metadata is not backend._prefill_metadata
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_cls", [TrtllmRaggedPrefillBackend, FlashInferPrefillBackend]
|
||||
)
|
||||
def test_prefill_backend_does_not_pin_grown_workspace(monkeypatch, backend_cls):
|
||||
"""Reserving workspace at init must not keep a view of it: when another user
|
||||
grows the shared workspace, the old buffer must be freed."""
|
||||
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", "4096")
|
||||
init_workspace_manager(torch.device("cpu"))
|
||||
try:
|
||||
manager = current_workspace_manager()
|
||||
backend = backend_cls(
|
||||
num_heads=4,
|
||||
scale=0.5,
|
||||
kv_lora_rank=8,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=32,
|
||||
vllm_config=MagicMock(),
|
||||
)
|
||||
(view,) = manager.get_simultaneous(((1,), torch.uint8))
|
||||
old_storage = view.untyped_storage()._weak_ref()
|
||||
del view
|
||||
|
||||
manager.get_simultaneous(((1 << 20,), torch.uint8))
|
||||
gc.collect()
|
||||
|
||||
assert torch.UntypedStorage._expired(old_storage)
|
||||
del backend
|
||||
finally:
|
||||
reset_workspace_manager()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cleanup_overrides():
|
||||
"""Clear any overrides after each test."""
|
||||
yield
|
||||
for member in list(MLAPrefillBackendEnum):
|
||||
member.clear_override()
|
||||
|
||||
|
||||
def _remove_dynamic_member(enum_cls, member):
|
||||
value = member.value
|
||||
name = member.name
|
||||
enum_cls._member_map_.pop(name, None)
|
||||
enum_cls._member_names_.remove(name)
|
||||
delattr(enum_cls, name)
|
||||
if enum_cls._value2member_map_.get(value) is member:
|
||||
del enum_cls._value2member_map_[value]
|
||||
|
||||
|
||||
def test_custom_is_not_alias_of_any_backend():
|
||||
all_backends = list(MLAPrefillBackendEnum)
|
||||
|
||||
aliases = []
|
||||
for backend in all_backends:
|
||||
if backend.name != "CUSTOM" and backend is MLAPrefillBackendEnum.CUSTOM:
|
||||
aliases.append(backend.name)
|
||||
|
||||
assert len(aliases) == 0, (
|
||||
f"BUG! CUSTOM is an alias of: {', '.join(aliases)}!\n"
|
||||
f"CUSTOM.value = {repr(MLAPrefillBackendEnum.CUSTOM.value)}\n"
|
||||
f"All MLA prefill backend values:\n"
|
||||
+ "\n".join(f" {b.name}: {repr(b.value)}" for b in all_backends)
|
||||
)
|
||||
|
||||
assert MLAPrefillBackendEnum.CUSTOM.name == "CUSTOM"
|
||||
|
||||
|
||||
def test_custom_unregistered_raises():
|
||||
with pytest.raises(ValueError, match="must be registered before use"):
|
||||
MLAPrefillBackendEnum.CUSTOM.get_path()
|
||||
|
||||
|
||||
def test_register_custom_backend_with_class_path():
|
||||
register_mla_prefill_backend(
|
||||
MLAPrefillBackendEnum.CUSTOM,
|
||||
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
|
||||
)
|
||||
assert MLAPrefillBackendEnum.CUSTOM.is_overridden()
|
||||
assert MLAPrefillBackendEnum.CUSTOM.get_class().get_name() == "CUSTOM"
|
||||
|
||||
|
||||
def test_register_custom_backend_as_decorator():
|
||||
@register_mla_prefill_backend(MLAPrefillBackendEnum.CUSTOM)
|
||||
class DecoratedPrefillBackend(MLAPrefillBackend):
|
||||
supported_dtypes = [torch.bfloat16]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "DECORATED"
|
||||
|
||||
def run_prefill_new_tokens(self, q, k, v, return_softmax_lse):
|
||||
raise NotImplementedError
|
||||
|
||||
def run_prefill_context_chunk(self, chunk, q, k, v, out=None):
|
||||
raise NotImplementedError
|
||||
|
||||
assert MLAPrefillBackendEnum.CUSTOM.is_overridden()
|
||||
assert "DecoratedPrefillBackend" in MLAPrefillBackendEnum.CUSTOM.get_path()
|
||||
|
||||
|
||||
def test_override_existing_backend():
|
||||
register_mla_prefill_backend(
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
|
||||
)
|
||||
assert MLAPrefillBackendEnum.FLASH_ATTN.get_class().get_name() == "CUSTOM"
|
||||
assert MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
|
||||
|
||||
|
||||
def test_clear_override():
|
||||
original_path = MLAPrefillBackendEnum.FLASH_ATTN.get_path()
|
||||
register_mla_prefill_backend(
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
|
||||
)
|
||||
MLAPrefillBackendEnum.FLASH_ATTN.clear_override()
|
||||
assert not MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
|
||||
assert MLAPrefillBackendEnum.FLASH_ATTN.get_path() == original_path
|
||||
|
||||
|
||||
def test_unknown_backend_name_raises():
|
||||
with pytest.raises(ValueError, match="Unknown MLA prefill backend"):
|
||||
MLAPrefillBackendEnum["NONEXISTENT"]
|
||||
|
||||
|
||||
def test_rocm_aiter_fa_registered():
|
||||
"""ROCM_AITER_FA is a known backend pointing at the AITER FA class."""
|
||||
assert "ROCM_AITER_FA" in MLAPrefillBackendEnum.__members__
|
||||
|
||||
path = MLAPrefillBackendEnum.ROCM_AITER_FA.get_path()
|
||||
assert path == (
|
||||
"vllm.v1.attention.backends.mla.prefill.aiter_flash_attn."
|
||||
"AiterFlashAttnPrefillBackend"
|
||||
)
|
||||
|
||||
backend_cls = MLAPrefillBackendEnum.ROCM_AITER_FA.get_class()
|
||||
assert backend_cls.get_name() == "ROCM_AITER_FA"
|
||||
# The AITER FA path is the fp16/bf16 generic-varlen prefill path.
|
||||
assert backend_cls.supports_dtype(torch.bfloat16)
|
||||
assert backend_cls.supports_dtype(torch.float16)
|
||||
|
||||
|
||||
def test_register_dynamic_member():
|
||||
p = "tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
|
||||
member = MLAPrefillBackendEnum.register("DYNAMIC_TEST", p)
|
||||
assert member.name == "DYNAMIC_TEST"
|
||||
assert member is MLAPrefillBackendEnum["DYNAMIC_TEST"]
|
||||
|
||||
_remove_dynamic_member(MLAPrefillBackendEnum, member)
|
||||
|
||||
|
||||
def test_register_dynamic_member_duplicate_raises():
|
||||
path = "some.module.Class"
|
||||
MLAPrefillBackendEnum.register("DUP_TEST", path)
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
MLAPrefillBackendEnum.register("DUP_TEST", "other.module.OtherClass")
|
||||
_remove_dynamic_member(MLAPrefillBackendEnum, MLAPrefillBackendEnum.DUP_TEST)
|
||||
|
||||
|
||||
class StringDecoratorMLAPrefillBackend(MLAPrefillBackend):
|
||||
"""Mock backend defined at module level so get_class() can resolve
|
||||
the auto-generated class path (local classes are not importable)."""
|
||||
|
||||
supported_dtypes = [torch.bfloat16]
|
||||
requires_r1_mla_dimensions = False
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "DECORATED"
|
||||
|
||||
def run_prefill_new_tokens(self, q, k, v, return_softmax_lse):
|
||||
raise NotImplementedError
|
||||
|
||||
def run_prefill_context_chunk(self, chunk_idx, q, k, v):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def test_register_mla_prefill_backend_with_string_name_direct():
|
||||
register_mla_prefill_backend(
|
||||
"STRING_DIRECT",
|
||||
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
|
||||
)
|
||||
member = MLAPrefillBackendEnum.STRING_DIRECT
|
||||
assert member.is_overridden()
|
||||
assert member.get_class().get_name() == "CUSTOM"
|
||||
|
||||
member.clear_override()
|
||||
_remove_dynamic_member(MLAPrefillBackendEnum, member)
|
||||
|
||||
|
||||
def test_register_mla_prefill_backend_with_string_name_decorator():
|
||||
# The decorated class must be module-level: the decorator derives a
|
||||
# class path from it, and get_class() re-imports that path. A class
|
||||
# defined inside this test would have a non-importable <locals> path.
|
||||
decorated_cls = StringDecoratorMLAPrefillBackend
|
||||
|
||||
result = register_mla_prefill_backend("STRING_DECORATOR")(decorated_cls)
|
||||
assert result is decorated_cls
|
||||
|
||||
member = MLAPrefillBackendEnum.STRING_DECORATOR
|
||||
assert member.is_overridden()
|
||||
assert member.get_path() == (
|
||||
f"{decorated_cls.__module__}.{decorated_cls.__qualname__}"
|
||||
)
|
||||
assert member.get_class() is decorated_cls
|
||||
assert member.get_class().get_name() == "DECORATED"
|
||||
|
||||
member.clear_override()
|
||||
_remove_dynamic_member(MLAPrefillBackendEnum, member)
|
||||
@@ -1,631 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for MLA prefill backend selector."""
|
||||
|
||||
from contextlib import suppress
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import AttentionConfig, ModelConfig, VllmConfig
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability, Platform
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLADimensions
|
||||
from vllm.v1.attention.backends.mla.prefill.registry import MLAPrefillBackendEnum
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import (
|
||||
MLAPrefillSelectorConfig,
|
||||
_auto_select_mla_prefill_backend,
|
||||
get_mla_prefill_backend,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cache():
|
||||
"""Clear lru cache to ensure each test case runs without caching."""
|
||||
_auto_select_mla_prefill_backend.cache_clear()
|
||||
|
||||
|
||||
def _make_mock_model_config(
|
||||
qk_nope_head_dim: int = 128,
|
||||
qk_rope_head_dim: int = 64,
|
||||
v_head_dim: int = 128,
|
||||
dtype: torch.dtype = torch.bfloat16,
|
||||
) -> ModelConfig:
|
||||
mock_config = MagicMock(spec=ModelConfig)
|
||||
mock_config.dtype = dtype
|
||||
mock_config.hf_text_config = MagicMock()
|
||||
mock_config.hf_text_config.qk_nope_head_dim = qk_nope_head_dim
|
||||
mock_config.hf_text_config.qk_rope_head_dim = qk_rope_head_dim
|
||||
mock_config.hf_text_config.v_head_dim = v_head_dim
|
||||
return mock_config
|
||||
|
||||
|
||||
def _make_vllm_config(
|
||||
model_config: ModelConfig | None = None,
|
||||
mla_prefill_backend: MLAPrefillBackendEnum | None = None,
|
||||
) -> VllmConfig:
|
||||
if model_config is None:
|
||||
model_config = _make_mock_model_config()
|
||||
|
||||
attention_config = AttentionConfig(mla_prefill_backend=mla_prefill_backend)
|
||||
mock_vllm_config = MagicMock(spec=VllmConfig)
|
||||
mock_vllm_config.model_config = model_config
|
||||
mock_vllm_config.attention_config = attention_config
|
||||
return mock_vllm_config
|
||||
|
||||
|
||||
class TestPlatformMLAPrefillHooks:
|
||||
"""Tests for the Platform.get_mla_prefill_backend_cls hook itself."""
|
||||
|
||||
def _get_tried_backends(self, capability, mla_dimensions):
|
||||
"""Run the default hook, returning the backend order tried."""
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=mla_dimensions,
|
||||
)
|
||||
tried: list[MLAPrefillBackendEnum] = []
|
||||
|
||||
def mock_get_class(backend_enum):
|
||||
tried.append(backend_enum)
|
||||
cls = MagicMock()
|
||||
cls.validate_configuration.return_value = ["not available"]
|
||||
return cls
|
||||
|
||||
with (
|
||||
patch.object(Platform, "get_device_capability", return_value=capability),
|
||||
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
|
||||
suppress(ValueError),
|
||||
):
|
||||
Platform.get_mla_prefill_backend_cls(selector_config)
|
||||
return tried
|
||||
|
||||
def test_priorities_no_capability(self):
|
||||
tried = self._get_tried_backends(
|
||||
None,
|
||||
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
|
||||
)
|
||||
assert tried == [MLAPrefillBackendEnum.FLASH_ATTN]
|
||||
|
||||
def test_priorities_blackwell_glm_dimensions(self):
|
||||
tried = self._get_tried_backends(
|
||||
DeviceCapability(major=10, minor=0),
|
||||
MLADimensions(qk_nope_head_dim=192, qk_rope_head_dim=64, v_head_dim=256),
|
||||
)
|
||||
assert tried == [
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
MLAPrefillBackendEnum.FLASHINFER,
|
||||
MLAPrefillBackendEnum.TOKENSPEED_MLA,
|
||||
]
|
||||
|
||||
def test_priorities_blackwell_deepseek_dimensions(self):
|
||||
tried = self._get_tried_backends(
|
||||
DeviceCapability(major=10, minor=0),
|
||||
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
|
||||
)
|
||||
assert tried == [
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
MLAPrefillBackendEnum.FLASHINFER,
|
||||
MLAPrefillBackendEnum.TOKENSPEED_MLA,
|
||||
]
|
||||
|
||||
def test_priorities_hopper(self):
|
||||
tried = self._get_tried_backends(
|
||||
DeviceCapability(major=9, minor=0),
|
||||
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
|
||||
)
|
||||
assert tried == [MLAPrefillBackendEnum.FLASH_ATTN]
|
||||
|
||||
def test_skips_import_error_backends(self):
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=192,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
),
|
||||
)
|
||||
valid = MagicMock()
|
||||
valid.validate_configuration.return_value = []
|
||||
|
||||
def mock_get_class(backend_enum):
|
||||
if backend_enum is MLAPrefillBackendEnum.FLASH_ATTN:
|
||||
return valid
|
||||
raise ImportError("not installed")
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
Platform,
|
||||
"get_device_capability",
|
||||
return_value=DeviceCapability(major=10, minor=0),
|
||||
),
|
||||
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
|
||||
):
|
||||
selected = Platform.get_mla_prefill_backend_cls(selector_config)
|
||||
assert selected is valid
|
||||
|
||||
def test_all_invalid_raises_error(self):
|
||||
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
|
||||
invalid = MagicMock()
|
||||
invalid.validate_configuration.return_value = ["not available"]
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
Platform,
|
||||
"get_device_capability",
|
||||
return_value=DeviceCapability(major=10, minor=0),
|
||||
),
|
||||
patch.object(MLAPrefillBackendEnum, "get_class", return_value=invalid),
|
||||
pytest.raises(ValueError, match="No valid MLA"),
|
||||
):
|
||||
Platform.get_mla_prefill_backend_cls(selector_config)
|
||||
|
||||
def test_cpu_platform_returns_fixed_backend(self):
|
||||
"""CPU backends are returned via the fixed-backend hook."""
|
||||
try:
|
||||
cpu_cls = MLAPrefillBackendEnum.CPU.get_class()
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
except ImportError:
|
||||
pytest.skip("CPU MLA prefill backend not available")
|
||||
return
|
||||
|
||||
from vllm.platforms.cpu import CpuPlatform
|
||||
|
||||
expected = zen_cls if zen_cls.is_available() else cpu_cls
|
||||
assert (
|
||||
CpuPlatform.get_mla_prefill_backend_cls(
|
||||
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
)
|
||||
is expected
|
||||
)
|
||||
|
||||
|
||||
class TestGetMLAPrefillBackend:
|
||||
"""Tests for get_mla_prefill_backend (public API)."""
|
||||
|
||||
def test_cpu_uses_sdpa_prefill(self):
|
||||
vllm_config = _make_vllm_config()
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = (
|
||||
MLAPrefillBackendEnum.CPU.get_class()
|
||||
)
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend is MLAPrefillBackendEnum.CPU.get_class()
|
||||
|
||||
def test_zen_cpu_prefers_zentorch_prefill(self):
|
||||
from vllm.platforms.cpu import CpuPlatform
|
||||
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
|
||||
with patch.object(zen_cls, "is_available", return_value=True):
|
||||
backend = CpuPlatform.get_mla_prefill_backend_cls(
|
||||
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
)
|
||||
assert backend is zen_cls
|
||||
|
||||
def test_zen_cpu_falls_back_when_zentorch_unavailable(self):
|
||||
from vllm.platforms.cpu import CpuPlatform
|
||||
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
|
||||
with patch.object(zen_cls, "is_available", return_value=False):
|
||||
backend = CpuPlatform.get_mla_prefill_backend_cls(
|
||||
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
)
|
||||
assert backend is MLAPrefillBackendEnum.CPU.get_class()
|
||||
|
||||
def test_no_device_capability_returns_flash_attn(self):
|
||||
vllm_config = _make_vllm_config()
|
||||
|
||||
class FlashAttnBackend:
|
||||
@staticmethod
|
||||
def get_name():
|
||||
return "FLASH_ATTN"
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = FlashAttnBackend
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend.get_name() == "FLASH_ATTN"
|
||||
|
||||
def test_explicit_flash_attn_selection(self):
|
||||
try:
|
||||
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
|
||||
except ImportError:
|
||||
pytest.skip("FLASH_ATTN backend not available")
|
||||
return
|
||||
|
||||
vllm_config = _make_vllm_config(
|
||||
mla_prefill_backend=MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.is_cpu.return_value = False
|
||||
mock_platform.get_device_capability.return_value = DeviceCapability(
|
||||
major=9, minor=0
|
||||
)
|
||||
|
||||
with patch.object(
|
||||
flash_attn_cls,
|
||||
"validate_configuration",
|
||||
return_value=[],
|
||||
):
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend.get_name() == "FLASH_ATTN"
|
||||
|
||||
def test_explicit_backend_invalid_raises_error(self):
|
||||
vllm_config = _make_vllm_config(
|
||||
mla_prefill_backend=MLAPrefillBackendEnum.FLASHINFER,
|
||||
)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.is_cpu.return_value = False
|
||||
mock_platform.get_device_capability.return_value = DeviceCapability(
|
||||
major=9, minor=0
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="is not valid"):
|
||||
get_mla_prefill_backend(vllm_config)
|
||||
|
||||
def test_explicit_backend_import_error_raises(self):
|
||||
vllm_config = _make_vllm_config(
|
||||
mla_prefill_backend=MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.is_cpu.return_value = False
|
||||
mock_platform.get_device_capability.return_value = DeviceCapability(
|
||||
major=10, minor=0
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
"get_class",
|
||||
side_effect=ImportError("trtllm not installed"),
|
||||
),
|
||||
pytest.raises(ValueError, match="is not valid"),
|
||||
):
|
||||
get_mla_prefill_backend(vllm_config)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("qk_nope_head_dim", "v_head_dim"),
|
||||
[(128, 128), (192, 256), (64, 128)],
|
||||
ids=["deepseek", "glm", "mistral_s4"],
|
||||
)
|
||||
def test_auto_selection_on_hopper(self, qk_nope_head_dim: int, v_head_dim: int):
|
||||
try:
|
||||
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
|
||||
except ImportError:
|
||||
pytest.skip("FLASH_ATTN backend not available")
|
||||
return
|
||||
|
||||
vllm_config = _make_vllm_config(
|
||||
_make_mock_model_config(
|
||||
qk_nope_head_dim=qk_nope_head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
)
|
||||
)
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.current_platform") as mock_platform,
|
||||
patch.object(flash_attn_cls, "is_available", return_value=True),
|
||||
patch(
|
||||
"vllm.v1.attention.backends.mla.prefill.flash_attn."
|
||||
"get_flash_attn_version",
|
||||
return_value=3,
|
||||
),
|
||||
):
|
||||
mock_platform.is_cpu.return_value = False
|
||||
mock_platform.get_device_capability.return_value = DeviceCapability(
|
||||
major=9, minor=0
|
||||
)
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = flash_attn_cls
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend.get_name() == "FLASH_ATTN"
|
||||
|
||||
|
||||
class TestAutoSelectMLAPrefillBackend:
|
||||
"""Tests for fallback and error paths in auto-selection."""
|
||||
|
||||
def test_blackwell_glm_dimensions_use_trtllm(self):
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=192,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
trtllm_cls = MLAPrefillBackendEnum.TRTLLM_RAGGED.get_class()
|
||||
except ImportError:
|
||||
pytest.skip("MLA prefill backend not available")
|
||||
return
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.current_platform") as mock_platform,
|
||||
patch.object(trtllm_cls, "validate_configuration", return_value=[]),
|
||||
):
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = trtllm_cls
|
||||
backend = _auto_select_mla_prefill_backend(selector_config)
|
||||
assert backend.get_name() == "TRTLLM_RAGGED"
|
||||
|
||||
def test_platform_hook_raises_propagates(self):
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
),
|
||||
)
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.current_platform") as mock_platform,
|
||||
pytest.raises(ValueError, match="No valid MLA"),
|
||||
):
|
||||
mock_platform.get_mla_prefill_backend_cls.side_effect = ValueError(
|
||||
"No valid MLA prefill backend found"
|
||||
)
|
||||
_auto_select_mla_prefill_backend(selector_config)
|
||||
|
||||
|
||||
class TestBackendValidation:
|
||||
"""Tests for backend validation logic."""
|
||||
|
||||
def test_backend_supported_dimension_validation(self):
|
||||
try:
|
||||
from vllm.v1.attention.backends.mla.prefill.flashinfer import (
|
||||
FlashInferPrefillBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.trtllm_ragged import (
|
||||
TrtllmRaggedPrefillBackend,
|
||||
)
|
||||
except ImportError:
|
||||
pytest.skip("MLA prefill backend not available")
|
||||
return
|
||||
|
||||
capability = DeviceCapability(major=10, minor=0)
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
),
|
||||
)
|
||||
|
||||
with patch.object(FlashInferPrefillBackend, "is_available", return_value=True):
|
||||
invalid_reasons = FlashInferPrefillBackend.validate_configuration(
|
||||
capability,
|
||||
selector_config,
|
||||
)
|
||||
assert len(invalid_reasons) == 0
|
||||
|
||||
selector_config_invalid = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=64,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
),
|
||||
)
|
||||
|
||||
with patch.object(FlashInferPrefillBackend, "is_available", return_value=True):
|
||||
invalid_reasons = FlashInferPrefillBackend.validate_configuration(
|
||||
capability,
|
||||
selector_config_invalid,
|
||||
)
|
||||
assert len(invalid_reasons) == 1
|
||||
assert "supported MLA dimensions" in invalid_reasons[0]
|
||||
|
||||
selector_config_glm5 = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=192,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
),
|
||||
)
|
||||
|
||||
with patch.object(
|
||||
TrtllmRaggedPrefillBackend, "is_available", return_value=True
|
||||
):
|
||||
invalid_reasons = TrtllmRaggedPrefillBackend.validate_configuration(
|
||||
capability,
|
||||
selector_config_glm5,
|
||||
)
|
||||
assert invalid_reasons == []
|
||||
|
||||
def test_flash_attn_accepts_glm53_flash_nope_dimensions(self):
|
||||
"""(256, 0, 256) runs the same FA kernels as GLM-5's (192, 64, 256); a
|
||||
RoPE-carrying 320-wide query does not."""
|
||||
try:
|
||||
from vllm.v1.attention.backends.mla.prefill.flash_attn import (
|
||||
FlashAttnPrefillBackend,
|
||||
)
|
||||
except ImportError:
|
||||
pytest.skip("MLA prefill backend not available")
|
||||
return
|
||||
|
||||
capability = DeviceCapability(major=10, minor=0)
|
||||
|
||||
def validate(qk_rope_head_dim: int) -> list[str]:
|
||||
selector_config = MLAPrefillSelectorConfig(
|
||||
dtype=torch.bfloat16,
|
||||
mla_dimensions=MLADimensions(
|
||||
qk_nope_head_dim=256,
|
||||
qk_rope_head_dim=qk_rope_head_dim,
|
||||
v_head_dim=256,
|
||||
),
|
||||
)
|
||||
with patch.object(
|
||||
FlashAttnPrefillBackend, "is_available", return_value=True
|
||||
):
|
||||
return FlashAttnPrefillBackend.validate_configuration(
|
||||
capability, selector_config
|
||||
)
|
||||
|
||||
assert validate(qk_rope_head_dim=0) == []
|
||||
invalid_reasons = validate(qk_rope_head_dim=64)
|
||||
assert len(invalid_reasons) == 1
|
||||
assert "supported MLA dimensions" in invalid_reasons[0]
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="Imports vllm.platforms.rocm, whose module init requires a CUDA or "
|
||||
"ROCm torch build; not importable on XPU/CPU/TPU.",
|
||||
)
|
||||
class TestROCmAiterFAPrefillSelection:
|
||||
"""Tests for the ROCm AITER FlashAttention MLA prefill backend."""
|
||||
|
||||
def test_rocm_priorities_prefer_aiter_fa(self):
|
||||
"""On ROCm, ROCM_AITER_FA is tried first, FLASH_ATTN as fallback."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
tried: list[MLAPrefillBackendEnum] = []
|
||||
|
||||
def mock_get_class(backend_enum):
|
||||
tried.append(backend_enum)
|
||||
cls = MagicMock()
|
||||
cls.validate_configuration.return_value = ["not available"]
|
||||
return cls
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
RocmPlatform,
|
||||
"get_device_capability",
|
||||
return_value=MagicMock(),
|
||||
),
|
||||
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
|
||||
suppress(ValueError),
|
||||
):
|
||||
RocmPlatform.get_mla_prefill_backend_cls(selector_config)
|
||||
|
||||
assert tried == [
|
||||
MLAPrefillBackendEnum.ROCM_AITER_FA,
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
]
|
||||
|
||||
def test_supported_dtypes_are_fp16_bf16_only(self):
|
||||
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
|
||||
AiterFlashAttnPrefillBackend,
|
||||
)
|
||||
|
||||
assert AiterFlashAttnPrefillBackend.supports_dtype(torch.bfloat16)
|
||||
assert AiterFlashAttnPrefillBackend.supports_dtype(torch.float16)
|
||||
# FP8 is served by the separate AITER ASM backend, not this one.
|
||||
assert not AiterFlashAttnPrefillBackend.supports_dtype(torch.float8_e4m3fn)
|
||||
|
||||
def test_supports_compute_capability_on_rocm(self):
|
||||
from vllm.v1.attention.backends.mla.prefill import aiter_flash_attn as mod
|
||||
|
||||
# Gating is decided by on_mi3xx(), not by capability
|
||||
capability = MagicMock()
|
||||
|
||||
with patch.object(mod.current_platform, "is_rocm", return_value=False):
|
||||
assert not mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
|
||||
capability
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(mod.current_platform, "is_rocm", return_value=True),
|
||||
patch("vllm.platforms.rocm.on_mi3xx", return_value=False),
|
||||
):
|
||||
assert not mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
|
||||
capability
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(mod.current_platform, "is_rocm", return_value=True),
|
||||
patch("vllm.platforms.rocm.on_mi3xx", return_value=True),
|
||||
):
|
||||
assert mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
|
||||
capability
|
||||
)
|
||||
|
||||
def test_is_available_delegates_to_rocm_aiter_ops(self):
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.backends.mla.prefill import aiter_flash_attn as mod
|
||||
|
||||
with patch.object(rocm_aiter_ops, "is_enabled", return_value=False):
|
||||
assert not mod.AiterFlashAttnPrefillBackend.is_available()
|
||||
|
||||
with patch.object(rocm_aiter_ops, "is_enabled", return_value=True):
|
||||
assert mod.AiterFlashAttnPrefillBackend.is_available()
|
||||
|
||||
def test_auto_select_prefers_aiter_fa_on_rocm(self):
|
||||
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
|
||||
AiterFlashAttnPrefillBackend,
|
||||
)
|
||||
|
||||
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = (
|
||||
AiterFlashAttnPrefillBackend
|
||||
)
|
||||
backend = _auto_select_mla_prefill_backend(selector_config)
|
||||
assert backend.get_name() == "ROCM_AITER_FA"
|
||||
|
||||
def test_auto_select_falls_back_to_flash_attn_when_aiter_invalid(self):
|
||||
try:
|
||||
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
|
||||
except ImportError:
|
||||
pytest.skip("FLASH_ATTN backend not available")
|
||||
return
|
||||
|
||||
# the fallback is forced by the mocked get_mla_prefill_backend_cls,
|
||||
# not the capability.
|
||||
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.get_mla_prefill_backend_cls.return_value = flash_attn_cls
|
||||
backend = _auto_select_mla_prefill_backend(selector_config)
|
||||
assert backend.get_name() == "FLASH_ATTN"
|
||||
|
||||
|
||||
class TestMLAPrefillBackendParsing:
|
||||
"""Tests for string-based mla_prefill_backend parsing from CLI args."""
|
||||
|
||||
def test_valid_string_parses_to_enum(self):
|
||||
config = AttentionConfig(
|
||||
mla_prefill_backend="FLASH_ATTN",
|
||||
)
|
||||
assert config.mla_prefill_backend == MLAPrefillBackendEnum.FLASH_ATTN
|
||||
|
||||
def test_invalid_string_raises_error(self):
|
||||
with pytest.raises(ValueError, match="Unknown MLA prefill backend"):
|
||||
AttentionConfig(
|
||||
mla_prefill_backend="NONEXISTENT",
|
||||
)
|
||||
|
||||
|
||||
class TestMLAPrefillBackendConfig:
|
||||
"""Tests for mla_prefill_backend configuration in AttentionConfig."""
|
||||
|
||||
def test_default_backend_is_none(self):
|
||||
config = AttentionConfig()
|
||||
assert config.mla_prefill_backend is None
|
||||
|
||||
def test_explicit_flash_attn_backend(self):
|
||||
config = AttentionConfig(
|
||||
mla_prefill_backend=MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
)
|
||||
assert config.mla_prefill_backend == MLAPrefillBackendEnum.FLASH_ATTN
|
||||
|
||||
def test_explicit_trtllm_ragged_backend(self):
|
||||
config = AttentionConfig(
|
||||
mla_prefill_backend=MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
)
|
||||
assert config.mla_prefill_backend == MLAPrefillBackendEnum.TRTLLM_RAGGED
|
||||
@@ -1,885 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""mm_prefix query-range metadata and the FA4 mask_mod that consumes it.
|
||||
|
||||
The metadata tests run anywhere. The FA4 tests need SM100 and run the real
|
||||
kernel against a dense float32 reference, which is the only way to check what
|
||||
cannot be reasoned about from the Python side:
|
||||
|
||||
* ``q_ranges[token_idx, 0]`` indexing an aux tensor with a runtime ``Int32``.
|
||||
* ``cu_seqlens_q[b] + q_local`` matching FA4's own packing of a varlen batch.
|
||||
|
||||
The mask_mod is the *entire* mask (``(causal ∧ window) ∨ mm_prefix``), so
|
||||
callers must pass ``causal=False`` and no FA-layer window. FA #155 stopped
|
||||
auto-clearing those when ``mask_mod`` is set; leaving ``causal=True`` would
|
||||
short out the mask_mod on SM90 and clip bidirectional ranges on SM100.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.utils import (
|
||||
fill_mm_prefix_query_ranges,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import KVCacheLayout
|
||||
|
||||
|
||||
def _fa4_available() -> bool:
|
||||
if not current_platform.is_cuda():
|
||||
return False
|
||||
from vllm.v1.attention.backends.fa_utils import is_fa_version_supported
|
||||
|
||||
return is_fa_version_supported(4)
|
||||
|
||||
|
||||
requires_fa4 = pytest.mark.skipif(
|
||||
not _fa4_available(), reason="FA4 mm_prefix mask_mod requires FA4"
|
||||
)
|
||||
|
||||
# Imported conditionally because these pull in CuTe / FA4 build artifacts that
|
||||
# are absent wherever requires_fa4 skips.
|
||||
if _fa4_available():
|
||||
from types import MethodType
|
||||
|
||||
from tests.v1.attention.test_attention_backends import (
|
||||
MockAttentionLayer,
|
||||
create_and_prepopulate_kv_cache,
|
||||
)
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
create_standard_kv_cache_spec,
|
||||
create_vllm_config,
|
||||
)
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionImpl,
|
||||
FlashAttentionMetadataBuilder,
|
||||
_make_mm_prefix_mask_mod,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, get_kv_quant_mode
|
||||
from vllm.vllm_flash_attn.flash_attn_interface import flash_attn_varlen_func
|
||||
|
||||
DEVICE = torch.device("cuda:0")
|
||||
DTYPE = torch.bfloat16
|
||||
HEAD_SIZE = 128
|
||||
NUM_HEADS = 8
|
||||
NUM_KV_HEADS = 8
|
||||
SLIDING_WINDOW_LEFT = 129
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Metadata construction
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# Stands in for the builder's persistent (max_num_batched_tokens, 2) buffer.
|
||||
STAGING_CAPACITY = 64
|
||||
|
||||
|
||||
def _query_ranges(mm_ranges, query_lens, seq_lens):
|
||||
"""Fill a staging buffer and return the written rows, or None if empty."""
|
||||
query_start_loc = torch.tensor(
|
||||
[0, *torch.tensor(query_lens).cumsum(0).tolist()], dtype=torch.int32
|
||||
)
|
||||
# Poison the buffer so a stale row surviving the fill is visible.
|
||||
out = np.full((STAGING_CAPACITY, 2), 12345, dtype=np.int32)
|
||||
num_tokens = fill_mm_prefix_query_ranges(
|
||||
out,
|
||||
mm_ranges,
|
||||
query_start_loc,
|
||||
torch.tensor(seq_lens, dtype=torch.int32),
|
||||
)
|
||||
if num_tokens == 0:
|
||||
return None
|
||||
return torch.from_numpy(out[:num_tokens])
|
||||
|
||||
|
||||
def test_matches_range_scan_semantics_with_context_offset():
|
||||
"""Pin the equivalence the O(1) lookup rests on.
|
||||
|
||||
The kernel checks ``r_start <= kv_idx <= r_end`` for the range containing
|
||||
the query token, which is only equal to the old scan's
|
||||
``any(q in r and kv in r)`` because ranges never overlap. Request 1 carries
|
||||
a context offset so the local-to-absolute query mapping is exercised too.
|
||||
"""
|
||||
mm_ranges = {0: [(1, 3), (5, 7)], 1: [(2, 4), (9, 12)]}
|
||||
query_lens = [8, 6]
|
||||
seq_lens = [8, 13]
|
||||
|
||||
query_ranges = _query_ranges(mm_ranges, query_lens, seq_lens)
|
||||
assert query_ranges is not None
|
||||
|
||||
token_start = 0
|
||||
for req_idx, query_len in enumerate(query_lens):
|
||||
context_len = seq_lens[req_idx] - query_len
|
||||
for q_local in range(query_len):
|
||||
q_abs = context_len + q_local
|
||||
r_start, r_end = query_ranges[token_start + q_local].tolist()
|
||||
for kv_idx in range(seq_lens[req_idx]):
|
||||
old_scan_keep = any(
|
||||
start < end and start <= q_abs <= end and start <= kv_idx <= end
|
||||
for start, end in mm_ranges[req_idx]
|
||||
)
|
||||
new_keep = r_start <= kv_idx <= r_end
|
||||
assert new_keep == old_scan_keep, (req_idx, q_abs, kv_idx)
|
||||
token_start += query_len
|
||||
|
||||
|
||||
def test_ranges_beyond_scheduled_chunk_are_clipped():
|
||||
"""Chunked prefill must not error or produce a wrong mask.
|
||||
|
||||
``disable_chunked_mm_input`` keeps a single mm item intact but still splits
|
||||
a prompt across steps, so a request's ranges routinely sit entirely past the
|
||||
tokens scheduled so far. Sizing by query token makes the out-of-chunk part
|
||||
a no-op rather than an out-of-bounds condition.
|
||||
"""
|
||||
# Step 1 of "TTTT IIIIII": only the 4 text tokens are scheduled, so the
|
||||
# range is entirely ahead of the chunk. The old bounds check raised here.
|
||||
assert _query_ranges({0: [(4, 9)]}, query_lens=[4], seq_lens=[4]) is None
|
||||
|
||||
# A range starting mid-chunk and running past its end keeps its absolute
|
||||
# bounds, so the bidirectional block still reaches the range's later keys
|
||||
# once they are cached. Query tokens here are absolute positions 2..5.
|
||||
query_ranges = _query_ranges({0: [(4, 9)]}, query_lens=[4], seq_lens=[6])
|
||||
assert query_ranges is not None
|
||||
expected = torch.tensor([[-1, -1], [-1, -1], [4, 9], [4, 9]], dtype=torch.int32)
|
||||
torch.testing.assert_close(query_ranges, expected)
|
||||
|
||||
|
||||
def test_buffer_reuse_does_not_leak_previous_rows():
|
||||
"""The staging buffer persists across steps, so every reported row must be
|
||||
rewritten. Guards against dropping the ``-1`` fill as an optimization: a
|
||||
step whose ranges shrink would otherwise expose the prior step's bounds and
|
||||
silently widen the bidirectional mask.
|
||||
"""
|
||||
out = np.zeros((STAGING_CAPACITY, 2), dtype=np.int32)
|
||||
query_start_loc = torch.tensor([0, 8], dtype=torch.int32)
|
||||
seq_lens = torch.tensor([8], dtype=torch.int32)
|
||||
|
||||
num_tokens = fill_mm_prefix_query_ranges(
|
||||
out, {0: [(0, 7)]}, query_start_loc, seq_lens
|
||||
)
|
||||
assert num_tokens == 8
|
||||
np.testing.assert_array_equal(out[:8], np.tile([0, 7], (8, 1)))
|
||||
|
||||
# Same rows scheduled, but now only tokens 2..3 sit inside a range.
|
||||
num_tokens = fill_mm_prefix_query_ranges(
|
||||
out, {0: [(2, 3)]}, query_start_loc, seq_lens
|
||||
)
|
||||
assert num_tokens == 8
|
||||
expected = np.full((8, 2), -1, dtype=np.int32)
|
||||
expected[2:4] = (2, 3)
|
||||
np.testing.assert_array_equal(out[:8], expected)
|
||||
|
||||
|
||||
def test_returns_none_when_no_range_covers_a_query_token():
|
||||
"""No aux tensor means forward() skips the mask_mod entirely.
|
||||
|
||||
Returning None rather than an all-``-1`` tensor is what keeps text-only and
|
||||
decode-only batches off the fill path.
|
||||
"""
|
||||
# Text-only batch on an mm_prefix model: every request present, no ranges.
|
||||
assert _query_ranges({0: [], 1: []}, query_lens=[2, 2], seq_lens=[2, 2]) is None
|
||||
# Degenerate single-token ranges are skipped, matching the Triton path's
|
||||
# `start < end` validity check.
|
||||
assert _query_ranges({0: [(1, 1)]}, query_lens=[4], seq_lens=[4]) is None
|
||||
# Decode rows: the query token is generated, so it is in no range.
|
||||
assert _query_ranges({0: [(1, 3)]}, query_lens=[1], seq_lens=[9]) is None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# FA4 kernel
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _cu_seqlens(lens: list[int]) -> torch.Tensor:
|
||||
out = torch.zeros(len(lens) + 1, dtype=torch.int32)
|
||||
out[1:] = torch.tensor(lens, dtype=torch.int32).cumsum(0)
|
||||
return out
|
||||
|
||||
|
||||
def _dense_reference(
|
||||
q,
|
||||
k_per_req,
|
||||
v_per_req,
|
||||
query_lens,
|
||||
seq_lens,
|
||||
mm_ranges,
|
||||
sliding_window_left,
|
||||
scale,
|
||||
mm_clamp_sw=0,
|
||||
):
|
||||
"""Dense float32 ``(causal AND window) OR mm_prefix`` per request.
|
||||
|
||||
``mm_clamp_sw`` confines the bidirectional block to the window, reproducing
|
||||
Gemma4's ``mm_prefix_clamp_sliding_window``. Only the past bound applies, so
|
||||
future keys inside a range still pass.
|
||||
"""
|
||||
out = torch.empty_like(q, dtype=torch.float32)
|
||||
repeats = q.shape[1] // k_per_req[0].shape[1]
|
||||
q_off = 0
|
||||
for req_idx, (q_len, k_len) in enumerate(zip(query_lens, seq_lens)):
|
||||
ctx = k_len - q_len
|
||||
q_pos = torch.arange(q_len, device=q.device) + ctx
|
||||
k_pos = torch.arange(k_len, device=q.device)
|
||||
delta = q_pos[:, None] - k_pos[None, :]
|
||||
|
||||
keep = delta >= 0
|
||||
if sliding_window_left is not None:
|
||||
keep &= delta < sliding_window_left
|
||||
|
||||
for start, end in mm_ranges.get(req_idx, []):
|
||||
if start >= end:
|
||||
continue
|
||||
q_in = (q_pos >= start) & (q_pos <= end)
|
||||
k_in = (k_pos >= start) & (k_pos <= end)
|
||||
mm = q_in[:, None] & k_in[None, :]
|
||||
if mm_clamp_sw > 0:
|
||||
mm &= delta < mm_clamp_sw
|
||||
keep |= mm
|
||||
|
||||
q_i = q[q_off : q_off + q_len].float().transpose(0, 1)
|
||||
k_i = k_per_req[req_idx].float().transpose(0, 1)
|
||||
v_i = v_per_req[req_idx].float().transpose(0, 1)
|
||||
if repeats > 1:
|
||||
k_i = k_i.repeat_interleave(repeats, dim=0)
|
||||
v_i = v_i.repeat_interleave(repeats, dim=0)
|
||||
|
||||
scores = (q_i @ k_i.transpose(-1, -2)) * scale
|
||||
scores = scores.masked_fill(~keep[None], float("-inf"))
|
||||
out[q_off : q_off + q_len] = (scores.softmax(-1) @ v_i).transpose(0, 1)
|
||||
q_off += q_len
|
||||
return out
|
||||
|
||||
|
||||
def _split(packed: torch.Tensor, lens: list[int]) -> list[torch.Tensor]:
|
||||
return list(packed.split(lens))
|
||||
|
||||
|
||||
def _reference(q, k, v, query_lens, seq_lens, mm_ranges, sw_left, scale, **kwargs):
|
||||
return _dense_reference(
|
||||
q,
|
||||
_split(k, seq_lens),
|
||||
_split(v, seq_lens),
|
||||
query_lens,
|
||||
seq_lens,
|
||||
mm_ranges,
|
||||
sw_left,
|
||||
scale,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _run_kernel(
|
||||
q, k, v, query_lens, seq_lens, mm_ranges, sliding_window_left, scale, mm_clamp_sw=0
|
||||
):
|
||||
cu_q = _cu_seqlens(query_lens)
|
||||
cu_k = _cu_seqlens(seq_lens)
|
||||
|
||||
staging = torch.full((int(cu_q[-1]), 2), 12345, dtype=torch.int32).numpy()
|
||||
num_rows = fill_mm_prefix_query_ranges(
|
||||
staging, mm_ranges, cu_q, torch.tensor(seq_lens, dtype=torch.int32)
|
||||
)
|
||||
assert num_rows > 0, "test case must have at least one in-range query token"
|
||||
q_ranges = torch.from_numpy(staging[:num_rows]).to(DEVICE)
|
||||
cu_q_gpu = cu_q.to(DEVICE)
|
||||
|
||||
out = torch.empty_like(q)
|
||||
flash_attn_varlen_func(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
out=out,
|
||||
cu_seqlens_q=cu_q_gpu,
|
||||
cu_seqlens_k=cu_k.to(DEVICE),
|
||||
max_seqlen_q=max(query_lens),
|
||||
max_seqlen_k=max(seq_lens),
|
||||
softmax_scale=scale,
|
||||
causal=False,
|
||||
fa_version=4,
|
||||
mask_mod=_make_mm_prefix_mask_mod(
|
||||
sliding_window=mm_clamp_sw, sliding_window_left=sliding_window_left
|
||||
),
|
||||
aux_tensors=[q_ranges, cu_q_gpu],
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _randn_qkv(query_lens, seq_lens):
|
||||
torch.manual_seed(0)
|
||||
q = torch.randn(sum(query_lens), NUM_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
|
||||
k = torch.randn(sum(seq_lens), NUM_KV_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
|
||||
v = torch.randn(sum(seq_lens), NUM_KV_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
|
||||
return q, k, v, HEAD_SIZE**-0.5
|
||||
|
||||
|
||||
# (name, query_lens, seq_lens, mm_ranges). One shape per index computation the
|
||||
# mask_mod performs; shapes that differ only in request count are omitted.
|
||||
CASES = [
|
||||
# cu_seqlens_q[b] + q_local: unequal query lens across the batch, the
|
||||
# packing the pooling workload never produced.
|
||||
(
|
||||
"varlen_batch",
|
||||
[128, 64, 200],
|
||||
[128, 64, 200],
|
||||
{0: [(8, 71)], 1: [(0, 31), (40, 55)], 2: [(64, 191)]},
|
||||
),
|
||||
# q_abs = q_idx + (seqlen_k - seqlen_q): ranges are absolute prompt
|
||||
# positions, so part of each range sits in the context.
|
||||
(
|
||||
"context_offset",
|
||||
[64],
|
||||
[320],
|
||||
{0: [(32, 95), (200, 287)]},
|
||||
),
|
||||
# Decode rows: the query token is generated, so it is in no range and must
|
||||
# get the (-1, -1) sentinel. One prefill row keeps the batch mixed.
|
||||
(
|
||||
"mixed_prefill_decode",
|
||||
[160, 1, 1, 1],
|
||||
[160, 512, 300, 97],
|
||||
{0: [(32, 127)], 1: [(4, 259)], 2: [(8, 71)], 3: [(1, 64)]},
|
||||
),
|
||||
]
|
||||
|
||||
# A 320-token range, wider than the window. Every CASES range is narrower than
|
||||
# the window and therefore clamp-insensitive, so the window modes are exercised
|
||||
# on this shape instead: images larger than the window are exactly why
|
||||
# mm_prefix_clamp_sliding_window exists.
|
||||
WIDE_RANGE_CASE = ([384], [384], {0: [(32, 351)]})
|
||||
|
||||
# (sliding_window_left, mm_clamp_sw). sliding_window_left selects between the
|
||||
# two mask_mod variants; mm_clamp_sw gates the Gemma4 clamp inside the sliding
|
||||
# one. Gemma4 sets mm_clamp_sw == sw_val, and the unclamped variant ignores
|
||||
# mm_clamp_sw, so a clamp without a window is not a reachable configuration.
|
||||
WINDOW_MODES = [
|
||||
(None, 0),
|
||||
(SLIDING_WINDOW_LEFT, 0),
|
||||
(SLIDING_WINDOW_LEFT, SLIDING_WINDOW_LEFT),
|
||||
]
|
||||
WINDOW_IDS = ["full_causal", "window", "window_clamped"]
|
||||
|
||||
|
||||
@requires_fa4
|
||||
@pytest.mark.parametrize("case", CASES, ids=[c[0] for c in CASES])
|
||||
def test_mm_prefix_mask_mod_matches_dense_reference(case):
|
||||
_, query_lens, seq_lens, mm_ranges = case
|
||||
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
|
||||
args = (q, k, v, query_lens, seq_lens, mm_ranges, SLIDING_WINDOW_LEFT, scale)
|
||||
torch.testing.assert_close(
|
||||
_run_kernel(*args).float(), _reference(*args), atol=2e-2, rtol=2e-2
|
||||
)
|
||||
|
||||
|
||||
@requires_fa4
|
||||
@pytest.mark.parametrize("window_mode", WINDOW_MODES, ids=WINDOW_IDS)
|
||||
def test_window_modes_on_a_range_wider_than_the_window(window_mode):
|
||||
"""Cover the three reachable window configurations.
|
||||
|
||||
The clamped mode additionally asserts the clamp changes the mask at all,
|
||||
without which a range narrower than the window would leave the clamp branch
|
||||
unexercised while the test still passed.
|
||||
"""
|
||||
sliding_window_left, mm_clamp_sw = window_mode
|
||||
query_lens, seq_lens, mm_ranges = WIDE_RANGE_CASE
|
||||
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
|
||||
args = (q, k, v, query_lens, seq_lens, mm_ranges, sliding_window_left, scale)
|
||||
|
||||
expected = _reference(*args, mm_clamp_sw=mm_clamp_sw)
|
||||
if mm_clamp_sw:
|
||||
assert not torch.allclose(
|
||||
expected, _reference(*args, mm_clamp_sw=0), atol=2e-2, rtol=2e-2
|
||||
), "range is not wide enough to exercise the clamp branch"
|
||||
|
||||
actual = _run_kernel(*args, mm_clamp_sw=mm_clamp_sw)
|
||||
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
|
||||
|
||||
|
||||
@requires_fa4
|
||||
def test_ranges_outside_chunk_degrade_to_causal():
|
||||
"""A range fully behind the scheduled chunk must not widen the mask.
|
||||
|
||||
Under chunked prefill a request's ranges routinely sit entirely in the
|
||||
already-computed context. Indexing by query token makes those a no-op; the
|
||||
result must be identical to running with no ranges at all.
|
||||
"""
|
||||
query_lens, seq_lens = [64], [512]
|
||||
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
|
||||
|
||||
# Range (16, 79) is entirely below the chunk start (448), plus one live
|
||||
# range so the fill still reports rows.
|
||||
args = (q, k, v, query_lens, seq_lens)
|
||||
actual = _run_kernel(*args, {0: [(16, 79), (448, 511)]}, None, scale)
|
||||
expected = _reference(*args, {0: [(448, 511)]}, None, scale)
|
||||
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# FA4 through the metadata builder and the paged KV cache
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# Stock google/gemma-4-E2B-it ships text_config.use_bidirectional_attention as
|
||||
# null, so is_mm_prefix_lm is False out of the box. Tests that exercise the
|
||||
# builder must flip it via `_enable_mm_prefix`. Only config.json / tokenizer
|
||||
# are read; weights are never loaded.
|
||||
MODEL = "google/gemma-4-E2B-it"
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
SLIDING_WINDOW = 256
|
||||
|
||||
# Request 0 is a prefill chunk whose range starts mid-context; requests 1-3 are
|
||||
# decodes whose generated token sits outside every range.
|
||||
PAGED_SEQ_LENS = [352, 513, 200, 97]
|
||||
PAGED_QUERY_LENS = [96, 1, 1, 1]
|
||||
PAGED_MM_RANGES = {
|
||||
0: [(224, 287), (300, 351)],
|
||||
1: [(4, 259)],
|
||||
2: [(0, 63), (80, 143)],
|
||||
3: [(1, 64)],
|
||||
}
|
||||
|
||||
|
||||
def _enable_mm_prefix(vllm_config):
|
||||
"""Flip stock Gemma4's null use_bidirectional_attention to "vision".
|
||||
|
||||
``ModelConfig.__init__`` derives ``model_arch_config`` once from
|
||||
``hf_text_config``, and ``is_mm_prefix_lm`` is a ``cached_property`` that
|
||||
may already hold False from that first derivation, so re-derive and drop
|
||||
the cache.
|
||||
"""
|
||||
model_config = vllm_config.model_config
|
||||
model_config.hf_text_config.use_bidirectional_attention = "vision"
|
||||
model_config.model_arch_config = model_config.get_model_arch_config()
|
||||
model_config.__dict__.pop("is_mm_prefix_lm", None)
|
||||
return vllm_config
|
||||
|
||||
|
||||
@requires_fa4
|
||||
def test_decode_only_batch_reports_no_ranges():
|
||||
"""Decode-only steps must carry no mm_prefix metadata at all.
|
||||
|
||||
This is what makes FULL CUDA graph capture consistent for this feature.
|
||||
Capture runs through ``_dummy_run`` with no multimodal requests, so no
|
||||
mask_mod is attached to the captured graph; a decode-only replay must
|
||||
therefore also want no mask_mod, or the captured graph would silently drop
|
||||
it. Indexing by query token gives that for free, because a generated token
|
||||
is always past every prompt range.
|
||||
|
||||
The range-id scheme keyed off the request having ranges at all, so it
|
||||
attached a mask_mod to decode steps and did not have this property.
|
||||
"""
|
||||
vllm_config = _enable_mm_prefix(
|
||||
create_vllm_config(
|
||||
model_name=MODEL,
|
||||
max_model_len=1024,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_gpu_blocks=256,
|
||||
)
|
||||
)
|
||||
decode_batch = BatchSpec(
|
||||
seq_lens=[513, 200, 97], query_lens=[1, 1, 1], name="decode_only"
|
||||
)
|
||||
common = create_common_attn_metadata(decode_batch, BLOCK_SIZE, DEVICE)
|
||||
common.mm_req_doc_ranges = {0: [(4, 259)], 1: [(0, 63)], 2: [(1, 64)]}
|
||||
|
||||
builder = FlashAttentionMetadataBuilder(
|
||||
create_standard_kv_cache_spec(vllm_config),
|
||||
["model.layers.0.self_attn.attn"],
|
||||
vllm_config,
|
||||
DEVICE,
|
||||
)
|
||||
md = builder.build(common_prefix_len=0, common_attn_metadata=common)
|
||||
assert md.mm_prefix_query_range_tensor is None
|
||||
|
||||
|
||||
@requires_fa4
|
||||
@pytest.mark.parametrize(
|
||||
"head_size",
|
||||
[
|
||||
# 128: FA4's default SM100 path (not the dedicated hd256 kernel), so
|
||||
# paged KV + seqused_k works on B200 and H100. Non-paged mm_prefix
|
||||
# cases in this file already use HEAD_SIZE=128.
|
||||
pytest.param(128, id="hd128"),
|
||||
# 512: Gemma4 global head dim; FA4 resolves on H100, skips on
|
||||
# Blackwell (TMEM).
|
||||
pytest.param(512, id="global_512"),
|
||||
],
|
||||
)
|
||||
def test_mm_prefix_kv_cache_path(head_size: int):
|
||||
"""FA4 + mask_mod + block_table matches a dense reference.
|
||||
|
||||
Use head_size=128 on B200/H100 (FA4 + paged/`seqused_k` supported) and
|
||||
512 on H100 only (Blackwell FA4 rejects 512 via TMEM). Avoid 256: SM100's
|
||||
dedicated hd256 2CTA kernel asserts away ``seqused_k``, which paged KV
|
||||
requires.
|
||||
|
||||
Tensors, kv_cache_spec, and FlashAttentionImpl must all use the same
|
||||
``head_size`` — ``run_attention_backend`` / ``create_standard_kv_cache_spec``
|
||||
read ``get_head_size()`` (=512 for Gemma4), so this test builds them
|
||||
explicitly. The sliding window is set on the impl; mm_prefix encodes it in
|
||||
mask_mod and clears FA's built-in window at forward time.
|
||||
"""
|
||||
torch.manual_seed(0)
|
||||
vllm_config = _enable_mm_prefix(
|
||||
create_vllm_config(
|
||||
model_name=MODEL,
|
||||
max_model_len=max(PAGED_SEQ_LENS),
|
||||
block_size=BLOCK_SIZE,
|
||||
num_gpu_blocks=2048,
|
||||
)
|
||||
)
|
||||
assert vllm_config.model_config.is_mm_prefix_lm
|
||||
|
||||
mc = vllm_config.model_config
|
||||
# Keep every get_head_size() reader (builder helpers, etc.) on the same dim.
|
||||
mc.get_head_size = MethodType(lambda self: head_size, mc)
|
||||
|
||||
# Skip under the same config Gemma4 forces (flash_attn_version=4), so the
|
||||
# check matches FlashAttentionImpl's get_flash_attn_version call.
|
||||
with set_current_vllm_config(vllm_config):
|
||||
if get_flash_attn_version(head_size=head_size) != 4:
|
||||
pytest.skip(f"FA4 does not support head_size={head_size} on this device")
|
||||
|
||||
num_heads = mc.get_num_attention_heads(vllm_config.parallel_config)
|
||||
num_kv_heads = mc.get_num_kv_heads(vllm_config.parallel_config)
|
||||
scale = head_size**-0.5
|
||||
|
||||
batch = BatchSpec(
|
||||
seq_lens=PAGED_SEQ_LENS, query_lens=PAGED_QUERY_LENS, name="mm_prefix_mixed"
|
||||
)
|
||||
kv_cache_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_size=head_size,
|
||||
dtype=mc.dtype,
|
||||
sliding_window=SLIDING_WINDOW,
|
||||
kv_quant_mode=get_kv_quant_mode(vllm_config.cache_config.cache_dtype),
|
||||
)
|
||||
common = create_common_attn_metadata(batch, BLOCK_SIZE, DEVICE)
|
||||
common.mm_req_doc_ranges = PAGED_MM_RANGES
|
||||
|
||||
qs, new_ks, new_vs, k_fulls, v_fulls, k_ctxs, v_ctxs = [], [], [], [], [], [], []
|
||||
for q_len, s_len in zip(PAGED_QUERY_LENS, PAGED_SEQ_LENS):
|
||||
ctx = s_len - q_len
|
||||
shape = (num_kv_heads, head_size)
|
||||
qs.append(torch.randn(q_len, num_heads, head_size, dtype=DTYPE, device=DEVICE))
|
||||
k_full = torch.randn(s_len, *shape, dtype=DTYPE, device=DEVICE)
|
||||
v_full = torch.randn(s_len, *shape, dtype=DTYPE, device=DEVICE)
|
||||
k_fulls.append(k_full)
|
||||
v_fulls.append(v_full)
|
||||
k_ctxs.append(k_full[:ctx])
|
||||
v_ctxs.append(v_full[:ctx])
|
||||
new_ks.append(k_full[ctx:])
|
||||
new_vs.append(v_full[ctx:])
|
||||
|
||||
query = torch.cat(qs)
|
||||
key = torch.cat(new_ks)
|
||||
value = torch.cat(new_vs)
|
||||
kv_cache = create_and_prepopulate_kv_cache(
|
||||
k_contexts=k_ctxs,
|
||||
v_contexts=v_ctxs,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_size=head_size,
|
||||
dtype=DTYPE,
|
||||
device=DEVICE,
|
||||
num_blocks=2048,
|
||||
common_attn_metadata=common,
|
||||
layout=KVCacheLayout.LBNHC,
|
||||
randomize_blocks=True,
|
||||
)
|
||||
|
||||
# Packed KV layout is [..., 2 * head_size]; impl.split(head_size) needs match.
|
||||
assert kv_cache.shape[-1] == 2 * head_size
|
||||
|
||||
layer_names = ["model.layers.0.self_attn.attn"]
|
||||
with set_current_vllm_config(vllm_config):
|
||||
builder = FlashAttentionMetadataBuilder(
|
||||
kv_cache_spec, layer_names, vllm_config, DEVICE
|
||||
)
|
||||
attn_metadata = builder.build(common_prefix_len=0, common_attn_metadata=common)
|
||||
# head_size=128 keeps FA4 under local attention on Blackwell (the
|
||||
# FA4→FA2 demotion is only for local+256). Window is still encoded in
|
||||
# mask_mod at forward; FA's built-in window is cleared there.
|
||||
impl = FlashAttentionImpl(
|
||||
num_heads=num_heads,
|
||||
head_size=head_size,
|
||||
scale=scale,
|
||||
num_kv_heads=num_kv_heads,
|
||||
alibi_slopes=None,
|
||||
sliding_window=SLIDING_WINDOW,
|
||||
kv_cache_dtype="auto",
|
||||
)
|
||||
assert impl.vllm_flash_attn_version == 4, (
|
||||
f"expected FA4, got FA{impl.vllm_flash_attn_version} for "
|
||||
f"head_size={head_size}"
|
||||
)
|
||||
assert impl.head_size == head_size == kv_cache_spec.head_size
|
||||
|
||||
mock_layer = MockAttentionLayer(DEVICE)
|
||||
output = torch.empty_like(query)
|
||||
impl.do_kv_cache_update(
|
||||
mock_layer, key, value, kv_cache, attn_metadata.slot_mapping
|
||||
)
|
||||
actual = impl.forward(
|
||||
mock_layer, query, key, value, kv_cache, attn_metadata, output=output
|
||||
)
|
||||
|
||||
ref_args = (query, k_fulls, v_fulls, PAGED_QUERY_LENS, PAGED_SEQ_LENS)
|
||||
expected = _dense_reference(*ref_args, PAGED_MM_RANGES, SLIDING_WINDOW, scale)
|
||||
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
|
||||
|
||||
# Without this the assertion above would also pass if the mask_mod were
|
||||
# silently dropped, since the batch would then be plain causal + window.
|
||||
causal_only = _dense_reference(*ref_args, {}, SLIDING_WINDOW, scale)
|
||||
assert not torch.allclose(expected, causal_only, atol=2e-2, rtol=2e-2), (
|
||||
"test batch does not actually exercise the mm_prefix branch"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA backend imports")
|
||||
@pytest.mark.parametrize(
|
||||
"query_len,seq_len,spans,expected,unclamped_expected",
|
||||
[
|
||||
(16, 32, [(20, 28)], True, True),
|
||||
(16, 32, [(0, 16)], False, True),
|
||||
(16, 32, [(0, 17)], True, True),
|
||||
(16, 32, [(32, 40)], False, False),
|
||||
(16, 32, [(31, 40)], False, True),
|
||||
(1, 24, [(20, 28)], False, True),
|
||||
(0, 24, [(20, 28)], False, False),
|
||||
(16, 32, [(20, 20)], False, False),
|
||||
(16, 64, [(20, 28)], False, False),
|
||||
],
|
||||
)
|
||||
def test_composite_routes_queries_that_need_image_masking(
|
||||
query_len, seq_len, spans, expected, unclamped_expected
|
||||
):
|
||||
"""Historical images and single-query steps must use the causal graph path."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.v1.attention.backends.composite import requires_mm_prefix
|
||||
|
||||
common = SimpleNamespace(
|
||||
max_query_len=query_len,
|
||||
mm_req_doc_ranges={0: spans},
|
||||
query_start_loc_cpu=torch.tensor([0, query_len]),
|
||||
seq_lens_cpu_upper_bound=torch.tensor([seq_len]),
|
||||
)
|
||||
assert requires_mm_prefix(common) is expected
|
||||
assert requires_mm_prefix(common, unclamped_window=True) is unclamped_expected
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA attention kernels")
|
||||
@pytest.mark.parametrize("head_size", [256, 512])
|
||||
@pytest.mark.parametrize(
|
||||
"reverse_children,cache_dtype",
|
||||
[(False, "auto"), (True, "auto"), (False, "fp8_e4m3")],
|
||||
)
|
||||
@pytest.mark.parametrize("causal_backend_name", ["FLASHINFER", "FLASH_ATTN"])
|
||||
def test_composite_shared_cache_across_image_and_causal_steps(
|
||||
head_size, reverse_children, cache_dtype, causal_backend_name
|
||||
):
|
||||
"""Changing routes must preserve KV writes, image masking and graph replay."""
|
||||
if causal_backend_name == "FLASHINFER":
|
||||
if not current_platform.is_device_capability_family(100):
|
||||
pytest.skip("The Triton/FlashInfer composite supports Blackwell")
|
||||
else:
|
||||
if not current_platform.is_device_capability(90):
|
||||
pytest.skip("The Triton/FlashAttention composite supports Hopper")
|
||||
if reverse_children or cache_dtype != "auto":
|
||||
pytest.skip("Reverse-child and FP8 coverage is backend-independent")
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.model_executor.layers.attention import Attention
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
from vllm.v1.attention.backend import AttentionCGSupport, CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.composite import (
|
||||
MMPrefixAttentionRouting,
|
||||
create_composite_attention_backend,
|
||||
)
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.flashinfer import (
|
||||
FlashInferBackend,
|
||||
FlashInferMetadata,
|
||||
FlashInferTrtllmAPIDecode,
|
||||
TRTLLMPrefill,
|
||||
)
|
||||
from vllm.v1.attention.backends.triton_attn import (
|
||||
TritonAttentionBackend,
|
||||
TritonAttentionMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.triton_flash_attn import (
|
||||
TritonFlashAttentionBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.triton_flashinfer import (
|
||||
TritonFlashInferBackend,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, SlidingWindowSpec
|
||||
|
||||
if causal_backend_name == "FLASHINFER":
|
||||
backend = TritonFlashInferBackend
|
||||
causal_metadata_type = FlashInferMetadata
|
||||
block_size = backend.get_supported_kernel_block_sizes()[0]
|
||||
else:
|
||||
backend = TritonFlashAttentionBackend
|
||||
causal_metadata_type = FlashAttentionMetadata
|
||||
block_size = backend.get_preferred_block_size(16)
|
||||
num_blocks = (209 + block_size - 1) // block_size
|
||||
torch.manual_seed(42)
|
||||
attention_config = {"backend": backend.get_name()}
|
||||
if causal_backend_name == "FLASH_ATTN":
|
||||
attention_config["flash_attn_version"] = 4
|
||||
cfg = EngineArgs(
|
||||
model="google/gemma-4-31B-it",
|
||||
dtype="bfloat16",
|
||||
max_model_len=512,
|
||||
max_num_seqs=4,
|
||||
max_num_batched_tokens=512,
|
||||
block_size=block_size,
|
||||
kv_cache_dtype=cache_dtype,
|
||||
enforce_eager=True,
|
||||
attention_config=attention_config,
|
||||
).create_engine_config()
|
||||
cfg.cache_config.kv_cache_layout = "LBHNC"
|
||||
window = 128 if head_size == 256 else None
|
||||
storage_dtype = torch.uint8 if cache_dtype == "fp8_e4m3" else DTYPE
|
||||
spec_kwargs = dict(
|
||||
block_size=block_size,
|
||||
num_kv_heads=16,
|
||||
head_size=head_size,
|
||||
dtype=storage_dtype,
|
||||
kv_quant_mode=get_kv_quant_mode(cache_dtype),
|
||||
)
|
||||
spec = (
|
||||
SlidingWindowSpec(**spec_kwargs, sliding_window=window)
|
||||
if window
|
||||
else FullAttentionSpec(**spec_kwargs)
|
||||
)
|
||||
if reverse_children:
|
||||
# Swapping the children and policy must preserve outputs and KV writes;
|
||||
# dispatch cannot depend on a particular child's class or position.
|
||||
class ReversedRouting(MMPrefixAttentionRouting):
|
||||
capture_variant = 0
|
||||
|
||||
def select(self, metadata):
|
||||
return 1 - super().select(metadata)
|
||||
|
||||
@staticmethod
|
||||
def variant_uses_mm_prefix(variant):
|
||||
return variant == 1
|
||||
|
||||
backend = create_composite_attention_backend(
|
||||
FlashInferBackend,
|
||||
TritonAttentionBackend,
|
||||
name="ReversedCompositeBackend",
|
||||
backend_name="CUSTOM",
|
||||
module=__name__,
|
||||
routing_policy=ReversedRouting,
|
||||
)
|
||||
with set_current_vllm_config(cfg), set_default_torch_dtype(DTYPE):
|
||||
layer = Attention(
|
||||
32,
|
||||
head_size,
|
||||
head_size**-0.5,
|
||||
num_kv_heads=16,
|
||||
cache_config=cfg.cache_config,
|
||||
prefix="composite_test",
|
||||
per_layer_sliding_window=window,
|
||||
attn_backend=backend,
|
||||
).to(DEVICE)
|
||||
layer.mm_prefix_clamp_sliding_window = window is not None
|
||||
assert backend.get_builder_cls().get_cudagraph_support(cfg, spec) == (
|
||||
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
|
||||
)
|
||||
if window:
|
||||
layer.mm_prefix_clamp_sliding_window = False
|
||||
assert backend.get_builder_cls().get_cudagraph_support(cfg, spec) == (
|
||||
AttentionCGSupport.NEVER
|
||||
)
|
||||
layer.mm_prefix_clamp_sliding_window = True
|
||||
builder = backend.get_builder_cls()(spec, ["composite_test"], cfg, DEVICE)
|
||||
# Match production, where unwritten page tails are zero-initialized.
|
||||
cache = torch.zeros(
|
||||
num_blocks,
|
||||
16,
|
||||
block_size,
|
||||
2 * head_size,
|
||||
dtype=storage_dtype,
|
||||
device=DEVICE,
|
||||
)
|
||||
keys = torch.randn(209, 16, head_size, dtype=DTYPE, device=DEVICE)
|
||||
values = torch.randn_like(keys)
|
||||
if cache_dtype == "fp8_e4m3":
|
||||
keys = keys.to(torch.float8_e4m3fn).to(DTYPE)
|
||||
values = values.to(torch.float8_e4m3fn).to(DTYPE)
|
||||
table = torch.arange(num_blocks, dtype=torch.int32, device=DEVICE).unsqueeze(0)
|
||||
previous = 0
|
||||
for end, spans, metadata_type in [
|
||||
(128, [(32, 111)], TritonAttentionMetadata),
|
||||
(129, [(32, 111)], causal_metadata_type),
|
||||
(145, [(32, 111)], causal_metadata_type),
|
||||
(209, [(32, 111), (160, 207)], TritonAttentionMetadata),
|
||||
]:
|
||||
qlen = end - previous
|
||||
starts = torch.tensor([0, qlen], dtype=torch.int32)
|
||||
lengths = torch.tensor([end], dtype=torch.int32)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=starts.to(DEVICE),
|
||||
query_start_loc_cpu=starts,
|
||||
seq_lens=lengths.to(DEVICE),
|
||||
seq_lens_cpu_upper_bound=lengths,
|
||||
num_reqs=1,
|
||||
num_actual_tokens=qlen,
|
||||
max_query_len=qlen,
|
||||
max_seq_len=end,
|
||||
block_table_tensor=table,
|
||||
slot_mapping=torch.arange(previous, end, device=DEVICE),
|
||||
mm_req_doc_ranges={0: spans},
|
||||
)
|
||||
metadata = builder.build(0, common)
|
||||
assert isinstance(metadata, metadata_type)
|
||||
if isinstance(metadata, FlashInferMetadata):
|
||||
if qlen == 1:
|
||||
assert isinstance(metadata.decode, FlashInferTrtllmAPIDecode)
|
||||
else:
|
||||
assert isinstance(metadata.prefill, TRTLLMPrefill)
|
||||
query = torch.randn(qlen, 32, head_size, dtype=DTYPE, device=DEVICE)
|
||||
if cache_dtype == "fp8_e4m3":
|
||||
query = query.to(torch.float8_e4m3fn).to(DTYPE)
|
||||
key, value = keys[previous:end], values[previous:end]
|
||||
output = torch.empty_like(query)
|
||||
layer.impl.do_kv_cache_update(layer, key, value, cache, common.slot_mapping)
|
||||
layer.impl.forward(layer, query, key, value, cache, metadata, output)
|
||||
expected = _dense_reference(
|
||||
query,
|
||||
[keys[:end]],
|
||||
[values[:end]],
|
||||
[qlen],
|
||||
[end],
|
||||
{0: spans},
|
||||
window,
|
||||
head_size**-0.5,
|
||||
mm_clamp_sw=window or 0,
|
||||
)
|
||||
torch.testing.assert_close(output.float(), expected, atol=2e-2, rtol=2e-2)
|
||||
if qlen == 1:
|
||||
metadata = builder.build_for_cudagraph_capture(common)
|
||||
assert isinstance(metadata, metadata_type)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
layer.impl.forward(
|
||||
layer, query, key, value, cache, metadata, output
|
||||
)
|
||||
output.zero_()
|
||||
graph.replay()
|
||||
torch.testing.assert_close(
|
||||
output.float(), expected, atol=2e-2, rtol=2e-2
|
||||
)
|
||||
previous = end
|
||||
@@ -1,315 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Routing/selection tests for the AITER ASM cprr DCP-verify route.
|
||||
|
||||
Companion to the upstream segmented-verify tests. Everything here is pure CPU:
|
||||
it pins the *decisions* (which route a KV group takes, which head count the
|
||||
kernel runs at, which configurations are refused) rather than kernel numerics.
|
||||
The numerics parity test against the segmented route needs a GPU and both
|
||||
routes built; it is marked and skipped when unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
rocm_aiter_mla = pytest.importorskip(
|
||||
"vllm.v1.attention.backends.mla.rocm_aiter_mla",
|
||||
reason="ROCm AITER MLA backend not available",
|
||||
)
|
||||
|
||||
_heads = rocm_aiter_mla._asm_dcp_verify_heads
|
||||
_configured = rocm_aiter_mla._asm_dcp_verify_configured
|
||||
_select_route = rocm_aiter_mla._select_dcp_decode_route
|
||||
Route = rocm_aiter_mla._DCPDecodeRoute
|
||||
NATIVE = rocm_aiter_mla._NATIVE_CPRR_HEADS
|
||||
MIN_QLEN = rocm_aiter_mla._MIN_CPRR_QLEN
|
||||
|
||||
|
||||
def test_dcp_verify_env_defaults_to_auto(monkeypatch):
|
||||
monkeypatch.delenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", raising=False)
|
||||
assert rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "auto"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["auto", "asm", "segmented"])
|
||||
def test_dcp_verify_env_accepts_routes(monkeypatch, route):
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", route)
|
||||
assert route == rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY
|
||||
|
||||
|
||||
def test_dcp_verify_env_rejects_unknown_route(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "unknown")
|
||||
with pytest.raises(ValueError, match="Invalid value"):
|
||||
_ = rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# _asm_dcp_verify_heads -- which head count the cprr kernel runs at
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", NATIVE)
|
||||
def test_native_head_counts_are_used_as_is(n):
|
||||
assert _heads(n) == n
|
||||
|
||||
|
||||
def test_non_native_head_count_pads_up_to_the_next_native():
|
||||
"""K3 at TP8/DCP8 gathers 96 heads for the target; the kernel has no 96
|
||||
variant, so it must run at 128, not silently fall out of the asm path."""
|
||||
assert _heads(96) == 128
|
||||
assert _heads(1) == 16
|
||||
assert _heads(17) == 32
|
||||
assert _heads(65) == 128
|
||||
|
||||
|
||||
def test_head_count_above_the_largest_native_is_unservable():
|
||||
"""0 means 'cannot serve'; anything else would route a shape the kernel
|
||||
has no build for."""
|
||||
assert _heads(max(NATIVE) + 1) == 0
|
||||
assert _heads(256) == 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# _asm_dcp_verify_configured -- reachability
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def on_gfx950(monkeypatch):
|
||||
"""The cprr kernels are built only for gfx950, so the gate checks the arch.
|
||||
Patched rather than detected, so both branches run on any runner."""
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx950", lambda: True)
|
||||
|
||||
|
||||
def test_route_needs_dcp(on_gfx950):
|
||||
assert _configured(dcp_world_size=1, cp_interleave=1, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
|
||||
True
|
||||
)
|
||||
|
||||
|
||||
def test_round_robin_interleave_other_than_one_is_excluded(on_gfx950):
|
||||
"""The kernel's global-position causal window assumes interleave 1, the
|
||||
same restriction the segmented gate carries."""
|
||||
assert _configured(dcp_world_size=8, cp_interleave=2, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=16, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
def test_route_needs_multi_token_decode(on_gfx950):
|
||||
"""Single-token decode is already served. Enabling the route for it would
|
||||
pad the head count on every step and buy nothing."""
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=False) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
def test_route_needs_gfx950(monkeypatch):
|
||||
"""hsa/gfx942/mla and hsa/gfx1250/mla carry no cprr rows, so off gfx950 the
|
||||
kernel lookup fails at the first verify step rather than falling back."""
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx950", lambda: False)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# AiterMLAMetadataBuilder -- the route the env value resolves to
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
DCP = 8
|
||||
|
||||
|
||||
def _build(monkeypatch, route, gathered_heads, segmented_supported=True):
|
||||
"""Run the real builder __init__ on CPU at TP8/DCP8 with speculative decoding.
|
||||
|
||||
Stubs only what needs a GPU, AITER, or a DCP group, so the route decision
|
||||
under test is the one the builder actually makes.
|
||||
"""
|
||||
|
||||
def init_common_builder(self, *args, **kwargs):
|
||||
self.num_heads = gathered_heads // DCP
|
||||
self.q_data_type = torch.bfloat16
|
||||
self.mla_dims = SimpleNamespace(
|
||||
kv_lora_rank=512,
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
)
|
||||
self.dcp_world_size = DCP
|
||||
self.reorder_batch_threshold = 5
|
||||
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla.MLACommonMetadataBuilder, "__init__", init_common_builder
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla,
|
||||
"_segmented_dcp_verify_supported",
|
||||
lambda *args: segmented_supported,
|
||||
)
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_fp8_mla_prefill_supported", lambda: False)
|
||||
# These cases pick between cprr and segmented. On a gfx942 runner the real
|
||||
# arch would add the Triton verify route, which this stub cannot build.
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx942", lambda: False)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "get_dcp_group", lambda: SimpleNamespace(rank_in_group=0)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
torch.cuda,
|
||||
"get_device_properties",
|
||||
lambda device: SimpleNamespace(multi_processor_count=256),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(
|
||||
dtypes=SimpleNamespace(fp8="fp8", fp16="fp16", bf16="bf16"),
|
||||
get_mla_metadata_info_v1=lambda *args, **kwargs: tuple(
|
||||
(1, torch.int32) for _ in range(6)
|
||||
),
|
||||
),
|
||||
)
|
||||
if route is None:
|
||||
monkeypatch.delenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", route)
|
||||
|
||||
config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=4),
|
||||
parallel_config=SimpleNamespace(
|
||||
decode_context_parallel_size=DCP, cp_kv_cache_interleave_size=1
|
||||
),
|
||||
model_config=SimpleNamespace(max_model_len=16, dtype=torch.bfloat16),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=2),
|
||||
cache_config=SimpleNamespace(cache_dtype="fp8_e4m3", num_gpu_blocks=None),
|
||||
compilation_config=SimpleNamespace(
|
||||
cudagraph_mode=SimpleNamespace(has_full_cudagraphs=lambda: False)
|
||||
),
|
||||
)
|
||||
return rocm_aiter_mla.AiterMLAMetadataBuilder(
|
||||
kv_cache_spec=SimpleNamespace(block_size=1, dtype=torch.bfloat16),
|
||||
layer_names=["layer.0"],
|
||||
vllm_config=config,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", [None, "auto", "AUTO"])
|
||||
def test_auto_selects_cprr_for_k3_gathered_heads(on_gfx950, monkeypatch, route):
|
||||
"""K3 at TP8/DCP8 gathers 96 heads; auto must take cprr padded to 128."""
|
||||
builder = _build(monkeypatch, route, gathered_heads=96)
|
||||
assert builder._asm_dcp_verify
|
||||
assert builder._asm_dcp_verify_heads == 128
|
||||
assert builder._num_attention_heads == 128
|
||||
|
||||
|
||||
def test_auto_falls_back_to_segmented_above_largest_native(on_gfx950, monkeypatch):
|
||||
builder = _build(monkeypatch, "auto", gathered_heads=256)
|
||||
assert not builder._asm_dcp_verify
|
||||
assert builder._supports_segmented_dcp_verify
|
||||
|
||||
|
||||
def test_auto_without_any_route_names_the_missing_segmented_build(
|
||||
on_gfx950, monkeypatch
|
||||
):
|
||||
with pytest.raises(ValueError) as exc:
|
||||
_build(monkeypatch, "auto", gathered_heads=256, segmented_supported=False)
|
||||
assert "VLLM_ROCM_AITER_MLA_DCP_VERIFY=auto" in str(exc.value)
|
||||
assert "lacks segmented MLA decode" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["asm", "ASM"])
|
||||
def test_explicit_asm_is_case_insensitive(on_gfx950, monkeypatch, route):
|
||||
"""env_with_choices returns the raw string; ASM used to mean segmented."""
|
||||
assert _build(monkeypatch, route, gathered_heads=96)._asm_dcp_verify
|
||||
|
||||
|
||||
def test_explicit_asm_refuses_unservable_heads(on_gfx950, monkeypatch):
|
||||
with pytest.raises(ValueError) as exc:
|
||||
_build(monkeypatch, "ASM", gathered_heads=256)
|
||||
assert "VLLM_ROCM_AITER_MLA_DCP_VERIFY=asm" in str(exc.value)
|
||||
assert "Set VLLM_ROCM_AITER_MLA_DCP_VERIFY=segmented" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["segmented", "SEGMENTED"])
|
||||
def test_explicit_segmented_never_selects_cprr(on_gfx950, monkeypatch, route):
|
||||
assert not _build(monkeypatch, route, gathered_heads=96)._asm_dcp_verify
|
||||
|
||||
|
||||
def test_auto_off_gfx950_stays_segmented(monkeypatch):
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx950", lambda: False)
|
||||
assert not _build(monkeypatch, "auto", gathered_heads=96)._asm_dcp_verify
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# qlen floor
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_min_cprr_qlen_is_above_two():
|
||||
"""Qlen 2 is below CPRR's floor and must use segmented verification."""
|
||||
assert MIN_QLEN > 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"segmented,triton,causal,qlen,asm,expected",
|
||||
[
|
||||
(True, False, True, 1, True, Route.PLAIN),
|
||||
(True, False, True, 2, True, Route.SEGMENTED),
|
||||
(True, False, True, 3, True, Route.CPRR),
|
||||
(True, False, True, 4, True, Route.CPRR),
|
||||
(True, False, True, 4, False, Route.SEGMENTED),
|
||||
(True, False, False, 2, True, Route.PLAIN),
|
||||
(True, False, False, 4, False, Route.PLAIN),
|
||||
(False, False, True, 3, True, Route.CPRR),
|
||||
# gfx942: no cprr and no segmented, so causal verify goes to Triton.
|
||||
(False, True, True, 1, False, Route.PLAIN),
|
||||
(False, True, True, 2, False, Route.TRITON),
|
||||
(False, True, True, 4, False, Route.TRITON),
|
||||
(False, True, False, 4, False, Route.PLAIN),
|
||||
# cprr still wins at or above its qlen floor.
|
||||
(False, True, True, 4, True, Route.CPRR),
|
||||
(False, True, True, 2, True, Route.TRITON),
|
||||
],
|
||||
)
|
||||
def test_dcp_decode_route(segmented, triton, causal, qlen, asm, expected):
|
||||
route = _select_route(
|
||||
supports_segmented=segmented,
|
||||
supports_triton=triton,
|
||||
causal=causal,
|
||||
max_qo_len=qlen,
|
||||
asm_selected=asm,
|
||||
)
|
||||
assert route is expected
|
||||
|
||||
|
||||
def test_causal_multi_token_batch_without_a_valid_route_fails():
|
||||
with pytest.raises(RuntimeError, match="requires either segmented MLA"):
|
||||
_select_route(
|
||||
supports_segmented=False,
|
||||
supports_triton=False,
|
||||
causal=True,
|
||||
max_qo_len=2,
|
||||
asm_selected=True,
|
||||
)
|
||||
|
||||
|
||||
# Kernel numerics live in test_rocm_aiter_mla_dcp_cprr_numerics.py, which runs
|
||||
# the real builder and the real asm kernel on a gfx950 GPU.
|
||||
@@ -1,547 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""GPU numerics for the AITER ASM cprr DCP-verify route.
|
||||
|
||||
Runs the REAL metadata builder (``AiterMLAMetadataBuilder.build``, so
|
||||
``get_mla_metadata_v1`` is exercised with the cprr kwargs and the persistent
|
||||
schedule buffers are produced) and the REAL asm kernel, on ONE GPU with the DCP
|
||||
ranks simulated one after another.
|
||||
|
||||
That is legitimate because the aiter MLA backend contains no collective on this
|
||||
path: the query all-gather happens in the *layer*, strictly before
|
||||
``forward_mqa``, so the head fold, the round-robin kernel call and the un-fold
|
||||
are pure per-rank local arithmetic in which ``cp_world_size``/``cp_rank`` are
|
||||
just numbers feeding the causal-mask maths. Restricting a shard to a residue
|
||||
class of global positions is exactly what DCP rank r sees.
|
||||
|
||||
Three properties are checked:
|
||||
* each shard matches an exact torch reference over the positions it holds,
|
||||
with causality applied on the GLOBAL position (the thing cprr reconstructs
|
||||
in-kernel and the segmented route instead carries in per-row lengths);
|
||||
* the LSE merge of all shards reproduces full-context attention;
|
||||
* a shard told the wrong ``cp_rank`` fails both -- without this positive
|
||||
control a passing run proves nothing, since a kernel that ignored global
|
||||
positions still produces plausible-looking output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found # noqa: E402
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla # noqa: E402
|
||||
|
||||
KV_LORA_RANK = 512
|
||||
QK_ROPE_HEAD_DIM = 64
|
||||
QK_NOPE_HEAD_DIM = 128
|
||||
HEAD_SIZE = KV_LORA_RANK + QK_ROPE_HEAD_DIM
|
||||
SCALE = (QK_NOPE_HEAD_DIM + QK_ROPE_HEAD_DIM) ** -0.5
|
||||
|
||||
DCP = 8
|
||||
NUM_REQS = 8
|
||||
CTX = 256
|
||||
QLEN = 5 # 1 + num_speculative_tokens; must clear _MIN_CPRR_QLEN
|
||||
|
||||
# fp8-e4m3 keeps 3 mantissa bits, so the relative error floor is ~6.2e-2. Gates
|
||||
# are relative for the same reason: an absolute bound would just be a bound on
|
||||
# the output magnitude.
|
||||
SHARD_RTOL = 1.0e-1
|
||||
MERGE_RTOL = 5.0e-2
|
||||
|
||||
MODEL = "deepseek-ai/DeepSeek-R1"
|
||||
|
||||
|
||||
def _gpu_available() -> bool:
|
||||
return is_aiter_found() and torch.accelerator.is_available()
|
||||
|
||||
|
||||
def _on_gfx950() -> bool:
|
||||
if not is_aiter_found():
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
return on_gfx950()
|
||||
|
||||
|
||||
requires_cprr = pytest.mark.skipif(
|
||||
not (_gpu_available() and _on_gfx950()),
|
||||
reason="cprr DCP verify needs ROCm + AITER on gfx950",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def select_asm_route(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "asm")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# reference maths
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _torch_reference(q_f32, kv_f32, ctx, qlen, scale, positions):
|
||||
"""Exact absorbed-MLA decode over an explicit set of GLOBAL KV positions.
|
||||
|
||||
A shard sees only ``positions``, but causality still uses the global
|
||||
position: query token i (global position ctx + i) may attend to any p in
|
||||
positions with p <= ctx + i. Restricting ``positions`` to a round-robin
|
||||
residue class is precisely DCP rank r's view.
|
||||
"""
|
||||
nr, _, heads, _ = q_f32.shape
|
||||
dev = q_f32.device
|
||||
o = torch.zeros(nr, qlen, heads, KV_LORA_RANK, dtype=torch.float32, device=dev)
|
||||
lse = torch.full((nr, qlen, heads), float("-inf"), dtype=torch.float32, device=dev)
|
||||
for r in range(nr):
|
||||
kv_sel = kv_f32[r].index_select(0, positions)
|
||||
for i in range(qlen):
|
||||
valid = positions <= (ctx + i)
|
||||
if not bool(valid.any()):
|
||||
continue
|
||||
k = kv_sel[valid]
|
||||
s = (q_f32[r, i] @ k.T) * scale
|
||||
m = s.max(dim=-1, keepdim=True).values
|
||||
p = torch.exp(s - m)
|
||||
denom = p.sum(dim=-1, keepdim=True)
|
||||
o[r, i] = (p / denom) @ k[:, :KV_LORA_RANK]
|
||||
lse[r, i] = m.squeeze(-1) + torch.log(denom.squeeze(-1))
|
||||
return o, lse
|
||||
|
||||
|
||||
def _merge_partials(os_, lses):
|
||||
"""Cross-shard softmax merge (natural-log LSE)."""
|
||||
stack_lse = torch.stack(lses)
|
||||
m = stack_lse.max(dim=0).values
|
||||
w = torch.exp(stack_lse - m)
|
||||
num = (w.unsqueeze(-1) * torch.stack(os_)).sum(dim=0)
|
||||
den = w.sum(dim=0).unsqueeze(-1)
|
||||
return num / den, m + torch.log(w.sum(dim=0))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# single-process rank simulation
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _FakeGroup:
|
||||
def __init__(self, world_size: int, rank: int):
|
||||
self.world_size = world_size
|
||||
self.rank_in_group = rank
|
||||
self.rank = rank
|
||||
self.local_rank = rank
|
||||
|
||||
def all_gather(self, tensor, dim=0):
|
||||
raise RuntimeError(
|
||||
"collective called in a single-process test -- the path under test "
|
||||
"is supposed to be collective-free; this indicates a real change"
|
||||
)
|
||||
|
||||
|
||||
def _install_fake_groups(dcp_size: int, cp_rank: int, tp_size: int = 1) -> None:
|
||||
"""Point vLLM's parallel_state at rank-simulating stubs (no NCCL)."""
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
|
||||
|
||||
dcp = _FakeGroup(dcp_size, cp_rank)
|
||||
tp = _FakeGroup(tp_size, cp_rank)
|
||||
ps.get_dcp_group = lambda: dcp
|
||||
ps.get_tp_group = lambda: tp
|
||||
# Both of these imported the symbol directly at module import time, so
|
||||
# patching parallel_state alone leaves them resolving the real group (and
|
||||
# the builder then reports dcp_world_size 1, silently skipping the route).
|
||||
backend.get_dcp_group = lambda: dcp
|
||||
mla_attention.get_dcp_group = lambda: dcp
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_parallel_groups():
|
||||
"""Undo _install_fake_groups after every test.
|
||||
|
||||
It patches module globals in three modules, so without this the fake DCP
|
||||
group leaks into the rest of the pytest session and silently breaks
|
||||
unrelated tests that expect a real (or absent) group.
|
||||
"""
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
|
||||
|
||||
saved = [
|
||||
(mod, name, getattr(mod, name))
|
||||
for mod, name in (
|
||||
(ps, "get_dcp_group"),
|
||||
(ps, "get_tp_group"),
|
||||
(backend, "get_dcp_group"),
|
||||
(mla_attention, "get_dcp_group"),
|
||||
)
|
||||
]
|
||||
yield
|
||||
for mod, name, value in saved:
|
||||
setattr(mod, name, value)
|
||||
|
||||
|
||||
class _PrefillBackendStub:
|
||||
"""The base builder does ``attention_layer.prefill_backend.clone()``.
|
||||
|
||||
prefill_backend is consulted only from the chunked-context prefill path,
|
||||
which a decode-only test never enters.
|
||||
"""
|
||||
|
||||
def clone(self):
|
||||
return self
|
||||
|
||||
|
||||
def _make_ctx_layer(vllm_config):
|
||||
"""Stand-in for the registered attention layer in static_forward_context.
|
||||
|
||||
``MLACommonMetadataBuilder.__init__`` reads the MLA dims, ``dcp_manager``
|
||||
and ``prefill_backend`` off this object. ``dcp_manager`` is the Direct-DCP
|
||||
symmetric-memory workspace, used ONLY by the chunked-prefill KV all-gather;
|
||||
it is constructed without running __init__ so no peer pointers are exchanged
|
||||
and no collective is issued. That is what keeps this test single-process.
|
||||
"""
|
||||
from vllm.v1.attention.ops.dcp import MLADCPManager
|
||||
|
||||
mgr = object.__new__(MLADCPManager)
|
||||
mgr.init_kv_gather = lambda *a, **k: None
|
||||
|
||||
return SimpleNamespace(
|
||||
non_causal_multi_token_decode=False,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=KV_LORA_RANK,
|
||||
qk_nope_head_dim=QK_NOPE_HEAD_DIM,
|
||||
qk_rope_head_dim=QK_ROPE_HEAD_DIM,
|
||||
v_head_dim=QK_NOPE_HEAD_DIM,
|
||||
dcp_manager=mgr,
|
||||
prefill_backend=_PrefillBackendStub(),
|
||||
)
|
||||
|
||||
|
||||
def _ensure_workspace_manager(device: torch.device) -> None:
|
||||
"""Init the global workspace manager, which GPUModelRunner does in production.
|
||||
|
||||
``AiterMLAMetadataBuilder.__init__`` reserves the fp8 prefill
|
||||
persistent-scheduling scratch through ``current_workspace_manager()``, so
|
||||
merely constructing a builder outside a serve trips its assert. Idempotent:
|
||||
one builder is constructed per DCP shard. Deliberately does NOT lock the
|
||||
workspace -- production locks only after warmup, and this keeps allocating
|
||||
across shards.
|
||||
"""
|
||||
from vllm.v1.worker.workspace import (
|
||||
init_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
if not is_workspace_manager_initialized():
|
||||
init_workspace_manager(device)
|
||||
|
||||
|
||||
class _Layer:
|
||||
def __init__(self, device):
|
||||
self._q_scale = torch.tensor(1.0, device=device)
|
||||
self._k_scale = torch.tensor(1.0, device=device)
|
||||
self._v_scale = torch.tensor(1.0, device=device)
|
||||
|
||||
|
||||
def _build_impl(num_heads: int, dcp: int, cp_rank: int):
|
||||
"""Real AiterMLAImpl.forward_mqa bound to a minimally-populated instance.
|
||||
|
||||
Constructing the full impl would drag in kv_b_proj and the rest of the
|
||||
weight-dependent MLA setup -- i.e. model loading, which this test exists to
|
||||
avoid. forward_mqa's fold path reads only the attributes set below.
|
||||
"""
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAImpl
|
||||
|
||||
impl = object.__new__(AiterMLAImpl)
|
||||
impl.kv_lora_rank = KV_LORA_RANK
|
||||
impl.qk_rope_head_dim = QK_ROPE_HEAD_DIM
|
||||
impl.num_heads = num_heads
|
||||
impl.dcp_world_size = dcp
|
||||
impl.dcp_rank = cp_rank
|
||||
impl.pcp_world_size = 1
|
||||
impl.kv_cache_dtype = "fp8"
|
||||
impl.scale = SCALE
|
||||
# `_decode_num_heads` is a read-only property deriving num_heads *
|
||||
# dcp_world_size, both set above; assert rather than assign.
|
||||
assert impl._decode_num_heads == num_heads * dcp
|
||||
return impl
|
||||
|
||||
|
||||
def _make_vllm_config(heads_per_rank: int):
|
||||
"""A DCP8 MLA config with no weights and no distributed init.
|
||||
|
||||
DeepSeek-R1's config supplies the MLA dims (kv_lora_rank 512, rope 64,
|
||||
nope 128) that the aiter asm kernel is built for; only the head count is
|
||||
overridden, to place the GATHERED count (heads_per_rank * DCP) on the
|
||||
kernel variant under test. ``get_num_attention_heads`` reads
|
||||
model_arch_config, a snapshot taken at config-creation time, so patching
|
||||
hf_config alone would be inert.
|
||||
"""
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name=MODEL,
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=2048,
|
||||
max_num_seqs=NUM_REQS * 2,
|
||||
max_num_batched_tokens=4096,
|
||||
)
|
||||
vllm_config.model_config.model_arch_config.total_num_attention_heads = (
|
||||
heads_per_rank
|
||||
)
|
||||
# Without a speculative config the batch reorder threshold stays at 1 and a
|
||||
# qlen-QLEN row is classified as a PREFILL, so the decode path under test is
|
||||
# never reached. _init_reorder_batch_threshold reads exactly these two
|
||||
# fields, so a stand-in is enough and avoids pulling in a draft model.
|
||||
vllm_config.speculative_config = SimpleNamespace(
|
||||
num_speculative_tokens=QLEN - 1, parallel_drafting=False
|
||||
)
|
||||
vllm_config.cache_config.cache_dtype = "fp8"
|
||||
vllm_config.parallel_config.decode_context_parallel_size = DCP
|
||||
vllm_config.parallel_config.cp_kv_cache_interleave_size = 1
|
||||
return vllm_config
|
||||
|
||||
|
||||
def _run_shard(
|
||||
vllm_config,
|
||||
spec,
|
||||
layer_name,
|
||||
device,
|
||||
cp_rank,
|
||||
kern_rank,
|
||||
q_flat,
|
||||
kv_flat,
|
||||
nr,
|
||||
qlen,
|
||||
ctx,
|
||||
dcp,
|
||||
pos,
|
||||
):
|
||||
"""Build real metadata for one DCP rank and run the real asm kernel.
|
||||
|
||||
``kern_rank`` is separate from ``cp_rank`` so the positive control can hand
|
||||
rank r's pages to the kernel while telling it that it is rank r+1.
|
||||
"""
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
|
||||
|
||||
L = ctx + qlen
|
||||
local_len = int(pos.numel())
|
||||
|
||||
# One GLOBAL kv cache: page (req*L + p) holds request req position p. Shards
|
||||
# select pages by residue class, so every shard reads the same underlying
|
||||
# bytes and no re-quantisation noise is introduced between arms.
|
||||
block_table = (
|
||||
torch.arange(nr, device=device).view(nr, 1) * L + pos.view(1, -1)
|
||||
).to(torch.int32)
|
||||
|
||||
# seq_lens is the GLOBAL context; dcp_local_seq_lens is what this rank
|
||||
# actually holds. Passing the global length as the local one walks the
|
||||
# kernel off the end of the page table.
|
||||
seq_lens_cpu = torch.full((nr,), L, dtype=torch.int32)
|
||||
local_cpu = torch.full((nr,), local_len, dtype=torch.int32)
|
||||
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=torch.arange(
|
||||
0, nr * qlen + 1, qlen, dtype=torch.int32, device=device
|
||||
),
|
||||
query_start_loc_cpu=torch.arange(0, nr * qlen + 1, qlen, dtype=torch.int32),
|
||||
seq_lens=seq_lens_cpu.to(device),
|
||||
num_reqs=nr,
|
||||
num_actual_tokens=nr * qlen,
|
||||
max_query_len=qlen,
|
||||
max_seq_len=L,
|
||||
block_table_tensor=block_table,
|
||||
slot_mapping=torch.arange(nr * qlen, dtype=torch.int64, device=device),
|
||||
causal=True,
|
||||
dcp_local_seq_lens=local_cpu.to(device),
|
||||
dcp_local_seq_lens_cpu_upper_bound=local_cpu,
|
||||
)
|
||||
|
||||
_install_fake_groups(dcp, kern_rank)
|
||||
builder = AiterMLAMetadataBuilder(spec, [layer_name], vllm_config, device)
|
||||
md = builder.build(0, common)
|
||||
|
||||
impl = _build_impl(builder.num_heads, dcp, kern_rank)
|
||||
o, lse = impl.forward_mqa(q_flat, kv_flat, md, _Layer(device))
|
||||
torch.accelerator.synchronize()
|
||||
return md, o, lse, local_len
|
||||
|
||||
|
||||
def _numerics(heads_per_rank: int, sabotage: bool = False):
|
||||
"""Run every DCP shard and return (per-shard max rel err, merged rel err)."""
|
||||
import aiter
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
|
||||
device = torch.device("cuda", 0)
|
||||
torch.accelerator.set_device_index(device.index)
|
||||
torch.manual_seed(0)
|
||||
_ensure_workspace_manager(device)
|
||||
|
||||
_install_fake_groups(DCP, 0)
|
||||
vllm_config = _make_vllm_config(heads_per_rank)
|
||||
|
||||
with set_current_vllm_config(vllm_config):
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
|
||||
layer_name = "model.layers.0.self_attn.attn"
|
||||
vllm_config.compilation_config.static_forward_context[layer_name] = (
|
||||
_make_ctx_layer(vllm_config)
|
||||
)
|
||||
# block_size 1: one page per token, so page ids are positions and the
|
||||
# residue-class page table is expressible directly.
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1,
|
||||
num_kv_heads=1,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=vllm_config.model_config.dtype,
|
||||
non_causal_multi_token_decode=False,
|
||||
)
|
||||
|
||||
nr, ctx, qlen = NUM_REQS, CTX, QLEN
|
||||
L = ctx + qlen
|
||||
gathered_heads = heads_per_rank * DCP
|
||||
kv_dtype = aiter.dtypes.fp8
|
||||
|
||||
kv_flat = torch.randn(
|
||||
nr * L, 1, HEAD_SIZE, dtype=torch.float32, device=device
|
||||
).to(kv_dtype)
|
||||
q_flat = (
|
||||
torch.randn(
|
||||
nr * qlen,
|
||||
gathered_heads,
|
||||
HEAD_SIZE,
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
)
|
||||
.mul_(0.5)
|
||||
.to(kv_dtype)
|
||||
)
|
||||
# Dequantise for the reference so the comparison measures the kernel,
|
||||
# not the fp8 cast that both sides share.
|
||||
kv_f32 = kv_flat.float().view(nr, L, HEAD_SIZE)
|
||||
q_f32 = q_flat.float().view(nr, qlen, gathered_heads, HEAD_SIZE)
|
||||
|
||||
ref_o, _ = _torch_reference(
|
||||
q_f32, kv_f32, ctx, qlen, SCALE, torch.arange(L, device=device)
|
||||
)
|
||||
|
||||
shard_o, shard_lse = [], []
|
||||
max_shard_rel = 0.0
|
||||
for r in range(DCP):
|
||||
pos = torch.arange(r, L, DCP, device=device) # residue class r
|
||||
kern_rank = (r + 1) % DCP if sabotage else r
|
||||
md, o, lse, _ = _run_shard(
|
||||
vllm_config,
|
||||
spec,
|
||||
layer_name,
|
||||
device,
|
||||
r,
|
||||
kern_rank,
|
||||
q_flat,
|
||||
kv_flat,
|
||||
nr,
|
||||
qlen,
|
||||
ctx,
|
||||
DCP,
|
||||
pos,
|
||||
)
|
||||
# The route actually under test must have been taken; a silent
|
||||
# fall-out to Triton/segmented would otherwise pass quietly.
|
||||
assert md.decode.dcp_route is rocm_aiter_mla._DCPDecodeRoute.CPRR
|
||||
assert md.decode.asm_decode_num_heads, "cprr asm route was not taken"
|
||||
|
||||
o = o.float().view(nr, qlen, gathered_heads, KV_LORA_RANK)
|
||||
shard_lse.append(lse.float().view(nr, qlen, gathered_heads))
|
||||
shard_o.append(o)
|
||||
|
||||
po, _ = _torch_reference(q_f32, kv_f32, ctx, qlen, SCALE, pos)
|
||||
rel = (o - po).abs().max().item() / max(po.abs().max().item(), 1e-6)
|
||||
max_shard_rel = max(max_shard_rel, rel)
|
||||
|
||||
merged, _ = _merge_partials(shard_o, shard_lse)
|
||||
merge_rel = (merged - ref_o).abs().max().item() / max(
|
||||
ref_o.abs().max().item(), 1e-6
|
||||
)
|
||||
return max_shard_rel, merge_rel
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# tests
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@requires_cprr
|
||||
@pytest.mark.parametrize(
|
||||
"heads_per_rank",
|
||||
[
|
||||
16, # 128 gathered heads -- a NATIVE cprr kernel, no padding
|
||||
12, # 96 gathered heads -- K3's DSpark target, must pad up to 128
|
||||
],
|
||||
ids=["native-128", "padded-96-to-128"],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_cprr_shards_match_reference_and_merge_to_full_context(heads_per_rank):
|
||||
"""Every DCP shard must be right, and their LSE merge must reproduce
|
||||
full-context attention.
|
||||
|
||||
A shard that ignored global positions (applying a local causal tail
|
||||
instead) still produces plausible-looking output; it only diverges from the
|
||||
reference on the tokens whose causal window is truncated. Checking the merge
|
||||
alone would hide that, so both are asserted.
|
||||
"""
|
||||
shard_rel, merge_rel = _numerics(heads_per_rank)
|
||||
assert shard_rel < SHARD_RTOL, f"per-shard rel err {shard_rel:.3e}"
|
||||
assert merge_rel < MERGE_RTOL, f"merged rel err {merge_rel:.3e}"
|
||||
|
||||
|
||||
@requires_cprr
|
||||
@torch.inference_mode()
|
||||
def test_wrong_cp_rank_breaks_the_result():
|
||||
"""Positive control: without it, a passing run above proves nothing.
|
||||
|
||||
Feeding shard r's pages to the kernel while telling it that it is rank r+1
|
||||
shifts every reconstructed global position by one, so both the causal mask
|
||||
and the round-robin reconstruction are wrong. If the error does NOT blow up,
|
||||
the kernel is not using cp_rank and the test above has no power.
|
||||
"""
|
||||
shard_rel, merge_rel = _numerics(16, sabotage=True)
|
||||
assert shard_rel > SHARD_RTOL or merge_rel > MERGE_RTOL, (
|
||||
f"sabotaged run still passed (shard {shard_rel:.3e}, merge "
|
||||
f"{merge_rel:.3e}) -- cp_rank is not reaching the kernel"
|
||||
)
|
||||
|
||||
|
||||
@requires_cprr
|
||||
def test_cprr_kernel_is_selected_for_the_k3_shape():
|
||||
"""The K3 DSpark target shape must actually reach the cprr route.
|
||||
|
||||
Guards against a silent fall-out to segmented/Triton, which is what the
|
||||
stock configuration does and what this route exists to avoid.
|
||||
"""
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla as m
|
||||
|
||||
assert (
|
||||
m._asm_dcp_verify_configured(
|
||||
dcp_world_size=DCP, cp_interleave=1, multi_token_decode=True
|
||||
)
|
||||
is True
|
||||
)
|
||||
assert QLEN >= m._MIN_CPRR_QLEN
|
||||
route = m._select_dcp_decode_route(
|
||||
supports_segmented=True,
|
||||
supports_triton=False,
|
||||
causal=True,
|
||||
max_qo_len=QLEN,
|
||||
asm_selected=True,
|
||||
)
|
||||
assert route is m._DCPDecodeRoute.CPRR
|
||||
assert m._asm_dcp_verify_heads(96) in m._NATIVE_CPRR_HEADS
|
||||
@@ -1,331 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Causal target verify under DCP on gfx942 (MI300/MI325).
|
||||
|
||||
Reproduces the attention shape of
|
||||
|
||||
vllm serve moonshotai/Kimi-K3 --tensor-parallel-size 8 \
|
||||
--decode-context-parallel-size 8 \
|
||||
--speculative-config '{"method": "dspark", "num_speculative_tokens": 5}'
|
||||
|
||||
96 gathered heads, bf16 KV, qlen 6 and the 768-token blocks the hybrid KDA
|
||||
layers impose. Segmented MLA tiles those blocks at 128 tokens and needs 128 KiB
|
||||
of LDS (gfx942 has 64 KiB), so the builder must route this shape to the generic
|
||||
Triton split-KV kernel. DeepSeek-V3 with MTP and an fp8 KV cache at DCP 8 hits
|
||||
the same limit through its 128 gathered heads. Shapes segmented MLA fits stay
|
||||
on it.
|
||||
|
||||
The real metadata builder and ``forward_mqa`` run on one GPU with the DCP ranks
|
||||
simulated one after another. That is sound because this path has no
|
||||
collective: the query all-gather happens in the layer, before ``forward_mqa``.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found # noqa: E402
|
||||
|
||||
# DeepSeek-R1 supplies the MLA dims, which Kimi-K3 and DeepSeek-V3 share; only
|
||||
# the head count is overridden.
|
||||
MODEL = "deepseek-ai/DeepSeek-R1"
|
||||
KV_LORA_RANK, ROPE_DIM, NOPE_DIM = 512, 64, 128
|
||||
HEAD_SIZE = KV_LORA_RANK + ROPE_DIM
|
||||
SCALE = (NOPE_DIM + ROPE_DIM) ** -0.5
|
||||
DCP = 8
|
||||
# Each rank holds ~800 tokens per request, so its shard spans several blocks.
|
||||
NUM_REQS, CTX = 4, 6400
|
||||
FP8_KV_SCALE = 0.05
|
||||
|
||||
|
||||
def _on_gfx942() -> bool:
|
||||
if not (is_aiter_found() and torch.accelerator.is_available()):
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx942
|
||||
|
||||
return on_gfx942()
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(not _on_gfx942(), reason="needs ROCm + AITER on gfx942")
|
||||
|
||||
|
||||
class _FakeGroup:
|
||||
def __init__(self, world_size: int, rank: int):
|
||||
self.world_size = world_size
|
||||
self.rank_in_group = self.rank = self.local_rank = rank
|
||||
|
||||
def all_gather(self, tensor, dim=0):
|
||||
raise RuntimeError("DCP verify must not issue a collective")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_dcp_groups(monkeypatch):
|
||||
"""Point every importer of get_dcp_group at a settable rank stub."""
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
|
||||
|
||||
group = _FakeGroup(DCP, 0)
|
||||
for module in (ps, mla_attention, backend):
|
||||
monkeypatch.setattr(module, "get_dcp_group", lambda: group)
|
||||
monkeypatch.setattr(ps, "get_tp_group", lambda: _FakeGroup(1, 0))
|
||||
return group
|
||||
|
||||
|
||||
def _vllm_config(heads_per_rank: int, qlen: int, fp8_kv: bool):
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
|
||||
config = create_vllm_config(
|
||||
model_name=MODEL,
|
||||
max_model_len=CTX + qlen,
|
||||
max_num_seqs=NUM_REQS,
|
||||
max_num_batched_tokens=4096,
|
||||
)
|
||||
config.model_config.model_arch_config.total_num_attention_heads = heads_per_rank
|
||||
# The reorder threshold reads only these two fields; without them a
|
||||
# multi-token row is classified as prefill and never reaches decode.
|
||||
config.speculative_config = SimpleNamespace(
|
||||
num_speculative_tokens=qlen - 1, parallel_drafting=False
|
||||
)
|
||||
config.parallel_config.decode_context_parallel_size = DCP
|
||||
config.parallel_config.cp_kv_cache_interleave_size = 1
|
||||
if fp8_kv:
|
||||
config.cache_config.cache_dtype = "fp8"
|
||||
return config
|
||||
|
||||
|
||||
def _ctx_layer():
|
||||
"""The registered-layer fields MLACommonMetadataBuilder.__init__ reads."""
|
||||
from vllm.v1.attention.ops.dcp import MLADCPManager
|
||||
|
||||
dcp_manager = object.__new__(MLADCPManager)
|
||||
dcp_manager.init_kv_gather = lambda *args, **kwargs: None
|
||||
# Only chunked-context prefill uses the cloned backend.
|
||||
prefill_backend = SimpleNamespace()
|
||||
prefill_backend.clone = lambda: prefill_backend
|
||||
return SimpleNamespace(
|
||||
non_causal_multi_token_decode=False,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=KV_LORA_RANK,
|
||||
qk_nope_head_dim=NOPE_DIM,
|
||||
qk_rope_head_dim=ROPE_DIM,
|
||||
v_head_dim=NOPE_DIM,
|
||||
dcp_manager=dcp_manager,
|
||||
prefill_backend=prefill_backend,
|
||||
)
|
||||
|
||||
|
||||
def _impl(dcp_rank: int, heads_per_rank: int, fp8_kv: bool):
|
||||
"""forward_mqa needs these attributes, not the weight-loading __init__."""
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAImpl
|
||||
|
||||
impl = object.__new__(AiterMLAImpl)
|
||||
impl.num_heads = heads_per_rank
|
||||
impl.kv_lora_rank = KV_LORA_RANK
|
||||
impl.qk_rope_head_dim = ROPE_DIM
|
||||
impl.dcp_world_size = DCP
|
||||
impl.dcp_rank = dcp_rank
|
||||
impl.pcp_world_size = 1
|
||||
impl.kv_cache_dtype = "fp8" if fp8_kv else "auto"
|
||||
impl.scale = SCALE
|
||||
impl._sm_count = current_platform.num_compute_units()
|
||||
return impl
|
||||
|
||||
|
||||
def _run_rank(config, spec, layer_name, group, rank, q, kv_cache_src, k_scale):
|
||||
"""Shard the KV round-robin onto ``rank`` and run its verify step."""
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
|
||||
|
||||
device = q.device
|
||||
qlen, heads = q.shape[1], q.shape[2] // DCP
|
||||
seq_len = CTX + qlen
|
||||
positions = torch.arange(rank, seq_len, DCP, device=device)
|
||||
local_len = positions.numel()
|
||||
# Production block tables span max_model_len, so every rank's table is at
|
||||
# least as wide as the largest shard needs.
|
||||
blocks_per_req = cdiv(cdiv(seq_len, DCP), spec.block_size)
|
||||
kv_cache = torch.zeros(
|
||||
NUM_REQS * blocks_per_req,
|
||||
spec.block_size,
|
||||
HEAD_SIZE,
|
||||
dtype=kv_cache_src.dtype,
|
||||
device=device,
|
||||
)
|
||||
kv_cache.view(NUM_REQS, -1, HEAD_SIZE)[:, :local_len] = kv_cache_src[:, positions]
|
||||
block_table = torch.arange(
|
||||
NUM_REQS * blocks_per_req, dtype=torch.int32, device=device
|
||||
).view(NUM_REQS, blocks_per_req)
|
||||
|
||||
query_start_loc = torch.arange(
|
||||
0, NUM_REQS * qlen + 1, qlen, dtype=torch.int32, device=device
|
||||
)
|
||||
local_lens = torch.full((NUM_REQS,), local_len, dtype=torch.int32)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=query_start_loc,
|
||||
query_start_loc_cpu=query_start_loc.cpu(),
|
||||
seq_lens=torch.full((NUM_REQS,), seq_len, dtype=torch.int32, device=device),
|
||||
num_reqs=NUM_REQS,
|
||||
num_actual_tokens=NUM_REQS * qlen,
|
||||
max_query_len=qlen,
|
||||
max_seq_len=seq_len,
|
||||
block_table_tensor=block_table,
|
||||
slot_mapping=torch.arange(NUM_REQS * qlen, dtype=torch.int64, device=device),
|
||||
causal=True,
|
||||
dcp_local_seq_lens=local_lens.to(device),
|
||||
dcp_local_seq_lens_cpu_upper_bound=local_lens,
|
||||
)
|
||||
|
||||
group.rank_in_group = group.rank = group.local_rank = rank
|
||||
builder = AiterMLAMetadataBuilder(spec, [layer_name], config, device)
|
||||
metadata = builder.build(0, common)
|
||||
layer = SimpleNamespace(
|
||||
_q_scale=torch.tensor(1.0, device=device),
|
||||
_k_scale=torch.tensor(k_scale, device=device),
|
||||
)
|
||||
impl = _impl(rank, heads, kv_cache_src.dtype != torch.bfloat16)
|
||||
output, lse = impl.forward_mqa(q.flatten(0, 1), kv_cache, metadata, layer)
|
||||
return metadata.decode.dcp_route.name, output, lse
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"heads_per_rank, qlen, block_size, fp8_kv, route",
|
||||
[
|
||||
(12, 6, 768, False, "TRITON"),
|
||||
(12, 6, 64, False, "SEGMENTED"),
|
||||
(16, 2, 16, True, "TRITON"),
|
||||
],
|
||||
ids=["kimi-k3-hybrid-kda-blocks", "segmented-fits", "deepseek-v3-mtp-fp8-kv"],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_dcp_verify_matches_attention(
|
||||
fake_dcp_groups, heads_per_rank, qlen, block_size, fp8_kv, route
|
||||
):
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
from vllm.v1.worker.workspace import (
|
||||
init_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
device = torch.device("cuda", torch.accelerator.current_device_index())
|
||||
if not is_workspace_manager_initialized():
|
||||
init_workspace_manager(device)
|
||||
torch.manual_seed(0)
|
||||
seq_len = CTX + qlen
|
||||
q = torch.randn(
|
||||
NUM_REQS,
|
||||
qlen,
|
||||
heads_per_rank * DCP,
|
||||
HEAD_SIZE,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
kv = torch.randn(NUM_REQS, seq_len, HEAD_SIZE, device=device).clamp_(-4, 4)
|
||||
if fp8_kv:
|
||||
k_scale = FP8_KV_SCALE
|
||||
kv_cache_src = (kv / k_scale).to(current_platform.fp8_dtype())
|
||||
else:
|
||||
k_scale = 1.0
|
||||
kv_cache_src = kv.to(torch.bfloat16)
|
||||
kv_ref = kv_cache_src.float() * k_scale
|
||||
|
||||
config = _vllm_config(heads_per_rank, qlen, fp8_kv)
|
||||
layer_name = "model.layers.0.self_attn.attn"
|
||||
with set_current_vllm_config(config):
|
||||
config.compilation_config.static_forward_context[layer_name] = _ctx_layer()
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=kv_cache_src.dtype,
|
||||
cache_dtype_str="fp8" if fp8_kv else None,
|
||||
non_causal_multi_token_decode=False,
|
||||
)
|
||||
shards = [
|
||||
_run_rank(
|
||||
config,
|
||||
spec,
|
||||
layer_name,
|
||||
fake_dcp_groups,
|
||||
rank,
|
||||
q,
|
||||
kv_cache_src,
|
||||
k_scale,
|
||||
)
|
||||
for rank in range(DCP)
|
||||
]
|
||||
|
||||
assert {shard_route for shard_route, _, _ in shards} == {route}
|
||||
lses = torch.stack([lse.float() for _, _, lse in shards])
|
||||
weights = torch.exp(lses - lses.max(dim=0).values)
|
||||
merged = (
|
||||
weights.unsqueeze(-1) * torch.stack([out.float() for _, out, _ in shards])
|
||||
).sum(dim=0) / weights.sum(dim=0).unsqueeze(-1)
|
||||
|
||||
# Query token t of a request sees the context plus verify tokens 0..t.
|
||||
scores = torch.einsum("rthd,rld->rthl", q.float(), kv_ref) * SCALE
|
||||
visible = torch.arange(seq_len, device=device) <= CTX + torch.arange(
|
||||
qlen, device=device
|
||||
).view(-1, 1)
|
||||
scores.masked_fill_(~visible[None, :, None, :], float("-inf"))
|
||||
reference = torch.einsum(
|
||||
"rthl,rld->rthd", scores.softmax(dim=-1), kv_ref[..., :KV_LORA_RANK]
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
merged.view_as(reference), reference, rtol=2e-2, atol=2e-2
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fp8_kv, num_heads, block_size",
|
||||
[
|
||||
(False, 96, 768),
|
||||
(False, 128, 64),
|
||||
(True, 64, 128),
|
||||
(True, 128, 16),
|
||||
],
|
||||
)
|
||||
def test_segmented_lds_gate_matches_the_kernel(fp8_kv, num_heads, block_size):
|
||||
"""The gate must flag exactly the shapes AITER segmented MLA cannot compile."""
|
||||
from triton.runtime.errors import OutOfResources
|
||||
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
_get_segmented_mla_decode,
|
||||
_segmented_mla_fits_lds,
|
||||
_segmented_mla_page_size,
|
||||
)
|
||||
|
||||
page = _segmented_mla_page_size(block_size)
|
||||
kv_dtype = current_platform.fp8_dtype() if fp8_kv else torch.bfloat16
|
||||
q = torch.zeros(1, num_heads, HEAD_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
kv = torch.zeros(1, page, 1, HEAD_SIZE, dtype=kv_dtype, device="cuda")
|
||||
one_row = torch.tensor([0, 1], dtype=torch.int32, device="cuda")
|
||||
try:
|
||||
_get_segmented_mla_decode()(
|
||||
q,
|
||||
kv,
|
||||
None,
|
||||
one_row,
|
||||
torch.tensor([page], dtype=torch.int32, device="cuda"),
|
||||
page,
|
||||
torch.zeros(1, 1, dtype=torch.int32, device="cuda"),
|
||||
SCALE,
|
||||
KV_LORA_RANK,
|
||||
ROPE_DIM,
|
||||
causal=True,
|
||||
q_descale=None,
|
||||
kv_descale=torch.tensor(1.0, device="cuda"),
|
||||
skip_reduce=True,
|
||||
)
|
||||
compiles = True
|
||||
except OutOfResources:
|
||||
compiles = False
|
||||
assert _segmented_mla_fits_lds(num_heads, block_size, fp8_kv) == compiles
|
||||
@@ -1,202 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Decode-kernel routing for the ROCm AITER MLA backend.
|
||||
|
||||
Gluon exposes a single fp8-KV regime, bh16bn128. It is a bf16-query kernel that
|
||||
upcasts the cache in registers with a hardcoded scale of 1.0, and it asserts
|
||||
batch_size == 1, so it cannot serve a decode batch. Every fp8 shape therefore
|
||||
has to land on the asm kernels, which ship real fp8 variants for gqa=16. These
|
||||
tests pin that down at the predicates, since the failure it prevents is either a
|
||||
batch assertion or -- worse -- a silently wrong result.
|
||||
|
||||
Gluon is still the route for supported non-DCP decode shapes. DCP multi-token
|
||||
verification uses segmented MLA instead, so it depends on neither Gluon's
|
||||
query-head nor its long-context pipeline limits.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
|
||||
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla # noqa: E402
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAHelper # noqa: E402
|
||||
|
||||
FP8_DTYPES = ["fp8", "fp8_e4m3", "fp8_e5m2"]
|
||||
UNQUANTIZED_DTYPES = ["auto", "bfloat16"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gluon_available(monkeypatch):
|
||||
"""Pin the arch gate and the mode knob so only the dtype rules are in play.
|
||||
|
||||
Gluon ships a gfx950 build only, and VLLM_ROCM_AITER_MLA_ASM_PADDING can
|
||||
force the asm path on any arch. Without pinning both, the expectations that
|
||||
bf16 *keeps* Gluon would pass on a gfx950 host and fail on gfx942 for
|
||||
reasons that have nothing to do with what these tests cover.
|
||||
"""
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: True)
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_aiter_mla_small_head_mode", lambda: "auto")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [1, 2, 4, 5, 6, 8, 12, 16, 32, 128])
|
||||
@pytest.mark.parametrize("max_qo_len", [1, 2, 4, 5, 8, 15])
|
||||
def test_non_dcp_fp8_never_routes_to_gluon(kv_cache_dtype, num_heads, max_qo_len):
|
||||
"""No non-DCP fp8 shape reaches either Gluon entry point.
|
||||
|
||||
The head count is deliberately swept across divisors of 16 as well as
|
||||
non-divisors: the divisor case (e.g. 8 heads at TP8) is the one that stays
|
||||
on Gluon for bf16 and so is the one an fp8 guard has to override.
|
||||
"""
|
||||
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
|
||||
assert not AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [1, 2, 4, 8, 12])
|
||||
@pytest.mark.parametrize("mode", ["auto", "gluon", "asm"])
|
||||
def test_fp8_never_routes_to_gluon_under_any_mode(
|
||||
monkeypatch, kv_cache_dtype, num_heads, mode
|
||||
):
|
||||
"""VLLM_ROCM_AITER_MLA_ASM_PADDING cannot force a non-DCP fp8 cache onto Gluon.
|
||||
|
||||
The dtype guard deliberately precedes the mode knob: honouring an explicit
|
||||
"gluon" request under fp8 would hand Gluon the batch it asserts against, so
|
||||
it is overridden rather than obeyed. Pinned here because the override is a
|
||||
correctness decision, not a preference.
|
||||
"""
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: True)
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_aiter_mla_small_head_mode", lambda: mode)
|
||||
assert not AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
|
||||
assert not AiterMLAHelper.use_gluon_verify(num_heads, 8, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [16, 17, 32, 64, 128])
|
||||
@pytest.mark.parametrize("max_qo_len", [1, 4, 8])
|
||||
def test_large_head_counts_never_use_gluon(kv_cache_dtype, num_heads, max_qo_len):
|
||||
""">= 16 heads has always been asm-only; the dtype guard must not change it."""
|
||||
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
|
||||
assert not AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [8, 16, 32, 96])
|
||||
@pytest.mark.parametrize("max_qo_len", [2, 3, 8])
|
||||
def test_dcp_multitoken_verify_never_uses_gluon(
|
||||
gluon_available, kv_cache_dtype, num_heads, max_qo_len
|
||||
):
|
||||
assert not AiterMLAHelper.use_gluon_verify(
|
||||
num_heads, max_qo_len, kv_cache_dtype, dcp_world_size=8
|
||||
)
|
||||
|
||||
|
||||
def test_segmented_dcp_verify_does_not_depend_on_gluon(monkeypatch):
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: False)
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_segmented_mla_decode_supported", lambda: True)
|
||||
|
||||
assert rocm_aiter_mla._segmented_dcp_verify_supported(8, 1)
|
||||
# Round-robin interleaving other than 1 is not served by this route.
|
||||
assert not rocm_aiter_mla._segmented_dcp_verify_supported(8, 4)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [1, 2, 4, 8])
|
||||
def test_unquantized_divisor_heads_keep_gluon_decode(
|
||||
gluon_available, kv_cache_dtype, num_heads
|
||||
):
|
||||
"""Divisor head counts keep the Gluon single-token decode for bf16.
|
||||
|
||||
Gluon does not scale with KV length the way the asm persistent decode does,
|
||||
so this is the faster path where it is usable.
|
||||
"""
|
||||
assert AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [3, 5, 6, 7, 9, 12, 15])
|
||||
def test_unquantized_non_divisor_heads_use_asm_decode(kv_cache_dtype, num_heads):
|
||||
"""Non-divisor head counts are padded to 16 and take the asm decode."""
|
||||
assert not AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [5, 8, 12])
|
||||
@pytest.mark.parametrize("max_qo_len", [2, 4, 8, 15])
|
||||
def test_unquantized_small_head_verify_keeps_gluon(
|
||||
gluon_available, kv_cache_dtype, num_heads, max_qo_len
|
||||
):
|
||||
"""bf16 has no gqa<16, qseqlen>1 asm kernel, so verify still flattens onto Gluon.
|
||||
|
||||
Unlike the decode predicate, this one does not care whether the head count
|
||||
divides 16 -- the flatten reshapes to qseqlen=1 either way.
|
||||
"""
|
||||
assert AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
|
||||
# The verify flatten is a separate entry point from the single-token decode.
|
||||
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
|
||||
@pytest.mark.parametrize("num_heads", [5, 8, 12, 16, 32])
|
||||
def test_decode_and_verify_are_disjoint(kv_cache_dtype, num_heads):
|
||||
"""The two Gluon entry points partition on qlen and never both fire."""
|
||||
for max_qo_len in (1, 2, 8):
|
||||
assert not (
|
||||
AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
|
||||
and AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
|
||||
def test_oversized_kv_cache_refuses_gluon(gluon_available, kv_cache_dtype):
|
||||
"""Past 2 GiB per layer Gluon drops its KV bounds mask and reads out of range.
|
||||
|
||||
``None`` is the profiling case, before the cache is sized: nothing to
|
||||
refuse yet, so the usual route stands.
|
||||
"""
|
||||
bound = rocm_aiter_mla._GLUON_MAX_KV_CACHE_BYTES
|
||||
for kv_cache_bytes in (None, bound):
|
||||
assert AiterMLAHelper.use_gluon_decode(8, 1, kv_cache_dtype, kv_cache_bytes)
|
||||
assert AiterMLAHelper.use_gluon_verify(
|
||||
8, 8, kv_cache_dtype, kv_cache_bytes=kv_cache_bytes
|
||||
)
|
||||
assert not AiterMLAHelper.use_gluon_decode(8, 1, kv_cache_dtype, bound + 1)
|
||||
assert not AiterMLAHelper.use_gluon_verify(
|
||||
8, 8, kv_cache_dtype, kv_cache_bytes=bound + 1
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_heads", [1, 2, 3, 5, 6, 7, 8, 9, 12, 15])
|
||||
def test_padded_query_is_contiguous(num_heads):
|
||||
"""asm_mla.cu:805 requires Q.is_contiguous().
|
||||
|
||||
Padding a non-divisor head count to 16 tiles the query and slices it back
|
||||
down, which yields a non-contiguous view whenever more than one tile is
|
||||
needed (12 heads -> repeat to 24 -> slice to 16). The asm kernel rejects
|
||||
that outright, so the padding has to materialize the result.
|
||||
"""
|
||||
q = torch.randn(4, num_heads, 576)
|
||||
padded = AiterMLAHelper.get_mla_padded_q(num_heads, q)
|
||||
|
||||
assert padded.shape[1] == max(16, num_heads)
|
||||
assert padded.is_contiguous()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_heads", [1, 2, 3, 5, 6, 7, 8, 9, 12, 15, 16, 32])
|
||||
def test_pad_unpad_round_trip_preserves_head_order(num_heads):
|
||||
"""Unpadding recovers each original head from the padded output, in order."""
|
||||
q = torch.arange(num_heads, dtype=torch.float32).view(1, num_heads, 1)
|
||||
padded = AiterMLAHelper.get_mla_padded_q(num_heads, q)
|
||||
unpadded = AiterMLAHelper.get_mla_unpadded_o(num_heads, padded)
|
||||
|
||||
assert unpadded.shape == q.shape
|
||||
torch.testing.assert_close(unpadded, q)
|
||||
|
||||
|
||||
def test_a_non_causal_block_never_routes_to_gluon(gluon_available):
|
||||
"""A small-head block that normally uses Gluon must use ASM when non-causal."""
|
||||
assert not AiterMLAHelper.use_gluon_verify(12, 8, "auto", causal=False)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,54 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm() or not is_aiter_found_and_supported():
|
||||
pytest.skip(
|
||||
"ROCm AITER sparse indexer test requires ROCm with AITER.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as sparse_mod
|
||||
|
||||
|
||||
def test_rocm_fp8_mqa_logits_disables_clean_logits(monkeypatch):
|
||||
captured = {}
|
||||
expected = torch.empty((1, 1))
|
||||
|
||||
def fake_fp8_mqa_logits(*args, clean_logits):
|
||||
captured["clean_logits"] = clean_logits
|
||||
return expected
|
||||
|
||||
monkeypatch.setattr(sparse_mod, "_ON_GFX942", False)
|
||||
monkeypatch.setattr(rocm_aiter_ops, "is_enabled", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
sparse_mod,
|
||||
"mqa_logits_module",
|
||||
lambda: SimpleNamespace(fp8_mqa_logits=fake_fp8_mqa_logits),
|
||||
)
|
||||
|
||||
q = torch.empty((1, 1, 1))
|
||||
k_fp8 = torch.empty((1, 1))
|
||||
scale = torch.empty((1,))
|
||||
weights = torch.empty((1, 1))
|
||||
cu_seqlen_ks = torch.zeros((1,), dtype=torch.int32)
|
||||
cu_seqlen_ke = torch.ones((1,), dtype=torch.int32)
|
||||
|
||||
result = sparse_mod.rocm_fp8_mqa_logits(
|
||||
q,
|
||||
(k_fp8, scale),
|
||||
weights,
|
||||
cu_seqlen_ks,
|
||||
cu_seqlen_ke,
|
||||
)
|
||||
|
||||
assert result is expected
|
||||
assert captured["clean_logits"] is False
|
||||
@@ -1,331 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_rocm(), reason="ROCm-only aiter path"
|
||||
)
|
||||
|
||||
|
||||
def _rows_from_ragged(indices: torch.Tensor, indptr: torch.Tensor) -> list[list[int]]:
|
||||
ends = indptr.tolist()
|
||||
return [indices[s:e].tolist() for s, e in zip(ends, ends[1:])]
|
||||
|
||||
|
||||
def test_triton_sparse_mla_gate(monkeypatch) -> None:
|
||||
import vllm._aiter_ops as aiter_ops
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
aiter_ops.logger,
|
||||
"warning_once",
|
||||
lambda msg, *args, **kwargs: warnings.append(msg % args),
|
||||
)
|
||||
|
||||
def enabled(aiter: bool, flag: bool) -> bool:
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER", str(int(aiter)))
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA", str(int(flag)))
|
||||
rocm_aiter_ops.refresh_env_variables()
|
||||
return bool(rocm_aiter_ops.is_triton_sparse_mla_enabled())
|
||||
|
||||
try:
|
||||
assert not enabled(aiter=True, flag=False) and not warnings
|
||||
assert not enabled(aiter=False, flag=True)
|
||||
assert "VLLM_ROCM_USE_AITER is off" in warnings.pop()
|
||||
# On gfx950 the flag takes effect; elsewhere it warns and falls back.
|
||||
assert enabled(aiter=True, flag=True) == on_gfx950()
|
||||
if not on_gfx950():
|
||||
assert "gfx950" in warnings.pop()
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
rocm_aiter_ops.refresh_env_variables()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rope_dim",
|
||||
[0, 64],
|
||||
ids=["rope_free", "appended_rope"], # GLM-5.3-Flash; GLM-5.1/5.2, V3.2
|
||||
)
|
||||
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
|
||||
@torch.inference_mode()
|
||||
def test_forward_mqa_prepares_triton_sparse_mla_inputs(
|
||||
monkeypatch, rope_dim: int, kv_cache_dtype: str
|
||||
) -> None:
|
||||
"""What forward_mqa hands aiter: global slots built from the request-local
|
||||
top-k rows, q quantized with the layer's scale, and the cache as stored."""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
|
||||
ROCMAiterMLASparseImpl,
|
||||
)
|
||||
|
||||
device = torch.device("cuda")
|
||||
gen = torch.Generator().manual_seed(0)
|
||||
kv_lora_rank, num_heads, topk, block_size = 512, 16, 128, 16
|
||||
head_size = kv_lora_rank + rope_dim
|
||||
fp8 = kv_cache_dtype == "fp8"
|
||||
|
||||
# A decode row, then a short prefill.
|
||||
query_lens, seq_lens = [1, 5], [40, 20]
|
||||
num_tokens = sum(query_lens)
|
||||
block_table = torch.randperm(8, generator=gen).view(2, 4).to(device, torch.int32)
|
||||
topk_indices = torch.full((num_tokens, topk), -1, dtype=torch.int32)
|
||||
req_id_per_token: list[int] = []
|
||||
rows: list[list[int]] = []
|
||||
for req, (query_len, seq_len) in enumerate(zip(query_lens, seq_lens)):
|
||||
for pos in range(seq_len - query_len, seq_len):
|
||||
local = torch.randperm(pos + 1, generator=gen)
|
||||
topk_indices[len(rows), : pos + 1] = local.int()
|
||||
slots = block_table[req, local // block_size].cpu() * block_size
|
||||
rows.append((slots + local % block_size).tolist())
|
||||
req_id_per_token.append(req)
|
||||
indptr = torch.tensor([0] + [len(row) for row in rows]).cumsum(0)
|
||||
|
||||
impl = ROCMAiterMLASparseImpl.__new__(ROCMAiterMLASparseImpl)
|
||||
impl.num_heads = num_heads
|
||||
impl.kv_lora_rank = kv_lora_rank
|
||||
impl.qk_rope_head_dim = rope_dim
|
||||
impl.scale = head_size**-0.5
|
||||
impl.sinks = torch.randn(num_heads, generator=gen).to(device)
|
||||
impl.kv_cache_dtype = kv_cache_dtype
|
||||
impl.topk_indices_buffer = topk_indices.to(device)
|
||||
impl.owns_indexer = True
|
||||
impl.index_epoch = 0
|
||||
impl.use_aiter_sparse_mla = True
|
||||
layer = SimpleNamespace(
|
||||
_q_scale=torch.tensor([0.02], device=device),
|
||||
_k_scale=torch.tensor([0.01], device=device),
|
||||
)
|
||||
metadata = SimpleNamespace(
|
||||
num_actual_tokens=num_tokens,
|
||||
topk_tokens=topk,
|
||||
req_id_per_token=torch.tensor(req_id_per_token, dtype=torch.int32).to(device),
|
||||
block_table=block_table,
|
||||
block_size=block_size,
|
||||
paged_kv_indptr=indptr.to(device, torch.int32),
|
||||
paged_kv_indices=torch.zeros(num_tokens * topk, dtype=torch.int32).to(device),
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
)
|
||||
cache_dtype = current_platform.fp8_dtype() if fp8 else torch.bfloat16
|
||||
kv_cache = torch.zeros(8, block_size, head_size, device=device).to(cache_dtype)
|
||||
# Two rows of cudagraph padding past the real tokens.
|
||||
q = torch.randn(num_tokens + 2, num_heads, head_size, generator=gen).to(
|
||||
device, torch.bfloat16
|
||||
)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_ops, "triton_sparse_mla_fwd", lambda *a, **k: calls.append((a, k))
|
||||
)
|
||||
|
||||
out, lse = impl.forward_mqa(q, kv_cache, metadata, layer)
|
||||
|
||||
assert len(calls) == 1
|
||||
(q_in, kv_in, o, sm_scale, kv_indptr, kv_indices), kwargs = calls[0]
|
||||
assert _rows_from_ragged(kv_indices, kv_indptr) == rows
|
||||
assert q_in.shape[0] == num_tokens
|
||||
if fp8:
|
||||
assert q_in.dtype == cache_dtype
|
||||
torch.testing.assert_close(
|
||||
q_in.float() * layer._q_scale, q[:num_tokens].float(), atol=1e-3, rtol=0.07
|
||||
)
|
||||
else:
|
||||
assert q_in.data_ptr() == q.data_ptr()
|
||||
assert kv_in.shape == (8 * block_size, 1, 1, head_size)
|
||||
assert kv_in.data_ptr() == kv_cache.data_ptr()
|
||||
assert o.data_ptr() == out.data_ptr() and o.shape[0] == num_tokens
|
||||
assert sm_scale == impl.scale
|
||||
assert kwargs["kv_lora_rank"] == kv_lora_rank
|
||||
assert kwargs["qk_rope_head_dim"] == rope_dim
|
||||
assert kwargs["q_scale"] is layer._q_scale
|
||||
assert kwargs["kv_scale"] is layer._k_scale
|
||||
assert kwargs["attn_sink"] is impl.sinks
|
||||
assert lse is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "compress_ratio"),
|
||||
[("deepseek_v41", 1), ("deepseek_v41", 2), ("deepseek_v4", 4)],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_paged_prefill_indices_match_gathered_prefill(
|
||||
monkeypatch, model: str, compress_ratio: int
|
||||
) -> None:
|
||||
"""The aiter prefill reads the paged caches through the SWA builder's rows
|
||||
and build_prefill_topk_ragged_indices, and must attend exactly the keys the
|
||||
dequantize-and-gather prefill does."""
|
||||
import importlib
|
||||
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
build_prefill_topk_ragged_indices,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import SlidingWindowMLASpec
|
||||
|
||||
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
|
||||
builder_cls = (
|
||||
rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder
|
||||
if model == "deepseek_v41"
|
||||
else rocm.DeepseekV4ROCMAiterSparseSWAMetadataBuilder
|
||||
)
|
||||
device = torch.device("cuda")
|
||||
gen = torch.Generator().manual_seed(compress_ratio)
|
||||
window, width, block_size, max_model_len = 16, 32, 16, 128
|
||||
comp_block = block_size // compress_ratio
|
||||
num_compressed = max_model_len // compress_ratio
|
||||
|
||||
# A decode row, then prefills with and without a prefix.
|
||||
prefix_lens, query_lens = [20, 0, 13, 40], [1, 7, 20, 9]
|
||||
seq_lens = [p + q for p, q in zip(prefix_lens, query_lens)]
|
||||
num_decodes = num_decode_tokens = 1
|
||||
num_tokens = sum(query_lens)
|
||||
qsl = torch.tensor([0] + query_lens).cumsum(0).to(torch.int32)
|
||||
positions = torch.cat([torch.arange(p, s) for p, s in zip(prefix_lens, seq_lens)])
|
||||
token_to_req = torch.repeat_interleave(
|
||||
torch.arange(len(query_lens)), torch.tensor(query_lens)
|
||||
)
|
||||
swa_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
|
||||
comp_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name="facebook/opt-125m",
|
||||
max_model_len=max_model_len,
|
||||
block_size=block_size,
|
||||
max_num_seqs=4,
|
||||
max_num_batched_tokens=64,
|
||||
hf_config_override={
|
||||
"compress_ratios": [compress_ratio],
|
||||
"index_topk": width,
|
||||
"sliding_window": window,
|
||||
},
|
||||
)
|
||||
swa_spec = SlidingWindowMLASpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=512,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=window,
|
||||
cache_dtype_str="fp8_ds_mla",
|
||||
model_version="deepseek_v4",
|
||||
)
|
||||
slots = swa_bt.cpu()[token_to_req, positions // block_size] * block_size + (
|
||||
positions % block_size
|
||||
)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=qsl.to(device),
|
||||
query_start_loc_cpu=qsl,
|
||||
seq_lens=torch.tensor(seq_lens, dtype=torch.int32).to(device),
|
||||
seq_lens_cpu_upper_bound=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
num_reqs=len(query_lens),
|
||||
num_actual_tokens=num_tokens,
|
||||
max_query_len=max(query_lens),
|
||||
max_seq_len=max(seq_lens),
|
||||
block_table_tensor=swa_bt,
|
||||
slot_mapping=slots.to(device, torch.int64),
|
||||
positions=positions.to(device),
|
||||
causal=True,
|
||||
)
|
||||
|
||||
def build(enabled: bool):
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: enabled
|
||||
)
|
||||
return builder_cls(swa_spec, ["swa"], vllm_config, device).build(0, common)
|
||||
|
||||
assert build(enabled=False).prefill_swa_ragged_indices is None
|
||||
md = build(enabled=True)
|
||||
assert md.num_decode_tokens == num_decode_tokens
|
||||
|
||||
# Local top-k rows. Under each row's causal cap sit a failed candidate and
|
||||
# one past the pool; past the cap, stale values neither path may read.
|
||||
num_prefill_tokens = num_tokens - num_decode_tokens
|
||||
topk = torch.full((num_prefill_tokens, width), -1, dtype=torch.int32)
|
||||
for row in range(num_prefill_tokens):
|
||||
visible = (int(positions[row + num_decode_tokens]) + 1) // compress_ratio
|
||||
cap = min(visible, width)
|
||||
topk[row, :cap] = torch.randperm(visible, generator=gen)[:cap].int()
|
||||
if cap >= 2:
|
||||
topk[row, :2] = torch.tensor([-1, num_compressed + 3])
|
||||
topk[row, cap:] = torch.randint(
|
||||
0, num_compressed, (width - cap,), generator=gen
|
||||
).int()
|
||||
topk = topk.to(device)
|
||||
|
||||
topk_indices, topk_indptr = build_prefill_topk_ragged_indices(
|
||||
topk,
|
||||
md.token_to_req_indices,
|
||||
md.query_start_loc,
|
||||
md.seq_lens,
|
||||
md.is_valid_token,
|
||||
comp_bt,
|
||||
block_size=comp_block,
|
||||
compress_ratio=compress_ratio,
|
||||
num_compressed=num_compressed,
|
||||
token_offset=num_decode_tokens,
|
||||
)
|
||||
paged_keys = [
|
||||
sorted([("s", x) for x in swa if x >= 0] + [("c", x) for x in top if x >= 0])
|
||||
for swa, top in zip(
|
||||
_rows_from_ragged(
|
||||
md.prefill_swa_ragged_indices, md.prefill_swa_ragged_indptr
|
||||
),
|
||||
_rows_from_ragged(topk_indices, topk_indptr),
|
||||
)
|
||||
]
|
||||
|
||||
# The gathered path's combine, mapped from workspace offsets to cache slots.
|
||||
M = num_compressed + window + num_tokens
|
||||
combined, combined_lens = rocm.combine_topk_swa_indices(
|
||||
topk,
|
||||
md.query_start_loc[num_decodes:],
|
||||
md.prefill_seq_lens,
|
||||
md.prefill_gather_lens,
|
||||
window,
|
||||
compress_ratio,
|
||||
width,
|
||||
M,
|
||||
num_compressed,
|
||||
)
|
||||
gather_start = (md.prefill_seq_lens - md.prefill_gather_lens).tolist()
|
||||
swa_bt_cpu, comp_bt_cpu = swa_bt.cpu(), comp_bt.cpu()
|
||||
|
||||
def slot(block_table, req, pos, size):
|
||||
return int(block_table[req, pos // size]) * size + pos % size
|
||||
|
||||
gathered_keys = []
|
||||
for row, (values, n) in enumerate(zip(combined.tolist(), combined_lens.tolist())):
|
||||
req = int(token_to_req[row + num_decode_tokens])
|
||||
chunk_req = req - num_decodes
|
||||
keys = []
|
||||
for value in values[:n]:
|
||||
if value < 0:
|
||||
continue
|
||||
offset = value - chunk_req * M
|
||||
if offset < num_compressed:
|
||||
keys.append(("c", slot(comp_bt_cpu, req, offset, comp_block)))
|
||||
else:
|
||||
pos = gather_start[chunk_req] + offset - num_compressed
|
||||
keys.append(("s", slot(swa_bt_cpu, req, pos, block_size)))
|
||||
gathered_keys.append(sorted(keys))
|
||||
|
||||
assert paged_keys == gathered_keys
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["deepseek_v4", "deepseek_v41"])
|
||||
def test_aiter_sparse_mla_stays_off_with_kv_connector(monkeypatch, model) -> None:
|
||||
import importlib
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
|
||||
monkeypatch.setattr(rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: True)
|
||||
assert rocm._aiter_sparse_mla_enabled(has_kv_transfer=False)
|
||||
assert not rocm._aiter_sparse_mla_enabled(has_kv_transfer=True)
|
||||
@@ -1,992 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for attention backend selectors."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.attention import AttentionConfig
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.selector import AttentionSelectorConfig
|
||||
|
||||
# ROCm-specific attention backend selection tests
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_rocm(), reason="ROCm-specific tests"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_vllm_config():
|
||||
"""Create a mock VllmConfig for testing."""
|
||||
config = MagicMock()
|
||||
config.model_config.dtype = torch.float16
|
||||
config.model_config.hf_config.architectures = ["LlamaForCausalLM"]
|
||||
config.cache_config.block_size = 16
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_get_cdna_version():
|
||||
"""Mock cdna version arch detection to return True."""
|
||||
with patch("vllm.platforms.rocm.get_cdna_version", return_value=3):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cleared_attention_selector_cache():
|
||||
from vllm.v1.attention.selector import _cached_get_attn_backend
|
||||
|
||||
_cached_get_attn_backend.cache_clear()
|
||||
yield
|
||||
_cached_get_attn_backend.cache_clear()
|
||||
|
||||
|
||||
def test_deepseek_rocm_backend_registry_paths_are_model_specific():
|
||||
assert AttentionBackendEnum.ROCM_FLASHMLA_SPARSE_DSV4.get_path() == (
|
||||
"vllm.models.deepseek_v4.amd.rocm.DeepseekV4ROCMAiterMLASparseBackend"
|
||||
)
|
||||
assert AttentionBackendEnum.ROCM_FLASHMLA_SPARSE_DSV41.get_path() == (
|
||||
"vllm.models.deepseek_v41.amd.rocm.DeepseekV41ROCMAiterMLASparseBackend"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_name, expect_warning",
|
||||
[
|
||||
("ROCM_FLASHMLA_SPARSE_DSV4", True),
|
||||
("ROCM_FLASHMLA_SPARSE_DSV41", False),
|
||||
],
|
||||
ids=["legacy", "canonical"],
|
||||
)
|
||||
def test_deepseek_v41_rocm_accepts_legacy_backend_alias(backend_name, expect_warning):
|
||||
from vllm.models.deepseek_v41.amd import model as dsv41_model
|
||||
from vllm.models.deepseek_v41.amd.rocm import (
|
||||
DeepseekV41ROCMAiterMLAAttention,
|
||||
DeepseekV41ROCMAiterMLASparseBackend,
|
||||
)
|
||||
|
||||
config = SimpleNamespace(
|
||||
attention_config=AttentionConfig(backend=backend_name),
|
||||
parallel_config=ParallelConfig(),
|
||||
)
|
||||
|
||||
with patch.object(dsv41_model.logger, "warning_once") as warning_once:
|
||||
selected = dsv41_model._select_dsv4_attn_cls(config)
|
||||
|
||||
assert selected is DeepseekV41ROCMAiterMLAAttention
|
||||
if expect_warning:
|
||||
warning_once.assert_called_once()
|
||||
else:
|
||||
warning_once.assert_not_called()
|
||||
assert (
|
||||
DeepseekV41ROCMAiterMLASparseBackend.get_name() == "ROCM_FLASHMLA_SPARSE_DSV41"
|
||||
)
|
||||
|
||||
|
||||
def test_aiter_unified_attention_uses_dedicated_metadata_builder():
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionBackend,
|
||||
RocmAiterUnifiedAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.rocm_attn import (
|
||||
RocmAttentionBackend,
|
||||
RocmAttentionMetadataBuilder,
|
||||
)
|
||||
|
||||
assert RocmAttentionBackend.get_builder_cls() is RocmAttentionMetadataBuilder
|
||||
assert (
|
||||
RocmAiterUnifiedAttentionBackend.get_builder_cls()
|
||||
is RocmAiterUnifiedAttentionMetadataBuilder
|
||||
)
|
||||
|
||||
|
||||
def test_rocm_backends_do_not_support_mm_prefix():
|
||||
"""Regression test: ROCm backends must not claim mm_prefix support.
|
||||
|
||||
If they do, prefix-LM multimodal models that attend vision tokens
|
||||
bidirectionally (e.g. Gemma3 4B) will use bidirectional attention
|
||||
via the ROCm backend instead of falling back to Triton, producing
|
||||
incorrect results. Remove this test only if support is properly added.
|
||||
"""
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
|
||||
|
||||
assert not RocmAttentionBackend.supports_mm_prefix(), (
|
||||
"RocmAttentionBackend does not support mm_prefix — "
|
||||
"defer to Triton unified attention instead for now"
|
||||
"See https://github.com/vllm-project/vllm/issues/48172"
|
||||
)
|
||||
assert not RocmAiterUnifiedAttentionBackend.supports_mm_prefix(), (
|
||||
"RocmAiterUnifiedAttentionBackend does not support mm_prefix — "
|
||||
"defer to Triton unified attention instead for now"
|
||||
"See https://github.com/ROCm/aiter/issues/4168"
|
||||
)
|
||||
|
||||
|
||||
def test_segmented_attention_uses_dedicated_backend_components():
|
||||
from vllm.v1.attention.backends.rocm_segmented_attn import (
|
||||
RocmSegmentedAttentionBackend,
|
||||
RocmSegmentedAttentionImpl,
|
||||
RocmSegmentedAttentionMetadataBuilder,
|
||||
)
|
||||
|
||||
assert (
|
||||
RocmSegmentedAttentionBackend.get_builder_cls()
|
||||
is RocmSegmentedAttentionMetadataBuilder
|
||||
)
|
||||
assert RocmSegmentedAttentionBackend.get_impl_cls() is RocmSegmentedAttentionImpl
|
||||
assert RocmSegmentedAttentionBackend.get_name() == "ROCM_SEGMENTED_ATTN"
|
||||
assert RocmSegmentedAttentionBackend.supports_non_causal()
|
||||
assert RocmSegmentedAttentionBackend.supports_sliding_window()
|
||||
assert RocmSegmentedAttentionBackend.supports_sink()
|
||||
assert not RocmSegmentedAttentionBackend.supports_mm_prefix()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sliding_window,logits_soft_cap,has_sinks",
|
||||
[(4096, None, False), (None, 50.0, False), (None, None, True)],
|
||||
)
|
||||
def test_segmented_attention_admits_unified_fallback_features(
|
||||
monkeypatch, sliding_window, logits_soft_cap, has_sinks
|
||||
):
|
||||
from vllm.platforms import rocm
|
||||
from vllm.v1.attention.backend import AttentionType
|
||||
from vllm.v1.attention.backends.rocm_segmented_attn import (
|
||||
RocmSegmentedAttentionImpl,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
|
||||
monkeypatch.setattr(rocm, "on_gfx12x", lambda: True)
|
||||
sinks = torch.zeros(8) if has_sinks else None
|
||||
|
||||
impl = RocmSegmentedAttentionImpl(
|
||||
num_heads=8,
|
||||
head_size=128,
|
||||
scale=128**-0.5,
|
||||
num_kv_heads=2,
|
||||
alibi_slopes=None,
|
||||
sliding_window=sliding_window,
|
||||
kv_cache_dtype="auto",
|
||||
logits_soft_cap=logits_soft_cap,
|
||||
attn_type=AttentionType.DECODER,
|
||||
sinks=sinks,
|
||||
)
|
||||
|
||||
assert isinstance(impl, RocmSegmentedAttentionImpl)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"platform,rdna",
|
||||
[("cuda", False), ("cpu", False), ("xpu", False), ("rocm", False), ("rocm", True)],
|
||||
)
|
||||
def test_segmented_attention_requires_rocm_rdna(monkeypatch, platform, rdna):
|
||||
"""Reject unsupported platforms before probing ROCm or constructing kernels."""
|
||||
from vllm.platforms import rocm
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends import rocm_segmented_attn as segmented
|
||||
|
||||
monkeypatch.setattr(
|
||||
segmented,
|
||||
"current_platform",
|
||||
SimpleNamespace(is_rocm=lambda: platform == "rocm"),
|
||||
)
|
||||
|
||||
def on_rdna():
|
||||
assert platform == "rocm", "Must not probe ROCm on another platform"
|
||||
return rdna
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", on_rdna)
|
||||
reason = segmented.RocmSegmentedAttentionBackend.supports_combination(
|
||||
128,
|
||||
torch.bfloat16,
|
||||
"auto",
|
||||
32,
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
DeviceCapability(12, 0),
|
||||
)
|
||||
if rdna:
|
||||
assert reason is None
|
||||
segmented.RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
|
||||
else:
|
||||
assert reason == "ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm"
|
||||
with pytest.raises(ValueError, match="requires AMD RDNA GPUs on ROCm"):
|
||||
segmented.RocmSegmentedAttentionImpl(
|
||||
8, 128, 128**-0.5, 2, None, None, "auto"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("explicit_cache", [False, True])
|
||||
def test_segmented_triton_cache_survives_standalone_compilation(
|
||||
monkeypatch, tmp_path, explicit_cache
|
||||
):
|
||||
"""Backend initialization preserves one cache across model compilations."""
|
||||
import os
|
||||
|
||||
from vllm.compilation.compiler_interface import InductorStandaloneAdaptor
|
||||
from vllm.platforms import rocm
|
||||
from vllm.v1.attention.backends.rocm_segmented_attn import (
|
||||
RocmSegmentedAttentionImpl,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
|
||||
monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("TRITON_CACHE_DIR", raising=False)
|
||||
monkeypatch.delenv("TORCHINDUCTOR_CACHE_DIR", raising=False)
|
||||
expected = tmp_path / "rocm_segmented_attention" / "triton"
|
||||
if explicit_cache:
|
||||
expected = tmp_path / "custom"
|
||||
monkeypatch.setenv("TRITON_CACHE_DIR", str(expected))
|
||||
for model in ("target", "draft", "restart_target"):
|
||||
RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
|
||||
assert os.environ["TRITON_CACHE_DIR"] == str(expected)
|
||||
assert expected.is_dir()
|
||||
InductorStandaloneAdaptor(
|
||||
use_aot_compile=True, save_format="binary"
|
||||
).initialize_cache(str(tmp_path / model))
|
||||
assert os.environ["TRITON_CACHE_DIR"] == str(expected)
|
||||
|
||||
|
||||
def test_segmented_attention_is_opt_in(monkeypatch):
|
||||
from vllm.platforms import rocm
|
||||
from vllm.platforms.rocm import RocmPlatform, _get_backend_priorities
|
||||
|
||||
assert AttentionBackendEnum.ROCM_SEGMENTED_ATTN not in _get_backend_priorities(
|
||||
use_mla=False, use_sparse=False
|
||||
)
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
|
||||
monkeypatch.setattr(rocm, "on_gfx12x", lambda: True)
|
||||
config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="fp8",
|
||||
block_size=32,
|
||||
)
|
||||
|
||||
path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_SEGMENTED_ATTN,
|
||||
attn_selector_config=config,
|
||||
)
|
||||
|
||||
assert path == AttentionBackendEnum.ROCM_SEGMENTED_ATTN.get_path()
|
||||
|
||||
|
||||
def test_segmented_attention_rejects_mm_prefix_at_selection(monkeypatch):
|
||||
from vllm.platforms import rocm
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
|
||||
config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=32,
|
||||
use_mm_prefix=True,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="multimodal token full attention"):
|
||||
RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_SEGMENTED_ATTN,
|
||||
attn_selector_config=config,
|
||||
)
|
||||
|
||||
|
||||
def test_segmented_attention_forward_uses_dedicated_dispatch(monkeypatch):
|
||||
from vllm.config import KernelConfig
|
||||
from vllm.platforms import rocm
|
||||
from vllm.v1.attention.backends.rocm_segmented_attn import (
|
||||
RocmSegmentedAttentionImpl,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
|
||||
impl = RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
|
||||
impl._segmented_attention_config = SimpleNamespace(
|
||||
kernel_config=KernelConfig(),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=1, max_num_batched_tokens=3),
|
||||
model_config=SimpleNamespace(max_model_len=16),
|
||||
)
|
||||
query = torch.empty(3, 8, 128, dtype=torch.bfloat16)
|
||||
key = torch.empty(3, 2, 128, dtype=torch.bfloat16)
|
||||
value = torch.empty_like(key)
|
||||
output = torch.empty_like(query)
|
||||
kv_cache = torch.empty(2, 2, 16, 256, dtype=torch.bfloat16)
|
||||
metadata = SimpleNamespace(
|
||||
num_actual_tokens=3,
|
||||
block_table=torch.zeros(1, 1, dtype=torch.int32),
|
||||
query_start_loc=torch.tensor([0, 3], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([3], dtype=torch.int32),
|
||||
max_seq_len=3,
|
||||
max_query_len=3,
|
||||
causal=True,
|
||||
)
|
||||
layer = SimpleNamespace(_k_scale=torch.ones(()), _v_scale=torch.ones(()))
|
||||
|
||||
with patch(
|
||||
"vllm.v1.attention.backends.rocm_segmented_attn.segmented_attention"
|
||||
) as dispatch:
|
||||
result = impl.forward(layer, query, key, value, kv_cache, metadata, output)
|
||||
|
||||
assert result is output
|
||||
dispatch.assert_called_once()
|
||||
assert dispatch.call_args.kwargs["key_cache"].shape == (2, 16, 2, 128)
|
||||
|
||||
|
||||
def test_aiter_unified_attention_capture_preserves_query_start_locations():
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionMetadataBuilder,
|
||||
)
|
||||
|
||||
builder = object.__new__(RocmAiterUnifiedAttentionMetadataBuilder)
|
||||
metadata = MagicMock()
|
||||
metadata.seq_lens = torch.tensor([1048576, 524288], dtype=torch.int32)
|
||||
builder.build = MagicMock(return_value=metadata)
|
||||
common = MagicMock()
|
||||
expected_query_start_loc = torch.tensor([0, 2, 5], dtype=torch.int32)
|
||||
common.query_start_loc = expected_query_start_loc.clone()
|
||||
metadata.query_start_loc = common.query_start_loc
|
||||
|
||||
actual = builder.build_for_cudagraph_capture(common)
|
||||
|
||||
builder.build.assert_called_once_with(0, common)
|
||||
assert actual is metadata
|
||||
assert torch.equal(actual.seq_lens, torch.ones_like(actual.seq_lens))
|
||||
assert actual.query_start_loc is common.query_start_loc
|
||||
assert torch.equal(actual.query_start_loc, expected_query_start_loc)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_dcp", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"env_vars, selected_backend, expected_backend_path",
|
||||
[
|
||||
# Test Case: Explicit FLEX_ATTENTION backend
|
||||
(
|
||||
{},
|
||||
"FLEX_ATTENTION",
|
||||
AttentionBackendEnum.FLEX_ATTENTION.get_path(),
|
||||
),
|
||||
# Test Case 1: Default (no env vars, no explicit backend)
|
||||
(
|
||||
{},
|
||||
None,
|
||||
AttentionBackendEnum.ROCM_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 2: Explicit TRITON_ATTN backend
|
||||
(
|
||||
{},
|
||||
"TRITON_ATTN",
|
||||
AttentionBackendEnum.TRITON_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 3: Explicit ROCM_ATTN backend
|
||||
(
|
||||
{},
|
||||
"ROCM_ATTN",
|
||||
AttentionBackendEnum.ROCM_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 4: Explicit ROCM_AITER_FA backend
|
||||
(
|
||||
{},
|
||||
"ROCM_AITER_FA",
|
||||
AttentionBackendEnum.ROCM_AITER_FA.get_path(),
|
||||
),
|
||||
# Test Case 5: Explicit ROCM_AITER_UNIFIED_ATTN backend
|
||||
(
|
||||
{},
|
||||
"ROCM_AITER_UNIFIED_ATTN",
|
||||
AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 6: VLLM_ROCM_USE_AITER=1
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
None,
|
||||
AttentionBackendEnum.ROCM_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 7: VLLM_ROCM_USE_AITER=1 + explicit TRITON_ATTN
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
"TRITON_ATTN",
|
||||
AttentionBackendEnum.TRITON_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 8: VLLM_ROCM_USE_AITER=1 + VLLM_ROCM_USE_AITER_MHA=0
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1", "VLLM_ROCM_USE_AITER_MHA": "0"},
|
||||
None,
|
||||
AttentionBackendEnum.ROCM_ATTN.get_path(),
|
||||
),
|
||||
# Test Case 9: VLLM_ROCM_USE_AITER=1 + explicit ROCM_ATTN
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
"ROCM_ATTN",
|
||||
AttentionBackendEnum.ROCM_ATTN.get_path(),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_standard_attention_backend_selection(
|
||||
env_vars,
|
||||
selected_backend,
|
||||
expected_backend_path,
|
||||
use_dcp,
|
||||
mock_vllm_config,
|
||||
mock_get_cdna_version,
|
||||
monkeypatch,
|
||||
):
|
||||
"""Standard ROCm backends remain selectable without DCP and reject DCP."""
|
||||
# Set environment variables
|
||||
for key, value in env_vars.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
# Import after setting env vars to ensure they're picked up
|
||||
# Reload envs to pick up new environment variables
|
||||
import importlib
|
||||
|
||||
import vllm.envs as envs
|
||||
|
||||
importlib.reload(envs)
|
||||
|
||||
# Convert string backend to enum if provided
|
||||
backend_enum = None
|
||||
if selected_backend:
|
||||
backend_enum = getattr(AttentionBackendEnum, selected_backend)
|
||||
|
||||
# Get the backend class path
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
|
||||
if use_dcp:
|
||||
with pytest.raises(ValueError, match="DCP not supported"):
|
||||
RocmPlatform.get_attn_backend_cls(backend_enum, attn_selector_config)
|
||||
return
|
||||
|
||||
backend_path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=backend_enum, attn_selector_config=attn_selector_config
|
||||
)
|
||||
|
||||
assert backend_path == expected_backend_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_dcp", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"env_vars, selected_backend, block_size, expected_backend_path, should_raise",
|
||||
[
|
||||
# Test Case 1: TRITON_MLA with block_size != 1
|
||||
(
|
||||
{},
|
||||
"TRITON_MLA",
|
||||
16,
|
||||
AttentionBackendEnum.TRITON_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 2: TRITON_MLA with block_size == 1 (should raise)
|
||||
(
|
||||
{},
|
||||
"TRITON_MLA",
|
||||
1,
|
||||
None,
|
||||
True,
|
||||
),
|
||||
# Test Case 3: ROCM_AITER_MLA with block_size == 1
|
||||
(
|
||||
{},
|
||||
"ROCM_AITER_MLA",
|
||||
1,
|
||||
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 4: ROCM_AITER_MLA with block_size != 1 (should raise)
|
||||
(
|
||||
{},
|
||||
"ROCM_AITER_MLA",
|
||||
16,
|
||||
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 5: VLLM_ROCM_USE_AITER=1 with block_size == 1
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
None,
|
||||
1,
|
||||
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 6: VLLM_ROCM_USE_AITER=1 with block_size == 16
|
||||
# (should use ROCM_AITER_MLA now, as it supports block_size 16)
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
None,
|
||||
16,
|
||||
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 7: VLLM_ROCM_USE_AITER=1 + explicit TRITON_MLA
|
||||
(
|
||||
{"VLLM_ROCM_USE_AITER": "1"},
|
||||
"TRITON_MLA",
|
||||
16,
|
||||
AttentionBackendEnum.TRITON_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
# Test Case 8: Explicit ROCM_AITER_TRITON_MLA
|
||||
(
|
||||
{},
|
||||
"ROCM_AITER_TRITON_MLA",
|
||||
16,
|
||||
AttentionBackendEnum.ROCM_AITER_TRITON_MLA.get_path(),
|
||||
False,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_mla_backend_selection(
|
||||
env_vars,
|
||||
selected_backend,
|
||||
block_size,
|
||||
expected_backend_path,
|
||||
should_raise,
|
||||
use_dcp,
|
||||
mock_vllm_config,
|
||||
monkeypatch,
|
||||
):
|
||||
"""Dense MLA remains selectable with DCP for valid block sizes."""
|
||||
# Set environment variables
|
||||
for key, value in env_vars.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
# Import after setting env vars
|
||||
# Reload envs
|
||||
import importlib
|
||||
|
||||
import vllm.envs as envs
|
||||
|
||||
importlib.reload(envs)
|
||||
|
||||
# Mock is_aiter_mla_enabled based on env vars and block_size
|
||||
aiter_enabled = env_vars.get("VLLM_ROCM_USE_AITER") == "1"
|
||||
|
||||
mock_rocm_ops = MagicMock()
|
||||
mock_rocm_ops.is_mla_enabled.return_value = aiter_enabled
|
||||
mock_aiter_module = MagicMock()
|
||||
mock_aiter_module.rocm_aiter_ops = mock_rocm_ops
|
||||
|
||||
with patch.dict("sys.modules", {"vllm._aiter_ops": mock_aiter_module}):
|
||||
# Convert string backend to enum if provided
|
||||
backend_enum = None
|
||||
if selected_backend:
|
||||
backend_enum = getattr(AttentionBackendEnum, selected_backend)
|
||||
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
if should_raise:
|
||||
with pytest.raises(ValueError):
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=block_size,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=block_size,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
backend_path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=backend_enum,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
else:
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=block_size,
|
||||
use_mla=True,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
|
||||
backend_path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=backend_enum, attn_selector_config=attn_selector_config
|
||||
)
|
||||
|
||||
assert backend_path == expected_backend_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_dcp", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"selected_backend", [None, AttentionBackendEnum.ROCM_AITER_MLA_SPARSE]
|
||||
)
|
||||
def test_sparse_mla_backend_rejects_dcp(selected_backend, use_dcp):
|
||||
"""Sparse MLA remains selectable without DCP and fails early with DCP."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
selector_config = AttentionSelectorConfig(
|
||||
head_size=576,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
use_mla=True,
|
||||
use_sparse=True,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
if use_dcp:
|
||||
with pytest.raises(ValueError, match="DCP not supported"):
|
||||
RocmPlatform.get_attn_backend_cls(selected_backend, selector_config)
|
||||
else:
|
||||
assert RocmPlatform.get_attn_backend_cls(selected_backend, selector_config) == (
|
||||
AttentionBackendEnum.ROCM_AITER_MLA_SPARSE.get_path()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_dcp", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"selected_backend, head_size, kv_cache_dtype",
|
||||
[
|
||||
(AttentionBackendEnum.TRITON_ATTN_DIFFKV, 192, "bfloat16"),
|
||||
# A 128-dimensional head uses 118 packed bytes, or 59 fp16 elements.
|
||||
(AttentionBackendEnum.TURBOQUANT, 59, "turboquant_k3v4_nc"),
|
||||
],
|
||||
)
|
||||
def test_specialized_attention_backends_reject_dcp(
|
||||
selected_backend, head_size, kv_cache_dtype, use_dcp
|
||||
):
|
||||
"""Valid DiffKV and compressed-cache configurations must reject DCP."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
selector_config = AttentionSelectorConfig(
|
||||
head_size=head_size,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
block_size=16,
|
||||
use_dcp=use_dcp,
|
||||
)
|
||||
if use_dcp:
|
||||
with pytest.raises(ValueError, match="DCP not supported"):
|
||||
RocmPlatform.get_attn_backend_cls(selected_backend, selector_config)
|
||||
else:
|
||||
assert RocmPlatform.get_attn_backend_cls(selected_backend, selector_config) == (
|
||||
selected_backend.get_path()
|
||||
)
|
||||
|
||||
|
||||
def test_aiter_fa_requires_mi3xx(mock_vllm_config):
|
||||
"""Test that ROCM_AITER_FA requires CDNA3+ architecture."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
# Mock cdna version to return 1 (used by supports_compute_capability)
|
||||
with (
|
||||
patch("vllm.platforms.rocm.get_cdna_version", return_value=1),
|
||||
pytest.raises(
|
||||
ValueError,
|
||||
match="compute capability not supported",
|
||||
),
|
||||
):
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
)
|
||||
|
||||
RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_AITER_FA,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def turboquant_run_config():
|
||||
"""Current config of a run whose KV cache dtype is a turboquant_* preset."""
|
||||
config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(cache_dtype="turboquant_k8v4")
|
||||
)
|
||||
with patch(
|
||||
"vllm.config.get_current_vllm_config_or_none",
|
||||
return_value=config,
|
||||
):
|
||||
yield config
|
||||
|
||||
|
||||
def test_turboquant_boundary_selection_is_not_cached_from_ordinary_run(
|
||||
cleared_attention_selector_cache,
|
||||
):
|
||||
from vllm.config import CacheConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
|
||||
from vllm.v1.attention.selector import get_attn_backend
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
ordinary_config = VllmConfig(cache_config=CacheConfig(cache_dtype="auto"))
|
||||
turboquant_config = VllmConfig(
|
||||
cache_config=CacheConfig(cache_dtype="turboquant_k8v4")
|
||||
)
|
||||
|
||||
backend_priorities = [
|
||||
AttentionBackendEnum.ROCM_ATTN,
|
||||
AttentionBackendEnum.TRITON_ATTN,
|
||||
AttentionBackendEnum.TURBOQUANT,
|
||||
]
|
||||
with patch(
|
||||
"vllm.platforms.rocm._get_backend_priorities",
|
||||
return_value=backend_priorities,
|
||||
):
|
||||
with set_current_vllm_config(ordinary_config):
|
||||
ordinary_backend = get_attn_backend(128, torch.float16, "auto")
|
||||
|
||||
with set_current_vllm_config(turboquant_config):
|
||||
boundary_backend = get_attn_backend(128, torch.float16, "auto")
|
||||
quantized_backend = get_attn_backend(128, torch.float16, "turboquant_k8v4")
|
||||
|
||||
assert ordinary_backend is AttentionBackendEnum.ROCM_ATTN.get_class()
|
||||
assert quantized_backend is AttentionBackendEnum.TURBOQUANT.get_class()
|
||||
assert get_supported_kv_cache_layouts([boundary_backend, quantized_backend]) == [
|
||||
KVCacheLayout.LBNHC
|
||||
]
|
||||
|
||||
|
||||
def test_turboquant_run_does_not_mask_unsupported_selected_backend(
|
||||
turboquant_run_config,
|
||||
):
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
)
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.rocm.get_cdna_version", return_value=1),
|
||||
pytest.raises(ValueError, match="compute capability not supported"),
|
||||
):
|
||||
RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_AITER_FA,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
|
||||
def test_turboquant_layout_check_respects_backend_override():
|
||||
from vllm.platforms.rocm import _shares_layout_with_turboquant
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
boundary_backend = MagicMock()
|
||||
boundary_backend.supported_kv_cache_layouts.return_value = (KVCacheLayout.LBHNC,)
|
||||
turboquant_override = MagicMock()
|
||||
turboquant_override.supported_kv_cache_layouts.return_value = (KVCacheLayout.LBHNC,)
|
||||
|
||||
with patch.object(
|
||||
AttentionBackendEnum.TURBOQUANT,
|
||||
"get_class",
|
||||
return_value=turboquant_override,
|
||||
) as get_turboquant_class:
|
||||
assert _shares_layout_with_turboquant(boundary_backend)
|
||||
get_turboquant_class.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"selected_backend",
|
||||
[None, "ROCM_ATTN", "ROCM_AITER_FA", "TURBOQUANT"],
|
||||
)
|
||||
def test_turboquant_boundary_layers_share_a_layout(
|
||||
selected_backend,
|
||||
turboquant_run_config,
|
||||
mock_get_cdna_version,
|
||||
):
|
||||
"""A turboquant_* run must resolve to backends with a common KV layout.
|
||||
|
||||
The boundary layers keep the native dtype and pick their own backend while
|
||||
every other layer picks TURBOQUANT. Engine startup hard-errors when the two
|
||||
share no layout, so the boundary layers must not land on a native ROCm or
|
||||
AITER backend, whichever backend the run asked for.
|
||||
"""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
|
||||
|
||||
backend_enum = (
|
||||
getattr(AttentionBackendEnum, selected_backend) if selected_backend else None
|
||||
)
|
||||
|
||||
def resolve(kv_cache_dtype):
|
||||
path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=backend_enum,
|
||||
attn_selector_config=AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
block_size=16,
|
||||
),
|
||||
)
|
||||
return resolve_obj_by_qualname(path)
|
||||
|
||||
boundary_backend = resolve("auto")
|
||||
quantized_backend = resolve("turboquant_k8v4")
|
||||
|
||||
assert quantized_backend is AttentionBackendEnum.TURBOQUANT.get_class()
|
||||
# Raises when the intersection is empty, which is the startup failure.
|
||||
assert get_supported_kv_cache_layouts([boundary_backend, quantized_backend])
|
||||
|
||||
|
||||
def test_sparse_not_supported(mock_vllm_config):
|
||||
"""Test that sparse MLA without use_mla flag raises an error."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="No valid attention backend found",
|
||||
):
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=True,
|
||||
)
|
||||
|
||||
RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=None, attn_selector_config=attn_selector_config
|
||||
)
|
||||
|
||||
|
||||
def _kv_connector_selector_config() -> AttentionSelectorConfig:
|
||||
return AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype="auto",
|
||||
block_size=16,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_kv_connector=True,
|
||||
)
|
||||
|
||||
|
||||
def test_unified_attn_declares_kv_connector_support():
|
||||
"""ROCM_AITER_UNIFIED_ATTN opts into KV connectors and ROCM_ATTN does not."""
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
|
||||
|
||||
assert RocmAiterUnifiedAttentionBackend.supports_kv_connector() is True
|
||||
assert RocmAttentionBackend.supports_kv_connector() is False
|
||||
|
||||
|
||||
def test_unified_attn_supports_kv_connector(mock_vllm_config, mock_get_cdna_version):
|
||||
"""ROCM_AITER_UNIFIED_ATTN can be selected with KV connectors."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
backend_path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
|
||||
attn_selector_config=_kv_connector_selector_config(),
|
||||
)
|
||||
|
||||
assert backend_path == AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN.get_path()
|
||||
|
||||
|
||||
def test_rocm_attn_rejects_kv_connector(mock_vllm_config, mock_get_cdna_version):
|
||||
"""Selecting ROCM_ATTN with a KV connector is illegal."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
attn_selector_config = _kv_connector_selector_config()
|
||||
|
||||
with pytest.raises(ValueError, match="KV connector not supported"):
|
||||
RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.ROCM_ATTN,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"aiter_found, expected_backend",
|
||||
[
|
||||
(True, AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN),
|
||||
(False, AttentionBackendEnum.TRITON_ATTN),
|
||||
],
|
||||
)
|
||||
def test_auto_selection_for_kv_connector(
|
||||
aiter_found, expected_backend, mock_vllm_config, mock_get_cdna_version
|
||||
):
|
||||
"""Auto-selection with a KV connector and AITER enabled resolves to unified attn,
|
||||
and to triton attn if AITER not enabled."""
|
||||
from vllm.platforms.rocm import RocmPlatform
|
||||
|
||||
with patch(
|
||||
"vllm._aiter_ops.is_aiter_found_and_supported", return_value=aiter_found
|
||||
):
|
||||
backend_path = RocmPlatform.get_attn_backend_cls(
|
||||
selected_backend=None,
|
||||
attn_selector_config=_kv_connector_selector_config(),
|
||||
)
|
||||
|
||||
assert backend_path == expected_backend.get_path()
|
||||
|
||||
|
||||
def test_unified_attn_prefers_block_contiguous_layout():
|
||||
"""Unified attn prefers a block-first KV layout, hence ok with kv connectors."""
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
|
||||
|
||||
unified_preferred = RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()[0]
|
||||
rocm_attn_preferred = RocmAttentionBackend.supported_kv_cache_layouts()[0]
|
||||
|
||||
assert unified_preferred.is_block_contiguous is True
|
||||
assert rocm_attn_preferred.is_block_contiguous is False
|
||||
|
||||
|
||||
def test_unified_attn_drops_lhbnc_with_kv_connector():
|
||||
"""Connectors move a block as one contiguous byte range, which LHBNC breaks."""
|
||||
from vllm.config import KVTransferConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
|
||||
RocmAiterUnifiedAttentionBackend,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import KVCacheLayout
|
||||
|
||||
assert KVCacheLayout.LHBNC in (
|
||||
RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()
|
||||
)
|
||||
|
||||
config = VllmConfig(
|
||||
kv_transfer_config=KVTransferConfig(
|
||||
kv_connector="ExampleConnector", kv_role="kv_both"
|
||||
)
|
||||
)
|
||||
with set_current_vllm_config(config):
|
||||
layouts = RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()
|
||||
|
||||
assert layouts
|
||||
assert all(layout.is_block_compact for layout in layouts)
|
||||
@@ -1,310 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import set_random_seed
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla_sparse as sparse_mod
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
|
||||
ROCMAiterMLASparseBackend,
|
||||
_use_rocm_sparse_triton,
|
||||
fit_kpool_indices_to_aiter,
|
||||
)
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
_sparse_kv_row_offset,
|
||||
_validate_dsv4_sparse_dims,
|
||||
_validate_sparse_dims,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import KVCacheLayout
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _store_sparse_kv_row_offset_kernel(slot_ptr, output_ptr, stride: tl.constexpr):
|
||||
slot = tl.load(slot_ptr)
|
||||
tl.store(output_ptr, _sparse_kv_row_offset(slot, stride))
|
||||
|
||||
|
||||
def _fit_kpool_indices_reference(
|
||||
token_indices: torch.Tensor, topk_tokens: int
|
||||
) -> torch.Tensor:
|
||||
history = token_indices[:, :topk_tokens]
|
||||
tail = token_indices[:, topk_tokens:]
|
||||
valid_history = (history >= 0).sum(dim=1)
|
||||
valid_tail = (tail >= 0).sum(dim=1)
|
||||
keep_history = torch.minimum(valid_history, topk_tokens - valid_tail)
|
||||
|
||||
columns = torch.arange(topk_tokens, device=token_indices.device).unsqueeze(0)
|
||||
tail_offsets = columns - keep_history.unsqueeze(1)
|
||||
tail_values = torch.gather(
|
||||
tail, 1, tail_offsets.clamp(min=0, max=tail.shape[1] - 1)
|
||||
)
|
||||
output = torch.where(columns < keep_history.unsqueeze(1), history, tail_values)
|
||||
valid_output = columns < (keep_history + valid_tail).unsqueeze(1)
|
||||
return torch.where(valid_output, output, -1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
|
||||
def test_fit_kpool_indices_preserves_tail_and_best_history():
|
||||
token_indices = torch.tensor(
|
||||
[
|
||||
[10, 9, 8, 7, 6, 5, 100, 101],
|
||||
[10, 9, 8, -1, -1, -1, 100, -1],
|
||||
[-1, -1, -1, -1, -1, -1, -1, -1],
|
||||
],
|
||||
dtype=torch.int32,
|
||||
device="cuda",
|
||||
)
|
||||
|
||||
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=6)
|
||||
|
||||
assert fitted.tolist() == [
|
||||
[10, 9, 8, 7, 100, 101],
|
||||
[10, 9, 8, 100, -1, -1],
|
||||
[-1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
|
||||
@pytest.mark.parametrize(
|
||||
("num_tokens", "topk_tokens", "tail_width"),
|
||||
[(1, 4, 1), (7, 6, 2), (13, 128, 128), (3, 2048, 128)],
|
||||
)
|
||||
def test_fit_kpool_indices_matches_eager_reference(num_tokens, topk_tokens, tail_width):
|
||||
"""The Triton fit must reproduce the eager packing rule exactly."""
|
||||
set_random_seed(topk_tokens + num_tokens)
|
||||
width = topk_tokens + tail_width
|
||||
token_indices = torch.randint(0, 4096, (num_tokens, width), dtype=torch.int32)
|
||||
valid = torch.rand((num_tokens, width)) < 0.5
|
||||
valid[0] = False
|
||||
valid[-1] = True
|
||||
token_indices = torch.where(valid, token_indices, -1).cuda()
|
||||
|
||||
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=topk_tokens)
|
||||
|
||||
torch.testing.assert_close(
|
||||
fitted, _fit_kpool_indices_reference(token_indices, topk_tokens)
|
||||
)
|
||||
|
||||
|
||||
def test_fit_kpool_indices_exact_width_is_noop():
|
||||
token_indices = torch.tensor([[3, 2, 1, -1]], dtype=torch.int32)
|
||||
|
||||
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=4)
|
||||
|
||||
assert fitted.data_ptr() == token_indices.data_ptr()
|
||||
|
||||
|
||||
def test_fit_kpool_indices_rejects_narrow_input():
|
||||
with pytest.raises(ValueError, match="at least topk_tokens"):
|
||||
fit_kpool_indices_to_aiter(
|
||||
torch.zeros((1, 3), dtype=torch.int32), topk_tokens=4
|
||||
)
|
||||
|
||||
|
||||
def test_rocm_sparse_mla_supports_glm_packed_layout():
|
||||
assert KVCacheLayout.BLHNC in ROCMAiterMLASparseBackend.supported_kv_cache_layouts()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"kv_cache_dtype",
|
||||
"head_size",
|
||||
"num_prefills",
|
||||
"num_decodes",
|
||||
"num_decode_tokens",
|
||||
"max_query_len",
|
||||
"expected",
|
||||
),
|
||||
[
|
||||
("auto", 512, 1, 0, 0, 32, True),
|
||||
("auto", 512, 1, 2, 2, 32, True),
|
||||
("auto", 512, 0, 2, 2, 1, True),
|
||||
("fp8", 512, 1, 0, 0, 32, False),
|
||||
("auto", 576, 1, 0, 0, 32, False),
|
||||
("auto", 512, 0, 2, 4, 2, True),
|
||||
("auto", 512, 0, 2, 12, 6, True),
|
||||
("auto", 512, 0, 0, 0, 0, False),
|
||||
],
|
||||
)
|
||||
def test_rocm_sparse_triton_route(
|
||||
kv_cache_dtype,
|
||||
head_size,
|
||||
num_prefills,
|
||||
num_decodes,
|
||||
num_decode_tokens,
|
||||
max_query_len,
|
||||
expected,
|
||||
):
|
||||
"""Validate Triton routing for prefill, decode, and MTP verification."""
|
||||
assert (
|
||||
_use_rocm_sparse_triton(
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
head_size=head_size,
|
||||
kv_lora_rank=512,
|
||||
num_prefills=num_prefills,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
max_query_len=max_query_len,
|
||||
)
|
||||
is expected
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("gfx942", "fp8", "num_prefills", "num_decodes", "prefill_max_seq_len", "route"),
|
||||
[
|
||||
pytest.param(True, False, 1, 0, 129, "triton", id="above-topk"),
|
||||
pytest.param(False, False, 1, 0, 129, "aiter", id="gfx950"),
|
||||
pytest.param(True, True, 1, 0, 129, "aiter", id="fp8"),
|
||||
pytest.param(True, False, 0, 2, 129, "aiter", id="decode-only"),
|
||||
pytest.param(True, False, 1, 1, 129, "aiter", id="mixed"),
|
||||
pytest.param(True, False, 1, 0, 128, "aiter", id="equal-topk"),
|
||||
pytest.param(True, False, 1, 0, 127, "aiter", id="below-topk"),
|
||||
pytest.param(True, False, 0, 0, 129, "aiter", id="empty"),
|
||||
pytest.param(
|
||||
True, False, 1, 0, None, "missing", id="required-prefill-metadata"
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_rocm_long_bf16_prefill_dispatch(
|
||||
monkeypatch, gfx942, fp8, num_prefills, num_decodes, prefill_max_seq_len, route
|
||||
):
|
||||
"""Check the new dispatch gate using CPU tensors and intercepted kernels."""
|
||||
monkeypatch.setattr("vllm.platforms.rocm.on_gfx942", lambda: gfx942)
|
||||
|
||||
class KernelSelected(Exception):
|
||||
pass
|
||||
|
||||
def triton_kernel(**kwargs):
|
||||
raise KernelSelected("triton")
|
||||
|
||||
def aiter_kernel(*args, **kwargs):
|
||||
raise KernelSelected("aiter")
|
||||
|
||||
monkeypatch.setattr(sparse_mod, "rocm_sparse_attn_prefill", triton_kernel)
|
||||
monkeypatch.setattr(sparse_mod.rocm_aiter_ops, "mla_decode_fwd", aiter_kernel)
|
||||
impl = object.__new__(sparse_mod.ROCMAiterMLASparseImpl)
|
||||
impl.num_heads = 64
|
||||
impl.kv_lora_rank = 512
|
||||
impl.kv_cache_dtype = "fp8" if fp8 else "auto"
|
||||
impl.scale = 576**-0.5
|
||||
impl.sinks = None
|
||||
|
||||
dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16
|
||||
q = torch.empty(2, 64, 576, dtype=dtype)
|
||||
kv = torch.empty(4, 1, 576, dtype=dtype)
|
||||
metadata = SimpleNamespace(
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
num_prefills=num_prefills,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decodes,
|
||||
max_query_len=2,
|
||||
prefill_max_seq_len=prefill_max_seq_len,
|
||||
topk_tokens=128,
|
||||
work_meta_data=None,
|
||||
qo_indptr=torch.arange(3, dtype=torch.int32),
|
||||
paged_kv_indices=torch.empty(0, dtype=torch.int32),
|
||||
paged_kv_indptr=torch.zeros(3, dtype=torch.int32),
|
||||
paged_kv_last_page_len=torch.ones(2, dtype=torch.int32),
|
||||
)
|
||||
# Irrelevant routes must not inspect prefill-only metadata.
|
||||
if (
|
||||
not gfx942
|
||||
or fp8
|
||||
or num_decodes
|
||||
or not num_prefills
|
||||
or prefill_max_seq_len is None
|
||||
):
|
||||
del metadata.prefill_max_seq_len
|
||||
del metadata.topk_tokens
|
||||
layer = SimpleNamespace(_q_scale=1.0, _k_scale=1.0)
|
||||
error = AttributeError if route == "missing" else KernelSelected
|
||||
match = "prefill_max_seq_len" if route == "missing" else f"^{route}$"
|
||||
with pytest.raises(error, match=match):
|
||||
impl._forward_mla(layer, q, kv, metadata)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gfx942", [False, True])
|
||||
@pytest.mark.parametrize("num_heads", [8, 12])
|
||||
def test_rocm_sparse_triton_route_preserves_padded_sinks(
|
||||
monkeypatch, num_heads, gfx942
|
||||
):
|
||||
monkeypatch.setattr("vllm.platforms.rocm.on_gfx942", lambda: gfx942)
|
||||
captured = {}
|
||||
|
||||
def fake_rocm_sparse_attn_prefill(**kwargs):
|
||||
output = kwargs["output"]
|
||||
captured["attn_sink"] = kwargs["attn_sink"]
|
||||
output.copy_(
|
||||
captured["attn_sink"].to(output.dtype).view(1, -1, 1).expand_as(output)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
sparse_mod, "rocm_sparse_attn_prefill", fake_rocm_sparse_attn_prefill
|
||||
)
|
||||
|
||||
impl = object.__new__(sparse_mod.ROCMAiterMLASparseImpl)
|
||||
impl.num_heads = num_heads
|
||||
impl.kv_lora_rank = 512
|
||||
impl.kv_cache_dtype = "auto"
|
||||
impl.scale = 512**-0.5
|
||||
impl.sinks = torch.arange(num_heads, dtype=torch.float32)
|
||||
|
||||
q = torch.zeros(2, 16, 512, dtype=torch.bfloat16)
|
||||
kv = torch.zeros(4, 1, 512, dtype=torch.bfloat16)
|
||||
metadata = SimpleNamespace(
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
num_prefills=1,
|
||||
num_decodes=0,
|
||||
num_decode_tokens=0,
|
||||
max_query_len=2,
|
||||
paged_kv_indices=torch.empty(0, dtype=torch.int32),
|
||||
paged_kv_indptr=torch.zeros(3, dtype=torch.int32),
|
||||
)
|
||||
|
||||
output, lse = impl._forward_mla(SimpleNamespace(), q, kv, metadata)
|
||||
|
||||
if num_heads == 8:
|
||||
expected_sinks = impl.sinks.repeat_interleave(2)
|
||||
else:
|
||||
expected_sinks = torch.cat((impl.sinks, impl.sinks[:4]))
|
||||
torch.testing.assert_close(captured["attn_sink"], expected_sinks)
|
||||
assert output.shape == (2, num_heads, 512)
|
||||
torch.testing.assert_close(
|
||||
output[:, :, 0].float(),
|
||||
impl.sinks.expand(2, -1),
|
||||
)
|
||||
assert lse is None
|
||||
|
||||
|
||||
def test_rocm_sparse_attention_accepts_glm_nope_dimensions():
|
||||
_validate_sparse_dims(512, 512, 0, "test")
|
||||
|
||||
|
||||
def test_rocm_sparse_attention_rejects_inconsistent_dimensions():
|
||||
with pytest.raises(AssertionError, match="expected head_dim"):
|
||||
_validate_sparse_dims(511, 512, 0, "test")
|
||||
|
||||
|
||||
def test_dsv4_sparse_attention_keeps_layout_constraint():
|
||||
_validate_dsv4_sparse_dims(512, 448, 64, "test")
|
||||
with pytest.raises(AssertionError, match="expects 448 NoPE dims"):
|
||||
_validate_dsv4_sparse_dims(512, 512, 0, "test")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
|
||||
def test_sparse_prefill_kv_row_offset_does_not_overflow_int32():
|
||||
# GLM's 640-token pages cross the signed-int32 address boundary at block
|
||||
# 6554 for a 512-element KV row. The production kernel must promote the
|
||||
# slot before multiplying by the row stride.
|
||||
slot = torch.tensor([6554 * 640], dtype=torch.int32, device="cuda")
|
||||
output = torch.empty(1, dtype=torch.int64, device="cuda")
|
||||
|
||||
_store_sparse_kv_row_offset_kernel[(1,)](slot, output, stride=512)
|
||||
|
||||
assert output.item() == 6554 * 640 * 512
|
||||
@@ -1,445 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import multi_gpu_only
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_prefill import context_row_indices
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"padded,lengths,starts,total,expected",
|
||||
[
|
||||
([3, 2], [[7, 6], [2, 1]], [5, 0], 6, [0, 1, 5, 3, 4, 8]),
|
||||
([3], [[2, 9]], [4], 3, [3, 4, 5]),
|
||||
([3], [[1, 1]], [0], 3, None),
|
||||
],
|
||||
ids=["padding_and_chunk_starts", "empty_rank", "inconsistent_total"],
|
||||
)
|
||||
def test_dcp_context_indices(padded, lengths, starts, total, expected):
|
||||
chunk = SimpleNamespace(
|
||||
padded_local_seq_lens=padded,
|
||||
local_context_lens_allranks=lengths,
|
||||
local_starts=starts,
|
||||
num_local_context_tokens=sum(padded),
|
||||
num_context_tokens=total,
|
||||
)
|
||||
if expected is None:
|
||||
with pytest.raises(AssertionError):
|
||||
context_row_indices(chunk, torch.device("cpu"))
|
||||
else:
|
||||
rows = context_row_indices(chunk, torch.device("cpu"))
|
||||
assert rows.tolist() == expected
|
||||
assert rows.dtype == torch.int32
|
||||
|
||||
|
||||
def test_compressed_gather_preserves_bytes_and_workspace_partition(monkeypatch):
|
||||
from vllm.v1.attention.ops import rocm_aiter_mla_prefill as prefill
|
||||
|
||||
workspace = torch.full((12, 4), -1, dtype=torch.bfloat16)
|
||||
cache = torch.arange(8, dtype=torch.uint8).reshape(2, 4)
|
||||
chunk = SimpleNamespace(
|
||||
num_local_context_tokens=2,
|
||||
local_context_lens_allranks=[[2, 2]],
|
||||
padded_local_cu_seq_lens=torch.tensor([0, 2]),
|
||||
num_requests=1,
|
||||
starts=torch.tensor([0]),
|
||||
)
|
||||
|
||||
def local_gather(src, dst, *args):
|
||||
assert src.dtype == dst.dtype == torch.uint8
|
||||
dst.copy_(src)
|
||||
|
||||
def allgather(dst, src):
|
||||
assert dst.dtype == src.dtype == torch.uint8
|
||||
assert dst.shape == (4, 4)
|
||||
assert src.shape == (2, 4)
|
||||
dst[:2].copy_(src)
|
||||
dst[2:].copy_(src + 16)
|
||||
|
||||
monkeypatch.setattr(prefill.ops, "cp_gather_cache", local_gather)
|
||||
gathered = prefill.gather_compressed_context(
|
||||
cache, workspace, torch.empty(1, 1), chunk, allgather, torch.float8_e4m3fn
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
gathered.view(torch.uint8), torch.cat((cache, cache + 16))
|
||||
)
|
||||
# Retain the original logical capacity even though the byte view is larger.
|
||||
assert gathered.data_ptr() - workspace.data_ptr() == 4 * 4
|
||||
torch.testing.assert_close(workspace.view(torch.uint8).reshape(-1, 4)[:2], cache)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"unsupported",
|
||||
[
|
||||
"packed_cache",
|
||||
"e5m2",
|
||||
"bf16_cache",
|
||||
"quantized_weight",
|
||||
"bias",
|
||||
"no_indices",
|
||||
"query_dtype",
|
||||
"prefill_dtype",
|
||||
"weight_dtype",
|
||||
"weight_layout",
|
||||
"cache_layout",
|
||||
"dimensions",
|
||||
"no_aiter",
|
||||
],
|
||||
)
|
||||
def test_dcp_prefill_unsupported_formats_use_original_path(monkeypatch, unsupported):
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm MLA backend")
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
AiterMLAImpl,
|
||||
MLACommonImpl,
|
||||
)
|
||||
|
||||
if unsupported == "no_aiter":
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.attention.backends.mla.rocm_aiter_mla."
|
||||
"is_aiter_found_and_supported",
|
||||
lambda: False,
|
||||
)
|
||||
|
||||
impl = object.__new__(AiterMLAImpl)
|
||||
impl.kv_cache_dtype = {
|
||||
"packed_cache": "fp8_ds_mla",
|
||||
"e5m2": "fp8_e5m2",
|
||||
"bf16_cache": "auto",
|
||||
}.get(unsupported, "fp8")
|
||||
impl.kv_lora_rank = 512
|
||||
if unsupported == "dimensions":
|
||||
impl.kv_lora_rank = 256
|
||||
impl.qk_nope_head_dim = impl.v_head_dim = 128
|
||||
impl.qk_rope_head_dim = 64
|
||||
impl.num_heads = 1
|
||||
impl.kv_b_proj = SimpleNamespace(
|
||||
weight=torch.empty(256, 512, dtype=torch.bfloat16),
|
||||
weight_scale=torch.ones(1) if unsupported == "quantized_weight" else None,
|
||||
bias=torch.ones(256) if unsupported == "bias" else None,
|
||||
)
|
||||
if unsupported == "weight_dtype":
|
||||
impl.kv_b_proj.weight = impl.kv_b_proj.weight.half()
|
||||
elif unsupported == "weight_layout":
|
||||
impl.kv_b_proj.weight = torch.empty(512, 256, dtype=torch.bfloat16).T
|
||||
metadata = SimpleNamespace(
|
||||
prefill=SimpleNamespace(
|
||||
q_data_type=torch.float16
|
||||
if unsupported == "prefill_dtype"
|
||||
else torch.bfloat16
|
||||
),
|
||||
dcp_context_row_indices=None if unsupported == "no_indices" else [],
|
||||
)
|
||||
expected = (torch.ones(1), torch.zeros(1))
|
||||
|
||||
def fused_mla_kv_concat(kv_nope, k_pe, use_fp8_prefill):
|
||||
raise AssertionError("The fallback should receive the callback")
|
||||
|
||||
def original_path(*args):
|
||||
assert args[-1] is fused_mla_kv_concat
|
||||
return expected
|
||||
|
||||
monkeypatch.setattr(
|
||||
MLACommonImpl,
|
||||
"_context_parallel_compute_prefill_context",
|
||||
original_path,
|
||||
)
|
||||
q = torch.empty(1, 1, 192, dtype=torch.bfloat16)
|
||||
cache = torch.empty(1, 1536, 576, dtype=torch.uint8)
|
||||
if unsupported == "query_dtype":
|
||||
q = q.half()
|
||||
elif unsupported == "cache_layout":
|
||||
cache = torch.empty(1, 1536, 1152, dtype=torch.uint8)[..., ::2]
|
||||
assert (
|
||||
impl._context_parallel_compute_prefill_context(
|
||||
q,
|
||||
cache,
|
||||
metadata,
|
||||
torch.ones(1),
|
||||
8,
|
||||
fused_mla_kv_concat_fn=fused_mla_kv_concat,
|
||||
)
|
||||
is expected
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm MLA backend")
|
||||
@multi_gpu_only(num_gpus=2)
|
||||
@pytest.mark.parametrize("interleave", [1, 64])
|
||||
@pytest.mark.parametrize(
|
||||
"context_lens,workspace_size",
|
||||
[([145, 37], 1024), ([545, 0, 3, 0], 256)],
|
||||
ids=["single_chunk", "continuations_and_empty_context"],
|
||||
)
|
||||
def test_dcp_prefill_matches_full_attention(
|
||||
interleave, context_lens, workspace_size, tmp_path
|
||||
):
|
||||
"""Real DCP gather, fused expansion and suffix/chunk merges match dense SDPA."""
|
||||
import torch.multiprocessing as mp
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
|
||||
if not is_aiter_found_and_supported():
|
||||
pytest.skip("AITER on CDNA 3 or newer is required")
|
||||
mp.spawn(
|
||||
_dcp_prefill_worker,
|
||||
args=(
|
||||
f"file://{tmp_path / 'dist_init'}",
|
||||
interleave,
|
||||
context_lens,
|
||||
workspace_size,
|
||||
),
|
||||
nprocs=2,
|
||||
)
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def _dcp_prefill_worker(rank, init_method, interleave, context_lens, workspace_size):
|
||||
import torch.nn.functional as F
|
||||
|
||||
from tests.v1.attention.test_mla_backends import MockMLAAttentionLayer
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
create_vllm_config,
|
||||
)
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed import (
|
||||
cleanup_dist_env_and_memory,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
|
||||
AiterFlashAttnPrefillBackend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
AiterMLAImpl,
|
||||
AiterMLAMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.ops.dcp import MLADCPManager
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
from vllm.v1.worker.workspace import init_workspace_manager
|
||||
|
||||
torch.accelerator.set_device_index(rank)
|
||||
torch.set_num_threads(1)
|
||||
device = torch.device(f"cuda:{rank}")
|
||||
init_workspace_manager(device)
|
||||
world_size, num_heads, block_size = 2, 12, 64
|
||||
config = create_vllm_config(
|
||||
model_name="deepseek-ai/DeepSeek-V2-Lite",
|
||||
dtype=torch.bfloat16,
|
||||
tensor_parallel_size=world_size,
|
||||
max_model_len=2048,
|
||||
block_size=block_size,
|
||||
max_num_seqs=8,
|
||||
max_num_batched_tokens=2048,
|
||||
)
|
||||
config.cache_config.cache_dtype = "fp8"
|
||||
config.parallel_config.decode_context_parallel_size = world_size
|
||||
config.parallel_config.cp_kv_cache_interleave_size = interleave
|
||||
config.attention_config.use_prefill_query_quantization = False
|
||||
config.kernel_config.enable_jit_warmup = False
|
||||
with set_current_vllm_config(config):
|
||||
init_distributed_environment(
|
||||
world_size=world_size,
|
||||
rank=rank,
|
||||
local_rank=rank,
|
||||
distributed_init_method=init_method,
|
||||
)
|
||||
initialize_model_parallel(
|
||||
tensor_model_parallel_size=world_size,
|
||||
decode_context_model_parallel_size=world_size,
|
||||
)
|
||||
try:
|
||||
projection = ColumnParallelLinear(
|
||||
512,
|
||||
num_heads * world_size * 256,
|
||||
bias=False,
|
||||
params_dtype=torch.bfloat16,
|
||||
).to(device)
|
||||
torch.manual_seed(101 + rank)
|
||||
projection.weight.copy_(torch.randn_like(projection.weight) * 0.02)
|
||||
dims = dict(
|
||||
kv_lora_rank=512,
|
||||
qk_nope_head_dim=128,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
)
|
||||
impl = AiterMLAImpl(
|
||||
num_heads=num_heads,
|
||||
head_size=576,
|
||||
scale=192**-0.5,
|
||||
num_kv_heads=1,
|
||||
alibi_slopes=None,
|
||||
sliding_window=None,
|
||||
kv_cache_dtype="fp8",
|
||||
logits_soft_cap=None,
|
||||
attn_type="decoder",
|
||||
kv_sharing_target_layer_name=None,
|
||||
q_lora_rank=None,
|
||||
qk_head_dim=192,
|
||||
kv_b_proj=projection,
|
||||
**dims,
|
||||
)
|
||||
layer = MockMLAAttentionLayer(
|
||||
impl=impl,
|
||||
num_heads=num_heads,
|
||||
device=device,
|
||||
kv_b_proj=projection,
|
||||
q_scale=1.0,
|
||||
k_scale=0.07,
|
||||
**dims,
|
||||
)
|
||||
layer.prefill_backend = AiterFlashAttnPrefillBackend(
|
||||
num_heads=num_heads,
|
||||
scale=impl.scale,
|
||||
vllm_config=config,
|
||||
**dims,
|
||||
)
|
||||
layer.dcp_manager = MLADCPManager(
|
||||
config,
|
||||
device,
|
||||
num_heads,
|
||||
576,
|
||||
512,
|
||||
torch.bfloat16,
|
||||
torch.bfloat16,
|
||||
None,
|
||||
True,
|
||||
False,
|
||||
)
|
||||
config.compilation_config.static_forward_context["mla"] = layer
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=576,
|
||||
dtype=current_platform.fp8_dtype(),
|
||||
cache_dtype_str="fp8",
|
||||
)
|
||||
builder = AiterMLAMetadataBuilder(spec, ["mla"], config, device)
|
||||
builder.chunked_prefill_workspace_size = workspace_size
|
||||
builder.chunked_prefill_workspace = torch.empty(
|
||||
(workspace_size + workspace_size // world_size, 576),
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
layer.dcp_manager.init_kv_gather(
|
||||
builder.chunked_prefill_workspace, workspace_size
|
||||
)
|
||||
query_lens = [i + 2 for i in range(len(context_lens))]
|
||||
batch = BatchSpec(
|
||||
seq_lens=[c + q for c, q in zip(context_lens, query_lens)],
|
||||
query_lens=query_lens,
|
||||
)
|
||||
common = create_common_attn_metadata(
|
||||
batch, block_size, device, arange_block_indices=True
|
||||
)
|
||||
metadata = builder.build(0, common)
|
||||
assert metadata.prefill is not None
|
||||
chunked = metadata.prefill.chunked_context
|
||||
assert chunked is not None and metadata.dcp_context_row_indices is not None
|
||||
if 0 in context_lens:
|
||||
assert chunked.empty_token_slices
|
||||
assert any(c.is_continuation for c in chunked.chunks)
|
||||
else:
|
||||
assert len(chunked.chunks) == 1
|
||||
blocks_per_req = common.block_table_tensor.shape[1]
|
||||
cache = torch.zeros(
|
||||
(len(context_lens) * blocks_per_req, block_size, 576),
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
).to(current_platform.fp8_dtype())
|
||||
queries, suffixes, references = [], [], []
|
||||
# All ranks reconstruct the same global cache before sharding it.
|
||||
torch.manual_seed(42)
|
||||
for request, (context_len, query_len) in enumerate(
|
||||
zip(context_lens, query_lens)
|
||||
):
|
||||
latent = torch.randn(
|
||||
context_len, 576, device=device, dtype=torch.bfloat16
|
||||
)
|
||||
quantized = (latent.float() / layer._k_scale).to(cache.dtype)
|
||||
positions = torch.arange(context_len, device=device)
|
||||
shard = quantized.view(torch.uint8)[
|
||||
(positions // interleave) % world_size == rank
|
||||
]
|
||||
cache.view(len(context_lens), -1, 576).view(torch.uint8)[
|
||||
request, : len(shard)
|
||||
].copy_(shard)
|
||||
suffix = torch.randn(
|
||||
query_len, 576, device=device, dtype=torch.bfloat16
|
||||
)
|
||||
q = (
|
||||
torch.randn(
|
||||
query_len, num_heads, 192, device=device, dtype=torch.bfloat16
|
||||
)
|
||||
* 0.5
|
||||
)
|
||||
full_latent = torch.cat(
|
||||
(
|
||||
(quantized.float() * layer._k_scale).to(torch.bfloat16),
|
||||
suffix,
|
||||
)
|
||||
)
|
||||
kv = F.linear(full_latent[:, :512], projection.weight).view(
|
||||
-1, num_heads, 256
|
||||
)
|
||||
k_nope, v = kv.split(128, dim=-1)
|
||||
k = torch.cat(
|
||||
(k_nope, full_latent[:, None, 512:].expand(-1, num_heads, -1)),
|
||||
dim=-1,
|
||||
)
|
||||
mask = torch.arange(context_len + query_len, device=device)[
|
||||
None, :
|
||||
] <= (context_len + torch.arange(query_len, device=device)[:, None])
|
||||
references.append(
|
||||
F.scaled_dot_product_attention(
|
||||
q.transpose(0, 1).float(),
|
||||
k.transpose(0, 1).float(),
|
||||
v.transpose(0, 1).float(),
|
||||
attn_mask=mask,
|
||||
scale=impl.scale,
|
||||
).transpose(0, 1)
|
||||
)
|
||||
queries.append(q)
|
||||
suffixes.append(suffix)
|
||||
q, suffix = torch.cat(queries), torch.cat(suffixes)
|
||||
output = torch.empty(
|
||||
q.shape[0], num_heads * 128, device=device, dtype=torch.bfloat16
|
||||
)
|
||||
# Ensure this test cannot silently succeed through the fallback.
|
||||
with pytest.MonkeyPatch.context() as patch:
|
||||
|
||||
def unexpected_fallback(*args, **kwargs):
|
||||
raise AssertionError("Expected the compressed DCP path")
|
||||
|
||||
patch.setattr(
|
||||
"vllm.model_executor.layers.attention.mla_attention."
|
||||
"MLACommonImpl._context_parallel_compute_prefill_context",
|
||||
unexpected_fallback,
|
||||
)
|
||||
impl.forward_mha(
|
||||
q,
|
||||
suffix[:, :512],
|
||||
suffix[:, None, 512:],
|
||||
cache,
|
||||
metadata,
|
||||
layer._k_scale,
|
||||
output,
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
output.view(-1, num_heads, 128).float(),
|
||||
torch.cat(references),
|
||||
rtol=0.03,
|
||||
atol=0.003,
|
||||
)
|
||||
finally:
|
||||
cleanup_dist_env_and_memory()
|
||||
@@ -1,32 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm() or not is_aiter_found_and_supported():
|
||||
pytest.skip("Requires ROCm with AITER.", allow_module_level=True)
|
||||
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _per_sequence_context_lens
|
||||
|
||||
|
||||
def test_per_row_table_uses_last_column():
|
||||
seq_lens = torch.tensor([8192, 1500, 3000, 700], dtype=torch.int32)
|
||||
next_n = 3
|
||||
offsets = torch.arange(next_n, dtype=torch.int32) - next_n + 1
|
||||
per_row = seq_lens.unsqueeze(1) + offsets
|
||||
|
||||
out = _per_sequence_context_lens(per_row)
|
||||
|
||||
assert out.shape == (4,)
|
||||
assert out.is_contiguous()
|
||||
assert torch.equal(out, seq_lens)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", [(4,), (4, 1)])
|
||||
def test_per_sequence_input_is_unchanged(shape):
|
||||
context_lens = torch.arange(1, 5, dtype=torch.int32).reshape(shape)
|
||||
assert _per_sequence_context_lens(context_lens) is context_lens
|
||||
@@ -1,163 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The ROCm MXFP4 indexer reads the paged cache in place, so each prefill
|
||||
chunk is split back into its requests' rows, which one launch finds through
|
||||
the chunk's query_start_loc. A chunk is whole requests or one query slice of a
|
||||
long request, and both have to come back with the right rows and the right
|
||||
block-table rows.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm-only", allow_module_level=True)
|
||||
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
DeepseekV32IndexerPrefillChunkMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
|
||||
native_decode,
|
||||
plan_gather_launches,
|
||||
plan_prefill_chunks,
|
||||
split_prefill_chunks,
|
||||
)
|
||||
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import rocm_mxfp4_consumer_rows
|
||||
|
||||
|
||||
def _chunk(block_table, token_start, token_end, row_ends):
|
||||
ends = torch.tensor(row_ends, dtype=torch.int32)
|
||||
return DeepseekV32IndexerPrefillChunkMetadata(
|
||||
block_table=block_table,
|
||||
cu_seqlen_ks=torch.full_like(ends, 7),
|
||||
cu_seqlen_ke=ends + 7,
|
||||
cu_seq_lens=torch.zeros(1, dtype=torch.int32),
|
||||
token_to_seq=torch.zeros(1, dtype=torch.int32),
|
||||
total_seq_lens=1,
|
||||
max_seqlen_k=int(ends.max()),
|
||||
token_start=token_start,
|
||||
token_end=token_end,
|
||||
num_reqs=block_table.shape[0],
|
||||
)
|
||||
|
||||
|
||||
# A decode (1 token), then prefills of 3, 3, 5 and 6 query tokens; the last
|
||||
# one is sliced into two chunks.
|
||||
QUERY_START_LOC = [0, 1, 4, 7, 12, 18]
|
||||
SEQ_LENS = torch.tensor([40, 10, 12, 21, 64])
|
||||
BLOCK_TABLE = torch.arange(20, dtype=torch.int32).view(5, 4)
|
||||
CHUNKS = [
|
||||
_chunk(BLOCK_TABLE[1:4], 1, 12, list(range(11))),
|
||||
_chunk(BLOCK_TABLE[4:5], 12, 15, [29, 30, 30]),
|
||||
_chunk(BLOCK_TABLE[4:5], 15, 18, [31, 31, 32]),
|
||||
]
|
||||
|
||||
|
||||
def _plans(min_gather_width, block=8):
|
||||
return plan_prefill_chunks(
|
||||
CHUNKS,
|
||||
QUERY_START_LOC,
|
||||
SEQ_LENS,
|
||||
SEQ_LENS.int() // 2,
|
||||
2,
|
||||
block,
|
||||
min_gather_width,
|
||||
torch.tensor(QUERY_START_LOC, dtype=torch.int32),
|
||||
)
|
||||
|
||||
|
||||
def test_chunks_split_into_requests():
|
||||
plans = _plans(20.0)
|
||||
|
||||
assert [p.requests for p in plans] == [
|
||||
[(0, 3, 0), (3, 6, 1), (6, 11, 2)],
|
||||
[(0, 3, 0)],
|
||||
[(0, 3, 0)],
|
||||
]
|
||||
# every chunk launches once, with offsets local to the chunk
|
||||
assert [p.query_start_loc.tolist() for p in plans] == [
|
||||
[0, 3, 6, 11],
|
||||
[0, 3],
|
||||
[0, 3],
|
||||
]
|
||||
# the logits are as wide as the longest compressed context in the chunk
|
||||
assert [p.width for p in plans] == [10, 32, 32]
|
||||
assert [p.context_lens.tolist() for p in plans] == [[5, 6, 10], [32], [32]]
|
||||
torch.testing.assert_close(plans[2].row_ends, torch.tensor([31, 31, 32]).int())
|
||||
torch.testing.assert_close(plans[2].block_ends, torch.tensor([4, 4, 4]).int())
|
||||
assert [p.use_gather for p in plans] == [False, True, True]
|
||||
assert [p.first_request for p in plans] == [1, 4, 4]
|
||||
# no candidate blocks, as in the model-neutral builder
|
||||
for plan in _plans(None, block=0):
|
||||
assert plan.block_ends is None and not plan.use_gather
|
||||
|
||||
|
||||
def test_launches_follow_the_logits_budget(monkeypatch):
|
||||
"""Each launch's fp32 logits fit in VLLM_SPARSE_INDEXER_MAX_LOGITS_MB. A dense
|
||||
chunk's logits are [rows, longest context in the chunk]: K is read in place,
|
||||
not gathered, so requests share a launch until their rows no longer fit, and
|
||||
a request that does not fit alone is split on its query rows. A consumer's
|
||||
logits are [rows, pool]."""
|
||||
budget = 4 * 1000 * 30
|
||||
contexts, queries = torch.tensor([1000, 600, 200]), torch.tensor([10, 10, 10])
|
||||
assert split_prefill_chunks(contexts, queries, budget, 2) == [
|
||||
(slice(2, 5), slice(0, 30))
|
||||
]
|
||||
# the third request would take the chunk past the budget
|
||||
queries = torch.tensor([10, 10, 11])
|
||||
assert split_prefill_chunks(contexts, queries, budget) == [
|
||||
(slice(0, 2), slice(0, 20)),
|
||||
(slice(2, 3), slice(0, 11)),
|
||||
]
|
||||
assert split_prefill_chunks(torch.tensor([1000]), torch.tensor([100]), budget) == [
|
||||
(slice(0, 1), slice(lo, min(lo + 30, 100))) for lo in range(0, 100, 30)
|
||||
]
|
||||
# the default 512 MiB holds 128 rows of a 1M context, or 8192 of a 16K pool
|
||||
assert split_prefill_chunks(
|
||||
torch.tensor([1 << 20]), torch.tensor([200]), 512 << 20
|
||||
) == [(slice(0, 1), slice(0, 128)), (slice(0, 1), slice(128, 200))]
|
||||
monkeypatch.setenv("VLLM_SPARSE_INDEXER_MAX_LOGITS_MB", "512")
|
||||
assert rocm_mxfp4_consumer_rows(16384) == 8192
|
||||
|
||||
|
||||
def test_gather_launches_rejoin_a_requests_rows():
|
||||
"""The consumers' logits are [rows, pool] whatever the context, so a
|
||||
request's rows go back together across the chunks that cut them, and a
|
||||
launch never mixes requests."""
|
||||
# the first chunk is too narrow to gather, the last request's slices rejoin
|
||||
(joined,) = plan_gather_launches(CHUNKS, _plans(20.0), 100)
|
||||
assert (joined.token_start, joined.token_end) == (12, 18)
|
||||
# every chunk gathers: the first chunk's three requests launch apart
|
||||
launches = plan_gather_launches(CHUNKS, _plans(0.0), 100)
|
||||
assert [(g.token_start, g.token_end) for g in launches] == [
|
||||
(1, 4),
|
||||
(4, 7),
|
||||
(7, 12),
|
||||
(12, 18),
|
||||
]
|
||||
assert plan_gather_launches(CHUNKS, _plans(None), 100) == []
|
||||
|
||||
|
||||
def test_decode_launches_native_on_uniform_steps():
|
||||
"""A decode step goes to the kernel as next_n-row sequences only when its
|
||||
shape says so: each request has next_n rows, and cudagraph padding (query
|
||||
length 0) comes only after them. A FULL graph captured on a uniform batch
|
||||
then replays the same launch on a padded one."""
|
||||
rows = torch.zeros(8, dtype=torch.int32)
|
||||
row_block_table = torch.arange(32, dtype=torch.int32).view(8, 4)
|
||||
context_lens = torch.tensor([9, 4, 7, 0, 5], dtype=torch.int32)
|
||||
|
||||
native = native_decode(rows, row_block_table, [2, 2, 2, 0], 2, context_lens)
|
||||
assert native is not None and native.next_n == 2
|
||||
assert native.context_lens.tolist() == [9, 4, 7, 0]
|
||||
# every request's first flattened row, as a view
|
||||
assert native.block_table.tolist() == row_block_table[::2].tolist()
|
||||
assert native.block_table.data_ptr() == row_block_table.data_ptr()
|
||||
|
||||
assert native_decode(rows, row_block_table, [2, 0, 2, 2], 2, context_lens) is None
|
||||
# a ragged step, rows padded past the requests, and no speculation
|
||||
assert native_decode(rows[:5], row_block_table, [2, 1, 2], 2, context_lens) is None
|
||||
assert native_decode(rows, row_block_table, [2, 2, 2], 2, context_lens) is None
|
||||
assert native_decode(rows[:4], row_block_table, [1] * 4, 1, context_lens) is None
|
||||
@@ -1,188 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU tests for the decode top-k row->token mapping (no GPU required).
|
||||
|
||||
On non-uniform decode batches (``requires_padding`` -- mixed plain-decode and
|
||||
spec-verify requests, or variable MTP verify lens; taken on Hopper where the
|
||||
varlen/flatten logits path is unavailable), the pool-topk rows follow the
|
||||
PADDED ``[batch_size, next_n]`` grid: row ``(b, t)`` is flat decode token
|
||||
``offset_b + t``. The former inline ``dec_seq = positions[:n] + 1``
|
||||
(``n = batch_size * next_n``) indexes the flat per-token layout with padded
|
||||
coordinates, so rows after the first non-uniform request read another
|
||||
request's positions and rows past the decode region read prefill tokens --
|
||||
``expand_pools_and_append_tail`` then anchors the tail at a foreign length.
|
||||
|
||||
These tests pin the defect with the exact production arithmetic and verify
|
||||
the layout-aware replacement (``_decode_topk_seq_lens``), including the tail
|
||||
expansion consequences via the pure-torch expand/append pair that the fused
|
||||
kernel is documented to replicate.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
# Bootstrap the glm5next package before importing kpool_compress directly: its
|
||||
# import runs glm5next/__init__, which pulls model -> attention -> the indexer
|
||||
# dispatcher (sparse_indexer) -> back into the nvidia/amd sparse_indexer
|
||||
# modules. Production always enters via attention.py first.
|
||||
# isort: off
|
||||
import vllm.models.glm5next # noqa: F401
|
||||
from vllm.models.glm5next.nvidia.ops.kpool_compress import ( # noqa: E402
|
||||
append_tail_to_topk,
|
||||
expand_pools_to_tokens,
|
||||
)
|
||||
# isort: on
|
||||
|
||||
from vllm.models.glm5next.common.sparse_indexer import (
|
||||
_decode_topk_seq_lens,
|
||||
_fill_short_decode_causal_indices,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.models.glm5next.amd import sparse_indexer as indexer_mod
|
||||
else:
|
||||
from vllm.models.glm5next.nvidia import sparse_indexer as indexer_mod
|
||||
|
||||
KPOOL = 4
|
||||
TOPK_TOKENS = 16
|
||||
SELECT_K = TOPK_TOKENS // KPOOL
|
||||
|
||||
|
||||
def test_kpool_ops_dispatch_matches_platform():
|
||||
expected_backend = ".amd." if current_platform.is_rocm() else ".nvidia."
|
||||
assert expected_backend in indexer_mod.kpool_ops.__name__
|
||||
|
||||
|
||||
def test_short_decode_fills_exact_causal_rows():
|
||||
topk = torch.full((3, 8), 99, dtype=torch.int32)
|
||||
positions = torch.tensor([0, 3, 7], dtype=torch.int64)
|
||||
|
||||
assert _fill_short_decode_causal_indices(topk, positions, 3, 8, 8)
|
||||
assert topk.tolist() == [
|
||||
[0, -1, -1, -1, -1, -1, -1, -1],
|
||||
[0, 1, 2, 3, -1, -1, -1, -1],
|
||||
[0, 1, 2, 3, 4, 5, 6, 7],
|
||||
]
|
||||
|
||||
|
||||
def test_short_decode_leaves_buffer_unchanged_for_sparse_context():
|
||||
topk = torch.full((2, 8), 99, dtype=torch.int32)
|
||||
before = topk.clone()
|
||||
|
||||
assert not _fill_short_decode_causal_indices(topk, torch.tensor([7, 8]), 2, 9, 8)
|
||||
assert torch.equal(topk, before)
|
||||
|
||||
|
||||
def make_non_uniform_batch():
|
||||
"""3 requests: plain decode (1 token), MTP verify (4), adaptive verify (3).
|
||||
|
||||
Flat decode positions (production layout: decode tokens first, then any
|
||||
prefill tokens of the same batch):
|
||||
req0: [30] (context len 30)
|
||||
req1: [100..103] (verify at context len 100)
|
||||
req2: [7, 8, 9] (verify at context len 7)
|
||||
Followed by 4 prefill tokens at positions 555..558 so the flat tensor is
|
||||
at least ``n = 3 * 4`` long, as it is in a real mixed batch.
|
||||
"""
|
||||
decode_lens = torch.tensor([1, 4, 3], dtype=torch.int64)
|
||||
per_req_positions = [[30], [100, 101, 102, 103], [7, 8, 9]]
|
||||
flat_decode = [p for req in per_req_positions for p in req]
|
||||
positions = torch.tensor(flat_decode + [555, 556, 557, 558], dtype=torch.int64)
|
||||
return decode_lens, per_req_positions, positions
|
||||
|
||||
|
||||
def expected_row_seq_lens(per_req_positions, batch_size, next_n):
|
||||
"""Ground truth: row (b, t) -> pos + 1 for real rows, 0 for pad rows."""
|
||||
out = torch.zeros(batch_size * next_n, dtype=torch.int32)
|
||||
for b, req in enumerate(per_req_positions):
|
||||
for t, pos in enumerate(req):
|
||||
out[b * next_n + t] = pos + 1
|
||||
return out
|
||||
|
||||
|
||||
def test_legacy_flat_layout_misaligns_and_bleeds():
|
||||
"""The bug: ``positions[:n] + 1`` with padded-row coordinates reads other
|
||||
requests' positions and prefill positions."""
|
||||
decode_lens, per_req, positions = make_non_uniform_batch()
|
||||
batch_size = decode_lens.shape[0]
|
||||
next_n = int(decode_lens.max())
|
||||
n = batch_size * next_n
|
||||
assert n == 12
|
||||
|
||||
legacy = positions[:n].to(torch.int32) + 1
|
||||
expected = expected_row_seq_lens(per_req, batch_size, next_n)
|
||||
|
||||
# Row (1, 0): req1's first verify token (pos 100, seq 101) reads flat
|
||||
# index 4 -> req1's LAST verify token (pos 103). Its true tail token is
|
||||
# dropped and the tail anchors 3 tokens late.
|
||||
assert int(legacy[4]) == 104 and int(expected[4]) == 101
|
||||
|
||||
# Rows (2, *): req2 starts at flat offset 5, but padded coordinates point
|
||||
# at flat indices 8..11 -- the batch's PREFILL positions.
|
||||
for t in range(3):
|
||||
assert int(legacy[2 * next_n + t]) >= 556, (
|
||||
"legacy row (2, t) should read prefill positions"
|
||||
)
|
||||
assert not torch.equal(legacy, expected)
|
||||
|
||||
|
||||
def test_helper_uniform_layout_matches_flat_slice():
|
||||
"""Uniform batches keep the flat shortcut (zero behavior/perf change)."""
|
||||
per_req = [[200, 201, 202, 203], [50, 51, 52, 53]]
|
||||
positions = torch.tensor([p for r in per_req for p in r], dtype=torch.int64)
|
||||
decode_lens = torch.tensor([4, 4], dtype=torch.int64)
|
||||
out = _decode_topk_seq_lens(positions, decode_lens, 8, 2, 4, requires_padding=False)
|
||||
assert torch.equal(out, positions[:8].to(torch.int32) + 1)
|
||||
|
||||
|
||||
def test_helper_padded_layout_per_row():
|
||||
"""Non-uniform batches map every padded row to its own token's position;
|
||||
pad rows get 0 (empty tail)."""
|
||||
decode_lens, per_req, positions = make_non_uniform_batch()
|
||||
out = _decode_topk_seq_lens(positions, decode_lens, 8, 3, 4, requires_padding=True)
|
||||
expected = expected_row_seq_lens(per_req, 3, 4)
|
||||
assert torch.equal(out, expected)
|
||||
# Pad rows (0, 1..3) and (2, 3) collapse to 0 -> no tail appended.
|
||||
assert out[1] == 0 and out[2] == 0 and out[3] == 0 and out[11] == 0
|
||||
|
||||
|
||||
def expand_tail_region(dec_seq):
|
||||
"""Run the production pure-torch expand + append pair (the fused kernel
|
||||
replicates it exactly on the identity path) and return the tail columns
|
||||
[TOPK_TOKENS, TOPK_TOKENS + KPOOL - 1)."""
|
||||
rows = dec_seq.shape[0]
|
||||
pool_ids = torch.arange(SELECT_K, dtype=torch.int64).expand(rows, SELECT_K)
|
||||
valid = torch.ones_like(pool_ids, dtype=torch.bool)
|
||||
expanded = expand_pools_to_tokens(pool_ids, valid, TOPK_TOKENS, KPOOL)
|
||||
seq_lens = dec_seq.to(torch.int32)
|
||||
pool_lens = (seq_lens // KPOOL).to(torch.int32)
|
||||
out = append_tail_to_topk(expanded, seq_lens, pool_lens, KPOOL)
|
||||
return out[:, TOPK_TOKENS:]
|
||||
|
||||
|
||||
def test_tail_expansion_legacy_vs_fixed():
|
||||
"""End-to-end tail consequence: the fixed mapping appends exactly the
|
||||
request's trailing incomplete pool; the legacy flat slice drops real tail
|
||||
tokens and emits indices far past the request's own sequence."""
|
||||
decode_lens, per_req, positions = make_non_uniform_batch()
|
||||
n = 12
|
||||
fixed = _decode_topk_seq_lens(
|
||||
positions, decode_lens, 8, 3, 4, requires_padding=True
|
||||
)
|
||||
legacy = positions[:n].to(torch.int32) + 1
|
||||
|
||||
fixed_tail = expand_tail_region(fixed)
|
||||
legacy_tail = expand_tail_region(legacy)
|
||||
|
||||
# Fixed: row (1, 0) (seq 101) keeps its single tail token 100; row (2, 2)
|
||||
# (seq 10) keeps its full trailing pool [8, 9].
|
||||
assert fixed_tail[4, 0].item() == 100
|
||||
assert fixed_tail[10, :2].tolist() == [8, 9]
|
||||
|
||||
# Legacy: row (1, 0) loses its tail token (anchored at 104, count 0)...
|
||||
assert legacy_tail[4, 0].item() == -1
|
||||
# ...and row (2, 2) reads prefill position 557 -> tail indices 556/557,
|
||||
# way past req2's 10-token sequence -> out-of-bounds block-table reads.
|
||||
assert legacy_tail[10, :2].tolist() == [556, 557]
|
||||
|
||||
assert not torch.equal(legacy_tail, fixed_tail)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,127 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Sparse MLA allocation and warmup must agree on physical addressing."""
|
||||
|
||||
from types import MethodType, SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import MLAAttention
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backend import MultipleOf
|
||||
from vllm.v1.attention.backends.mla.indexer import DeepseekV32IndexerBackend
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL,
|
||||
flat_kv_row_view,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
|
||||
from vllm.v1.core.kv_cache_planning import get_kv_cache_config_from_groups
|
||||
from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
from vllm.v1.worker.utils import allocate_kv_cache, customize_attention_spec
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"device",
|
||||
[
|
||||
"cpu",
|
||||
pytest.param(
|
||||
"cuda",
|
||||
marks=pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUDA only"
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"layout", [KVCacheLayout.BLHNC, KVCacheLayout.BLNHC, KVCacheLayout.LBNHC]
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"backend,cache_dtype,sm100,stride_alignment",
|
||||
[
|
||||
(AttentionBackendEnum.FLASHINFER_MLA_SPARSE, "auto", True, 32 * 1152),
|
||||
(AttentionBackendEnum.FLASHINFER_MLA_SPARSE, "fp8", True, 32 * 576),
|
||||
pytest.param(
|
||||
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE_FA4,
|
||||
"auto",
|
||||
True,
|
||||
64 * 1152,
|
||||
marks=pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUDA only"
|
||||
),
|
||||
),
|
||||
(AttentionBackendEnum.FLASHMLA_SPARSE, "auto", True, 1152),
|
||||
(AttentionBackendEnum.FLASHMLA_SPARSE, "fp8_ds_mla", False, MultipleOf(64)),
|
||||
(AttentionBackendEnum.FLASHMLA_SPARSE, "fp8_ds_mla", True, 656),
|
||||
(AttentionBackendEnum.FLASHMLA_SPARSE, "nvfp4_ds_mla", True, 352),
|
||||
],
|
||||
)
|
||||
def test_allocation_and_warmup_follow_addressing_mode(
|
||||
monkeypatch, layout, backend, cache_dtype, sm100, stride_alignment, device
|
||||
):
|
||||
backend = backend.get_class()
|
||||
monkeypatch.setattr(
|
||||
current_platform, "is_device_capability_family", lambda family: sm100
|
||||
)
|
||||
config = SimpleNamespace(
|
||||
cache_config=CacheConfig(block_size=64),
|
||||
model_config=SimpleNamespace(dtype=torch.bfloat16),
|
||||
attention_config=SimpleNamespace(hisparse_config=None),
|
||||
kernel_config=SimpleNamespace(enable_jit_warmup=True),
|
||||
)
|
||||
config.cache_config.kv_cache_layout = layout.name
|
||||
layer = SimpleNamespace(
|
||||
_vllm_config=config,
|
||||
attn_backend=backend,
|
||||
kv_cache_dtype=cache_dtype,
|
||||
head_size=576,
|
||||
sliding_window=None,
|
||||
indexer=None,
|
||||
non_causal_multi_token_decode=False,
|
||||
)
|
||||
layer._uses_flat_kv_cache = MethodType(MLAAttention._uses_flat_kv_cache, layer)
|
||||
spec = customize_attention_spec(
|
||||
backend, MLAAttention.get_kv_cache_spec(layer, config)
|
||||
)
|
||||
indexer = SimpleNamespace(
|
||||
cache_config=config.cache_config, head_dim=132, dtype=torch.uint8
|
||||
)
|
||||
index_spec = DeepseekV32IndexerCache.get_kv_cache_spec(indexer, config)
|
||||
assert spec.block_stride_alignment == stride_alignment
|
||||
assert index_spec.block_stride_alignment is None
|
||||
assert layout in get_supported_kv_cache_layouts(
|
||||
[backend, DeepseekV32IndexerBackend]
|
||||
)
|
||||
specs = {"mla": spec, "indexer": index_spec}
|
||||
group = KVCacheGroupSpec(
|
||||
list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs)
|
||||
)
|
||||
cache = get_kv_cache_config_from_groups(config, [group], 2**20)
|
||||
views = allocate_kv_cache(cache, torch.device(device), layout)
|
||||
register = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL, "register_warmup", register
|
||||
)
|
||||
MLAAttention.bind_kv_cache(layer, views["mla"])
|
||||
DeepseekV32IndexerCache.bind_kv_cache(indexer, views["indexer"])
|
||||
assert indexer.kv_cache.stride(0) == views["indexer"].stride(0)
|
||||
alignment = spec.get_block_stride_alignment()
|
||||
assert views["mla"].stride(0) * views["mla"].element_size() % alignment == 0
|
||||
if not layer._uses_flat_kv_cache():
|
||||
register.assert_not_called()
|
||||
else:
|
||||
rows, stride = flat_kv_row_view(layer.kv_cache, 64)
|
||||
register.assert_called_once_with(config, block_stride_rows=stride)
|
||||
layer.kv_cache[1, 0].fill_(3)
|
||||
torch.testing.assert_close(rows[stride], layer.kv_cache[1, 0])
|
||||
if alignment == 1:
|
||||
assert cache.kv_cache_tensors[0].size == cache.num_blocks * sum(
|
||||
item.page_size_bytes for item in specs.values()
|
||||
)
|
||||
@@ -1,51 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
pytest.importorskip("cutlass")
|
||||
|
||||
from vllm.model_executor.layers.attention.sparse_mla_attention import (
|
||||
_build_topk_mask,
|
||||
_topk_mask_shape,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_build_topk_mask_single_request_matches_generic_path() -> None:
|
||||
topk = torch.tensor(
|
||||
[[0, 31, 32, 63, -1], [1, 64, 127, -1, -1]],
|
||||
dtype=torch.int32,
|
||||
device="cuda",
|
||||
)
|
||||
|
||||
num_words = (128 + 31) // 32
|
||||
single_out = torch.zeros(1, 2, num_words, dtype=torch.int32, device="cuda")
|
||||
generic_out = torch.zeros(2, 1, num_words, dtype=torch.int32, device="cuda")
|
||||
single_req = _build_topk_mask([topk], [2], 2, 128, single_out)
|
||||
generic = _build_topk_mask([topk[:1], topk[1:]], [1, 1], 1, 128, generic_out)
|
||||
|
||||
torch.testing.assert_close(single_req[0, 0], generic[0, 0])
|
||||
torch.testing.assert_close(single_req[0, 1], generic[1, 0])
|
||||
|
||||
|
||||
def test_topk_mask_rows_are_aligned_for_vectorized_loads() -> None:
|
||||
assert _topk_mask_shape(2, 129, 129) == (2, 256, 8)
|
||||
assert _topk_mask_shape(2, 129, 129, reserve_key_starts_word=True) == (
|
||||
2,
|
||||
256,
|
||||
8,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_build_topk_mask_preserves_aligned_row_storage() -> None:
|
||||
shape = _topk_mask_shape(1, 1, 129)
|
||||
out = torch.zeros(shape, dtype=torch.int32, device="cuda")
|
||||
topk = torch.tensor([[0, 128]], dtype=torch.int32, device="cuda")
|
||||
|
||||
mask = _build_topk_mask([topk], [1], 1, 129, out)
|
||||
|
||||
assert mask.shape == (1, 1, 8)
|
||||
assert mask[0, 0].tolist() == [1, 0, 0, 0, 1, 0, 0, 0]
|
||||
@@ -1,563 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Integration tests for TRTLLM gen-full attention through FlashInfer."""
|
||||
|
||||
import dataclasses
|
||||
import unittest.mock
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch.nn.attention.flex_attention import create_block_mask, flex_attention
|
||||
|
||||
from tests.kernels.attention.test_trtllm_kvfp8_dequant import make_random_kv_cache
|
||||
from tests.v1.attention.test_attention_backends import create_and_prepopulate_kv_cache
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
create_vllm_config,
|
||||
)
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import (
|
||||
is_strictly_contiguous,
|
||||
nvfp4_kv_cache_full_dim,
|
||||
set_random_seed,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import PerLayerParameters
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheLayout, KVQuantMode
|
||||
|
||||
if not current_platform.is_device_capability_family(100):
|
||||
pytest.skip(
|
||||
"TRTLLM integration tests require NVIDIA Blackwell (SM100).",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.v1.attention.backends.flashinfer import ( # noqa: E402
|
||||
FlashInferDecodeKernel,
|
||||
FlashInferImpl,
|
||||
FlashInferMetadataBuilder,
|
||||
FlashInferTrtllmAPIDecode,
|
||||
TRTLLMPrefill,
|
||||
trtllm_prefill_attn_kvfp8_dequant,
|
||||
)
|
||||
|
||||
|
||||
class MockAttentionLayer:
|
||||
"""Minimal mock of an attention layer for testing."""
|
||||
|
||||
def __init__(self, device: torch.device):
|
||||
self._q_scale = torch.tensor(2.0, device=device)
|
||||
self._k_scale = torch.tensor(3.0, device=device)
|
||||
self._v_scale = torch.tensor(4.0, device=device)
|
||||
self._q_scale_float = 2.0
|
||||
self._k_scale_float = 3.0
|
||||
self._v_scale_float = 4.0
|
||||
self._o_scale_float = None
|
||||
|
||||
|
||||
MODEL = "Qwen/Qwen2.5-0.5B"
|
||||
MODEL_NVFP4 = "Qwen/Qwen3-4B" # nvfp4 needs head_dim >= 128 (or 80)
|
||||
BLOCK_SIZE = 16
|
||||
NUM_GPU_BLOCKS = 8192
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
BATCH_SPECS = {
|
||||
"decode_only": BatchSpec(
|
||||
seq_lens=[128, 256, 512],
|
||||
query_lens=[1, 1, 1],
|
||||
),
|
||||
"prefill_only": BatchSpec(
|
||||
seq_lens=[64, 128, 256],
|
||||
query_lens=[16, 32, 16],
|
||||
),
|
||||
"mixed": BatchSpec(
|
||||
seq_lens=[128, 256, 512, 128],
|
||||
query_lens=[1, 1, 8, 16],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _mock_get_per_layer_parameters(vllm_config, layer_names, impl_cls):
|
||||
head_size = vllm_config.model_config.get_head_size()
|
||||
return {
|
||||
name: PerLayerParameters(
|
||||
window_left=-1,
|
||||
logits_soft_cap=0.0,
|
||||
sm_scale=1.0 / (head_size**0.5),
|
||||
)
|
||||
for name in layer_names
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"block_size,num_prefills,has_host_lengths,quantize_query",
|
||||
[
|
||||
(16, 1, True, False),
|
||||
(64, 2, True, False),
|
||||
(128, 2, True, False),
|
||||
(16, 2, False, False),
|
||||
(16, 2, True, True),
|
||||
],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_prefill_dequant_scratch_ignores_unused_capacity(
|
||||
block_size, num_prefills, has_host_lengths, quantize_query, monkeypatch
|
||||
):
|
||||
"""Bound scratch by attended prefill KV, including cached prefixes."""
|
||||
device = torch.device("cuda")
|
||||
config = create_vllm_config(model_name=MODEL, max_model_len=32768)
|
||||
config.cache_config.cache_dtype = "fp8"
|
||||
config.cache_config.kv_cache_layout = "LBHNC"
|
||||
config.attention_config.use_trtllm_attention = True
|
||||
config.attention_config.disable_flashinfer_q_quantization = not quantize_query
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
|
||||
_mock_get_per_layer_parameters,
|
||||
)
|
||||
spec = FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=2,
|
||||
head_size=64,
|
||||
dtype=torch.uint8,
|
||||
kv_quant_mode=KVQuantMode.FP8_PER_TENSOR,
|
||||
)
|
||||
kv_cache, scale = make_random_kv_cache(32, 2, block_size, 64)
|
||||
batch = BatchSpec(
|
||||
seq_lens=[1024] + [17, 65][-num_prefills:],
|
||||
query_lens=[1] + [2, 8][-num_prefills:],
|
||||
)
|
||||
common = create_common_attn_metadata(batch, block_size, device)
|
||||
if not has_host_lengths:
|
||||
common.seq_lens_cpu_upper_bound = None
|
||||
live_pages = ((65 if has_host_lengths else 1024) + block_size - 1) // block_size
|
||||
with set_current_vllm_config(config):
|
||||
builder = FlashInferMetadataBuilder(spec, ["layer.0"], config, device)
|
||||
for capacity in (64, 256):
|
||||
# Unused columns can contain nonzero page IDs.
|
||||
common.block_table_tensor = torch.randint(
|
||||
1, 32, (batch.batch_size, capacity), dtype=torch.int32, device=device
|
||||
)
|
||||
metadata = builder.build(0, common)
|
||||
assert isinstance(metadata.prefill, TRTLLMPrefill)
|
||||
table = metadata.prefill.block_tables
|
||||
assert is_strictly_contiguous(table)
|
||||
assert (metadata.q_data_type_prefill == current_platform.fp8_dtype()) == (
|
||||
quantize_query
|
||||
)
|
||||
if not quantize_query:
|
||||
converted, _ = trtllm_prefill_attn_kvfp8_dequant(
|
||||
kv_cache, table, scale, scale, metadata.q_data_type_prefill
|
||||
)
|
||||
assert converted.shape[0] == num_prefills * live_pages + 1
|
||||
width = capacity if quantize_query else live_pages
|
||||
torch.testing.assert_close(table, common.block_table_tensor[1:, :width])
|
||||
|
||||
|
||||
def _create_nvfp4_hnd_kv_cache(
|
||||
k_contexts,
|
||||
v_contexts,
|
||||
block_size,
|
||||
num_kv_heads,
|
||||
head_size,
|
||||
dtype,
|
||||
device,
|
||||
num_blocks,
|
||||
common_attn_metadata,
|
||||
kv_scale_val,
|
||||
):
|
||||
"""Create an nvfp4 KV cache by quantizing bf16 context via
|
||||
reshape_and_cache_flash, using the same block-table layout as
|
||||
create_and_prepopulate_kv_cache.
|
||||
|
||||
The returned tensor is dtype ``uint8`` with head-group layout
|
||||
``(num_blocks, 2 * num_kv_heads, block_size, full_dim)``
|
||||
where K heads occupy the first ``num_kv_heads`` heads and V heads the second.
|
||||
Each ``full_dim = head_size // 2 + head_size // 16`` block packs two regions:
|
||||
- **FP4 data** (``head_size // 2`` bytes): pairs of E2M1 values,
|
||||
two per byte.
|
||||
- **FP8 block scales** (``head_size // 16`` bytes): one E4M3
|
||||
scale per 16-element block.
|
||||
|
||||
Args:
|
||||
k_contexts: List of key context tensors, one per sequence.
|
||||
v_contexts: List of value context tensors, one per sequence.
|
||||
block_size: Number of tokens per cache block.
|
||||
num_kv_heads: Number of key/value heads.
|
||||
head_size: Head dimension (must be divisible by 16).
|
||||
dtype: Source data type for the bf16 intermediate cache.
|
||||
device: Target device.
|
||||
num_blocks: Total number of blocks to allocate.
|
||||
common_attn_metadata: Metadata containing block tables and
|
||||
sequence lengths.
|
||||
kv_scale_val: Scalar float used as both k_scale and v_scale
|
||||
during quantization.
|
||||
|
||||
Returns:
|
||||
``torch.Tensor``: The nvfp4 kv_cache tensor (uint8, LBHNC-strided).
|
||||
|
||||
"""
|
||||
# First create a bf16 cache so block tables are populated.
|
||||
bf16_cache = create_and_prepopulate_kv_cache(
|
||||
k_contexts,
|
||||
v_contexts,
|
||||
block_size,
|
||||
num_kv_heads,
|
||||
head_size,
|
||||
dtype,
|
||||
device,
|
||||
num_blocks,
|
||||
common_attn_metadata,
|
||||
layout=KVCacheLayout.LBHNC,
|
||||
)
|
||||
|
||||
# (num_blocks, 2 * num_kv_heads, block_size, full_dim) — K heads first, then V heads
|
||||
full_dim = nvfp4_kv_cache_full_dim(head_size)
|
||||
nvfp4_cache = torch.zeros(
|
||||
(num_blocks, 2 * num_kv_heads, block_size, full_dim),
|
||||
dtype=torch.uint8,
|
||||
device=device,
|
||||
)
|
||||
k_cache, v_cache = nvfp4_cache.split(num_kv_heads, dim=1)
|
||||
|
||||
# Flatten bf16 context into tokens and quantize via reshape_and_cache_flash.
|
||||
# bf16_cache is (B, H, N, 2*hs); split K/V on the content dim.
|
||||
block_table = common_attn_metadata.block_table_tensor
|
||||
seq_lens = common_attn_metadata.seq_lens.cpu()
|
||||
query_lens = (
|
||||
common_attn_metadata.query_start_loc_cpu[1:]
|
||||
- common_attn_metadata.query_start_loc_cpu[:-1]
|
||||
)
|
||||
kv_scale_t = torch.tensor(kv_scale_val, dtype=torch.float32, device=device)
|
||||
|
||||
for i in range(len(k_contexts)):
|
||||
ctx_len = int(seq_lens[i]) - int(query_lens[i])
|
||||
if ctx_len == 0:
|
||||
continue
|
||||
# Gather context tokens from the bf16 cache using block table.
|
||||
n_ctx_blocks = (ctx_len + block_size - 1) // block_size
|
||||
blocks = block_table[i, :n_ctx_blocks]
|
||||
k_ctx = (
|
||||
bf16_cache[blocks, :, :, :head_size]
|
||||
.transpose(1, 2)
|
||||
.reshape(-1, num_kv_heads, head_size)[:ctx_len]
|
||||
)
|
||||
v_ctx = (
|
||||
bf16_cache[blocks, :, :, head_size:]
|
||||
.transpose(1, 2)
|
||||
.reshape(-1, num_kv_heads, head_size)[:ctx_len]
|
||||
)
|
||||
# Build slot mapping for these context tokens.
|
||||
token_offsets = torch.arange(ctx_len, device=device)
|
||||
block_indices = token_offsets // block_size
|
||||
intra_offsets = token_offsets % block_size
|
||||
slots = block_table[i, block_indices] * block_size + intra_offsets
|
||||
# reshape_and_cache_flash expects (B, N, H, D) cache views.
|
||||
torch.ops._C_cache_ops.reshape_and_cache_flash(
|
||||
k_ctx,
|
||||
v_ctx,
|
||||
k_cache.transpose(1, 2),
|
||||
v_cache.transpose(1, 2),
|
||||
slots,
|
||||
"nvfp4",
|
||||
kv_scale_t,
|
||||
kv_scale_t,
|
||||
)
|
||||
|
||||
return nvfp4_cache
|
||||
|
||||
|
||||
def _run_trtllm_integration(batch_spec, kv_cache_dtype="auto", model_name=MODEL):
|
||||
"""Run TRTLLM attention through the full FlashInfer pipeline
|
||||
and compare against an SDPA reference."""
|
||||
set_random_seed(42)
|
||||
device = torch.device(f"{DEVICE_TYPE}:0")
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name=model_name,
|
||||
max_model_len=max(batch_spec.seq_lens),
|
||||
block_size=BLOCK_SIZE,
|
||||
num_gpu_blocks=NUM_GPU_BLOCKS,
|
||||
)
|
||||
vllm_config.attention_config.use_trtllm_attention = True
|
||||
vllm_config.cache_config.cache_dtype = kv_cache_dtype
|
||||
|
||||
num_q_heads = vllm_config.model_config.get_num_attention_heads(
|
||||
vllm_config.parallel_config
|
||||
)
|
||||
num_kv_heads = vllm_config.model_config.get_num_kv_heads(
|
||||
vllm_config.parallel_config
|
||||
)
|
||||
head_size = vllm_config.model_config.get_head_size()
|
||||
dtype = vllm_config.model_config.dtype
|
||||
scale = 1.0 / (head_size**0.5)
|
||||
|
||||
# 1. Generate data and compute SDPA reference
|
||||
all_q, all_k, all_v = [], [], []
|
||||
all_sdpa_out = []
|
||||
k_contexts, v_contexts = [], []
|
||||
|
||||
for i in range(batch_spec.batch_size):
|
||||
s_len = batch_spec.seq_lens[i]
|
||||
q_len = batch_spec.query_lens[i]
|
||||
ctx_len = s_len - q_len
|
||||
|
||||
q = torch.randn(q_len, num_q_heads, head_size, dtype=dtype, device=device)
|
||||
k_full = torch.randn(s_len, num_kv_heads, head_size, dtype=dtype, device=device)
|
||||
v_full = torch.randn(s_len, num_kv_heads, head_size, dtype=dtype, device=device)
|
||||
|
||||
# SDPA reference (N=1, H, L, D)
|
||||
q_sdpa = q.unsqueeze(0).transpose(1, 2)
|
||||
k_sdpa = k_full.unsqueeze(0).transpose(1, 2)
|
||||
v_sdpa = v_full.unsqueeze(0).transpose(1, 2)
|
||||
|
||||
if num_q_heads != num_kv_heads:
|
||||
repeats = num_q_heads // num_kv_heads
|
||||
k_sdpa = k_sdpa.repeat_interleave(repeats, dim=1)
|
||||
v_sdpa = v_sdpa.repeat_interleave(repeats, dim=1)
|
||||
|
||||
def causal_mask_mod(b, h, q_idx, kv_idx, *, context_len):
|
||||
return (q_idx + context_len) >= kv_idx
|
||||
|
||||
mask_fn = partial(causal_mask_mod, context_len=ctx_len)
|
||||
block_mask = create_block_mask(
|
||||
mask_fn, B=None, H=None, Q_LEN=q_len, KV_LEN=s_len, device=device
|
||||
)
|
||||
sdpa_out = flex_attention(
|
||||
q_sdpa,
|
||||
k_sdpa,
|
||||
v_sdpa,
|
||||
block_mask=block_mask,
|
||||
scale=scale,
|
||||
enable_gqa=True,
|
||||
)
|
||||
all_sdpa_out.append(sdpa_out.transpose(1, 2).squeeze(0))
|
||||
|
||||
all_q.append(q)
|
||||
all_k.append(k_full[ctx_len:])
|
||||
all_v.append(v_full[ctx_len:])
|
||||
k_contexts.append(k_full[:ctx_len])
|
||||
v_contexts.append(v_full[:ctx_len])
|
||||
|
||||
query_vllm = torch.cat(all_q, dim=0)
|
||||
key_vllm = torch.cat(all_k, dim=0)
|
||||
value_vllm = torch.cat(all_v, dim=0)
|
||||
sdpa_output = torch.cat(all_sdpa_out, dim=0)
|
||||
|
||||
common_attn_metadata = create_common_attn_metadata(batch_spec, BLOCK_SIZE, device)
|
||||
|
||||
# 2. Create HND KV cache
|
||||
is_nvfp4 = kv_cache_dtype == "nvfp4"
|
||||
if is_nvfp4:
|
||||
# Compute a global scale from the context data.
|
||||
all_ctx = torch.cat(k_contexts + v_contexts, dim=0)
|
||||
kv_scale_val = (all_ctx.abs().amax() / 448.0).item()
|
||||
kv_cache = _create_nvfp4_hnd_kv_cache(
|
||||
k_contexts,
|
||||
v_contexts,
|
||||
BLOCK_SIZE,
|
||||
num_kv_heads,
|
||||
head_size,
|
||||
dtype,
|
||||
device,
|
||||
NUM_GPU_BLOCKS,
|
||||
common_attn_metadata,
|
||||
kv_scale_val,
|
||||
)
|
||||
else:
|
||||
kv_scale_val = 1.0
|
||||
kv_cache = create_and_prepopulate_kv_cache(
|
||||
k_contexts,
|
||||
v_contexts,
|
||||
BLOCK_SIZE,
|
||||
num_kv_heads,
|
||||
head_size,
|
||||
dtype,
|
||||
device,
|
||||
NUM_GPU_BLOCKS,
|
||||
common_attn_metadata,
|
||||
layout=KVCacheLayout.LBHNC,
|
||||
)
|
||||
|
||||
# 3. Run through FlashInfer with TRTLLM enabled
|
||||
vllm_config.cache_config.kv_cache_layout = "LBHNC"
|
||||
|
||||
is_nvfp4 = kv_cache_dtype == "nvfp4"
|
||||
kv_quant_mode = KVQuantMode.NVFP4 if is_nvfp4 else KVQuantMode.NONE
|
||||
spec_dtype = torch.uint8 if is_nvfp4 else dtype
|
||||
kv_cache_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_size=head_size,
|
||||
dtype=spec_dtype,
|
||||
kv_quant_mode=kv_quant_mode,
|
||||
)
|
||||
layer_names = ["test_layer_0"]
|
||||
|
||||
with (
|
||||
set_current_vllm_config(vllm_config),
|
||||
unittest.mock.patch(
|
||||
"vllm.utils.flashinfer.supports_trtllm_attention",
|
||||
return_value=True,
|
||||
),
|
||||
unittest.mock.patch(
|
||||
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
|
||||
_mock_get_per_layer_parameters,
|
||||
),
|
||||
):
|
||||
builder = FlashInferMetadataBuilder(
|
||||
kv_cache_spec, layer_names, vllm_config, device
|
||||
)
|
||||
attn_metadata = builder.build(
|
||||
common_prefix_len=0,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
)
|
||||
|
||||
# Verify the correct TRTLLM metadata types were produced.
|
||||
has_prefills = any(ql > 1 for ql in batch_spec.query_lens)
|
||||
has_decodes = any(ql == 1 for ql in batch_spec.query_lens)
|
||||
|
||||
if has_prefills:
|
||||
assert isinstance(attn_metadata.prefill, TRTLLMPrefill), (
|
||||
f"Expected TRTLLMPrefill, got {type(attn_metadata.prefill)}"
|
||||
)
|
||||
if has_decodes:
|
||||
assert isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode), (
|
||||
f"Expected FlashInferTrtllmAPIDecode, got {type(attn_metadata.decode)}"
|
||||
)
|
||||
assert attn_metadata.decode.kernel == FlashInferDecodeKernel.TRTLLM_GEN
|
||||
|
||||
impl = FlashInferImpl(
|
||||
num_heads=num_q_heads,
|
||||
head_size=head_size,
|
||||
scale=scale,
|
||||
num_kv_heads=num_kv_heads,
|
||||
alibi_slopes=None,
|
||||
sliding_window=None,
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
)
|
||||
|
||||
mock_layer = MockAttentionLayer(device)
|
||||
if is_nvfp4:
|
||||
# For nvfp4, k_scale/v_scale are the global quantization
|
||||
# scales (amax/448) used by reshape_and_cache_flash.
|
||||
kv_scale_t = torch.tensor(kv_scale_val, dtype=torch.float32, device=device)
|
||||
mock_layer._k_scale = kv_scale_t
|
||||
mock_layer._v_scale = kv_scale_t
|
||||
mock_layer._k_scale_float = kv_scale_val
|
||||
mock_layer._v_scale_float = kv_scale_val
|
||||
output = torch.empty_like(query_vllm)
|
||||
|
||||
impl.do_kv_cache_update(
|
||||
mock_layer,
|
||||
key_vllm,
|
||||
value_vllm,
|
||||
kv_cache,
|
||||
attn_metadata.slot_mapping,
|
||||
)
|
||||
|
||||
# nvfp4 trtllm kernel requires FP8 queries. In the real
|
||||
# pipeline the attention layer handles this; here we
|
||||
# quantize manually.
|
||||
if is_nvfp4:
|
||||
finfo = torch.finfo(torch.float8_e4m3fn)
|
||||
q_amax = query_vllm.abs().amax().clamp(min=1e-12)
|
||||
q_s = (finfo.max / q_amax * 0.1).item()
|
||||
query_vllm = (
|
||||
(query_vllm * q_s).clamp(finfo.min, finfo.max).to(torch.float8_e4m3fn)
|
||||
)
|
||||
mock_layer._q_scale = torch.tensor(
|
||||
1.0 / q_s, dtype=torch.float32, device=device
|
||||
)
|
||||
mock_layer._q_scale_float = 1.0 / q_s
|
||||
|
||||
output = impl.forward(
|
||||
mock_layer,
|
||||
query_vllm,
|
||||
key_vllm,
|
||||
value_vllm,
|
||||
kv_cache,
|
||||
attn_metadata,
|
||||
output=output,
|
||||
)
|
||||
|
||||
# 4. Compare against SDPA reference
|
||||
if is_nvfp4:
|
||||
atol, rtol = 1.0, 1.0 # nvfp4 has higher quantization error
|
||||
else:
|
||||
atol, rtol = 1e-2, 1e-2
|
||||
torch.testing.assert_close(output, sdpa_output, atol=atol, rtol=rtol)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_spec_name",
|
||||
list(BATCH_SPECS.keys()),
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_trtllm_gen_full_attention_integration(batch_spec_name: str):
|
||||
"""Test TRTLLM gen-full attention through the full FlashInfer
|
||||
MetadataBuilder.build() -> FlashInferImpl.forward() pipeline,
|
||||
with real TRTLLM kernels on Blackwell."""
|
||||
_run_trtllm_integration(BATCH_SPECS[batch_spec_name])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_spec_name",
|
||||
list(BATCH_SPECS.keys()),
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_trtllm_gen_nvfp4_kv_integration(batch_spec_name: str):
|
||||
"""Test TRTLLM attention with nvfp4 KV cache through the full
|
||||
FlashInfer MetadataBuilder.build() -> FlashInferImpl.forward() pipeline."""
|
||||
_run_trtllm_integration(
|
||||
BATCH_SPECS[batch_spec_name],
|
||||
kv_cache_dtype="nvfp4",
|
||||
model_name=MODEL_NVFP4,
|
||||
)
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def test_trtllm_gen_draft_decode_metadata_tracks_in_place_seq_lens(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""Fused draft steps reuse the step-1 build after advancing seq_lens in
|
||||
place, so its decode metadata must match the split path's step-2 rebuild."""
|
||||
monkeypatch.setattr(
|
||||
"vllm.utils.flashinfer.supports_trtllm_attention",
|
||||
unittest.mock.Mock(return_value=True),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
|
||||
_mock_get_per_layer_parameters,
|
||||
)
|
||||
vllm_config = create_vllm_config(
|
||||
model_name=MODEL, block_size=BLOCK_SIZE, num_gpu_blocks=NUM_GPU_BLOCKS
|
||||
)
|
||||
model_config = vllm_config.model_config
|
||||
kv_cache_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=model_config.get_num_kv_heads(vllm_config.parallel_config),
|
||||
head_size=model_config.get_head_size(),
|
||||
dtype=model_config.dtype,
|
||||
)
|
||||
device = torch.device(f"{DEVICE_TYPE}:0")
|
||||
with set_current_vllm_config(vllm_config):
|
||||
builder = FlashInferMetadataBuilder(
|
||||
kv_cache_spec, ["test_layer_0"], vllm_config, device
|
||||
)
|
||||
assert builder.supports_draft_decode_metadata_update
|
||||
|
||||
step1 = create_common_attn_metadata(BATCH_SPECS["decode_only"], BLOCK_SIZE, device)
|
||||
reused = builder.build(common_prefix_len=0, common_attn_metadata=step1)
|
||||
step1.seq_lens.add_(1)
|
||||
step2 = dataclasses.replace(step1, seq_lens_cpu_upper_bound=step1.seq_lens.cpu())
|
||||
rebuilt = builder.build(common_prefix_len=0, common_attn_metadata=step2)
|
||||
|
||||
assert isinstance(reused.decode, FlashInferTrtllmAPIDecode)
|
||||
for field in dataclasses.fields(reused.decode):
|
||||
value = getattr(reused.decode, field.name)
|
||||
expected = getattr(rebuilt.decode, field.name)
|
||||
if isinstance(value, torch.Tensor):
|
||||
assert torch.equal(value, expected), field.name
|
||||
else:
|
||||
assert value == expected, field.name
|
||||
@@ -1,775 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for contiguous KV cache packing.
|
||||
|
||||
Every cache group packs its layers densely into one block; groups overlay each other
|
||||
(a block ID is owned by one group at a time), so the packed block stride is the
|
||||
largest group's packing. The layout decides whether the layer dim sits outside the
|
||||
block dim (a contiguous region per layer) or inside it (all layers' pages within each
|
||||
block); the allocation is the same either way.
|
||||
"""
|
||||
|
||||
from dataclasses import replace
|
||||
from math import lcm
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.core.kv_cache_planning import (
|
||||
_get_kv_cache_bytes_per_block,
|
||||
_get_packed_kv_cache_groups,
|
||||
_pool_bytes_per_block,
|
||||
get_kv_cache_config_from_groups,
|
||||
get_kv_cache_groups,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
generate_scheduler_kv_cache_config,
|
||||
resolve_kv_cache_block_sizes,
|
||||
)
|
||||
from vllm.v1.hisparse.layout import _build_hisparse_kv_cache_tensors
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
HiSparseHotSpec,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
iter_layer_specs,
|
||||
)
|
||||
from vllm.v1.worker.utils import allocate_kv_cache
|
||||
|
||||
MEMORY = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def _mla(head_size: int) -> MLAAttentionSpec:
|
||||
return MLAAttentionSpec(
|
||||
block_size=64, num_kv_heads=1, head_size=head_size, dtype=torch.uint8
|
||||
)
|
||||
|
||||
|
||||
def _full() -> FullAttentionSpec:
|
||||
return FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=2, head_size=64, dtype=torch.float16
|
||||
)
|
||||
|
||||
|
||||
def _uniform_group(specs: dict) -> KVCacheGroupSpec:
|
||||
return KVCacheGroupSpec(
|
||||
list(specs),
|
||||
UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs),
|
||||
)
|
||||
|
||||
|
||||
def _mixed_page_groups(n_mla=3, n_idx=3, n_swa=5):
|
||||
"""A DeepSeek-V4-style hybrid: two groups with different page mixes."""
|
||||
g1 = {f"mla.{i}": _mla(512) for i in range(n_mla)}
|
||||
g1.update({f"idx.{i}": _mla(128) for i in range(n_idx)})
|
||||
g2 = {f"swa.{i}": _mla(512) for i in range(n_swa)}
|
||||
return [_uniform_group(g1), _uniform_group(g2)], g1, g2
|
||||
|
||||
|
||||
def _mock_vllm_config(layout: str | None):
|
||||
config = MagicMock()
|
||||
config.cache_config = CacheConfig()
|
||||
config.cache_config.num_gpu_blocks_override = None
|
||||
config.cache_config.kv_cache_layout = layout
|
||||
config.attention_config.hisparse_config = None
|
||||
return config
|
||||
|
||||
|
||||
def test_packed_alignment_preserves_hot_pages_and_generic_stride():
|
||||
"""One shared stride must satisfy both constraints, regardless of rounding order."""
|
||||
spec = replace(_mla(128), block_stride_alignment=1152)
|
||||
hot = HiSparseHotSpec(block_size=16, page_size=5120, blocks_per_request=2)
|
||||
groups = [KVCacheGroupSpec(["attention"], spec), KVCacheGroupSpec(["hot"], hot)]
|
||||
alignment = lcm(1152, hot.page_size_bytes)
|
||||
stride = _pool_bytes_per_block(_mock_vllm_config("BLHNC"), groups)
|
||||
assert stride == alignment
|
||||
layout = KVCacheLayout.BLHNC
|
||||
tensors = _build_hisparse_kv_cache_tensors(groups, 3, 3 * stride, layout, stride)
|
||||
assert {tensor.block_stride for tensor in tensors} == {alignment}
|
||||
assert {tensor.size for tensor in tensors} == {3 * alignment}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec", [_full(), _mla(128)])
|
||||
def test_block_alignment_survives_merge_and_rejects_incompatible_specs(spec):
|
||||
aligned = replace(spec, block_stride_alignment=512)
|
||||
assert type(spec).merge([aligned, aligned]).block_stride_alignment == 512
|
||||
with pytest.raises(AssertionError):
|
||||
type(spec).merge([aligned, spec])
|
||||
with pytest.raises(ValueError, match="must be positive"):
|
||||
replace(spec, block_stride_alignment=0)
|
||||
|
||||
|
||||
def _pages(groups) -> dict[str, int]:
|
||||
return {
|
||||
name: group.kv_cache_spec.kv_cache_specs[name].page_size_bytes
|
||||
if isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs)
|
||||
else group.kv_cache_spec.page_size_bytes
|
||||
for group in groups
|
||||
for name in group.layer_names
|
||||
}
|
||||
|
||||
|
||||
def _expected_bytes_per_block(groups) -> int:
|
||||
pages = _pages(groups)
|
||||
return max(sum(pages[n] for n in g.layer_names) for g in groups)
|
||||
|
||||
|
||||
def _bind(config, layout: str):
|
||||
return allocate_kv_cache(config, torch.device("cpu"), KVCacheLayout[layout], None)
|
||||
|
||||
|
||||
MAIN_KV_PAGE_BYTES = 2_048
|
||||
COMPRESSED_PAGE_BYTES = 128
|
||||
NUM_CACHE_TUPLES = 3
|
||||
BYTES_PER_BLOCK = NUM_CACHE_TUPLES * (MAIN_KV_PAGE_BYTES + COMPRESSED_PAGE_BYTES)
|
||||
|
||||
|
||||
def _main_kv_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn"
|
||||
|
||||
|
||||
def _compressed_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn.indexer.compressed_key_cache"
|
||||
|
||||
|
||||
def _compressor_state_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn.indexer.raw_key_cache"
|
||||
|
||||
|
||||
def _make_csa_linear_specs(
|
||||
num_mamba: int = 7,
|
||||
num_tuples: int = NUM_CACHE_TUPLES,
|
||||
) -> dict[str, KVCacheSpec]:
|
||||
specs: dict[str, KVCacheSpec] = {}
|
||||
for layer_index in range(num_mamba):
|
||||
specs[f"model.layers.{layer_index}.linear_attn"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((32,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
)
|
||||
specs["model.layers.0.ple"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((24,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
tp_replicated=True,
|
||||
)
|
||||
for layer_index in range(num_tuples):
|
||||
specs[_main_kv_name(layer_index)] = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=2,
|
||||
head_size=16,
|
||||
head_size_v=16,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
specs[_compressed_name(layer_index)] = MLAAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
)
|
||||
specs[_compressor_state_name(layer_index)] = CircularBufferSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=8,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def _shared_layout_config():
|
||||
config = _mock_vllm_config("BLNHC")
|
||||
config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
config.speculative_config = None
|
||||
config.model_config.max_model_len = 16
|
||||
config.model_config.get_total_num_hidden_layers.return_value = 64
|
||||
config.model_config.get_total_num_kv_heads.return_value = 2
|
||||
config.model_config.get_num_kv_heads.return_value = 2
|
||||
config.parallel_config.pipeline_parallel_size = 1
|
||||
config.parallel_config.decode_context_parallel_size = 1
|
||||
config.cache_config.block_size = 16
|
||||
config.cache_config.enable_prefix_caching = False
|
||||
config.cache_config.prefix_match_unit = None
|
||||
config.cache_config.mamba_cache_mode = "none"
|
||||
return config
|
||||
|
||||
|
||||
class TestCSALinearGrouping:
|
||||
"""A CSA + linear-attention model (sparse attention with a compressor ring,
|
||||
plus sharded GDN and one TP-replicated PLE state) goes through the generic
|
||||
packed-group path; no model-specific branch is involved."""
|
||||
|
||||
@staticmethod
|
||||
def _mamba_groups(groups):
|
||||
"""(group, per-layer mamba spec) for every group holding mamba state."""
|
||||
out = []
|
||||
for group in groups:
|
||||
spec = next(iter(iter_layer_specs(group.kv_cache_spec)))
|
||||
if isinstance(spec, MambaSpec):
|
||||
out.append((group, spec))
|
||||
return out
|
||||
|
||||
def test_replicated_state_gets_its_own_group(self):
|
||||
"""The PLE state is TP-replicated and a different size, so it must not
|
||||
share a manager group with the sharded GDN states (the NIXL worker
|
||||
requires exactly one single-layer replicated group)."""
|
||||
groups = get_kv_cache_groups(_shared_layout_config(), _make_csa_linear_specs())
|
||||
|
||||
mamba_groups = self._mamba_groups(groups)
|
||||
replicated = [g for g, spec in mamba_groups if spec.tp_replicated]
|
||||
assert len(replicated) == 1
|
||||
assert replicated[0].layer_names == ["model.layers.0.ple"]
|
||||
sharded = [g for g, spec in mamba_groups if not spec.tp_replicated]
|
||||
assert sharded, "GDN states must keep their own groups"
|
||||
assert sorted(n for g in sharded for n in g.layer_names) == sorted(
|
||||
f"model.layers.{i}.linear_attn" for i in range(7)
|
||||
)
|
||||
|
||||
def test_roles_land_in_separate_groups(self):
|
||||
groups = get_kv_cache_groups(_shared_layout_config(), _make_csa_linear_specs())
|
||||
|
||||
owner = next(g for g in groups if _main_kv_name(0) in g.layer_names)
|
||||
assert sorted(owner.layer_names) == sorted(
|
||||
[
|
||||
*(_main_kv_name(i) for i in range(NUM_CACHE_TUPLES)),
|
||||
*(_compressed_name(i) for i in range(NUM_CACHE_TUPLES)),
|
||||
]
|
||||
)
|
||||
assert owner.kv_cache_spec.prefix_cacheable
|
||||
|
||||
scratch = next(g for g in groups if _compressor_state_name(0) in g.layer_names)
|
||||
assert scratch.layer_names == [
|
||||
_compressor_state_name(i) for i in range(NUM_CACHE_TUPLES)
|
||||
]
|
||||
assert not scratch.kv_cache_spec.prefix_cacheable
|
||||
|
||||
def test_every_group_fits_one_packed_block(self):
|
||||
config = _shared_layout_config()
|
||||
groups = get_kv_cache_groups(config, _make_csa_linear_specs())
|
||||
bytes_per_block = _get_kv_cache_bytes_per_block(groups, KVCacheLayout.BLHNC)
|
||||
|
||||
pages = _pages(groups)
|
||||
for group in groups:
|
||||
assert sum(pages[n] for n in group.layer_names) <= bytes_per_block
|
||||
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=bytes_per_block * 32
|
||||
)
|
||||
assert kv_cache_config.num_blocks == 32
|
||||
# Groups overlay from byte 0 of each block, so a layer never addresses
|
||||
# past the block it belongs to.
|
||||
for tensor in kv_cache_config.kv_cache_tensors:
|
||||
assert tensor.block_stride == bytes_per_block
|
||||
assert tensor.offset < bytes_per_block
|
||||
|
||||
def test_scratch_group_survives_computed_block_truncation(self):
|
||||
"""The scratch group contributes no computed blocks, so truncating a
|
||||
lookup result must skip it: its block size is the ring capacity, which
|
||||
neither divides the hit length nor bounds the (empty) block list."""
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
config.cache_config.mamba_cache_mode = "align"
|
||||
specs = {
|
||||
name: replace(spec, mamba_cache_mode="align")
|
||||
if isinstance(spec, MambaSpec)
|
||||
else spec
|
||||
for name, spec in _make_csa_linear_specs().items()
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=BYTES_PER_BLOCK * 64
|
||||
)
|
||||
scheduler_config = generate_scheduler_kv_cache_config([kv_cache_config])
|
||||
manager = KVCacheManager(
|
||||
scheduler_config,
|
||||
max_model_len=8192,
|
||||
enable_caching=True,
|
||||
hash_block_size=16,
|
||||
scheduler_block_size=16,
|
||||
)
|
||||
blocks = manager.create_kv_cache_blocks(
|
||||
tuple(
|
||||
manager.block_pool.get_new_blocks(3)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
else []
|
||||
for group in scheduler_config.kv_cache_groups
|
||||
)
|
||||
)
|
||||
truncated = manager.truncate_computed_blocks(blocks, 48)
|
||||
scratch_index = next(
|
||||
i
|
||||
for i, group in enumerate(scheduler_config.kv_cache_groups)
|
||||
if not group.kv_cache_spec.prefix_cacheable
|
||||
)
|
||||
assert truncated.blocks[scratch_index] == []
|
||||
|
||||
def test_prefix_hits_respect_compression_alignment(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
config.cache_config.prefix_match_unit = 16
|
||||
config.cache_config.mamba_cache_mode = "align"
|
||||
specs = {
|
||||
name: replace(spec, mamba_cache_mode="align")
|
||||
if isinstance(spec, MambaSpec)
|
||||
else spec
|
||||
for name, spec in _make_csa_linear_specs(num_tuples=1).items()
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (16, 16)
|
||||
|
||||
# 2 tokens is not a multiple of the compression ratio 4: a prefix hit
|
||||
# could land inside a partially filled compressed state.
|
||||
config.cache_config.prefix_match_unit = 2
|
||||
with pytest.raises(ValueError, match="per-state compression"):
|
||||
resolve_kv_cache_block_sizes(kv_cache_config, config)
|
||||
|
||||
def test_scratch_ring_does_not_drag_hash_granularity(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
config.cache_config.mamba_cache_mode = "align"
|
||||
specs = {
|
||||
name: replace(spec, mamba_cache_mode="align")
|
||||
if isinstance(spec, MambaSpec)
|
||||
else spec
|
||||
for name, spec in _make_csa_linear_specs(num_tuples=1).items()
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
# The hash granularity is the GCD over prefix-cacheable groups only;
|
||||
# the 4-token scratch ring is excluded (it would drag it to 4).
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (16, 16)
|
||||
|
||||
def test_compressed_attention_hashes_can_be_finer_than_cache_hits(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
specs = {
|
||||
"compressed.4": MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
),
|
||||
"compressed.128": MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=128,
|
||||
),
|
||||
"compressor_state.4": SlidingWindowMLASpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=8,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=8,
|
||||
),
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
|
||||
# Hashes are computed every 4 tokens, but without an align-mode Mamba
|
||||
# group cache hits remain on the 256-token scheduler boundary.
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (256, 4)
|
||||
|
||||
@pytest.mark.parametrize("wide", ["unbalanced_attention", "unsplittable_state"])
|
||||
def test_mamba_split_measures_the_block_the_other_groups_already_force(self, wide):
|
||||
"""Whatever fixes the block stride -- a bucket with unequal layer counts
|
||||
per page size, which is emitted whole, or a single-layer state that
|
||||
cannot be split at all -- the mamba layers must be sized against it.
|
||||
Sizing them against a narrower bucket splits them past what the block
|
||||
already fits, spending a pool block per extra group for no saving."""
|
||||
config = _mock_vllm_config("BLNHC")
|
||||
config.speculative_config = None
|
||||
specs = {}
|
||||
if wide == "unbalanced_attention":
|
||||
for i in range(3):
|
||||
specs[f"wide.{i}"] = _mla(1024)
|
||||
specs["wide.odd"] = _mla(800)
|
||||
else:
|
||||
specs["wide.state"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((51_200,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
tp_replicated=True,
|
||||
)
|
||||
# Mixed and balanced, but far narrower than the bucket above.
|
||||
for i in range(10):
|
||||
specs[f"narrow.a.{i}"] = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=8, dtype=torch.uint8
|
||||
)
|
||||
specs[f"narrow.b.{i}"] = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=16, dtype=torch.uint8
|
||||
)
|
||||
for i in range(100):
|
||||
specs[f"gdn.{i}"] = MambaSpec(
|
||||
block_size=16, shapes=((512,),), dtypes=(torch.bfloat16,)
|
||||
)
|
||||
|
||||
groups = _get_packed_kv_cache_groups(config, specs)
|
||||
gdn = [g for g in groups if g.layer_names[0].startswith("gdn.")]
|
||||
|
||||
assert _get_kv_cache_bytes_per_block(groups, KVCacheLayout.BLHNC) == sum(
|
||||
specs[name].page_size_bytes for name in specs if name.startswith("wide.")
|
||||
)
|
||||
# That block holds every GDN state at once, so the repeat pattern alone
|
||||
# decides the split; the cap must not add groups on top of it.
|
||||
assert len(gdn) == 10
|
||||
|
||||
|
||||
class TestSlidingWindowBucketCap:
|
||||
def test_sliding_window_bucket_is_capped_at_the_main_page(self):
|
||||
"""DeepSeek-V4.1 shape: 43 SlidingWindowMLASpec SWA caches beside an
|
||||
unbalanced 8-layer paged MLA bucket. Left whole, the SWA bucket would
|
||||
set the block width and the MLA group would fill under a third of
|
||||
every block; capped, it splits into groups no wider than the MLA
|
||||
page."""
|
||||
config = _shared_layout_config()
|
||||
specs: dict[str, KVCacheSpec] = {}
|
||||
for layer, ratio in ((2, 2), (8, 2), (14, 2), (20, 1)):
|
||||
specs[f"layers.{layer}.attn"] = MLAAttentionSpec(
|
||||
block_size=128,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
tokens_per_state=ratio,
|
||||
alignment=576,
|
||||
)
|
||||
specs[f"layers.{layer}.idx"] = MLAAttentionSpec(
|
||||
block_size=128,
|
||||
num_kv_heads=1,
|
||||
head_size=132,
|
||||
dtype=torch.uint8,
|
||||
tokens_per_state=ratio,
|
||||
alignment=576,
|
||||
)
|
||||
for layer in range(43):
|
||||
specs[f"layers.{layer}.swa"] = SlidingWindowMLASpec(
|
||||
block_size=64,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
sliding_window=128,
|
||||
alignment=576,
|
||||
)
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
pages = _pages(groups)
|
||||
main = next(g for g in groups if "layers.2.attn" in g.layer_names)
|
||||
main_bytes = sum(pages[n] for n in main.layer_names)
|
||||
assert _get_kv_cache_bytes_per_block(groups, KVCacheLayout.BLHNC) == main_bytes
|
||||
swa_groups = [g for g in groups if g.layer_names[0].endswith(".swa")]
|
||||
per_group = main_bytes // pages["layers.0.swa"]
|
||||
assert len(swa_groups) == -(-43 // per_group)
|
||||
for g in swa_groups:
|
||||
assert sum(pages[n] for n in g.layer_names) <= main_bytes
|
||||
assert sorted(n for g in swa_groups for n in g.layer_names) == sorted(
|
||||
f"layers.{i}.swa" for i in range(43)
|
||||
)
|
||||
|
||||
|
||||
class TestDensePacking:
|
||||
def test_bytes_per_block_is_largest_group(self):
|
||||
groups, g1, g2 = _mixed_page_groups()
|
||||
assert _get_kv_cache_bytes_per_block(
|
||||
groups, KVCacheLayout.BLHNC
|
||||
) == _expected_bytes_per_block(groups)
|
||||
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config("BLHNC"), groups, MEMORY
|
||||
)
|
||||
# Groups overlay: both start at offset 0.
|
||||
assert [tensor.offset for tensor in config.kv_cache_tensors].count(0) == 2
|
||||
assert [tensor.layers for tensor in config.kv_cache_tensors] == [
|
||||
list(g1)[:3],
|
||||
list(g1)[3:],
|
||||
list(g2),
|
||||
]
|
||||
|
||||
def test_layers_within_a_group_are_dense(self):
|
||||
groups, _, _ = _mixed_page_groups()
|
||||
pages = _pages(groups)
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config("BLHNC"), groups, MEMORY
|
||||
)
|
||||
offsets = {
|
||||
name: tensor.offset + i * tensor.layer_stride
|
||||
for tensor in config.kv_cache_tensors
|
||||
for i, name in enumerate(tensor.layers)
|
||||
}
|
||||
for group in groups:
|
||||
expected = 0
|
||||
for name in group.layer_names:
|
||||
assert offsets[name] == expected
|
||||
expected += pages[name]
|
||||
|
||||
@pytest.mark.parametrize("layout", ["LBNHC", "BLHNC"])
|
||||
def test_allocation_is_layout_invariant(self, layout):
|
||||
specs = {f"l.{i}": _full() for i in range(4)}
|
||||
groups = [KVCacheGroupSpec(list(specs), _full())]
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config(layout), groups, MEMORY
|
||||
)
|
||||
(tensor,) = config.kv_cache_tensors
|
||||
page = _full().page_size_bytes
|
||||
assert tensor.layers == list(specs)
|
||||
assert config.num_blocks == MEMORY // (4 * page)
|
||||
assert tensor.size == 4 * page * config.num_blocks
|
||||
if layout == "LBNHC":
|
||||
assert (tensor.layer_stride, tensor.block_stride) == (
|
||||
page * config.num_blocks,
|
||||
page,
|
||||
)
|
||||
else:
|
||||
assert (tensor.layer_stride, tensor.block_stride) == (page, 4 * page)
|
||||
|
||||
@pytest.mark.parametrize("layout", ["LBNHC", "BLHNC"])
|
||||
def test_single_group_mixed_pages_follows_layout(self, layout):
|
||||
specs = {"mla.0": _mla(512), "mla.1": _mla(512), "idx.0": _mla(128)}
|
||||
groups = [_uniform_group(specs)]
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config(layout), groups, MEMORY
|
||||
)
|
||||
block_stride = _expected_bytes_per_block(groups)
|
||||
mla_tensor, idx_tensor = config.kv_cache_tensors
|
||||
assert mla_tensor.layers == ["mla.0", "mla.1"]
|
||||
assert idx_tensor.layers == ["idx.0"]
|
||||
assert {t.size for t in config.kv_cache_tensors} == {
|
||||
block_stride * config.num_blocks
|
||||
}
|
||||
if layout == "LBNHC":
|
||||
assert (
|
||||
idx_tensor.offset == 2 * _mla(512).page_size_bytes * config.num_blocks
|
||||
)
|
||||
assert mla_tensor.block_stride == _mla(512).page_size_bytes
|
||||
else:
|
||||
assert idx_tensor.offset == 2 * _mla(512).page_size_bytes
|
||||
assert mla_tensor.block_stride == block_stride
|
||||
|
||||
def test_layer_outer_pads_only_unaligned_pages(self):
|
||||
"""Layer-outer block strides are pages, so only an unaligned page pads."""
|
||||
mla_page = _mla(512).page_size_bytes
|
||||
idx = replace(_mla(128), block_stride_alignment=12288)
|
||||
groups = [_uniform_group({"mla.0": _mla(512), "idx.0": idx})]
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config("LBNHC"), groups, MEMORY
|
||||
)
|
||||
mla_tensor, idx_tensor = config.kv_cache_tensors
|
||||
assert config.num_blocks == MEMORY // (mla_page + 12288)
|
||||
assert (mla_tensor.block_stride, idx_tensor.block_stride) == (mla_page, 12288)
|
||||
assert idx_tensor.offset == mla_page * config.num_blocks
|
||||
_bind(config, "LBNHC")
|
||||
|
||||
def test_overlaid_groups_alias_and_stay_isolated(self):
|
||||
groups, g1, g2 = _mixed_page_groups()
|
||||
# Overlay models resolve to a block-outer layout at backend selection (the
|
||||
# model's backend declares it); mirror that here.
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config("BLNHC"), groups, MEMORY
|
||||
)
|
||||
assert config.num_blocks == MEMORY // _expected_bytes_per_block(groups)
|
||||
assert _pool_bytes_per_block(
|
||||
_mock_vllm_config("BLNHC"), groups
|
||||
) == _expected_bytes_per_block(groups)
|
||||
|
||||
views = _bind(config, "BLNHC")
|
||||
assert set(views) == set(g1) | set(g2)
|
||||
assert views["swa.0"].data_ptr() == views["mla.0"].data_ptr()
|
||||
|
||||
# A block is owned by one group at a time: writes to group-owned
|
||||
# blocks never disturb the other group's blocks.
|
||||
for i, name in enumerate(g1):
|
||||
views[name][0].fill_(i + 1)
|
||||
views[name][2].fill_(i + 1)
|
||||
for i, name in enumerate(g2):
|
||||
views[name][1].fill_(100 + i)
|
||||
views[name][3].fill_(100 + i)
|
||||
for i, name in enumerate(g1):
|
||||
assert (views[name][0].to(torch.int32) == i + 1).all()
|
||||
assert (views[name][2].to(torch.int32) == i + 1).all()
|
||||
for i, name in enumerate(g2):
|
||||
assert (views[name][1].to(torch.int32) == 100 + i).all()
|
||||
assert (views[name][3].to(torch.int32) == 100 + i).all()
|
||||
# Layers within a group are disjoint.
|
||||
views["mla.0"][0].fill_(77)
|
||||
for i, name in enumerate(list(g1)[1:], start=1):
|
||||
assert (views[name][0].to(torch.int32) == i + 1).all()
|
||||
|
||||
def test_layer_compact_layout_rejected_for_overlaid_groups(self):
|
||||
# The layout has a single writer (backend-selection resolution); a layer-
|
||||
# compact layout reaching an overlay model's allocation is an error, not a
|
||||
# silent flip.
|
||||
groups, _, _ = _mixed_page_groups()
|
||||
with pytest.raises(
|
||||
ValueError, match="cannot express this model's mixed page sizes"
|
||||
):
|
||||
get_kv_cache_config_from_groups(_mock_vllm_config("LBNHC"), groups, MEMORY)
|
||||
|
||||
def test_unresolved_layout_rejected(self):
|
||||
groups, _, _ = _mixed_page_groups()
|
||||
with pytest.raises(ValueError, match="has not been resolved"):
|
||||
get_kv_cache_config_from_groups(_mock_vllm_config(None), groups, MEMORY)
|
||||
|
||||
def test_head_outer_layout_rejected_for_mixed_pages(self):
|
||||
groups, _, _ = _mixed_page_groups()
|
||||
with pytest.raises(
|
||||
ValueError, match="cannot express this model's mixed page sizes"
|
||||
):
|
||||
get_kv_cache_config_from_groups(_mock_vllm_config("LHBNC"), groups, MEMORY)
|
||||
|
||||
@pytest.mark.parametrize("layout", ["LBNHC", "BLHNC"])
|
||||
def test_bound_views_round_trip(self, layout):
|
||||
specs = {"mla.0": _mla(512), "mla.1": _mla(512), "idx.0": _mla(128)}
|
||||
groups = [_uniform_group(specs)]
|
||||
config = get_kv_cache_config_from_groups(
|
||||
_mock_vllm_config(layout), groups, MEMORY
|
||||
)
|
||||
views = _bind(config, layout)
|
||||
for i, name in enumerate(specs):
|
||||
views[name].fill_(i + 1)
|
||||
for i, name in enumerate(specs):
|
||||
assert (views[name].to(torch.int32) == i + 1).all(), name
|
||||
assert views[name].shape[0] == config.num_blocks
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
|
||||
class TestCompressorRingGroup:
|
||||
def test_ring_beside_paged_groups_keeps_the_kv_block_as_scheduler_block(self):
|
||||
"""DeepSeek-V4.1 compressor state: a CircularBufferSpec ring (capacity
|
||||
8) beside 128-token paged MLA groups and 64-token SWA groups. The ring
|
||||
claims one block per request, never hashes, and does not disturb the
|
||||
scheduler/hash block sizes the paged groups imply."""
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
specs: dict[str, KVCacheSpec] = {
|
||||
"layers.2.attn": MLAAttentionSpec(
|
||||
block_size=128,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
tokens_per_state=2,
|
||||
alignment=576,
|
||||
),
|
||||
"layers.2.attn.compressor.state_cache": CircularBufferSpec(
|
||||
block_size=8,
|
||||
num_kv_heads=1,
|
||||
head_size=1024,
|
||||
head_size_v=0,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
}
|
||||
for layer in range(4):
|
||||
specs[f"layers.{layer}.attn.swa_cache"] = SlidingWindowMLASpec(
|
||||
block_size=64,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
sliding_window=128,
|
||||
alignment=576,
|
||||
)
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
ring_groups = [g for g in groups if "state_cache" in g.layer_names[0]]
|
||||
assert len(ring_groups) == 1
|
||||
assert not ring_groups[0].kv_cache_spec.prefix_cacheable
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config,
|
||||
groups,
|
||||
available_memory=64
|
||||
* _get_kv_cache_bytes_per_block(groups, KVCacheLayout.BLHNC),
|
||||
)
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (128, 64)
|
||||
manager = KVCacheManager(
|
||||
generate_scheduler_kv_cache_config([kv_cache_config]),
|
||||
max_model_len=8192,
|
||||
enable_caching=True,
|
||||
hash_block_size=64,
|
||||
scheduler_block_size=128,
|
||||
)
|
||||
assert len(manager.coordinator.single_type_managers) == len(groups)
|
||||
|
||||
|
||||
class TestSWABoundedReplayGrouping:
|
||||
def test_non_cacheable_swa_leaves_hits_to_the_paged_group(self):
|
||||
"""Under SWA bounded replay only the paged MLA group hashes (hash
|
||||
block = its block) and the coordinator probes one spec group."""
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
specs: dict[str, KVCacheSpec] = {
|
||||
"layers.2.attn": MLAAttentionSpec(
|
||||
block_size=128,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
tokens_per_state=2,
|
||||
alignment=576,
|
||||
),
|
||||
}
|
||||
swa = SlidingWindowMLASpec(
|
||||
block_size=32,
|
||||
num_kv_heads=1,
|
||||
head_size=584,
|
||||
dtype=torch.uint8,
|
||||
sliding_window=128,
|
||||
alignment=576,
|
||||
bounded_replay=True,
|
||||
)
|
||||
for layer in range(4):
|
||||
specs[f"layers.{layer}.attn.swa_cache"] = swa
|
||||
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
# The worker reads the replay window off the (packed) group specs to
|
||||
# arm the window clamp; the wrapper must forward it like cacheability.
|
||||
assert sorted(
|
||||
(g.kv_cache_spec.prefix_cacheable, g.kv_cache_spec.prefix_replay_tokens)
|
||||
for g in groups
|
||||
) == [(False, 128)] * 4 + [(True, 0)]
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config,
|
||||
groups,
|
||||
available_memory=64
|
||||
* _get_kv_cache_bytes_per_block(groups, KVCacheLayout.BLHNC),
|
||||
)
|
||||
manager = KVCacheManager(
|
||||
generate_scheduler_kv_cache_config([kv_cache_config]),
|
||||
max_model_len=8192,
|
||||
enable_caching=True,
|
||||
hash_block_size=128,
|
||||
scheduler_block_size=128,
|
||||
)
|
||||
assert len(manager.coordinator.attention_groups) == 1
|
||||
assert isinstance(
|
||||
manager.coordinator.attention_groups[0].spec, MLAAttentionSpec
|
||||
)
|
||||
|
||||
# Allocating and caching a request goes through every group's manager;
|
||||
# the 32-token SWA group must skip hashing rather than assert on the
|
||||
# 128-token hash block.
|
||||
from tests.v1.core.utils import create_requests
|
||||
|
||||
request = create_requests(num_requests=1, num_tokens=256, block_size=128)[0]
|
||||
assert manager.allocate_slots(request, 256) is not None
|
||||
request.num_computed_tokens = 256
|
||||
manager.cache_blocks(request, 256)
|
||||
for single in manager.coordinator.single_type_managers:
|
||||
cached = single.num_cached_block.get(request.request_id, 0)
|
||||
assert cached == (2 if single.kv_cache_spec.prefix_cacheable else 0)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,435 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
|
||||
import prometheus_client
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.conftest import VllmRunner
|
||||
from tests.utils import fork_new_process_for_each_test
|
||||
from vllm.config import AttentionConfig, HiSparseConfig, KVTransferConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.connector import (
|
||||
HiSparseConnector,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.worker import (
|
||||
HiSparseConnectorWorker,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import (
|
||||
MultiConnector,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
|
||||
|
||||
MODEL = "deepseek-ai/DeepSeek-V3.2"
|
||||
|
||||
HF_OVERRIDES = {
|
||||
"num_hidden_layers": 8,
|
||||
"hidden_size": 256,
|
||||
"intermediate_size": 512,
|
||||
"num_attention_heads": 8,
|
||||
"num_key_value_heads": 1,
|
||||
"n_routed_experts": 8,
|
||||
"num_experts_per_tok": 2,
|
||||
"index_topk": 128,
|
||||
}
|
||||
|
||||
|
||||
def _shrink_config(config):
|
||||
overrides = HF_OVERRIDES.copy()
|
||||
if any("MTP" in architecture for architecture in config.architectures):
|
||||
overrides.pop("num_hidden_layers")
|
||||
config.update(overrides)
|
||||
return config
|
||||
|
||||
|
||||
def _num_hisparse_spills(runner: VllmRunner) -> int:
|
||||
client = runner.llm.llm_engine.engine_core
|
||||
coordinator = get_hisparse_coordinator(
|
||||
client.engine_core.scheduler.kv_cache_manager
|
||||
)
|
||||
return coordinator.next_spill_id
|
||||
|
||||
|
||||
def _offload_load_bytes() -> float:
|
||||
return sum(
|
||||
sample.value
|
||||
for metric in prometheus_client.REGISTRY.collect()
|
||||
if metric.name == "vllm:kv_offload_load_bytes"
|
||||
for sample in metric.samples
|
||||
if sample.name == "vllm:kv_offload_load_bytes_total"
|
||||
)
|
||||
|
||||
|
||||
def _get_hisparse_worker(runner: VllmRunner) -> HiSparseConnectorWorker:
|
||||
engine_core = runner.llm.llm_engine.engine_core.engine_core
|
||||
model_runner = engine_core.model_executor.driver_worker.worker.model_runner
|
||||
connector = model_runner.kv_connector.kv_connector
|
||||
if isinstance(connector, MultiConnector):
|
||||
connector = next(
|
||||
child
|
||||
for child in connector.sub_connectors
|
||||
if isinstance(child, HiSparseConnector)
|
||||
)
|
||||
assert isinstance(connector, HiSparseConnector)
|
||||
assert connector.connector_worker is not None
|
||||
return connector.connector_worker
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="HiSparse requires NVIDIA CUDA"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"with_offloading,attention_backend",
|
||||
[
|
||||
pytest.param(False, None, id="standalone"),
|
||||
pytest.param(True, None, id="offload"),
|
||||
# Offloading does not touch the attention kernels: FA4 runs standalone.
|
||||
pytest.param(False, "FLASH_ATTN_MLA_SPARSE_FA4", id="standalone-fa4"),
|
||||
],
|
||||
)
|
||||
@fork_new_process_for_each_test
|
||||
def test_hisparse_spill_and_prefix_restore(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
vllm_runner: type[VllmRunner],
|
||||
with_offloading: bool,
|
||||
attention_backend: str | None,
|
||||
):
|
||||
"""Spilled prefixes restore and FULL-graph decode writes reach host KV.
|
||||
|
||||
A regression omitted attention metadata before FULL graph replay, so decode
|
||||
completed normally while its newly written KV rows were never copied to host.
|
||||
MTP layers write after the target forward; their rows used to be mirrored
|
||||
before the drafter wrote them, so the drafter later read stale host rows.
|
||||
"""
|
||||
capability = current_platform.get_device_capability()
|
||||
if capability is None or capability.major < 9:
|
||||
pytest.skip("Sparse MLA requires Hopper or newer")
|
||||
if attention_backend and not current_platform.is_device_capability_family(100):
|
||||
pytest.skip("FA4 sparse MLA requires SM 10.x")
|
||||
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
|
||||
|
||||
target = [1000 + i % 64 for i in range(257)]
|
||||
pressure = [
|
||||
[2000 + request_idx * 128 + i % 64 for i in range(257)]
|
||||
for request_idx in range(4)
|
||||
]
|
||||
hisparse_connector = {
|
||||
"kv_connector": "HiSparseConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"host_pool_gib": 1},
|
||||
}
|
||||
kv_transfer_config = KVTransferConfig(**hisparse_connector)
|
||||
if with_offloading:
|
||||
kv_transfer_config = KVTransferConfig(
|
||||
kv_connector="MultiConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={
|
||||
"connectors": [
|
||||
hisparse_connector,
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"cpu_bytes_to_use": 1 << 30},
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
with vllm_runner(
|
||||
MODEL,
|
||||
load_format="dummy",
|
||||
hf_overrides=_shrink_config,
|
||||
attention_config=AttentionConfig(
|
||||
hisparse_config=HiSparseConfig(
|
||||
device_buffer_size=512,
|
||||
)
|
||||
),
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
attention_backend=attention_backend,
|
||||
block_size=64,
|
||||
max_model_len=320,
|
||||
max_num_batched_tokens=1024,
|
||||
max_num_seqs=4,
|
||||
num_gpu_blocks_override=128,
|
||||
disable_log_stats=False,
|
||||
enable_chunked_prefill=True,
|
||||
enable_prefix_caching=True,
|
||||
speculative_config={"method": "mtp", "num_speculative_tokens": 3},
|
||||
compilation_config={
|
||||
"cudagraph_mode": "FULL_AND_PIECEWISE",
|
||||
"cudagraph_capture_sizes": [1, 4],
|
||||
},
|
||||
) as runner:
|
||||
worker = _get_hisparse_worker(runner)
|
||||
engine_core = runner.llm.llm_engine.engine_core.engine_core
|
||||
model_runner = engine_core.model_executor.driver_worker.worker.model_runner
|
||||
full_graph_calls = 0
|
||||
full_replay_pending = False
|
||||
original_run_fullgraph = model_runner.cudagraph_manager.run_fullgraph
|
||||
|
||||
def record_fullgraph(batch_desc):
|
||||
nonlocal full_graph_calls, full_replay_pending
|
||||
full_graph_calls += 1
|
||||
full_replay_pending = True
|
||||
return original_run_fullgraph(batch_desc)
|
||||
|
||||
monkeypatch.setattr(
|
||||
model_runner.cudagraph_manager, "run_fullgraph", record_fullgraph
|
||||
)
|
||||
|
||||
# The MTP layer writes its rows after the target forward, so it is
|
||||
# mirrored at the start of the next step instead of in finish_forward.
|
||||
draft_layers = set(worker._draft_layers)
|
||||
assert draft_layers
|
||||
original_finish_forward = worker.finish_forward
|
||||
original_finish_previous_step = worker._finish_previous_step
|
||||
verified_rows = {"target": 0, "draft": 0}
|
||||
copied_nonzero_kv = False
|
||||
draft_check_pending = False
|
||||
|
||||
def check_host_rows(layer_indices: set[int], kind: str) -> None:
|
||||
nonlocal copied_nonzero_kv
|
||||
# Synchronize only the test's inspection, not the worker itself.
|
||||
with gpu_sync_allowed():
|
||||
torch.accelerator.synchronize()
|
||||
assert worker._row_mirrors
|
||||
for layer_index in layer_indices:
|
||||
cache = worker.cache_handles[layer_index]
|
||||
source_index = cache.runtime.resident_source_index
|
||||
for mirror in worker._row_mirrors:
|
||||
source_row = mirror.source_starts[source_index]
|
||||
destination_row = mirror.destination_start
|
||||
num_rows = mirror.num_rows
|
||||
source_block, source_offset = divmod(
|
||||
source_row, worker.kernel_block_size
|
||||
)
|
||||
with gpu_sync_allowed():
|
||||
gpu_rows = worker.resident_caches[layer_index][
|
||||
source_block, source_offset : source_offset + num_rows
|
||||
].cpu()
|
||||
host_rows = worker.host_caches[layer_index][
|
||||
destination_row : destination_row + num_rows
|
||||
]
|
||||
assert torch.equal(host_rows, gpu_rows)
|
||||
copied_nonzero_kv |= bool(torch.count_nonzero(gpu_rows).item())
|
||||
verified_rows[kind] += num_rows
|
||||
|
||||
def finish_forward():
|
||||
nonlocal full_replay_pending, draft_check_pending
|
||||
try:
|
||||
original_finish_forward()
|
||||
if not full_replay_pending:
|
||||
return
|
||||
target_layers = set(range(len(worker.cache_handles))) - draft_layers
|
||||
check_host_rows(target_layers, "target")
|
||||
draft_check_pending = True
|
||||
finally:
|
||||
full_replay_pending = False
|
||||
|
||||
def finish_previous_step():
|
||||
nonlocal draft_check_pending
|
||||
original_finish_previous_step()
|
||||
if draft_check_pending:
|
||||
draft_check_pending = False
|
||||
check_host_rows(draft_layers, "draft")
|
||||
|
||||
monkeypatch.setattr(worker, "finish_forward", finish_forward)
|
||||
monkeypatch.setattr(worker, "_finish_previous_step", finish_previous_step)
|
||||
|
||||
expected = runner.generate_greedy([target], max_tokens=8)
|
||||
|
||||
assert full_graph_calls > 0
|
||||
assert verified_rows["target"] > 0
|
||||
assert verified_rows["draft"] > 0
|
||||
assert copied_nonzero_kv
|
||||
|
||||
runner.generate_greedy(pressure, max_tokens=8)
|
||||
|
||||
assert _num_hisparse_spills(runner) > 0
|
||||
load_bytes = _offload_load_bytes()
|
||||
actual = runner.generate_greedy([target], max_tokens=8)
|
||||
runner.generate_greedy([[42]], max_tokens=1)
|
||||
|
||||
assert actual == expected
|
||||
if with_offloading:
|
||||
assert _offload_load_bytes() > load_bytes
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="HiSparse requires NVIDIA CUDA"
|
||||
)
|
||||
@fork_new_process_for_each_test
|
||||
def test_hisparse_host_exhaustion_defers_requests(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
vllm_runner: type[VllmRunner],
|
||||
):
|
||||
"""A full host pool defers requests instead of leaving pages GPU-only."""
|
||||
capability = current_platform.get_device_capability()
|
||||
if capability is None or capability.major < 9:
|
||||
pytest.skip("Sparse MLA requires Hopper or newer")
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
|
||||
prompts = [
|
||||
[1000 + request_idx * 64 + i % 64 for i in range(257)]
|
||||
for request_idx in range(3)
|
||||
]
|
||||
with vllm_runner(
|
||||
MODEL,
|
||||
load_format="dummy",
|
||||
hf_overrides=_shrink_config,
|
||||
attention_config=AttentionConfig(
|
||||
hisparse_config=HiSparseConfig(device_buffer_size=512)
|
||||
),
|
||||
kv_transfer_config=KVTransferConfig(
|
||||
kv_connector="HiSparseConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"host_pool_gib": 1},
|
||||
),
|
||||
block_size=64,
|
||||
max_model_len=320,
|
||||
max_num_batched_tokens=512,
|
||||
max_num_seqs=3,
|
||||
num_gpu_blocks_override=128,
|
||||
enable_prefix_caching=False,
|
||||
enable_chunked_prefill=True,
|
||||
enforce_eager=True,
|
||||
) as runner:
|
||||
expected = [runner.generate_greedy([p], max_tokens=16)[0] for p in prompts]
|
||||
engine = runner.llm.llm_engine.engine_core.engine_core
|
||||
coordinator = get_hisparse_coordinator(engine.scheduler.kv_cache_manager)
|
||||
host = coordinator.host_manager
|
||||
assert host is not None
|
||||
# Leave room for one full request plus part of another.
|
||||
spare_blocks = 8
|
||||
num_pressure = host.block_pool.get_num_free_blocks() - spare_blocks
|
||||
host.allocate_new_blocks(
|
||||
"host-pressure",
|
||||
num_pressure * host.block_size,
|
||||
num_pressure * host.block_size,
|
||||
)
|
||||
original_plan = coordinator.plan_prefix_materialization
|
||||
original_count = host.get_num_blocks_to_allocate
|
||||
checked_steps = 0
|
||||
refusals = 0
|
||||
|
||||
def plan(request_id, num_computed_tokens):
|
||||
nonlocal checked_steps
|
||||
assert not any(b.is_null for b in host.req_to_blocks[request_id])
|
||||
checked_steps += 1
|
||||
original_plan(request_id, num_computed_tokens)
|
||||
|
||||
def count(*args, **kwargs):
|
||||
nonlocal refusals
|
||||
required = original_count(*args, **kwargs)
|
||||
refusals += int(required > 0)
|
||||
return required
|
||||
|
||||
monkeypatch.setattr(coordinator, "plan_prefix_materialization", plan)
|
||||
monkeypatch.setattr(host, "get_num_blocks_to_allocate", count)
|
||||
actual = runner.generate_greedy(prompts, max_tokens=16)
|
||||
|
||||
assert checked_steps > 0
|
||||
assert refusals > 0
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="HiSparse requires NVIDIA CUDA"
|
||||
)
|
||||
@fork_new_process_for_each_test
|
||||
def test_hisparse_terminal_prefix_reuse(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
vllm_runner: type[VllmRunner],
|
||||
):
|
||||
"""Finished requests publish mirrored host KV after a late acknowledgement."""
|
||||
capability = current_platform.get_device_capability()
|
||||
if capability is None or capability.major < 9:
|
||||
pytest.skip("Sparse MLA requires Hopper or newer")
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
|
||||
target = [1000 + i % 64 for i in range(257)]
|
||||
sampling = SamplingParams(temperature=0, max_tokens=1, ignore_eos=True)
|
||||
with vllm_runner(
|
||||
MODEL,
|
||||
load_format="dummy",
|
||||
hf_overrides=_shrink_config,
|
||||
attention_config=AttentionConfig(
|
||||
hisparse_config=HiSparseConfig(
|
||||
device_buffer_size=512, eager_host_mirror=True
|
||||
)
|
||||
),
|
||||
kv_transfer_config=KVTransferConfig(
|
||||
kv_connector="HiSparseConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"host_pool_gib": 0.01},
|
||||
),
|
||||
block_size=64,
|
||||
max_model_len=320,
|
||||
max_num_batched_tokens=512,
|
||||
max_num_seqs=2,
|
||||
num_gpu_blocks_override=128,
|
||||
enable_prefix_caching=True,
|
||||
enable_chunked_prefill=True,
|
||||
enforce_eager=True,
|
||||
) as runner:
|
||||
engine = runner.llm.llm_engine.engine_core.engine_core
|
||||
coordinator = get_hisparse_coordinator(engine.scheduler.kv_cache_manager)
|
||||
worker = _get_hisparse_worker(runner)
|
||||
original_updates = worker.take_transfer_updates
|
||||
original_free = coordinator.free
|
||||
held_completions: list[int] = []
|
||||
update_calls = 0
|
||||
terminal_pending_pages = 0
|
||||
|
||||
def take_updates():
|
||||
nonlocal update_calls
|
||||
with gpu_sync_allowed():
|
||||
torch.accelerator.synchronize()
|
||||
enqueued, completed = original_updates()
|
||||
held_completions.extend(completed)
|
||||
update_calls += 1
|
||||
if update_calls <= 2:
|
||||
return enqueued, []
|
||||
completed = held_completions.copy()
|
||||
held_completions.clear()
|
||||
return enqueued, completed
|
||||
|
||||
def free(request_id):
|
||||
nonlocal terminal_pending_pages
|
||||
state = coordinator.request_states.get(request_id)
|
||||
if state is not None:
|
||||
terminal_pending_pages += len(state.pending_pages)
|
||||
original_free(request_id)
|
||||
|
||||
def drain_pending_work():
|
||||
deadline = time.monotonic() + 10
|
||||
while coordinator.has_pending_work():
|
||||
assert time.monotonic() < deadline, "HiSparse transfers did not drain"
|
||||
runner.llm.llm_engine.step()
|
||||
|
||||
monkeypatch.setattr(worker, "take_transfer_updates", take_updates)
|
||||
monkeypatch.setattr(coordinator, "free", free)
|
||||
[first] = runner.llm.generate(
|
||||
[{"prompt_token_ids": target}], sampling, use_tqdm=False
|
||||
)
|
||||
assert terminal_pending_pages == 4
|
||||
assert first.num_cached_tokens == 0
|
||||
assert coordinator.has_pending_work()
|
||||
drain_pending_work()
|
||||
assert not coordinator.has_pending_work()
|
||||
assert not held_completions
|
||||
assert update_calls > 2
|
||||
|
||||
[repeated] = runner.llm.generate(
|
||||
[{"prompt_token_ids": target}], sampling, use_tqdm=False
|
||||
)
|
||||
assert repeated.num_cached_tokens == 256
|
||||
assert repeated.outputs[0].token_ids == first.outputs[0].token_ids
|
||||
drain_pending_work()
|
||||
assert not coordinator.has_pending_work()
|
||||
@@ -1,230 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import random
|
||||
from collections.abc import Iterable, Sequence
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.evals.gsm8k.gsm8k_eval import _build_gsm8k_prompts, evaluate_gsm8k_offline
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.assets.base import VLLM_S3_BUCKET_URL
|
||||
from vllm.assets.image import VLM_IMAGES_DIR
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.utils.torch_utils import set_random_seed
|
||||
from vllm.v1.metrics.reader import Metric
|
||||
|
||||
|
||||
def _skip_if_insufficient_gpus_for_tp(tp_size: int):
|
||||
"""Skip if fewer than ``tp_size`` accelerators are available."""
|
||||
available_gpus = torch.accelerator.device_count()
|
||||
if available_gpus < tp_size:
|
||||
pytest.skip(
|
||||
f"Test requires {tp_size} GPUs, but only {available_gpus} available"
|
||||
)
|
||||
|
||||
|
||||
Messages = list[dict[str, Any]]
|
||||
|
||||
|
||||
def get_test_prompts(mm_enabled: bool, num_prompts: int = 100) -> list[Messages]:
|
||||
prompt_types = ["repeat", "gsm8k"]
|
||||
if mm_enabled:
|
||||
prompt_types.append("mm")
|
||||
prompts: list[Messages] = []
|
||||
|
||||
num_repeat_prompts = num_prompts // len(prompt_types)
|
||||
if mm_enabled:
|
||||
num_gsm8k_prompts = num_prompts // len(prompt_types)
|
||||
num_mm_prompts = num_prompts - num_repeat_prompts - num_gsm8k_prompts
|
||||
else:
|
||||
num_mm_prompts = 0
|
||||
num_gsm8k_prompts = num_prompts - num_repeat_prompts
|
||||
|
||||
# Generate a mixed batch of prompts, some of which can be easily
|
||||
# predicted by n-gram matching and some which likely cannot.
|
||||
set_random_seed(0)
|
||||
for _ in range(num_repeat_prompts):
|
||||
word_choices = ["test", "temp", "hello", "where"]
|
||||
word = random.choice(word_choices)
|
||||
prompts.append(
|
||||
[
|
||||
{
|
||||
"role": "user",
|
||||
"content": f"""
|
||||
please repeat the word '{word}' 10 times.
|
||||
give no other output than the word at least ten times in a row,
|
||||
in lowercase with spaces between each word and without quotes.
|
||||
""",
|
||||
}
|
||||
]
|
||||
)
|
||||
prompts.extend(
|
||||
[{"role": "user", "content": prompt}]
|
||||
for prompt in _build_gsm8k_prompts(
|
||||
num_questions=num_gsm8k_prompts, num_shots=5
|
||||
)[0]
|
||||
)
|
||||
for _ in range(num_mm_prompts):
|
||||
placeholders = [
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"{VLLM_S3_BUCKET_URL}/{VLM_IMAGES_DIR}/stop_sign.jpg"
|
||||
},
|
||||
}
|
||||
]
|
||||
prompt = [
|
||||
*placeholders,
|
||||
{"type": "text", "text": "The meaning of the image is"},
|
||||
]
|
||||
prompts.append([{"role": "user", "content": prompt}])
|
||||
|
||||
return prompts
|
||||
|
||||
|
||||
def get_instruct_coder_messages(n: int) -> list[Messages]:
|
||||
from vllm.benchmarks.datasets import InstructCoderDataset
|
||||
|
||||
dataset = InstructCoderDataset(
|
||||
dataset_path="likaixin/InstructCoder", dataset_split="train"
|
||||
)
|
||||
prompts: Iterable[str] = dataset.sample_prompts(n=n)
|
||||
return [[{"role": "user", "content": prompt}] for prompt in prompts]
|
||||
|
||||
|
||||
def greedy_sampling() -> SamplingParams:
|
||||
return SamplingParams(temperature=0, max_tokens=10, ignore_eos=False)
|
||||
|
||||
|
||||
def stochastic_sampling() -> SamplingParams:
|
||||
return SamplingParams(temperature=1.0, max_tokens=10, ignore_eos=False)
|
||||
|
||||
|
||||
def evaluate_llm_for_gsm8k(llm: LLM, expected_accuracy_threshold: float = 0.70) -> None:
|
||||
"""Evaluate the LLM on GSM8K and check that accuracy is above a sanity threshold.
|
||||
|
||||
The default threshold assumes the LLM uses the same target model as the "model_name"
|
||||
fixture, with max model len == 4096. Precomputed reference value is 75% to 80%
|
||||
on GSM8K with greedy decoding, so we check that it's above a sanity threshold of 70%
|
||||
to verify that the model is correct.
|
||||
"""
|
||||
if expected_accuracy_threshold <= 0.0:
|
||||
print("Skipping GSM8K evaluation")
|
||||
return
|
||||
results = evaluate_gsm8k_offline(llm)
|
||||
accuracy = results["accuracy"]
|
||||
print(f"GSM8K accuracy: {accuracy:.3f}")
|
||||
assert accuracy >= expected_accuracy_threshold, (
|
||||
f"Expected GSM8K accuracy >= {expected_accuracy_threshold}, got {accuracy:.3f}"
|
||||
)
|
||||
|
||||
|
||||
def assert_request_outputs_match(
|
||||
ref_outputs: Sequence[RequestOutput],
|
||||
spec_outputs: Sequence[RequestOutput],
|
||||
*,
|
||||
required_matches: int,
|
||||
context: str,
|
||||
max_mismatches: int = 3,
|
||||
) -> None:
|
||||
"""Assert a thresholded exact-text match with bounded failure diagnostics."""
|
||||
assert ref_outputs, f"{context}: no reference outputs"
|
||||
assert len(ref_outputs) == len(spec_outputs), (
|
||||
f"{context}: output count differs: "
|
||||
f"reference={len(ref_outputs)}, speculative={len(spec_outputs)}"
|
||||
)
|
||||
assert 0 <= required_matches <= len(ref_outputs), (
|
||||
f"{context}: invalid required_matches={required_matches} for "
|
||||
f"{len(ref_outputs)} outputs"
|
||||
)
|
||||
|
||||
mismatches: list[str] = []
|
||||
matches = 0
|
||||
for index, (ref_output, spec_output) in enumerate(zip(ref_outputs, spec_outputs)):
|
||||
assert ref_output.outputs, (
|
||||
f"{context}: reference output {index} has no candidate"
|
||||
)
|
||||
assert spec_output.outputs, (
|
||||
f"{context}: speculative output {index} has no candidate"
|
||||
)
|
||||
ref_candidate = ref_output.outputs[0]
|
||||
spec_candidate = spec_output.outputs[0]
|
||||
if ref_candidate.text == spec_candidate.text:
|
||||
matches += 1
|
||||
elif len(mismatches) < max_mismatches:
|
||||
mismatches.append(
|
||||
f"[{index}] ref_text={ref_candidate.text[:240]!r}, "
|
||||
f"spec_text={spec_candidate.text[:240]!r}\n"
|
||||
f" ref_token_ids={list(ref_candidate.token_ids)[:64]}\n"
|
||||
f" spec_token_ids={list(spec_candidate.token_ids)[:64]}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"{context}: exact text matches={matches}/{len(ref_outputs)} "
|
||||
f"(required={required_matches})"
|
||||
)
|
||||
mismatch_summary = "\n".join(mismatches) or "no mismatches captured"
|
||||
assert matches >= required_matches, (
|
||||
f"{context}: only {matches}/{len(ref_outputs)} outputs matched; "
|
||||
f"required at least {required_matches}. First mismatches:\n"
|
||||
f"{mismatch_summary}"
|
||||
)
|
||||
|
||||
|
||||
def get_spec_decode_metric_value(metrics: Sequence[Metric], metric_name: str) -> float:
|
||||
"""Get a spec-decode metric with an actionable error when stats are absent."""
|
||||
name2metric = {metric.name: metric for metric in metrics}
|
||||
metric = name2metric.get(metric_name)
|
||||
assert metric is not None, (
|
||||
f"Missing metric {metric_name!r}. Ensure disable_log_stats=False. "
|
||||
"Available spec-decode metrics: "
|
||||
f"{sorted(name for name in name2metric if 'spec_decode' in name) or ['<none>']}"
|
||||
)
|
||||
return float(metric.value)
|
||||
|
||||
|
||||
def compute_acceptance_rate(
|
||||
metrics: list[Metric], prev_metrics: list[Metric] | None = None
|
||||
) -> float:
|
||||
n_draft_toks = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_draft_tokens"
|
||||
)
|
||||
if n_draft_toks == 0:
|
||||
return float("nan")
|
||||
n_accepted_toks = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
if prev_metrics is not None:
|
||||
n_draft_toks -= get_spec_decode_metric_value(
|
||||
prev_metrics, "vllm:spec_decode_num_draft_tokens"
|
||||
)
|
||||
n_accepted_toks -= get_spec_decode_metric_value(
|
||||
prev_metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
if n_draft_toks <= 0:
|
||||
return float("nan")
|
||||
return n_accepted_toks / n_draft_toks
|
||||
|
||||
|
||||
def compute_acceptance_len(
|
||||
metrics: list[Metric], prev_metrics: list[Metric] | None = None
|
||||
) -> float:
|
||||
n_drafts = get_spec_decode_metric_value(metrics, "vllm:spec_decode_num_drafts")
|
||||
n_accepted_toks = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
if n_drafts == 0:
|
||||
return 1
|
||||
if prev_metrics is not None:
|
||||
n_drafts -= get_spec_decode_metric_value(
|
||||
prev_metrics, "vllm:spec_decode_num_drafts"
|
||||
)
|
||||
n_accepted_toks -= get_spec_decode_metric_value(
|
||||
prev_metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
if n_drafts <= 0:
|
||||
return 1
|
||||
return 1 + (n_accepted_toks / n_drafts)
|
||||
@@ -1,121 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Predictable dummy model for testing extract_hidden_states.
|
||||
|
||||
Subclasses LlamaForCausalLM but overrides the model to produce deterministic
|
||||
hidden states: layer i outputs values equal to (i).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.models.interfaces import EagleModelMixin
|
||||
from vllm.model_executor.models.llama import LlamaForCausalLM
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
|
||||
class PredictableLlamaModel(nn.Module, EagleModelMixin):
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
self.config = vllm_config.model_config.hf_config
|
||||
|
||||
# Create minimal embed_tokens for embedding
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(
|
||||
self.config.vocab_size,
|
||||
self.config.hidden_size,
|
||||
)
|
||||
|
||||
# Required for pipeline parallelism
|
||||
from vllm.model_executor.models.utils import (
|
||||
make_empty_intermediate_tensors_factory,
|
||||
)
|
||||
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states", "residual"], self.config.hidden_size
|
||||
)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Embed input IDs."""
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**extra_layer_kwargs,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
|
||||
"""Forward pass that produces predictable outputs.
|
||||
|
||||
Returns:
|
||||
If aux_hidden_state_layers is set: (hidden_states, aux_hidden_states)
|
||||
Otherwise: hidden_states
|
||||
|
||||
"""
|
||||
# Determine sequence length
|
||||
if inputs_embeds is not None:
|
||||
seq_len = inputs_embeds.shape[0]
|
||||
device = inputs_embeds.device
|
||||
elif input_ids is not None:
|
||||
seq_len = input_ids.shape[0] if input_ids.ndim == 1 else input_ids.shape[-1]
|
||||
device = input_ids.device
|
||||
else:
|
||||
raise ValueError("Either input_ids or inputs_embeds must be provided")
|
||||
|
||||
# Final hidden states (last layer value)
|
||||
hidden_states = torch.full(
|
||||
(seq_len, self.config.hidden_size),
|
||||
fill_value=float(self.config.num_hidden_layers),
|
||||
device=device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
# Check if we need auxiliary hidden states
|
||||
if len(self.aux_hidden_state_layers) > 0:
|
||||
aux_hidden_states = []
|
||||
for layer_idx in self.aux_hidden_state_layers:
|
||||
# Fill with (layer_idx) for predictability
|
||||
layer_hidden = torch.full(
|
||||
(seq_len, self.config.hidden_size),
|
||||
fill_value=float(layer_idx),
|
||||
device=device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
aux_hidden_states.append(layer_hidden)
|
||||
|
||||
return hidden_states, aux_hidden_states
|
||||
|
||||
return hidden_states
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Skip weight loading."""
|
||||
return set()
|
||||
|
||||
|
||||
class PredictableLlamaForCausalLM(LlamaForCausalLM):
|
||||
"""Predictable Llama model for testing.
|
||||
|
||||
Overrides _init_model to use PredictableLlamaModel instead of LlamaModel.
|
||||
"""
|
||||
|
||||
def _init_model(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
prefix: str = "",
|
||||
layer_type: type[nn.Module] | None = None,
|
||||
):
|
||||
"""Initialize with predictable model."""
|
||||
return PredictableLlamaModel(vllm_config=vllm_config, prefix=prefix)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Skip weight loading for dummy model."""
|
||||
return set()
|
||||
@@ -1,235 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NixlConnector PD + speculative decoding acceptance length test.
|
||||
|
||||
- Loads MT-Bench prompts (80 prompts, 256 output tokens)
|
||||
- Sends through the PD proxy (completions API)
|
||||
- Scrapes Prometheus metrics from the decode server
|
||||
- Asserts acceptance metrics match standalone baselines
|
||||
|
||||
Supports EAGLE3 (default) and MTP, selected via SD_METHOD env var.
|
||||
|
||||
Environment variables (set by spec_decode_acceptance_test.sh):
|
||||
TEST_MODEL - target model name
|
||||
DECODE_PORT - port of the decode vLLM server (for /metrics)
|
||||
SD_METHOD - "eagle3" (default) or "mtp"
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from urllib.request import urlopen
|
||||
|
||||
import openai
|
||||
import regex as re
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm.benchmarks.datasets import get_samples
|
||||
|
||||
SERVER_HOST = os.environ.get("SERVER_HOST", "127.0.0.1")
|
||||
PROXY_BASE_URL = f"http://{SERVER_HOST}:8192/v1"
|
||||
DECODE_PORT = os.environ.get("DECODE_PORT", "8200")
|
||||
MODEL_NAME = os.environ.get("TEST_MODEL", "meta-llama/Llama-3.1-8B-Instruct")
|
||||
SD_METHOD = os.environ.get("SD_METHOD", "eagle3").lower()
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModelConfig:
|
||||
model: str
|
||||
method: str
|
||||
expected_acceptance_length: float
|
||||
drafter: str = ""
|
||||
expected_acceptance_lengths_per_pos: list[float] = field(default_factory=list)
|
||||
expected_acceptance_rate: float | None = None
|
||||
id: str = ""
|
||||
rtol: float | None = None
|
||||
|
||||
|
||||
# Standalone baselines (MT-Bench, 80 prompts, 256 tokens, temp=0).
|
||||
# EAGLE3 source: tests/v1/spec_decode/test_acceptance_length.py
|
||||
MODEL_CONFIGS = [
|
||||
ModelConfig(
|
||||
model="meta-llama/Llama-3.1-8B-Instruct",
|
||||
method="eagle3",
|
||||
drafter="RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3",
|
||||
expected_acceptance_length=2.60,
|
||||
expected_acceptance_lengths_per_pos=[0.7296, 0.5208, 0.3545],
|
||||
id="llama3-8b-eagle3",
|
||||
),
|
||||
ModelConfig(
|
||||
model="Qwen/Qwen3.5-0.8B-Base",
|
||||
method="mtp",
|
||||
expected_acceptance_length=1.798,
|
||||
id="qwen35-0.8b-mtp",
|
||||
),
|
||||
]
|
||||
|
||||
DEFAULT_NUM_PROMPTS = 80
|
||||
DEFAULT_OUTPUT_LEN = 256
|
||||
DEFAULT_RTOL = 0.05
|
||||
|
||||
|
||||
def _get_model_config() -> ModelConfig:
|
||||
"""Get the model config matching MODEL_NAME and SD_METHOD."""
|
||||
for config in MODEL_CONFIGS:
|
||||
if config.model == MODEL_NAME and config.method == SD_METHOD:
|
||||
return config
|
||||
raise ValueError(
|
||||
f"No config for model={MODEL_NAME}, method={SD_METHOD}. "
|
||||
f"Available: {[(c.model, c.method) for c in MODEL_CONFIGS]}"
|
||||
)
|
||||
|
||||
|
||||
def _get_mt_bench_prompts() -> list[str]:
|
||||
"""Load MT-Bench prompts via vllm.benchmarks.datasets.get_samples."""
|
||||
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
||||
args = SimpleNamespace(
|
||||
dataset_name="hf",
|
||||
dataset_path="philschmid/mt-bench",
|
||||
num_prompts=DEFAULT_NUM_PROMPTS,
|
||||
seed=42,
|
||||
no_oversample=False,
|
||||
endpoint_type="openai-chat",
|
||||
backend="openai-chat",
|
||||
input_len=None,
|
||||
output_len=DEFAULT_OUTPUT_LEN,
|
||||
sharegpt_output_len=DEFAULT_OUTPUT_LEN,
|
||||
hf_name=None,
|
||||
hf_split="train",
|
||||
hf_subset=None,
|
||||
hf_output_len=DEFAULT_OUTPUT_LEN,
|
||||
no_stream=True,
|
||||
disable_shuffle=False,
|
||||
skip_chat_template=False,
|
||||
trust_remote_code=False,
|
||||
enable_multimodal_chat=False,
|
||||
request_id_prefix="",
|
||||
)
|
||||
samples = get_samples(args, tokenizer)
|
||||
return [sample.prompt for sample in samples]
|
||||
|
||||
|
||||
def _fetch_metric(metric_name: str) -> float:
|
||||
"""Fetch a single counter metric from the decode server's /metrics."""
|
||||
url = f"http://{SERVER_HOST}:{DECODE_PORT}/metrics"
|
||||
body = urlopen(url).read().decode()
|
||||
for line in body.split("\n"):
|
||||
if line.startswith(metric_name + "{") or line.startswith(metric_name + " "):
|
||||
return float(line.rsplit(" ", 1)[-1])
|
||||
raise ValueError(f"Metric {metric_name} not found in decode /metrics")
|
||||
|
||||
|
||||
def _fetch_per_position_acceptance() -> dict[int, float]:
|
||||
"""Fetch per-position acceptance counts from decode /metrics."""
|
||||
url = f"http://{SERVER_HOST}:{DECODE_PORT}/metrics"
|
||||
body = urlopen(url).read().decode()
|
||||
counts: dict[int, float] = {}
|
||||
for line in body.split("\n"):
|
||||
if (
|
||||
"spec_decode_num_accepted_tokens_per_pos_total" in line
|
||||
and not line.startswith("#")
|
||||
):
|
||||
m = re.search(r'position="(\d+)"', line)
|
||||
if m:
|
||||
counts[int(m.group(1))] = float(line.rsplit(" ", 1)[-1])
|
||||
return counts
|
||||
|
||||
|
||||
def test_spec_decode_acceptance_length():
|
||||
"""Validate PD+SD acceptance length against standalone baseline.
|
||||
|
||||
Sends MT-Bench prompts through the PD proxy (completions API),
|
||||
then checks that the decode server's speculative decoding metrics
|
||||
match the known standalone baselines.
|
||||
"""
|
||||
config = _get_model_config()
|
||||
rtol = config.rtol if config.rtol is not None else DEFAULT_RTOL
|
||||
|
||||
prompts = _get_mt_bench_prompts()
|
||||
assert len(prompts) == DEFAULT_NUM_PROMPTS, (
|
||||
f"Expected {DEFAULT_NUM_PROMPTS} prompts, got {len(prompts)}"
|
||||
)
|
||||
|
||||
client = openai.OpenAI(api_key="EMPTY", base_url=PROXY_BASE_URL)
|
||||
for i, prompt in enumerate(prompts):
|
||||
resp = client.completions.create(
|
||||
model=MODEL_NAME,
|
||||
prompt=prompt,
|
||||
max_tokens=DEFAULT_OUTPUT_LEN,
|
||||
temperature=0.0,
|
||||
top_p=1.0,
|
||||
# Prompts are already chat-templated (contain BOS); avoid the
|
||||
# completions API prepending a second BOS, which would lower
|
||||
# acceptance ~5% vs the add_special_tokens=False standalone baselines.
|
||||
extra_body={"add_special_tokens": False},
|
||||
)
|
||||
if i < 3:
|
||||
text = resp.choices[0].text.strip()[:100]
|
||||
print(f" [{i}] {prompt[:60]}... -> {text}...")
|
||||
|
||||
# ── Extract metrics from decode server ────────────────────────────
|
||||
n_drafts = _fetch_metric("vllm:spec_decode_num_drafts_total")
|
||||
n_accepted = _fetch_metric("vllm:spec_decode_num_accepted_tokens_total")
|
||||
|
||||
assert n_drafts > 0, "No spec-decode drafts were generated"
|
||||
|
||||
acceptance_length = 1 + (n_accepted / n_drafts)
|
||||
expected = config.expected_acceptance_length
|
||||
|
||||
print(
|
||||
f"\n{config.id}: acceptance_length={acceptance_length:.3f} "
|
||||
f"(expected={expected:.3f})"
|
||||
)
|
||||
print(f" Drafts: {n_drafts:.0f}, Accepted: {n_accepted:.0f}")
|
||||
|
||||
# ── Assert acceptance length (all methods) ────────────────────────
|
||||
rel_error = abs(acceptance_length - expected) / expected
|
||||
assert rel_error <= rtol, (
|
||||
f"Acceptance length regression for {config.id}! "
|
||||
f"Expected: {expected:.3f}, "
|
||||
f"Got: {acceptance_length:.3f}, "
|
||||
f"Relative error: {rel_error:.2%} (tolerance: {rtol:.0%})"
|
||||
)
|
||||
|
||||
# ── Assert per-position acceptance (EAGLE3) ───────────────────────
|
||||
if config.expected_acceptance_lengths_per_pos:
|
||||
per_pos_counts = _fetch_per_position_acceptance()
|
||||
per_pos_rates = [
|
||||
per_pos_counts.get(i, 0) / n_drafts
|
||||
for i in range(len(config.expected_acceptance_lengths_per_pos))
|
||||
]
|
||||
for i, (actual, exp) in enumerate(
|
||||
zip(per_pos_rates, config.expected_acceptance_lengths_per_pos)
|
||||
):
|
||||
print(f" Position {i}: {actual:.4f} (expected: {exp:.4f})")
|
||||
if exp > 0:
|
||||
pos_err = abs(actual - exp) / exp
|
||||
assert pos_err <= rtol, (
|
||||
f"Per-position regression at pos {i} for {config.id}! "
|
||||
f"Expected: {exp:.4f}, Got: {actual:.4f}, "
|
||||
f"Relative error: {pos_err:.2%} (tolerance: {rtol:.0%})"
|
||||
)
|
||||
|
||||
# ── Assert acceptance rate (MTP) ──────────────────────────────────
|
||||
if config.expected_acceptance_rate is not None:
|
||||
n_draft_tokens = _fetch_metric("vllm:spec_decode_num_draft_tokens_total")
|
||||
acceptance_rate = n_accepted / n_draft_tokens if n_draft_tokens > 0 else 0.0
|
||||
print(
|
||||
f" Acceptance rate: {acceptance_rate:.3f} "
|
||||
f"(expected: {config.expected_acceptance_rate:.3f})"
|
||||
)
|
||||
rate_err = (
|
||||
abs(acceptance_rate - config.expected_acceptance_rate)
|
||||
/ config.expected_acceptance_rate
|
||||
)
|
||||
assert rate_err <= rtol, (
|
||||
f"Acceptance rate regression for {config.id}! "
|
||||
f"Expected: {config.expected_acceptance_rate:.3f}, "
|
||||
f"Got: {acceptance_rate:.3f}, "
|
||||
f"Relative error: {rate_err:.2%} (tolerance: {rtol:.0%})"
|
||||
)
|
||||
|
||||
print(
|
||||
f"\n=== PASS: {config.id} acceptance length {acceptance_length:.3f} "
|
||||
f"within {rtol:.0%} of {expected:.3f} ==="
|
||||
)
|
||||
@@ -1,27 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _mock_cpu_backend_block_sizes(monkeypatch):
|
||||
"""Mock the CPU attention backend's kernel block-size declaration.
|
||||
|
||||
Connector unit tests exercise transfer logic, never the attention
|
||||
kernel, and hard-code block_size=16. On CPU-only machines
|
||||
`CPUAttentionBackend` declares `MultipleOf(32)` (#54042), so every
|
||||
worker construction would fail in `select_common_block_size` before
|
||||
reaching the code under test.
|
||||
"""
|
||||
if not current_platform.is_cpu():
|
||||
return
|
||||
from vllm.v1.attention.backend import MultipleOf
|
||||
from vllm.v1.attention.backends.cpu_attn import CPUAttentionBackend
|
||||
|
||||
monkeypatch.setattr(
|
||||
CPUAttentionBackend,
|
||||
"get_supported_kernel_block_sizes",
|
||||
staticmethod(lambda kv_cache_spec=None: [MultipleOf(16)]),
|
||||
)
|
||||
@@ -1,682 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.common import (
|
||||
OffloadingConnectorMetadata,
|
||||
TransferJob,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import get_dtype_size
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheTensor,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.kv_offload.base import (
|
||||
CanonicalKVCacheRef,
|
||||
CanonicalKVCaches,
|
||||
GPULoadStoreSpec,
|
||||
LoadStoreSpec,
|
||||
OffloadingManager,
|
||||
OffloadingSpec,
|
||||
OffloadingWorker,
|
||||
)
|
||||
from vllm.v1.kv_offload.config import (
|
||||
OffloadingCacheConfig,
|
||||
OffloadingConfig,
|
||||
OffloadingModelConfig,
|
||||
OffloadingParallelConfig,
|
||||
)
|
||||
|
||||
NUM_BLOCKS = 10
|
||||
BLOCK_SIZE = 16
|
||||
NUM_KV_HEADS = 4
|
||||
HEAD_SIZE = 64
|
||||
DTYPE = torch.float16
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
# Attention backends to test
|
||||
ATTN_BACKENDS: list[str] = []
|
||||
if current_platform.is_cuda():
|
||||
ATTN_BACKENDS = [
|
||||
"FLASH_ATTN",
|
||||
"FLEX_ATTENTION",
|
||||
"FLASHINFER",
|
||||
"TRITON_ATTN",
|
||||
]
|
||||
elif current_platform.is_rocm():
|
||||
ATTN_BACKENDS = ["TRITON_ATTN"]
|
||||
elif current_platform.is_xpu():
|
||||
ATTN_BACKENDS = ["TRITON_ATTN", "FLASH_ATTN"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _allocate_kv_caches(
|
||||
kv_cache_config: KVCacheConfig,
|
||||
attn_groups: list[list],
|
||||
device: torch.device,
|
||||
):
|
||||
"""Allocate kv_caches exactly as the model runner does at startup."""
|
||||
from vllm.v1.worker.utils import allocate_kv_cache
|
||||
|
||||
kernel_block_sizes = [BLOCK_SIZE] * len(kv_cache_config.kv_cache_groups)
|
||||
return allocate_kv_cache(
|
||||
kv_cache_config, device, KVCacheLayout.LBNHC, kernel_block_sizes
|
||||
)
|
||||
|
||||
|
||||
def _single_rank_vllm_config(total_kv_heads: int):
|
||||
"""A one-rank (TP=1) parallel config, as canonical mappings are derived
|
||||
from it."""
|
||||
vllm_config = MagicMock()
|
||||
parallel_config = vllm_config.parallel_config
|
||||
parallel_config.tensor_parallel_size = 1
|
||||
parallel_config.decode_context_parallel_size = 1
|
||||
parallel_config.prefill_context_parallel_size = 1
|
||||
parallel_config.cp_kv_cache_interleave_size = 1
|
||||
parallel_config.world_size = 1
|
||||
parallel_config.rank = 0
|
||||
vllm_config.model_config.get_total_num_kv_heads.return_value = total_kv_heads
|
||||
return vllm_config
|
||||
|
||||
|
||||
def _make_worker(
|
||||
kv_cache_config: KVCacheConfig,
|
||||
replicated_layout: bool = False,
|
||||
rank: int = 0,
|
||||
canonical_layout: bool = False,
|
||||
):
|
||||
"""Create an OffloadingConnectorWorker with mocked dependencies."""
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.worker import (
|
||||
OffloadingConnectorWorker,
|
||||
)
|
||||
|
||||
spec = MagicMock(spec=OffloadingSpec)
|
||||
spec.replicated_layout = replicated_layout
|
||||
spec.config = MagicMock()
|
||||
spec.config.canonical_layout = canonical_layout
|
||||
spec.config.parallel.rank = rank
|
||||
spec.get_worker.return_value = MagicMock()
|
||||
|
||||
worker = OffloadingConnectorWorker(
|
||||
spec=spec,
|
||||
vllm_config=_single_rank_vllm_config(NUM_KV_HEADS),
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
worker.worker = MagicMock()
|
||||
|
||||
return worker, spec
|
||||
|
||||
|
||||
def _store_metadata(job_id: int) -> OffloadingConnectorMetadata:
|
||||
return OffloadingConnectorMetadata(
|
||||
load_jobs={},
|
||||
store_jobs={
|
||||
job_id: TransferJob(
|
||||
req_id="req",
|
||||
src_spec=GPULoadStoreSpec([0], group_sizes=(1,), block_indices=(0,)),
|
||||
dst_spec=LoadStoreSpec(),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _load_metadata(job_id: int) -> OffloadingConnectorMetadata:
|
||||
return OffloadingConnectorMetadata(
|
||||
load_jobs={
|
||||
job_id: TransferJob(
|
||||
req_id="req",
|
||||
src_spec=LoadStoreSpec(),
|
||||
dst_spec=GPULoadStoreSpec([0], group_sizes=(1,), block_indices=(0,)),
|
||||
)
|
||||
},
|
||||
store_jobs={},
|
||||
)
|
||||
|
||||
|
||||
def _empty_metadata() -> OffloadingConnectorMetadata:
|
||||
return OffloadingConnectorMetadata(load_jobs={}, store_jobs={})
|
||||
|
||||
|
||||
def _offloading_config(rank: int = 0) -> OffloadingConfig:
|
||||
return OffloadingConfig(
|
||||
groups=(),
|
||||
worker_kv_bytes_per_block=0,
|
||||
enable_kv_cache_events=False,
|
||||
extra_config={},
|
||||
engine_id="test-engine",
|
||||
model=OffloadingModelConfig(name="test-model", dtype="float16"),
|
||||
cache=OffloadingCacheConfig(tokens_per_hash=16, blocks_per_chunk=1),
|
||||
parallel=OffloadingParallelConfig(
|
||||
rank=rank,
|
||||
world_size=2,
|
||||
tp_size=2,
|
||||
pp_size=1,
|
||||
pcp_size=1,
|
||||
dcp_size=1,
|
||||
data_parallel_index=0,
|
||||
data_parallel_size=1,
|
||||
data_parallel_rank_local=None,
|
||||
is_parallelism_agnostic=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class BareExternalOffloadingSpec(OffloadingSpec):
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
raise NotImplementedError
|
||||
|
||||
def get_worker(self, kv_caches: CanonicalKVCaches) -> OffloadingWorker:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_prepare_store_kv_non_writer_marks_completed_without_submit():
|
||||
worker, _ = _make_worker(
|
||||
KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]),
|
||||
replicated_layout=True,
|
||||
rank=1,
|
||||
)
|
||||
|
||||
worker.prepare_store_kv(_store_metadata(7))
|
||||
worker.start_kv_transfers(_empty_metadata())
|
||||
|
||||
assert worker._unsubmitted_store_jobs == []
|
||||
assert worker.worker is not None
|
||||
worker.worker.submit_store.assert_not_called()
|
||||
meta = worker.build_connector_worker_meta()
|
||||
assert meta is not None
|
||||
assert meta.completed_jobs == {7: 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank,canonical_layout", [(0, False), (0, True), (1, True)])
|
||||
def test_prepare_store_kv_writer_submits_store(rank, canonical_layout):
|
||||
worker, _ = _make_worker(
|
||||
KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]),
|
||||
replicated_layout=True,
|
||||
rank=rank,
|
||||
canonical_layout=canonical_layout,
|
||||
)
|
||||
|
||||
worker.prepare_store_kv(_store_metadata(8))
|
||||
assert worker.build_connector_worker_meta() is None
|
||||
worker.start_kv_transfers(_empty_metadata())
|
||||
|
||||
assert worker.worker is not None
|
||||
worker.worker.submit_store.assert_called_once()
|
||||
|
||||
|
||||
def test_prepare_store_kv_non_replicated_rank_gt_zero_queues_store():
|
||||
worker, _ = _make_worker(
|
||||
KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]),
|
||||
replicated_layout=False,
|
||||
rank=1,
|
||||
)
|
||||
|
||||
worker.prepare_store_kv(_store_metadata(9))
|
||||
assert worker.build_connector_worker_meta() is None
|
||||
assert len(worker._unsubmitted_store_jobs) == 1
|
||||
|
||||
worker.start_kv_transfers(_empty_metadata())
|
||||
|
||||
assert worker.worker is not None
|
||||
worker.worker.submit_store.assert_called_once()
|
||||
assert worker._unsubmitted_store_jobs == []
|
||||
|
||||
|
||||
def test_handle_preemptions_non_writer_acks_flushed_store():
|
||||
worker, _ = _make_worker(
|
||||
KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]),
|
||||
replicated_layout=True,
|
||||
rank=1,
|
||||
)
|
||||
metadata = _store_metadata(10)
|
||||
metadata.jobs_to_flush = {10}
|
||||
|
||||
worker.handle_preemptions(metadata)
|
||||
|
||||
assert worker.worker is not None
|
||||
worker.worker.submit_store.assert_not_called()
|
||||
worker.worker.wait.assert_called_once_with({10})
|
||||
assert metadata.store_jobs == {}
|
||||
meta = worker.build_connector_worker_meta()
|
||||
assert meta is not None
|
||||
assert meta.completed_jobs == {10: 1}
|
||||
|
||||
|
||||
def test_start_kv_transfers_non_writer_still_submits_load():
|
||||
worker, _ = _make_worker(
|
||||
KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]),
|
||||
replicated_layout=True,
|
||||
rank=1,
|
||||
)
|
||||
|
||||
worker.start_kv_transfers(_load_metadata(10))
|
||||
|
||||
assert worker.worker is not None
|
||||
worker.worker.submit_load.assert_called_once()
|
||||
assert worker.build_connector_worker_meta() is None
|
||||
|
||||
|
||||
def test_offloading_connector_worker_accepts_plugin_spec_default_layout():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.worker import (
|
||||
OffloadingConnectorWorker,
|
||||
)
|
||||
|
||||
spec = BareExternalOffloadingSpec(_offloading_config(rank=1))
|
||||
|
||||
OffloadingConnectorWorker(
|
||||
spec=spec,
|
||||
vllm_config=_single_rank_vllm_config(NUM_KV_HEADS),
|
||||
kv_cache_config=KVCacheConfig(
|
||||
num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]
|
||||
),
|
||||
)
|
||||
|
||||
assert spec.replicated_layout is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend", ATTN_BACKENDS)
|
||||
def test_register_kv_caches(backend):
|
||||
"""Test register_kv_caches with multiple groups covering all layer types.
|
||||
|
||||
Creates one FullAttention group, one MLA group, one Mamba group, and
|
||||
one Mamba-padded group. Each group has GROUP_SIZE layers.
|
||||
|
||||
KVCacheTensors mirror the real allocation in kv_cache_utils.py: each group is one
|
||||
run of the shared allocation starting at offset 0, so layer i of every group
|
||||
aliases the same bytes.
|
||||
|
||||
Uses the real GPUModelRunner.initialize_kv_cache_tensors to produce
|
||||
the raw per-layer kv_caches registered by the connector.
|
||||
|
||||
Verifies that the canonicalized CanonicalKVCaches has the correct
|
||||
block tensors, tensor_idx references, and page sizes across all groups.
|
||||
"""
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
DeepseekV32IndexerBackend,
|
||||
)
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
MLA_HEAD_SIZE = NUM_KV_HEADS * HEAD_SIZE * 2
|
||||
|
||||
# padded mamba (missing HEAD_SIZE)
|
||||
CONV_STATE_SHAPE = (BLOCK_SIZE * NUM_KV_HEADS, HEAD_SIZE)
|
||||
UNALIGNED_SSM_STATE_SHAPE = (BLOCK_SIZE * NUM_KV_HEADS - 1, HEAD_SIZE)
|
||||
|
||||
PAGE_SIZE_BYTES = 2 * BLOCK_SIZE * NUM_KV_HEADS * HEAD_SIZE * get_dtype_size(DTYPE)
|
||||
unaligned_mamba_page_size = PAGE_SIZE_BYTES - HEAD_SIZE * get_dtype_size(DTYPE)
|
||||
|
||||
# unpadded mamba (fills page exactly)
|
||||
ALIGNED_SSM_STATE_SHAPE = (BLOCK_SIZE * NUM_KV_HEADS, HEAD_SIZE)
|
||||
|
||||
backend_cls = AttentionBackendEnum[backend].get_class()
|
||||
|
||||
attn_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
mla_spec = MLAAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=1,
|
||||
head_size=MLA_HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
unaligned_mamba_spec = MambaSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
shapes=(CONV_STATE_SHAPE, UNALIGNED_SSM_STATE_SHAPE),
|
||||
dtypes=(DTYPE, DTYPE),
|
||||
page_size_padded=PAGE_SIZE_BYTES,
|
||||
)
|
||||
aligned_mamba_spec = MambaSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
shapes=(CONV_STATE_SHAPE, ALIGNED_SSM_STATE_SHAPE),
|
||||
dtypes=(DTYPE, DTYPE),
|
||||
page_size_padded=PAGE_SIZE_BYTES,
|
||||
)
|
||||
|
||||
assert attn_spec.page_size_bytes == PAGE_SIZE_BYTES
|
||||
assert mla_spec.page_size_bytes == PAGE_SIZE_BYTES
|
||||
assert unaligned_mamba_spec.page_size_bytes == PAGE_SIZE_BYTES
|
||||
assert aligned_mamba_spec.page_size_bytes == PAGE_SIZE_BYTES
|
||||
|
||||
GROUP_SIZE = 3
|
||||
|
||||
# -- Build per-group layer info ----------------------------------------
|
||||
layer_idx = 0
|
||||
|
||||
attn_layer_names = []
|
||||
for _ in range(GROUP_SIZE):
|
||||
attn_layer_names.append(f"model.layers.{layer_idx}.self_attn")
|
||||
layer_idx += 1
|
||||
|
||||
mla_layer_names = []
|
||||
for _ in range(GROUP_SIZE):
|
||||
mla_layer_names.append(f"model.layers.{layer_idx}.self_attn")
|
||||
layer_idx += 1
|
||||
|
||||
unaligned_mamba_layer_names = []
|
||||
for _ in range(GROUP_SIZE):
|
||||
unaligned_mamba_layer_names.append(f"model.layers.{layer_idx}.mamba_unpadded")
|
||||
layer_idx += 1
|
||||
|
||||
aligned_mamba_layer_names = []
|
||||
for _ in range(GROUP_SIZE - 1):
|
||||
aligned_mamba_layer_names.append(f"model.layers.{layer_idx}.mamba_padded")
|
||||
layer_idx += 1
|
||||
|
||||
layer_groups = [
|
||||
attn_layer_names,
|
||||
mla_layer_names,
|
||||
unaligned_mamba_layer_names,
|
||||
aligned_mamba_layer_names,
|
||||
]
|
||||
|
||||
kv_cache_tensors: list[KVCacheTensor] = [
|
||||
KVCacheTensor(
|
||||
size=PAGE_SIZE_BYTES * NUM_BLOCKS * GROUP_SIZE,
|
||||
layers=group_layer_names,
|
||||
layer_stride=PAGE_SIZE_BYTES * NUM_BLOCKS,
|
||||
block_stride=PAGE_SIZE_BYTES,
|
||||
)
|
||||
for group_layer_names in layer_groups
|
||||
]
|
||||
|
||||
kv_cache_groups = [
|
||||
KVCacheGroupSpec(layer_names=attn_layer_names, kv_cache_spec=attn_spec),
|
||||
KVCacheGroupSpec(layer_names=mla_layer_names, kv_cache_spec=mla_spec),
|
||||
KVCacheGroupSpec(
|
||||
layer_names=unaligned_mamba_layer_names, kv_cache_spec=unaligned_mamba_spec
|
||||
),
|
||||
KVCacheGroupSpec(
|
||||
layer_names=aligned_mamba_layer_names, kv_cache_spec=aligned_mamba_spec
|
||||
),
|
||||
]
|
||||
|
||||
attn_groups = [
|
||||
[
|
||||
AttentionGroup(
|
||||
backend=backend_cls,
|
||||
layer_names=attn_layer_names,
|
||||
kv_cache_spec=attn_spec,
|
||||
kv_cache_group_id=0,
|
||||
),
|
||||
AttentionGroup(
|
||||
backend=DeepseekV32IndexerBackend,
|
||||
layer_names=mla_layer_names,
|
||||
kv_cache_spec=mla_spec,
|
||||
kv_cache_group_id=1,
|
||||
),
|
||||
AttentionGroup(
|
||||
backend=DeepseekV32IndexerBackend, # unused for mamba
|
||||
layer_names=unaligned_mamba_layer_names,
|
||||
kv_cache_spec=unaligned_mamba_spec,
|
||||
kv_cache_group_id=2,
|
||||
),
|
||||
AttentionGroup(
|
||||
backend=DeepseekV32IndexerBackend, # unused for mamba
|
||||
layer_names=aligned_mamba_layer_names,
|
||||
kv_cache_spec=aligned_mamba_spec,
|
||||
kv_cache_group_id=3,
|
||||
),
|
||||
]
|
||||
]
|
||||
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=NUM_BLOCKS,
|
||||
kv_cache_tensors=kv_cache_tensors,
|
||||
kv_cache_groups=kv_cache_groups,
|
||||
)
|
||||
|
||||
kv_caches = _allocate_kv_caches(
|
||||
kv_cache_config,
|
||||
attn_groups,
|
||||
device=torch.device(f"{DEVICE_TYPE}:0"),
|
||||
)
|
||||
|
||||
worker, spec = _make_worker(kv_cache_config)
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
canonical = spec.get_worker.call_args[0][0]
|
||||
assert isinstance(canonical, CanonicalKVCaches)
|
||||
|
||||
# -- Expected block tensors ----------------------------------------------
|
||||
# All tensors have the same padded page size (PAGE_SIZE_BYTES).
|
||||
# Tensor 0: shared by attn[0], mla[0], mamba_unaligned[0], mamba_aligned[0]
|
||||
# Tensor 1: shared by attn[1], mla[1], mamba_unaligned[1], mamba_aligned[1]
|
||||
# Tensor 2: shared by attn[2], mla[2], mamba_unaligned[2]
|
||||
# (mamba_aligned has only GROUP_SIZE-1 = 2 layers)
|
||||
expected_tensors = [
|
||||
(NUM_BLOCKS, PAGE_SIZE_BYTES),
|
||||
(NUM_BLOCKS, PAGE_SIZE_BYTES),
|
||||
(NUM_BLOCKS, PAGE_SIZE_BYTES),
|
||||
]
|
||||
|
||||
# -- Expected group data refs (order matches kv_cache_groups) -------------
|
||||
ref = CanonicalKVCacheRef
|
||||
expected_group_refs = [
|
||||
# attn group: layers attn[0..2] → tensors 0,1,2 with full page size
|
||||
[
|
||||
ref(tensor_idx=0, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
ref(tensor_idx=1, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
ref(tensor_idx=2, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
],
|
||||
# mla group: layers mla[0..2] → tensors 0,1,2 with full page size
|
||||
[
|
||||
ref(tensor_idx=0, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
ref(tensor_idx=1, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
ref(tensor_idx=2, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
],
|
||||
# unaligned mamba group: layers [0..2] → tensors 0,1,2 with unaligned page
|
||||
[
|
||||
ref(tensor_idx=0, page_size_bytes=unaligned_mamba_page_size),
|
||||
ref(tensor_idx=1, page_size_bytes=unaligned_mamba_page_size),
|
||||
ref(tensor_idx=2, page_size_bytes=unaligned_mamba_page_size),
|
||||
],
|
||||
# aligned mamba group: layers [0..1] → tensors 0,1 with full page size
|
||||
[
|
||||
ref(tensor_idx=0, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
ref(tensor_idx=1, page_size_bytes=PAGE_SIZE_BYTES),
|
||||
],
|
||||
]
|
||||
|
||||
# Verify block tensors
|
||||
assert len(canonical.tensors) == len(expected_tensors)
|
||||
for block_tensor, (exp_num_blocks, exp_page_size) in zip(
|
||||
canonical.tensors, expected_tensors
|
||||
):
|
||||
tensor = block_tensor.tensor
|
||||
assert tensor.dtype == torch.int8
|
||||
assert tensor.shape == (exp_num_blocks, exp_page_size)
|
||||
assert block_tensor.page_size_bytes == exp_page_size
|
||||
|
||||
# Verify group data refs
|
||||
assert len(canonical.group_data_refs) == len(expected_group_refs)
|
||||
for actual_refs, exp_refs in zip(canonical.group_data_refs, expected_group_refs):
|
||||
assert len(actual_refs) == len(exp_refs)
|
||||
for actual, expected in zip(actual_refs, exp_refs):
|
||||
assert actual.tensor_idx == expected.tensor_idx
|
||||
assert actual.page_size_bytes == expected.page_size_bytes
|
||||
# Every layer gets a canonical mapping, certified or opaque
|
||||
assert actual.mapping is not None
|
||||
|
||||
|
||||
def test_register_packed_kv_caches_skips_scratch_group():
|
||||
attn_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
page = attn_spec.page_size_bytes
|
||||
layers = ["layer0", "layer1"]
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=NUM_BLOCKS,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=2 * page * NUM_BLOCKS,
|
||||
layers=layers,
|
||||
layer_stride=page,
|
||||
block_stride=2 * page,
|
||||
)
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(layers, attn_spec),
|
||||
KVCacheGroupSpec(
|
||||
["scratch"],
|
||||
CircularBufferSpec(
|
||||
block_size=4, num_kv_heads=1, head_size=1, dtype=DTYPE
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
kv_caches = _allocate_kv_caches(
|
||||
kv_cache_config, [], device=torch.device(f"{DEVICE_TYPE}:0")
|
||||
)
|
||||
worker, spec = _make_worker(kv_cache_config)
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
canonical = spec.get_worker.call_args[0][0]
|
||||
assert len(canonical.tensors) == 1
|
||||
assert canonical.tensors[0].tensor.shape == (NUM_BLOCKS, 2 * page)
|
||||
assert canonical.group_data_refs == [[CanonicalKVCacheRef(0, 2 * page)]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend", ATTN_BACKENDS)
|
||||
def test_register_kv_caches_uniform_type(backend):
|
||||
"""Test register_kv_caches with UniformTypeKVCacheSpecs.
|
||||
|
||||
Two attention layers use the same backend but different num_kv_heads,
|
||||
giving them different per-layer page sizes. Each has its own
|
||||
KVCacheTensor and are wrapped in a UniformTypeKVCacheSpecs group.
|
||||
Verifies that each layer gets the correct tensor_idx and
|
||||
page_size_bytes in its block data ref.
|
||||
"""
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
backend_cls = AttentionBackendEnum[backend].get_class()
|
||||
|
||||
layer_a = "model.layers.0.self_attn"
|
||||
layer_b = "model.layers.1.self_attn"
|
||||
spec_a = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
spec_b = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS * 2,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
assert spec_a.page_size_bytes != spec_b.page_size_bytes
|
||||
|
||||
uniform_spec = UniformTypeKVCacheSpecs(
|
||||
block_size=BLOCK_SIZE,
|
||||
kv_cache_specs={layer_a: spec_a, layer_b: spec_b},
|
||||
)
|
||||
|
||||
# The group packs its two layers densely, one run each as their pages differ:
|
||||
# layer_a occupies the first page of every block, layer_b the rest.
|
||||
window = spec_a.page_size_bytes + spec_b.page_size_bytes
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=NUM_BLOCKS,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=window * NUM_BLOCKS,
|
||||
layers=[layer_a],
|
||||
layer_stride=spec_a.page_size_bytes * NUM_BLOCKS,
|
||||
block_stride=spec_a.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=window * NUM_BLOCKS,
|
||||
layers=[layer_b],
|
||||
layer_stride=spec_b.page_size_bytes * NUM_BLOCKS,
|
||||
block_stride=spec_b.page_size_bytes,
|
||||
offset=spec_a.page_size_bytes * NUM_BLOCKS,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
layer_names=[layer_a, layer_b],
|
||||
kv_cache_spec=uniform_spec,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
attn_groups = [
|
||||
[
|
||||
AttentionGroup(
|
||||
backend=backend_cls,
|
||||
layer_names=[layer_a],
|
||||
kv_cache_spec=spec_a,
|
||||
kv_cache_group_id=0,
|
||||
),
|
||||
AttentionGroup(
|
||||
backend=backend_cls,
|
||||
layer_names=[layer_b],
|
||||
kv_cache_spec=spec_b,
|
||||
kv_cache_group_id=0,
|
||||
),
|
||||
]
|
||||
]
|
||||
|
||||
kv_caches = _allocate_kv_caches(
|
||||
kv_cache_config,
|
||||
attn_groups,
|
||||
device=torch.device(f"{DEVICE_TYPE}:0"),
|
||||
)
|
||||
|
||||
worker, spec = _make_worker(kv_cache_config)
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
canonical = spec.get_worker.call_args[0][0]
|
||||
assert isinstance(canonical, CanonicalKVCaches)
|
||||
|
||||
for block_tensor in canonical.tensors:
|
||||
assert block_tensor.tensor.dtype == torch.int8
|
||||
|
||||
# Single group with refs from both layers
|
||||
assert len(canonical.group_data_refs) == 1
|
||||
group_refs = canonical.group_data_refs[0]
|
||||
assert len(group_refs) == 2
|
||||
|
||||
assert len(canonical.tensors) == 2
|
||||
assert canonical.tensors[0].page_size_bytes == spec_a.page_size_bytes
|
||||
assert canonical.tensors[1].page_size_bytes == spec_b.page_size_bytes
|
||||
assert canonical.tensors[0].tensor.shape == (NUM_BLOCKS, spec_a.page_size_bytes)
|
||||
assert canonical.tensors[1].tensor.shape == (NUM_BLOCKS, spec_b.page_size_bytes)
|
||||
|
||||
for ref, expected_tensor_idx, expected_spec in (
|
||||
(group_refs[0], 0, spec_a),
|
||||
(group_refs[1], 1, spec_b),
|
||||
):
|
||||
assert ref.tensor_idx == expected_tensor_idx
|
||||
assert ref.page_size_bytes == expected_spec.page_size_bytes
|
||||
assert ref.mapping is not None
|
||||
|
||||
# Only layer_a matches the model's total KV head count, so layer_b gets an
|
||||
# opaque mapping rather than a certified, parallelism-agnostic one
|
||||
assert group_refs[0].mapping.parallelism_agnostic
|
||||
assert not group_refs[1].mapping.parallelism_agnostic
|
||||
@@ -1,534 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import ctypes
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.example_connector import (
|
||||
ExampleConnector,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse import (
|
||||
worker as worker_module,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.connector import (
|
||||
HiSparseConnector,
|
||||
HiSparseConnectorMetadata,
|
||||
HiSparseConnectorScheduler,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.worker import (
|
||||
HiSparseConnectorWorker,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector
|
||||
from vllm.v1.core.kv_cache_metrics import KVCacheMetricsCollector
|
||||
from vllm.v1.hisparse import runtime as runtime_module
|
||||
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
|
||||
from vllm.v1.hisparse.runtime import (
|
||||
HiSparseCacheHandle,
|
||||
update_hisparse_residency,
|
||||
)
|
||||
from vllm.v1.hisparse.types import (
|
||||
SparseKVOffloadCommand,
|
||||
SparseKVPageTransfer,
|
||||
SparseKVResidencyUpdate,
|
||||
SparseKVRowMirror,
|
||||
)
|
||||
from vllm.v1.metrics.stats import KVCacheEvictionEvent
|
||||
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nested", [False, True])
|
||||
def test_cache_manager_binding_preserves_hisparse_and_legacy_pool_hooks(nested):
|
||||
"""Composite binding must reach HiSparse and existing pool-only connectors."""
|
||||
hisparse = object.__new__(HiSparseConnector)
|
||||
hisparse._role = KVConnectorRole.SCHEDULER
|
||||
hisparse.connector_scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
legacy = object.__new__(ExampleConnector)
|
||||
legacy.bind_gpu_block_pool = MagicMock()
|
||||
connector = object.__new__(MultiConnector)
|
||||
connector._connectors = [hisparse, legacy]
|
||||
if nested:
|
||||
parent = object.__new__(MultiConnector)
|
||||
parent._connectors = [connector]
|
||||
connector = parent
|
||||
from tests.v1.core.test_prefix_caching import make_hisparse_kv_cache_manager
|
||||
|
||||
manager = make_hisparse_kv_cache_manager(16, 16)
|
||||
|
||||
connector.bind_kv_cache_manager(manager)
|
||||
|
||||
assert hisparse.connector_scheduler.coordinator is get_hisparse_coordinator(manager)
|
||||
legacy.bind_gpu_block_pool.assert_called_once_with(manager.block_pool)
|
||||
|
||||
|
||||
def test_hisparse_requires_block_outermost_device_layout():
|
||||
assert HiSparseConnector.get_required_kvcache_layout(MagicMock()) == "BLHNC"
|
||||
|
||||
|
||||
def test_scheduler_stats_report_host_pool_usage():
|
||||
"""The scheduler-side stats sample the coordinator's host pool level."""
|
||||
from tests.v1.core.test_prefix_caching import (
|
||||
HISPARSE_BLOCK_SIZE,
|
||||
make_hisparse_kv_cache_manager,
|
||||
make_request,
|
||||
sha256,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import init_none_hash
|
||||
|
||||
init_none_hash(sha256)
|
||||
|
||||
manager = make_hisparse_kv_cache_manager(32, host_num_blocks=8)
|
||||
scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
scheduler.bind_coordinator(get_hisparse_coordinator(manager))
|
||||
coordinator = scheduler.coordinator
|
||||
|
||||
stats = scheduler.get_kv_connector_stats()
|
||||
assert stats.data["host_cache_usage_perc"] == [0.0]
|
||||
assert stats.data["pending_page_transfers"] == [0]
|
||||
|
||||
request = make_request(
|
||||
"request", list(range(4 * HISPARSE_BLOCK_SIZE)), HISPARSE_BLOCK_SIZE, sha256
|
||||
)
|
||||
assert manager.allocate_slots(request, num_new_tokens=64) is not None
|
||||
host_blocks = coordinator.host_manager.req_to_blocks[request.request_id]
|
||||
num_used = sum(not block.is_null for block in host_blocks)
|
||||
|
||||
# The pool reserves the null block, so 8 configured blocks yield 7 usable.
|
||||
expected = pytest.approx(num_used / 7)
|
||||
assert 0 < num_used <= 7
|
||||
for _ in range(2):
|
||||
stats = scheduler.get_kv_connector_stats()
|
||||
assert stats.data["host_cache_usage_perc"] == [expected]
|
||||
|
||||
|
||||
def test_hisparse_host_residency_reported_as_hisparse_metrics():
|
||||
"""Host blocks sample into HiSparse's own residency metrics."""
|
||||
from tests.v1.core.test_prefix_caching import (
|
||||
make_hisparse_kv_cache_config,
|
||||
make_kv_cache_manager,
|
||||
)
|
||||
from tests.v1.core.utils import create_requests
|
||||
|
||||
collector = KVCacheMetricsCollector(sample_rate=1.0)
|
||||
manager = make_kv_cache_manager(
|
||||
make_hisparse_kv_cache_config(2, 2),
|
||||
max_model_len=128,
|
||||
enable_caching=True,
|
||||
hash_block_size=16,
|
||||
metrics_collector=collector,
|
||||
)
|
||||
coordinator = get_hisparse_coordinator(manager)
|
||||
assert coordinator.host_manager is not None
|
||||
scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
scheduler.bind_coordinator(coordinator)
|
||||
device = manager.block_pool
|
||||
host = coordinator.host_manager.block_pool
|
||||
request = create_requests(1, num_tokens=16)[0]
|
||||
for pool, birth in ((device, 1), (host, 2)):
|
||||
with patch("time.monotonic_ns", return_value=birth * 10**9):
|
||||
block = pool.get_new_blocks(1)[0]
|
||||
assert block.block_id == 1
|
||||
pool.cache_full_blocks(request, [block], 0, 1, 16, 0)
|
||||
with patch("time.monotonic_ns", return_value=4_000_000_000):
|
||||
host.free_blocks([host.blocks[1]])
|
||||
host.evict_blocks({1})
|
||||
with patch("time.monotonic_ns", return_value=6_000_000_000):
|
||||
device.evict_blocks({1})
|
||||
|
||||
assert collector.drain_events() == [KVCacheEvictionEvent(5.0, 5.0, ())]
|
||||
stats = scheduler.get_kv_connector_stats()
|
||||
assert stats.data["host_block_lifetime_seconds"] == [2.0]
|
||||
assert stats.data["host_block_idle_before_evict_seconds"] == [2.0]
|
||||
|
||||
|
||||
def test_no_forward_enqueues_deferred_hisparse_transfers():
|
||||
"""A zero-token step must still enqueue deferred post-forward transfers."""
|
||||
connector = object.__new__(ActiveKVConnector)
|
||||
connector._disabled = False
|
||||
connector.pre_forward = MagicMock()
|
||||
connector.finish_forward = MagicMock()
|
||||
connector.post_forward = MagicMock(return_value=None)
|
||||
|
||||
scheduler_output = SimpleNamespace(finished_req_ids=set())
|
||||
connector.no_forward(scheduler_output)
|
||||
|
||||
connector.pre_forward.assert_called_once_with(scheduler_output)
|
||||
connector.finish_forward.assert_called_once_with()
|
||||
|
||||
|
||||
def test_full_graph_step_prepares_host_mirror_outside_model():
|
||||
"""Graph replay must restore host-mirror state cleared at step start."""
|
||||
runtime = SimpleNamespace(
|
||||
is_group_leader=True,
|
||||
eager_host_mirror=True,
|
||||
begin_forward=MagicMock(),
|
||||
invalidate_written_slots=MagicMock(),
|
||||
)
|
||||
handle = HiSparseCacheHandle(runtime)
|
||||
handle.mirror_slot_mapping = torch.tensor([4, 5])
|
||||
worker = object.__new__(HiSparseConnectorWorker)
|
||||
worker.cache_layer_names = ["layer"]
|
||||
worker.cache_handles = [handle]
|
||||
worker._group_leaders = (("layer", handle),)
|
||||
worker._per_layer_mirrored = set()
|
||||
worker._submitted_mirror_layers = set()
|
||||
worker._draft_layers = ()
|
||||
worker.is_host_writer = True
|
||||
worker._enqueue_row_dma = MagicMock()
|
||||
worker.start_step = MagicMock(
|
||||
side_effect=lambda *_args, **_kwargs: worker._clear_forward_mirror_state()
|
||||
)
|
||||
|
||||
connector = object.__new__(HiSparseConnector)
|
||||
connector.connector_worker = worker
|
||||
connector._get_connector_metadata = MagicMock(
|
||||
return_value=HiSparseConnectorMetadata(None, (), (), {}, True, {})
|
||||
)
|
||||
req_id_per_token = torch.tensor([0, 1], dtype=torch.int32)
|
||||
attn_metadata = SimpleNamespace(
|
||||
num_actual_tokens=2,
|
||||
num_decode_tokens=2,
|
||||
num_reqs=2,
|
||||
max_query_len=1,
|
||||
req_id_per_token=req_id_per_token,
|
||||
)
|
||||
|
||||
connector.start_load_kv(
|
||||
SimpleNamespace(),
|
||||
request_state_indices=None,
|
||||
request_ids=[],
|
||||
attn_metadata={"layer": attn_metadata},
|
||||
)
|
||||
|
||||
worker._enqueue_host_mirror()
|
||||
|
||||
worker._enqueue_row_dma.assert_called_once_with((0,), ready_event=None)
|
||||
runtime.invalidate_written_slots.assert_called_once()
|
||||
|
||||
|
||||
class _FakeEvent:
|
||||
log: list[tuple[str, object]] = []
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
pass
|
||||
|
||||
def record(self, stream=None) -> None:
|
||||
self.log.append(("event", self))
|
||||
|
||||
def query(self) -> bool:
|
||||
return True
|
||||
|
||||
def synchronize(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cg_mode", [CUDAGraphMode.FULL, CUDAGraphMode.NONE])
|
||||
def test_draft_layer_rows_mirrored_after_drafter(monkeypatch, cg_mode):
|
||||
"""Draft-layer host rows must hold the drafter's writes before page release.
|
||||
|
||||
The drafter writes its layers' rows after the target forward. Mirroring
|
||||
them at the end of the target forward (the only mirror a FULL graph gets)
|
||||
leaves pre-draft rows on the host, and the page is still reported clean.
|
||||
"""
|
||||
block_size, width = 4, 8
|
||||
resident_block, host_block, transfer_id = 2, 1, 7
|
||||
log: list[tuple[str, object]] = []
|
||||
_FakeEvent.log = log
|
||||
|
||||
def swap_blocks_batch(src, dst, sizes):
|
||||
for src_ptr, dst_ptr, size in zip(src.tolist(), dst.tolist(), sizes.tolist()):
|
||||
ctypes.memmove(dst_ptr, src_ptr, size)
|
||||
log.append(("dma", dst_ptr))
|
||||
|
||||
monkeypatch.setattr(torch, "Event", _FakeEvent)
|
||||
monkeypatch.setattr(torch, "Stream", lambda *args, **kwargs: MagicMock())
|
||||
monkeypatch.setattr(torch.cuda, "Stream", lambda *args, **kwargs: MagicMock())
|
||||
monkeypatch.setattr(torch.cuda, "stream", lambda _: contextlib.nullcontext())
|
||||
compute_stream = MagicMock()
|
||||
monkeypatch.setattr(worker_module, "current_stream", lambda: compute_stream)
|
||||
monkeypatch.setattr(worker_module.ops, "swap_blocks_batch", swap_blocks_batch)
|
||||
monkeypatch.setattr(
|
||||
runtime_module,
|
||||
"get_forward_context",
|
||||
lambda: SimpleNamespace(cudagraph_runtime_mode=cg_mode),
|
||||
)
|
||||
|
||||
slots = torch.arange(block_size) + resident_block * block_size
|
||||
request_state_indices = torch.full((1,), -1, dtype=torch.int32)
|
||||
handles = []
|
||||
for draft_layer in (False, True):
|
||||
runtime = SimpleNamespace(
|
||||
is_group_leader=True,
|
||||
eager_host_mirror=True,
|
||||
resident_source_index=0,
|
||||
host_cache=torch.zeros(4 * block_size, width),
|
||||
request_state_indices=request_state_indices,
|
||||
begin_forward=MagicMock(),
|
||||
invalidate_written_slots=MagicMock(),
|
||||
)
|
||||
handle = HiSparseCacheHandle(runtime)
|
||||
handle.view = SimpleNamespace(
|
||||
block_size=block_size, cache=torch.zeros(4, block_size, width)
|
||||
)
|
||||
handle.slot_mapping = slots
|
||||
handle.mirror_slot_mapping = slots
|
||||
handle.draft_layer = draft_layer
|
||||
handles.append(handle)
|
||||
target, draft = handles
|
||||
# Rows the draft layer held before this step's drafter ran.
|
||||
draft.view.cache[resident_block] = -1.0
|
||||
|
||||
worker = HiSparseConnectorWorker(
|
||||
SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(max_num_batched_tokens=16),
|
||||
num_lookahead_tokens=3,
|
||||
),
|
||||
MagicMock(),
|
||||
)
|
||||
worker.initialize(
|
||||
handles,
|
||||
["target", "draft"],
|
||||
MagicMock(),
|
||||
max_num_reqs=1,
|
||||
host_num_blocks=4,
|
||||
device=torch.device("cpu"),
|
||||
pinned_host_pools=[],
|
||||
)
|
||||
connector = object.__new__(HiSparseConnector)
|
||||
connector.connector_worker = worker
|
||||
connector._get_connector_metadata = MagicMock(
|
||||
return_value=HiSparseConnectorMetadata(
|
||||
SparseKVOffloadCommand(
|
||||
[
|
||||
SparseKVPageTransfer(
|
||||
transfer_id=transfer_id,
|
||||
host_block_id=host_block,
|
||||
resident_block_ids=(resident_block,),
|
||||
after_forward=True,
|
||||
)
|
||||
]
|
||||
),
|
||||
(),
|
||||
(),
|
||||
{
|
||||
"req": (
|
||||
SparseKVRowMirror(
|
||||
source_starts=(resident_block * block_size,),
|
||||
destination_start=host_block * block_size,
|
||||
num_rows=block_size,
|
||||
),
|
||||
)
|
||||
},
|
||||
True,
|
||||
{},
|
||||
)
|
||||
)
|
||||
# A verification step: four query tokens of one request fill the page.
|
||||
attn_metadata = SimpleNamespace(
|
||||
num_actual_tokens=block_size,
|
||||
num_decode_tokens=0,
|
||||
num_reqs=1,
|
||||
max_query_len=block_size,
|
||||
req_id_per_token=torch.zeros(block_size, dtype=torch.int32),
|
||||
)
|
||||
|
||||
connector.start_load_kv(
|
||||
SimpleNamespace(),
|
||||
request_state_indices=None,
|
||||
request_ids=["req"],
|
||||
num_tokens=block_size,
|
||||
attn_metadata={"target": attn_metadata, "draft": attn_metadata},
|
||||
)
|
||||
target.view.cache[resident_block] = 1.0
|
||||
if cg_mode != CUDAGraphMode.FULL:
|
||||
target.finish_kv_update()
|
||||
connector.finish_forward()
|
||||
enqueued_before_draft = list(worker._enqueued_transfer_ids)
|
||||
|
||||
# The drafter writes the draft layer's rows for the same positions.
|
||||
if cg_mode != CUDAGraphMode.FULL:
|
||||
draft.prepare_group_for_batch(attn_metadata)
|
||||
draft.view.cache[resident_block] = 2.0
|
||||
if cg_mode != CUDAGraphMode.FULL:
|
||||
draft.finish_kv_update()
|
||||
# The next step's start mirrors the drafter's rows, then hands the page over.
|
||||
compute_stream.wait_event.reset_mock()
|
||||
connector._get_connector_metadata.return_value = HiSparseConnectorMetadata(
|
||||
None, (), (), {}, True, {}
|
||||
)
|
||||
connector.start_load_kv(
|
||||
SimpleNamespace(),
|
||||
request_state_indices=None,
|
||||
request_ids=[],
|
||||
num_tokens=0,
|
||||
attn_metadata={},
|
||||
)
|
||||
((completion_event, _),) = worker._pending_transfer_events
|
||||
worker_meta = connector.build_connector_worker_meta()
|
||||
|
||||
host_rows = slice(host_block * block_size, (host_block + 1) * block_size)
|
||||
torch.testing.assert_close(target.runtime.host_cache[host_rows], torch.ones(4, 8))
|
||||
torch.testing.assert_close(
|
||||
draft.runtime.host_cache[host_rows], torch.full((4, 8), 2.0)
|
||||
)
|
||||
draft_host = draft.runtime.host_cache
|
||||
draft_host_range = range(
|
||||
draft_host.data_ptr(),
|
||||
draft_host.data_ptr() + draft_host.numel() * draft_host.element_size(),
|
||||
)
|
||||
draft_copies = [
|
||||
index
|
||||
for index, (kind, ptr) in enumerate(log)
|
||||
if kind == "dma" and ptr in draft_host_range
|
||||
]
|
||||
# One draft-layer copy, and the page is not handed back before it.
|
||||
assert len(draft_copies) == 1
|
||||
assert enqueued_before_draft == []
|
||||
assert log.index(("event", completion_event)) > draft_copies[0]
|
||||
# The next forward waits for the draft copy: the scheduler may already
|
||||
# have handed the blocks it reads and writes to another request.
|
||||
draft_copy_event = next(
|
||||
entry[1] for entry in log[draft_copies[0] :] if entry[0] == "event"
|
||||
)
|
||||
assert compute_stream.wait_event.call_args_list[0].args == (draft_copy_event,)
|
||||
assert worker_meta is not None
|
||||
assert worker_meta.enqueued_transfer_counts == {transfer_id: 1}
|
||||
assert worker_meta.completed_transfer_counts == {transfer_id: 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shared", [True, False])
|
||||
@pytest.mark.parametrize("num_tokens", [0, 4])
|
||||
def test_zero_token_step_holds_tp_ranks_after_host_write_wait(
|
||||
monkeypatch, shared, num_tokens
|
||||
):
|
||||
"""Steps without tokens hold every TP rank after its shared event wait."""
|
||||
calls: list[tuple[str, object]] = []
|
||||
compute_stream = MagicMock()
|
||||
compute_stream.wait_event.side_effect = lambda event: calls.append(("wait", event))
|
||||
tp_group = MagicMock()
|
||||
tp_group.barrier.side_effect = lambda: calls.append(("barrier", None))
|
||||
monkeypatch.setattr(worker_module, "current_stream", lambda: compute_stream)
|
||||
monkeypatch.setattr(worker_module, "get_tp_group", lambda: tp_group)
|
||||
|
||||
worker = object.__new__(HiSparseConnectorWorker)
|
||||
worker.shared_host_region = MagicMock() if shared else None
|
||||
worker.host_write_events = (MagicMock(), MagicMock())
|
||||
worker.host_write_event = worker.host_write_events[1]
|
||||
worker._next_host_write_event = 0
|
||||
worker._slot_mapping_staging = None
|
||||
worker.cache_handles = []
|
||||
worker._pending_invalid_block_ids = []
|
||||
for name in (
|
||||
"_stage_row_mirror_mapping",
|
||||
"_finish_previous_step",
|
||||
"_release_completed_dma_descriptors",
|
||||
"_set_row_mirrors",
|
||||
"_clear_forward_mirror_state",
|
||||
"_copy_host_blocks",
|
||||
"_restore_pages",
|
||||
"_submit_transfers",
|
||||
):
|
||||
setattr(worker, name, MagicMock())
|
||||
|
||||
worker.start_step(
|
||||
HiSparseConnectorMetadata(None, (), (), {}, True, {}),
|
||||
None,
|
||||
[],
|
||||
num_tokens=num_tokens,
|
||||
)
|
||||
|
||||
expected = [("wait", worker.host_write_events[1])]
|
||||
if shared and not num_tokens:
|
||||
expected.append(("barrier", None))
|
||||
assert calls == expected
|
||||
|
||||
|
||||
def test_scheduled_prefix_hit_publishes_adopted_copies():
|
||||
"""Copies adopted after scheduling reach the worker as a residency update,
|
||||
leaving the block-table row the scheduler output carries untouched."""
|
||||
from tests.v1.core.test_prefix_caching import (
|
||||
HISPARSE_BLOCK_SIZE,
|
||||
_allocate_scheduled,
|
||||
_publish_hisparse_pages,
|
||||
make_hisparse_kv_cache_manager,
|
||||
make_request,
|
||||
sha256,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import init_none_hash
|
||||
|
||||
init_none_hash(sha256)
|
||||
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
|
||||
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
|
||||
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
|
||||
assert _allocate_scheduled(manager, original, num_new_tokens=len(tokens))
|
||||
_publish_hisparse_pages(manager)
|
||||
copy_ids = [block.block_id for block in manager.get_blocks("original").blocks[2]]
|
||||
manager.free(original)
|
||||
|
||||
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
|
||||
computed, num_computed, _ = manager.get_computed_blocks(resumed)
|
||||
num_new_tokens = len(tokens) - num_computed
|
||||
assert manager.allocate_slots(
|
||||
resumed,
|
||||
num_new_tokens=num_new_tokens,
|
||||
num_new_computed_tokens=num_computed,
|
||||
new_computed_blocks=computed,
|
||||
)
|
||||
scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
scheduler.bind_coordinator(get_hisparse_coordinator(manager))
|
||||
scheduler.requests[resumed.request_id] = resumed
|
||||
scheduler_output = SimpleNamespace(
|
||||
scheduled_new_reqs=[
|
||||
SimpleNamespace(
|
||||
req_id=resumed.request_id,
|
||||
num_computed_tokens=num_computed,
|
||||
block_ids=manager.get_block_ids(resumed.request_id),
|
||||
)
|
||||
],
|
||||
scheduled_cached_reqs=SimpleNamespace(
|
||||
req_ids=[], num_computed_tokens=[], new_block_ids=[]
|
||||
),
|
||||
num_scheduled_tokens={resumed.request_id: num_new_tokens},
|
||||
)
|
||||
|
||||
core_row = list(scheduler_output.scheduled_new_reqs[0].block_ids[2])
|
||||
|
||||
metadata = scheduler.build_connector_meta(scheduler_output)
|
||||
|
||||
update = metadata.residency_updates[resumed.request_id]
|
||||
assert update.pages == [0, 1, 2, 3]
|
||||
assert update.block_ids[0][:3] == copy_ids[:3]
|
||||
assert manager.get_block_ids(resumed.request_id)[2] == core_row
|
||||
assert core_row[:3] == [0, 0, 0]
|
||||
|
||||
|
||||
def test_residency_updates_persist_by_state_row():
|
||||
"""Updates name requests by batch row but are stored by state row.
|
||||
|
||||
An update for a lost page and an appended page must leave the other pages
|
||||
and the other request's row intact across steps that reorder the batch.
|
||||
"""
|
||||
table = torch.zeros((4, 2, 4), dtype=torch.int32)
|
||||
update_hisparse_residency(
|
||||
table,
|
||||
{
|
||||
"a": SparseKVResidencyUpdate([0, 1, 2], ([1, 2, 3], [11, 12, 13])),
|
||||
"b": SparseKVResidencyUpdate([0, 1], ([4, 5], [14, 15])),
|
||||
},
|
||||
["a", "b"],
|
||||
torch.tensor([2, 0], dtype=torch.int32),
|
||||
)
|
||||
update_hisparse_residency(
|
||||
table,
|
||||
{"a": SparseKVResidencyUpdate([1, 3], ([0, 6], [0, 16]))},
|
||||
["b", "a"],
|
||||
torch.tensor([0, 2], dtype=torch.int32),
|
||||
)
|
||||
|
||||
assert table[[0, 2], 0].tolist() == [[4, 5, 0, 0], [1, 0, 3, 6]]
|
||||
assert table[[0, 2], 1].tolist() == [[14, 15, 0, 0], [11, 0, 13, 16]]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,382 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Per-request DiffusionGemma state behind structured reads: seed canvases,
|
||||
pinned positions, read-only slots and the per-slot step cap."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.models.diffusion_gemma import (
|
||||
_MASKED_LOGIT,
|
||||
DiffusionGemmaRequestStates,
|
||||
_compiled_sample_step,
|
||||
_concat_logprob_stashes,
|
||||
_denoise_temperature,
|
||||
_mask_rows_to_allowed,
|
||||
sample_row_stats_reference,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.outputs import LogprobsTensors
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="the sampler state lives on the GPU"
|
||||
)
|
||||
|
||||
CL = 8
|
||||
VOCAB = 64
|
||||
MAX_REQS = 4
|
||||
MAX_STEPS = 48
|
||||
|
||||
|
||||
def _states() -> DiffusionGemmaRequestStates:
|
||||
return DiffusionGemmaRequestStates(
|
||||
max_num_reqs=MAX_REQS,
|
||||
canvas_length=CL,
|
||||
vocab_size=VOCAB,
|
||||
max_denoising_steps=MAX_STEPS,
|
||||
device=torch.device("cuda"),
|
||||
hidden_size=4,
|
||||
stability_threshold=2,
|
||||
)
|
||||
|
||||
|
||||
def _slots(*idx: int) -> tuple[np.ndarray, torch.Tensor]:
|
||||
slots = np.array(idx, dtype=np.int64)
|
||||
return slots, torch.tensor(slots, device="cuda")
|
||||
|
||||
|
||||
def test_seed_canvas_replaces_only_seeded_slots():
|
||||
states = _states()
|
||||
for slot in range(3):
|
||||
states.add_request(slot)
|
||||
seed = list(range(CL))
|
||||
states.set_seed_canvas(1, seed)
|
||||
slots, slots_gpu = _slots(0, 1, 2)
|
||||
states.init_canvas(slots_gpu)
|
||||
before = states.canvas[slots_gpu].clone()
|
||||
|
||||
states.apply_seed_canvases(slots, slots_gpu)
|
||||
|
||||
after = states.canvas[slots_gpu]
|
||||
assert after[1].tolist() == seed
|
||||
assert torch.equal(after[0], before[0])
|
||||
assert torch.equal(after[2], before[2])
|
||||
|
||||
|
||||
def test_apply_seed_canvases_leaves_unseeded_batches_alone():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
slots, slots_gpu = _slots(0)
|
||||
states.init_canvas(slots_gpu)
|
||||
before = states.canvas[0].clone()
|
||||
|
||||
states.apply_seed_canvases(slots, slots_gpu)
|
||||
|
||||
assert torch.equal(states.canvas[0], before)
|
||||
|
||||
|
||||
def test_add_request_clears_seed_and_read_only():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.set_seed_canvas(0, [1] * CL)
|
||||
states.set_read_only(0)
|
||||
assert states.seeded_slots == {0}
|
||||
assert states.read_only_slots == {0}
|
||||
|
||||
states.add_request(0)
|
||||
|
||||
assert not states.seeded_slots
|
||||
assert not states.read_only_slots
|
||||
assert not bool(states.has_seed[0])
|
||||
assert not bool(states.read_only[0])
|
||||
|
||||
|
||||
def test_canvas_width_resets_with_the_slot():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.canvas_width_np[0] = 4
|
||||
states.set_seed_canvas(0, [7, 7, 7, 7])
|
||||
assert states.seed_canvas[0, :4].tolist() == [7, 7, 7, 7]
|
||||
|
||||
states.add_request(0)
|
||||
|
||||
assert states.canvas_width_np[0] == CL
|
||||
|
||||
|
||||
def test_remove_request_forgets_the_slot():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.set_seed_canvas(0, [1] * CL)
|
||||
states.set_read_only(0)
|
||||
|
||||
states.remove_request(0)
|
||||
|
||||
assert not states.seeded_slots
|
||||
assert not states.read_only_slots
|
||||
|
||||
|
||||
def _denoise_once(
|
||||
states: DiffusionGemmaRequestStates,
|
||||
slots: list[int],
|
||||
compute_sc: bool = True,
|
||||
width: int = CL,
|
||||
embed_weight: torch.Tensor | None = None,
|
||||
embed_dtype: torch.dtype = torch.float32,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""One compiled denoise step over ``slots`` with flat logits, so nothing
|
||||
converges by stability or confidence and only the step cap can end it.
|
||||
``width`` below CL runs the step on [:, :width] views, as the sampler
|
||||
does for a narrow tile."""
|
||||
n = len(slots)
|
||||
device = states.device
|
||||
decode_slots = torch.tensor(slots, dtype=torch.int64, device=device)
|
||||
decode_idx = torch.arange(n, dtype=torch.int64, device=device)
|
||||
sampled = torch.zeros(n, CL, dtype=torch.int32, device=device)[:, :width]
|
||||
num_sampled = torch.zeros(n, dtype=torch.int32, device=device)
|
||||
temp = _denoise_temperature(states.step, decode_slots, float(MAX_STEPS), 0.5, 1.0)
|
||||
argmax, sample, entropy, probs = sample_row_stats_reference(
|
||||
torch.zeros(n * width, VOCAB, device=device),
|
||||
temp,
|
||||
width,
|
||||
embed_dtype if compute_sc else None,
|
||||
)
|
||||
_compiled_sample_step(
|
||||
sample.view(n, width),
|
||||
argmax.view(n, width),
|
||||
entropy.view(n, width),
|
||||
probs.view(n, width, -1) if probs is not None else None,
|
||||
decode_slots,
|
||||
decode_idx,
|
||||
decode_slots,
|
||||
torch.full((n,), width, dtype=torch.int64, device=device),
|
||||
states.canvas[:, :width],
|
||||
states.argmax_canvas[:, :width],
|
||||
states.step,
|
||||
states.is_encoder_phase,
|
||||
states.confident,
|
||||
states.self_conditioning_embeds[:, :width],
|
||||
(
|
||||
torch.zeros(VOCAB, 4, dtype=embed_dtype, device=device)
|
||||
if embed_weight is None
|
||||
else embed_weight
|
||||
),
|
||||
torch.tensor(1.0, dtype=embed_dtype, device=device),
|
||||
states.accepted_canvas_history[:, :, :width],
|
||||
states.accepted_canvas_history_len,
|
||||
states.max_steps,
|
||||
states.pin_mask[:, :width],
|
||||
states.seed_canvas[:, :width],
|
||||
states.read_only,
|
||||
sampled,
|
||||
num_sampled,
|
||||
torch.zeros(MAX_REQS, CL, dtype=torch.int64, device=device),
|
||||
confidence_threshold=0.1,
|
||||
vocab_size=VOCAB,
|
||||
CL=width,
|
||||
ST=states.stability_threshold,
|
||||
entropy_bound=0.1,
|
||||
sc_vocab_start=0,
|
||||
sc_vocab_end=VOCAB,
|
||||
tp_size=1,
|
||||
tp_group_name="",
|
||||
compute_sc=compute_sc,
|
||||
)
|
||||
return sampled, num_sampled
|
||||
|
||||
|
||||
def test_pinned_positions_hold_their_seed_through_a_step():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.is_encoder_phase[0] = False
|
||||
seed = list(range(10, 10 + CL))
|
||||
states.set_seed_canvas(0, seed)
|
||||
states.canvas[0] = torch.tensor(seed, device="cuda")
|
||||
states.set_pins(0, [0, 1, 2, 3])
|
||||
|
||||
# Flat logits accept nothing, so every free position is renoised.
|
||||
_denoise_once(states, [0], embed_weight=torch.ones(VOCAB, 4, device="cuda"))
|
||||
|
||||
assert states.canvas[0, :4].tolist() == seed[:4]
|
||||
# The soft embed is zero at pinned positions and non-zero elsewhere.
|
||||
sc = states.self_conditioning_embeds[0]
|
||||
assert not sc[:4].any()
|
||||
assert sc[4:].any()
|
||||
|
||||
|
||||
def test_add_request_clears_pins():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.set_seed_canvas(0, [1] * CL)
|
||||
states.set_pins(0, [2, 3])
|
||||
assert states.pin_mask[0].tolist() == [False, False, True, True] + [False] * 4
|
||||
|
||||
states.add_request(0)
|
||||
|
||||
assert not states.pin_mask[0].any()
|
||||
|
||||
|
||||
def test_single_step_tile_skips_self_conditioning():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.is_encoder_phase[0] = False
|
||||
states.self_conditioning_embeds[0] = 1.0
|
||||
|
||||
_denoise_once(states, [0], compute_sc=False)
|
||||
|
||||
assert not states.self_conditioning_embeds[0].any()
|
||||
|
||||
|
||||
def test_sample_step_is_compiled():
|
||||
assert hasattr(_compiled_sample_step, "_torchdynamo_orig_callable")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stance", ["default", "force_eager"])
|
||||
def test_self_conditioning_stores_a_bf16_model_in_the_fp32_buffer(stance):
|
||||
# The model's embeddings are bf16 while the buffer is fp32. Compiled code
|
||||
# casts on the store, but eager does not, and the step runs eager once
|
||||
# torch.compile hits its recompile limit.
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.is_encoder_phase[0] = False
|
||||
|
||||
with torch.compiler.set_stance(stance):
|
||||
_denoise_once(
|
||||
states,
|
||||
[0],
|
||||
embed_weight=torch.ones(VOCAB, 4, dtype=torch.bfloat16, device="cuda"),
|
||||
embed_dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
assert states.self_conditioning_embeds.dtype == torch.float32
|
||||
# uniform probs @ an all-ones embedding
|
||||
assert torch.allclose(
|
||||
states.self_conditioning_embeds[0], torch.ones(CL, 4, device="cuda")
|
||||
)
|
||||
|
||||
|
||||
def test_narrow_tile_leaves_the_rest_of_the_canvas_alone():
|
||||
states = _states()
|
||||
states.add_request(0)
|
||||
states.is_encoder_phase[0] = False
|
||||
states.canvas[0] = 5
|
||||
states.argmax_canvas[0] = 5
|
||||
|
||||
_denoise_once(states, [0], width=4)
|
||||
|
||||
# Columns past the width are untouched; the step counted.
|
||||
assert states.canvas[0, 4:].tolist() == [5] * (CL - 4)
|
||||
assert states.argmax_canvas[0, 4:].tolist() == [5] * (CL - 4)
|
||||
assert states.step[0] == 1
|
||||
|
||||
|
||||
def test_step_cap_is_per_slot():
|
||||
states = _states()
|
||||
for slot in (0, 1):
|
||||
states.add_request(slot)
|
||||
states.is_encoder_phase[slot] = False
|
||||
states.max_steps[0] = 1
|
||||
|
||||
_denoise_once(states, [0, 1])
|
||||
|
||||
# Slot 0 hit its cap and moves to commit. Slot 1 keeps denoising.
|
||||
assert states.is_encoder_phase[:2].tolist() == [True, False]
|
||||
assert states.step[:2].tolist() == [1, 1]
|
||||
|
||||
|
||||
def _stash(rows: int, width: int, first_id: int) -> LogprobsTensors:
|
||||
ids = torch.arange(first_id, first_id + rows * width).reshape(rows, width)
|
||||
return LogprobsTensors(
|
||||
logprob_token_ids=ids,
|
||||
logprobs=-ids.float(),
|
||||
selected_token_ranks=torch.zeros(rows, dtype=torch.int64),
|
||||
)
|
||||
|
||||
|
||||
def test_stashes_of_different_widths_join():
|
||||
# A read that asked for 10 label ids and a generation that asked for 2
|
||||
# logprobs converged in different steps, so their stashes differ in width.
|
||||
wide, narrow = _stash(2, 11, 100), _stash(3, 3, 0)
|
||||
|
||||
out = _concat_logprob_stashes([narrow, wide], [0, 3])
|
||||
|
||||
assert out.logprob_token_ids.shape == (5, 11)
|
||||
assert out.logprobs.shape == (5, 11)
|
||||
assert out.cu_num_generated_tokens == [0, 3]
|
||||
# The narrow rows keep their values and pad with id 0 at -inf.
|
||||
assert torch.equal(out.logprob_token_ids[:3, :3], narrow.logprob_token_ids)
|
||||
assert not out.logprob_token_ids[:3, 3:].any()
|
||||
assert torch.isneginf(out.logprobs[:3, 3:]).all()
|
||||
assert torch.equal(out.logprobs[3:], wide.logprobs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("width", [4, CL])
|
||||
@pytest.mark.parametrize("steps", [1, 2])
|
||||
def test_read_emits_at_convergence_while_generation_waits_for_commit(width, steps):
|
||||
states = _states()
|
||||
for slot in (2, 0):
|
||||
states.add_request(slot)
|
||||
states.is_encoder_phase[slot] = False
|
||||
states.max_steps[slot] = steps
|
||||
states.set_read_only(2)
|
||||
|
||||
for step in range(steps):
|
||||
sampled, counts = _denoise_once(states, [2, 0], width=width)
|
||||
assert counts.tolist() == ([width, 0] if step == steps - 1 else [0, 0])
|
||||
|
||||
assert torch.equal(sampled[0], states.argmax_canvas[2, :width].int())
|
||||
assert not states.is_encoder_phase[2]
|
||||
assert states.is_encoder_phase[0]
|
||||
assert not states.self_conditioning_embeds[2].any()
|
||||
|
||||
sampled, counts = _denoise_once(states, [0], width=width)
|
||||
assert counts.tolist() == [width]
|
||||
assert torch.equal(sampled[0], states.argmax_canvas[0, :width].int())
|
||||
|
||||
|
||||
def test_batch_allowed_needs_one_shared_set():
|
||||
states = _states()
|
||||
states.constrained[0] = (1, 2, 3)
|
||||
states.constrained[1] = (4, 5)
|
||||
|
||||
# Mixed sets, or a slot with no set, fall back to per-row masking.
|
||||
assert states.batch_allowed([0, 1]) is None
|
||||
assert states.batch_allowed([0, 2]) is None
|
||||
assert states.batch_allowed([]) is None
|
||||
|
||||
shared = states.batch_allowed([0])
|
||||
assert shared is not None
|
||||
assert shared.tolist() == [1, 2, 3]
|
||||
assert shared.dtype == torch.int64
|
||||
assert states.batch_allowed([0, 0]) is shared
|
||||
assert states.allowed_tensor((1, 2, 3)) is shared
|
||||
|
||||
|
||||
def test_mask_rows_to_allowed_masks_only_constrained_rows():
|
||||
logits = torch.randn(5, VOCAB, device="cuda")
|
||||
before = logits.clone()
|
||||
first = torch.tensor([3, 7], device="cuda")
|
||||
third = torch.tensor([0], device="cuda")
|
||||
|
||||
out = _mask_rows_to_allowed(logits, [0, 2, 3], [2, 1, 2], [first, None, third])
|
||||
|
||||
assert out is not logits
|
||||
assert torch.equal(logits, before)
|
||||
# Masked columns hold the finite sentinel, so entropy stays finite.
|
||||
kept = out > _MASKED_LOGIT
|
||||
assert torch.isfinite(out).all()
|
||||
assert kept[0:2].sum(dim=1).tolist() == [2, 2]
|
||||
assert kept[0:2][:, first].all()
|
||||
assert torch.equal(out[0:2][:, first], before[0:2][:, first])
|
||||
assert torch.equal(out[2], before[2])
|
||||
assert kept[3:5].sum(dim=1).tolist() == [1, 1]
|
||||
assert torch.equal(out[3:5][:, third], before[3:5][:, third])
|
||||
# The masked row's softmax is the distribution renormalized over the set.
|
||||
torch.testing.assert_close(
|
||||
out[0].softmax(dim=-1)[first], before[0, first].softmax(dim=-1)
|
||||
)
|
||||
|
||||
|
||||
def test_mask_rows_to_allowed_is_a_no_op_without_constrained_rows():
|
||||
logits = torch.randn(3, VOCAB, device="cuda")
|
||||
assert _mask_rows_to_allowed(logits, [0, 1], [1, 2], [None, None]) is logits
|
||||
@@ -1,132 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The fused row statistics of the DiffusionGemma sampler against the PyTorch
|
||||
reference: argmax, entropy and softmax must match. A zero temperature must
|
||||
sample the argmax and a positive one must sample from the distribution."""
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.models.diffusion_gemma_sampler import (
|
||||
sample_row_stats,
|
||||
sample_row_stats_reference,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not torch.cuda.is_available(), reason="the fused kernel needs a GPU"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vocab", [5000, 9001])
|
||||
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
|
||||
def test_stats_match_reference(vocab: int, dtype: torch.dtype):
|
||||
torch.manual_seed(0)
|
||||
num_decode, cl = 9, 4
|
||||
logits = (torch.randn(num_decode * cl, vocab, device="cuda") * 3).to(dtype)
|
||||
temps = torch.tensor([0.0, 0.7, 2.0, 1.0, 0.0, 0.3, 1.5, 1.0, 0.0], device="cuda")
|
||||
argmax, sample, entropy, probs = sample_row_stats(
|
||||
logits, temps, cl, seed=1234, probs_dtype=torch.bfloat16
|
||||
)
|
||||
ref_argmax, _, ref_entropy, ref_probs = sample_row_stats_reference(
|
||||
logits, temps, cl, probs_dtype=torch.bfloat16
|
||||
)
|
||||
assert torch.equal(argmax, ref_argmax)
|
||||
torch.testing.assert_close(entropy, ref_entropy, atol=2e-3, rtol=1e-3)
|
||||
assert probs is not None
|
||||
assert ref_probs is not None
|
||||
torch.testing.assert_close(probs.float(), ref_probs.float(), atol=5e-3, rtol=2e-2)
|
||||
assert probs.dtype == torch.bfloat16
|
||||
assert probs.shape == logits.shape
|
||||
# A padded (all-zero) row is uniform: max entropy, argmax 0.
|
||||
zero = torch.zeros(1, vocab, device="cuda")
|
||||
a0, _, e0, _ = sample_row_stats(zero, temps[:1] + 1.0, 1, 1, None)
|
||||
assert a0.item() == 0
|
||||
assert abs(e0.item() - torch.log(torch.tensor(float(vocab))).item()) < 1e-3
|
||||
|
||||
|
||||
def test_zero_temperature_is_greedy_and_probs_optional():
|
||||
torch.manual_seed(0)
|
||||
logits = torch.randn(12, 4097, device="cuda")
|
||||
temps = torch.zeros(12, device="cuda")
|
||||
argmax, sample, entropy, probs = sample_row_stats(logits, temps, 1, 7, None)
|
||||
assert torch.equal(sample, argmax)
|
||||
assert probs is None
|
||||
assert torch.equal(argmax, logits.argmax(dim=-1))
|
||||
# Greedy entropy is that of the reference's clamped temperature.
|
||||
_, _, ref_entropy, _ = sample_row_stats_reference(logits, temps, 1, None)
|
||||
torch.testing.assert_close(entropy, ref_entropy, atol=2e-3, rtol=1e-3)
|
||||
|
||||
|
||||
def test_positive_temperature_samples_from_the_distribution():
|
||||
torch.manual_seed(0)
|
||||
rows, vocab = 2000, 4099
|
||||
# A peaked row samples its argmax almost always and a flat row rarely.
|
||||
peaked = torch.zeros(rows, vocab, device="cuda")
|
||||
peaked[:, 17] = 16.0 # p(17) = e^16 / (e^16 + 4098) > 0.999
|
||||
flat = torch.zeros(rows, vocab, device="cuda")
|
||||
temps = torch.ones(rows, device="cuda")
|
||||
_, s_peaked, _, _ = sample_row_stats(peaked, temps, 1, 99, None)
|
||||
_, s_flat, _, _ = sample_row_stats(flat, temps, 1, 99, None)
|
||||
assert (s_peaked == 17).float().mean().item() > 0.99
|
||||
assert s_flat.unique().numel() > rows // 2
|
||||
# The same seed repeats the draws and another seed changes them.
|
||||
_, s_again, _, _ = sample_row_stats(flat, temps, 1, 99, None)
|
||||
_, s_other, _, _ = sample_row_stats(flat, temps, 1, 100, None)
|
||||
assert torch.equal(s_flat, s_again)
|
||||
assert not torch.equal(s_flat, s_other)
|
||||
|
||||
|
||||
def test_empty_batch():
|
||||
logits = torch.empty(0, 128, device="cuda")
|
||||
temps = torch.empty(0, device="cuda")
|
||||
argmax, sample, entropy, probs = sample_row_stats(
|
||||
logits, temps, 1, 1, torch.bfloat16
|
||||
)
|
||||
assert argmax.numel() == sample.numel() == entropy.numel() == 0
|
||||
assert probs is not None and probs.shape == (0, 128)
|
||||
|
||||
|
||||
def test_masked_logits_keep_a_finite_entropy():
|
||||
"""top_k/top_p leave -inf logits. Masked columns gave NaN entropy, and a
|
||||
row with one live column has zero entropy."""
|
||||
logits = torch.full((4, 5000), float("-inf"), device="cuda")
|
||||
logits[:, 3] = 0.0
|
||||
logits[2, 9] = 0.0 # two live columns: entropy log 2
|
||||
temps = torch.tensor([1.0, 0.0, 1.0, 0.7], device="cuda")
|
||||
argmax, sample, entropy, probs = sample_row_stats(
|
||||
logits, temps, 1, 5, torch.float32
|
||||
)
|
||||
assert torch.isfinite(entropy).all()
|
||||
assert entropy[0].item() < 1e-6 and entropy[1].item() < 1e-6
|
||||
assert abs(entropy[2].item() - math.log(2.0)) < 1e-4
|
||||
assert torch.equal(argmax[[0, 1, 3]], torch.tensor([3, 3, 3], device="cuda"))
|
||||
assert probs is not None
|
||||
assert probs[0, 3].item() == 1.0 and probs[0].sum().item() == 1.0
|
||||
_, _, ref_entropy, _ = sample_row_stats_reference(logits, temps, 1, None)
|
||||
assert torch.isfinite(ref_entropy).all()
|
||||
|
||||
|
||||
def test_leading_masked_block_keeps_a_finite_entropy():
|
||||
"""top_k leaves most of the vocabulary -inf, so whole leading blocks can be
|
||||
masked before the first live logit. The running max was -inf through
|
||||
them, and -inf - -inf poisoned the row with NaN."""
|
||||
logits = torch.full((3, 9001), float("-inf"), device="cuda")
|
||||
logits[:, 8500] = 0.0 # the only live column, past the first block
|
||||
logits[1, 8600] = 0.0 # two live columns: entropy log 2
|
||||
logits[2, 4] = -1.0 # a live column in the first block as well
|
||||
temps = torch.tensor([1.0, 1.0, 0.7], device="cuda")
|
||||
argmax, sample, entropy, probs = sample_row_stats(
|
||||
logits, temps, 1, 5, torch.float32
|
||||
)
|
||||
_, _, ref_entropy, ref_probs = sample_row_stats_reference(
|
||||
logits, temps, 1, torch.float32
|
||||
)
|
||||
assert torch.isfinite(entropy).all() and torch.isfinite(probs).all()
|
||||
assert entropy[0].item() < 1e-6
|
||||
assert abs(entropy[1].item() - math.log(2.0)) < 1e-4
|
||||
torch.testing.assert_close(entropy, ref_entropy, atol=1e-4, rtol=1e-4)
|
||||
torch.testing.assert_close(probs, ref_probs, atol=1e-5, rtol=1e-4)
|
||||
assert argmax.tolist() == [8500, 8500, 8500]
|
||||
assert sample[0].item() == 8500
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,151 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test that we handle an Error in model forward and shutdown."""
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import wait_for_gpu_memory_to_clear
|
||||
from tests.v1.shutdown.utils import (
|
||||
SHUTDOWN_TEST_THRESHOLD_BYTES,
|
||||
SHUTDOWN_TEST_TIMEOUT_SEC,
|
||||
)
|
||||
from vllm import LLM, AsyncEngineArgs, SamplingParams
|
||||
from vllm.distributed import get_tensor_model_parallel_rank
|
||||
from vllm.model_executor.models.llama import LlamaForCausalLM
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
MODELS = ["hmellor/tiny-random-LlamaForCausalLM"]
|
||||
|
||||
|
||||
def evil_forward(self, *args, **kwargs):
|
||||
"""Evil forward method that raise an exception after 10 calls."""
|
||||
NUMBER_OF_GOOD_PASSES = 10
|
||||
|
||||
if not hasattr(self, "num_calls"):
|
||||
self.num_calls = 0
|
||||
|
||||
if (
|
||||
self.num_calls == NUMBER_OF_GOOD_PASSES
|
||||
and get_tensor_model_parallel_rank() == 0
|
||||
):
|
||||
raise Exception("Simulated illegal memory access on Rank 0!")
|
||||
self.num_calls += 1
|
||||
|
||||
kwargs.setdefault("intermediate_tensors", None) # required for MRV2
|
||||
return self.model(*args, **kwargs)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def evil_forward_fixture(spawn_sitecustomize_factory):
|
||||
lines = [
|
||||
"from vllm.distributed import get_tensor_model_parallel_rank",
|
||||
"from vllm.model_executor.models.llama import LlamaForCausalLM",
|
||||
inspect.getsource(evil_forward),
|
||||
f"LlamaForCausalLM.forward = {evil_forward.__name__}",
|
||||
]
|
||||
spawn_sitecustomize_factory(lines)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("tensor_parallel_size", [2, 1])
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
async def test_async_llm_model_error(
|
||||
monkeypatch, evil_forward_fixture, tensor_parallel_size: int, model: str
|
||||
) -> None:
|
||||
"""Test that AsyncLLM propagates a forward pass error and frees memory.
|
||||
|
||||
AsyncLLM always uses an MP client.
|
||||
"""
|
||||
if current_platform.device_count() < tensor_parallel_size:
|
||||
pytest.skip(reason="Not enough CUDA devices")
|
||||
|
||||
# Monkeypatch an error in the model.
|
||||
monkeypatch.setattr(LlamaForCausalLM, "forward", evil_forward)
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model=model, enforce_eager=True, tensor_parallel_size=tensor_parallel_size
|
||||
)
|
||||
async_llm = AsyncLLM.from_engine_args(engine_args)
|
||||
|
||||
async def generate(request_id: str):
|
||||
generator = async_llm.generate(
|
||||
"Hello my name is", request_id=request_id, sampling_params=SamplingParams()
|
||||
)
|
||||
try:
|
||||
async for _ in generator:
|
||||
pass
|
||||
except Exception as e:
|
||||
return e
|
||||
|
||||
NUM_REQS = 3
|
||||
tasks = [generate(f"request-{idx}") for idx in range(NUM_REQS)]
|
||||
outputs = await asyncio.gather(*tasks)
|
||||
|
||||
# Every request should get an EngineDeadError.
|
||||
for output in outputs:
|
||||
assert isinstance(output, EngineDeadError)
|
||||
|
||||
# AsyncLLM should be errored.
|
||||
assert async_llm.errored
|
||||
|
||||
# We should not be able to make another request.
|
||||
with pytest.raises(EngineDeadError):
|
||||
async for _ in async_llm.generate(
|
||||
"Hello my name is", request_id="abc", sampling_params=SamplingParams()
|
||||
):
|
||||
raise Exception("We should not get here.")
|
||||
|
||||
# Confirm all the processes are cleaned up.
|
||||
wait_for_gpu_memory_to_clear(
|
||||
devices=list(range(tensor_parallel_size)),
|
||||
threshold_bytes=2 * 2**30,
|
||||
timeout_s=60,
|
||||
)
|
||||
|
||||
# NOTE: shutdown is handled by the API Server if an exception
|
||||
# occurs, so it is expected that we would need to call this.
|
||||
async_llm.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.timeout(SHUTDOWN_TEST_TIMEOUT_SEC)
|
||||
@pytest.mark.parametrize("enable_multiprocessing", [True])
|
||||
@pytest.mark.parametrize("tensor_parallel_size", [2, 1])
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
def test_llm_model_error(
|
||||
monkeypatch,
|
||||
evil_forward_fixture,
|
||||
tensor_parallel_size: int,
|
||||
enable_multiprocessing: bool,
|
||||
model: str,
|
||||
) -> None:
|
||||
"""Test that LLM propagates a forward pass error and frees memory.
|
||||
TODO(andy) - LLM without multiprocessing; LLM with multiprocessing
|
||||
and >1 rank
|
||||
"""
|
||||
if current_platform.device_count() < tensor_parallel_size:
|
||||
pytest.skip(reason="Not enough CUDA devices")
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
MP_VALUE = "1" if enable_multiprocessing else "0"
|
||||
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", MP_VALUE)
|
||||
|
||||
# Monkeypatch an error in the model.
|
||||
m.setattr(LlamaForCausalLM, "forward", evil_forward)
|
||||
|
||||
llm = LLM(
|
||||
model=model, enforce_eager=True, tensor_parallel_size=tensor_parallel_size
|
||||
)
|
||||
|
||||
with pytest.raises(EngineDeadError if enable_multiprocessing else Exception):
|
||||
llm.generate("Hello my name is Robert and I")
|
||||
|
||||
# Confirm all the processes are cleaned up.
|
||||
wait_for_gpu_memory_to_clear(
|
||||
devices=list(range(tensor_parallel_size)),
|
||||
threshold_bytes=SHUTDOWN_TEST_THRESHOLD_BYTES,
|
||||
)
|
||||
@@ -1,127 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test that we handle a startup Error and shutdown."""
|
||||
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import wait_for_gpu_memory_to_clear
|
||||
from tests.v1.shutdown.utils import (
|
||||
SHUTDOWN_TEST_THRESHOLD_BYTES,
|
||||
SHUTDOWN_TEST_TIMEOUT_SEC,
|
||||
)
|
||||
from vllm import LLM
|
||||
from vllm.distributed import get_tensor_model_parallel_rank
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.model_executor.models.llama import LlamaForCausalLM
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
|
||||
MODELS = ["hmellor/tiny-random-LlamaForCausalLM"]
|
||||
|
||||
|
||||
def evil_method(self, *args, **kwargs):
|
||||
"""Evil method that raises an exception."""
|
||||
if get_tensor_model_parallel_rank() == 0:
|
||||
raise Exception("Simulated Error in startup!")
|
||||
|
||||
return self.model(*args, **kwargs, intermediate_tensors=None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def evil_method_fixture(spawn_sitecustomize_factory, request):
|
||||
failing_method = request.getfixturevalue("failing_method")
|
||||
lines = [
|
||||
"from vllm.distributed import get_tensor_model_parallel_rank",
|
||||
"from vllm.model_executor.models.llama import LlamaForCausalLM",
|
||||
inspect.getsource(evil_method),
|
||||
f"LlamaForCausalLM.{failing_method} = {evil_method.__name__}",
|
||||
]
|
||||
spawn_sitecustomize_factory(lines)
|
||||
|
||||
|
||||
@pytest.mark.timeout(SHUTDOWN_TEST_TIMEOUT_SEC)
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("tensor_parallel_size", [2, 1])
|
||||
@pytest.mark.parametrize("failing_method", ["forward", "load_weights"])
|
||||
def test_async_llm_startup_error(
|
||||
monkeypatch,
|
||||
evil_method_fixture,
|
||||
model: str,
|
||||
tensor_parallel_size: int,
|
||||
failing_method: str,
|
||||
) -> None:
|
||||
"""Test that AsyncLLM propagates an __init__ error & frees memory.
|
||||
Test profiling (forward()) and load weights failures.
|
||||
AsyncLLM always uses an MP client.
|
||||
"""
|
||||
if current_platform.device_count() < tensor_parallel_size:
|
||||
pytest.skip(reason="Not enough CUDA devices")
|
||||
|
||||
# Monkeypatch an error in the model.
|
||||
monkeypatch.setattr(LlamaForCausalLM, failing_method, evil_method)
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model=model, enforce_eager=True, tensor_parallel_size=tensor_parallel_size
|
||||
)
|
||||
|
||||
# Confirm we get an exception.
|
||||
with pytest.raises(Exception, match=r"initialization fail(ed|ure)"):
|
||||
_ = AsyncLLM.from_engine_args(engine_args)
|
||||
|
||||
# Confirm all the processes are cleaned up.
|
||||
wait_for_gpu_memory_to_clear(
|
||||
devices=list(range(tensor_parallel_size)),
|
||||
threshold_bytes=SHUTDOWN_TEST_THRESHOLD_BYTES,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.timeout(SHUTDOWN_TEST_TIMEOUT_SEC)
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("tensor_parallel_size", [2, 1])
|
||||
@pytest.mark.parametrize("enable_multiprocessing", [True])
|
||||
@pytest.mark.parametrize("failing_method", ["forward", "load_weights"])
|
||||
def test_llm_startup_error(
|
||||
monkeypatch,
|
||||
evil_method_fixture,
|
||||
model: str,
|
||||
tensor_parallel_size: int,
|
||||
enable_multiprocessing: bool,
|
||||
failing_method: str,
|
||||
) -> None:
|
||||
"""Test that LLM propagates an __init__ error and frees memory.
|
||||
Test profiling (forward()) and load weights failures.
|
||||
TODO(andy) - LLM without multiprocessing.
|
||||
"""
|
||||
# Skip non-Llama models since we monkeypatch LlamaForCausalLM specifically.
|
||||
# If MODELS list grows, each architecture needs its own test variant.
|
||||
if model != "JackFram/llama-68m":
|
||||
pytest.skip(reason="Only test JackFram/llama-68m")
|
||||
if current_platform.device_count() < tensor_parallel_size:
|
||||
pytest.skip(reason="Not enough CUDA devices")
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
MP_VALUE = "1" if enable_multiprocessing else "0"
|
||||
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", MP_VALUE)
|
||||
|
||||
# Monkeypatch an error in the model.
|
||||
monkeypatch.setattr(LlamaForCausalLM, failing_method, evil_method)
|
||||
|
||||
with pytest.raises(
|
||||
Exception,
|
||||
match=r"initialization fail(ed|ure)"
|
||||
if enable_multiprocessing
|
||||
else "Simulated Error in startup!",
|
||||
):
|
||||
_ = LLM(
|
||||
model=model,
|
||||
enforce_eager=True,
|
||||
tensor_parallel_size=tensor_parallel_size,
|
||||
)
|
||||
|
||||
# Confirm all the processes are cleaned up.
|
||||
wait_for_gpu_memory_to_clear(
|
||||
devices=list(range(tensor_parallel_size)),
|
||||
threshold_bytes=SHUTDOWN_TEST_THRESHOLD_BYTES,
|
||||
)
|
||||
@@ -1,329 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""EAGLE3 Acceptance Length Regression Tests.
|
||||
|
||||
These tests verify that acceptance lengths for EAGLE3 speculative decoding
|
||||
do not regress across vLLM commits. Each test runs inference on the MT-Bench
|
||||
dataset and asserts that the mean acceptance length is within tolerance of
|
||||
the expected baseline.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.conftest import VllmRunner
|
||||
from tests.utils import large_gpu_mark
|
||||
from vllm import SamplingParams
|
||||
from vllm.benchmarks.datasets import get_samples
|
||||
from vllm.inputs import TokensPrompt
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.selector import AttentionSelectorConfig
|
||||
from vllm.v1.metrics.reader import Counter, Vector
|
||||
|
||||
|
||||
@dataclass
|
||||
class Eagle3ModelConfig:
|
||||
verifier: str
|
||||
drafter: str
|
||||
expected_acceptance_length: float
|
||||
expected_acceptance_lengths_per_pos: list[float] = field(default_factory=list)
|
||||
id: str = ""
|
||||
# Backends that are incompatible with this model (will be skipped)
|
||||
excluded_backends: set[AttentionBackendEnum] = field(default_factory=set)
|
||||
# Pytest marks for this configuration
|
||||
marks: list = field(default_factory=list)
|
||||
# Custom relative tolerance (defaults to DEFAULT_RTOL if None)
|
||||
rtol: float | None = None
|
||||
# ROCm-specific test configuration
|
||||
rocm_expected_acceptance_lengths_per_pos: list[float] = field(default_factory=list)
|
||||
|
||||
|
||||
# Model configurations for EAGLE3 acceptance length tests.
|
||||
# Expected acceptance lengths are determined by running baseline benchmarks
|
||||
# using examples/features/speculative_decoding/spec_decode_offline.py
|
||||
# with the MT-Bench dataset.
|
||||
EAGLE3_MODEL_CONFIGS = [
|
||||
Eagle3ModelConfig(
|
||||
verifier="meta-llama/Llama-3.1-8B-Instruct",
|
||||
drafter="RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3",
|
||||
expected_acceptance_length=2.60,
|
||||
expected_acceptance_lengths_per_pos=[0.7296, 0.5208, 0.3545],
|
||||
id="llama3-8b-eagle3",
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="Qwen/Qwen3-8B",
|
||||
drafter="RedHatAI/Qwen3-8B-speculator.eagle3",
|
||||
expected_acceptance_length=2.26,
|
||||
expected_acceptance_lengths_per_pos=[0.6541, 0.3993, 0.2020],
|
||||
id="qwen3-8b-eagle3",
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="openai/gpt-oss-20b",
|
||||
drafter="RedHatAI/gpt-oss-20b-speculator.eagle3",
|
||||
expected_acceptance_length=2.56,
|
||||
expected_acceptance_lengths_per_pos=[0.7165, 0.5120, 0.3337],
|
||||
id="gpt-oss-20b-eagle3",
|
||||
# FLASHINFER incompatible: gpt-oss-20b uses sink attention which
|
||||
# FLASHINFER does not support ("sink setting not supported")
|
||||
excluded_backends={AttentionBackendEnum.FLASHINFER},
|
||||
rocm_expected_acceptance_lengths_per_pos=[0.7040, 0.4820, 0.3350],
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="Qwen/Qwen3-VL-30B-A3B-Instruct-FP8",
|
||||
drafter="nm-testing/Speculator-Qwen3-30B-MOE-VL-Eagle3",
|
||||
expected_acceptance_length=1.35,
|
||||
expected_acceptance_lengths_per_pos=[0.2900, 0.0620, 0.0115],
|
||||
id="qwen3-30b-moe-vl-eagle3",
|
||||
marks=[
|
||||
pytest.mark.slow_test,
|
||||
],
|
||||
rtol=0.15, # Higher tolerance due to small absolute values at position 2
|
||||
),
|
||||
]
|
||||
|
||||
# Default test parameters
|
||||
DEFAULT_NUM_SPEC_TOKENS = 3
|
||||
DEFAULT_NUM_PROMPTS = 80
|
||||
DEFAULT_OUTPUT_LEN = 256
|
||||
DEFAULT_MAX_MODEL_LEN = 16384
|
||||
DEFAULT_RTOL = 0.05
|
||||
|
||||
# TP sizes to test
|
||||
TP_SIZES = [1, 2, 4]
|
||||
|
||||
|
||||
# Backends excluded from testing due to significantly different behavior
|
||||
EXCLUDED_BACKENDS = {AttentionBackendEnum.FLEX_ATTENTION}
|
||||
|
||||
|
||||
def get_available_attention_backends() -> list[str]:
|
||||
if current_platform.is_rocm():
|
||||
return ["auto"]
|
||||
|
||||
# Check if get_valid_backends is actually defined in the platform class
|
||||
# (not just returning None from __getattr__)
|
||||
get_valid_backends = getattr(current_platform.__class__, "get_valid_backends", None)
|
||||
if get_valid_backends is None:
|
||||
return ["FLASH_ATTN"]
|
||||
|
||||
device_capability = current_platform.get_device_capability()
|
||||
if device_capability is None:
|
||||
return ["FLASH_ATTN"]
|
||||
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype=None,
|
||||
block_size=None,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_mm_prefix=False,
|
||||
)
|
||||
|
||||
valid_backends, _ = current_platform.get_valid_backends(
|
||||
device_capability=device_capability,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
return [
|
||||
candidate.backend.name
|
||||
for candidate in valid_backends
|
||||
if candidate.backend not in EXCLUDED_BACKENDS
|
||||
]
|
||||
|
||||
|
||||
def get_attention_backend_params() -> list[str]:
|
||||
return get_available_attention_backends()
|
||||
|
||||
|
||||
def get_tp_size_params() -> list[pytest.param]:
|
||||
num_gpus = torch.accelerator.device_count() if torch.cuda.is_available() else 1
|
||||
return [pytest.param(tp, id=f"tp{tp}") for tp in TP_SIZES if tp <= num_gpus]
|
||||
|
||||
|
||||
def get_mt_bench_prompts(
|
||||
tokenizer, num_prompts: int = DEFAULT_NUM_PROMPTS
|
||||
) -> list[list[int]]:
|
||||
args = SimpleNamespace(
|
||||
dataset_name="hf",
|
||||
dataset_path="philschmid/mt-bench",
|
||||
num_prompts=num_prompts,
|
||||
seed=42,
|
||||
no_oversample=False,
|
||||
endpoint_type="openai-chat",
|
||||
input_len=None,
|
||||
output_len=DEFAULT_OUTPUT_LEN,
|
||||
sharegpt_output_len=DEFAULT_OUTPUT_LEN,
|
||||
hf_name=None,
|
||||
hf_split="train",
|
||||
hf_subset=None,
|
||||
hf_output_len=DEFAULT_OUTPUT_LEN,
|
||||
no_stream=True,
|
||||
disable_shuffle=False,
|
||||
skip_chat_template=False,
|
||||
trust_remote_code=False,
|
||||
enable_multimodal_chat=False,
|
||||
request_id_prefix="",
|
||||
)
|
||||
samples = get_samples(args, tokenizer)
|
||||
prompt_ids = [
|
||||
tokenizer.encode(sample.prompt, add_special_tokens=False) for sample in samples
|
||||
]
|
||||
return prompt_ids
|
||||
|
||||
|
||||
def extract_acceptance_metrics(metrics, num_spec_tokens: int) -> dict:
|
||||
num_drafts = 0
|
||||
num_accepted_tokens = 0
|
||||
acceptance_counts = [0] * num_spec_tokens
|
||||
|
||||
for metric in metrics:
|
||||
if metric.name == "vllm:spec_decode_num_drafts":
|
||||
assert isinstance(metric, Counter)
|
||||
num_drafts += metric.value
|
||||
elif metric.name == "vllm:spec_decode_num_accepted_tokens":
|
||||
assert isinstance(metric, Counter)
|
||||
num_accepted_tokens += metric.value
|
||||
elif metric.name == "vllm:spec_decode_num_accepted_tokens_per_pos":
|
||||
assert isinstance(metric, Vector)
|
||||
for pos in range(min(len(metric.values), num_spec_tokens)):
|
||||
acceptance_counts[pos] += metric.values[pos]
|
||||
|
||||
# Calculate mean acceptance length
|
||||
# Formula: 1 + (accepted_tokens / num_drafts)
|
||||
acceptance_length = 1 + (num_accepted_tokens / num_drafts) if num_drafts > 0 else 1
|
||||
|
||||
# Calculate per-position acceptance lengths (contribution to total)
|
||||
# Each position contributes: accepted_at_pos / num_drafts
|
||||
acceptance_lengths_per_pos = [
|
||||
count / num_drafts if num_drafts > 0 else 0.0 for count in acceptance_counts
|
||||
]
|
||||
|
||||
return {
|
||||
"acceptance_length": acceptance_length,
|
||||
"acceptance_lengths_per_pos": acceptance_lengths_per_pos,
|
||||
"num_drafts": num_drafts,
|
||||
"num_accepted_tokens": num_accepted_tokens,
|
||||
}
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=40)
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="This test is only supported on CUDA-alike platforms.",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"model_config",
|
||||
[
|
||||
pytest.param(config, id=config.id, marks=config.marks)
|
||||
for config in EAGLE3_MODEL_CONFIGS
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("num_spec_tokens", [DEFAULT_NUM_SPEC_TOKENS])
|
||||
@pytest.mark.parametrize("tp_size", get_tp_size_params())
|
||||
@pytest.mark.parametrize("attention_backend", get_attention_backend_params())
|
||||
def test_eagle3_acceptance_length(
|
||||
model_config: Eagle3ModelConfig,
|
||||
num_spec_tokens: int,
|
||||
tp_size: int,
|
||||
attention_backend: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
# Skip if this backend is incompatible with the model
|
||||
attention_config = None
|
||||
if attention_backend != "auto":
|
||||
backend_enum = AttentionBackendEnum[attention_backend]
|
||||
if backend_enum in model_config.excluded_backends:
|
||||
pytest.skip(f"{attention_backend} is incompatible with {model_config.id}")
|
||||
attention_config = {"backend": attention_backend}
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
|
||||
with VllmRunner(
|
||||
model_name=model_config.verifier,
|
||||
speculative_config={
|
||||
"method": "eagle3",
|
||||
"model": model_config.drafter,
|
||||
"num_speculative_tokens": num_spec_tokens,
|
||||
},
|
||||
attention_config=attention_config,
|
||||
tensor_parallel_size=tp_size,
|
||||
gpu_memory_utilization=0.7,
|
||||
disable_log_stats=False,
|
||||
max_model_len=DEFAULT_MAX_MODEL_LEN,
|
||||
# Qwen/Qwen3-30B-A3B-FP8 with TP=4 needs EP
|
||||
# https://github.com/vllm-project/vllm/issues/25292
|
||||
enable_expert_parallel=(
|
||||
tp_size == 4 and "Qwen3-VL" in model_config.verifier
|
||||
),
|
||||
) as vllm_runner:
|
||||
tokenizer = vllm_runner.llm.get_tokenizer()
|
||||
prompt_ids = get_mt_bench_prompts(tokenizer, DEFAULT_NUM_PROMPTS)
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0,
|
||||
max_tokens=DEFAULT_OUTPUT_LEN,
|
||||
)
|
||||
vllm_runner.llm.generate(
|
||||
[TokensPrompt(prompt_token_ids=ids) for ids in prompt_ids],
|
||||
sampling_params=sampling_params,
|
||||
)
|
||||
|
||||
metrics = vllm_runner.llm.get_metrics()
|
||||
results = extract_acceptance_metrics(metrics, num_spec_tokens)
|
||||
|
||||
actual_acceptance_length = results["acceptance_length"]
|
||||
expected = model_config.expected_acceptance_length
|
||||
actual_per_pos = results["acceptance_lengths_per_pos"]
|
||||
expected_per_pos = model_config.expected_acceptance_lengths_per_pos
|
||||
if (
|
||||
current_platform.is_rocm()
|
||||
and model_config.rocm_expected_acceptance_lengths_per_pos
|
||||
):
|
||||
expected_per_pos = model_config.rocm_expected_acceptance_lengths_per_pos
|
||||
|
||||
rel_error = abs(actual_acceptance_length - expected) / expected
|
||||
|
||||
# Overall acceptance length always uses DEFAULT_RTOL
|
||||
assert rel_error <= DEFAULT_RTOL, (
|
||||
f"Acceptance length regression detected for {model_config.id}!\n"
|
||||
f" Expected: {expected:.3f}\n"
|
||||
f" Actual: {actual_acceptance_length:.3f}\n"
|
||||
f" Relative error: {rel_error:.2%} (tolerance: {DEFAULT_RTOL:.2%})\n"
|
||||
f" Drafts: {results['num_drafts']}, "
|
||||
f"Accepted tokens: {results['num_accepted_tokens']}"
|
||||
)
|
||||
|
||||
if expected_per_pos and len(expected_per_pos) == len(actual_per_pos):
|
||||
# Per-position checks use model-specific rtol if provided
|
||||
rtol = (
|
||||
model_config.rtol if model_config.rtol is not None else DEFAULT_RTOL
|
||||
)
|
||||
for pos, (actual, exp) in enumerate(
|
||||
zip(actual_per_pos, expected_per_pos)
|
||||
):
|
||||
if exp > 0:
|
||||
min_expected = exp * (1 - rtol)
|
||||
assert actual >= min_expected, (
|
||||
f"Per-position acceptance length regression at pos {pos} "
|
||||
f"for {model_config.id}!\n"
|
||||
f" Expected: {exp:.3f}\n"
|
||||
f" Actual: {actual:.3f}\n"
|
||||
f" Minimum: {min_expected:.3f}\n"
|
||||
f" Tolerance: rtol={rtol:.2%}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"\n{model_config.id} [tp={tp_size}, backend={attention_backend}]: "
|
||||
f"acceptance_length={actual_acceptance_length:.3f}"
|
||||
f" (expected={expected:.3f}, rel_error={rel_error:.2%})"
|
||||
)
|
||||
print(f" Per-position: {[f'{v:.3f}' for v in actual_per_pos]}")
|
||||
if expected_per_pos:
|
||||
print(f" Expected: {[f'{v:.3f}' for v in expected_per_pos]}")
|
||||
@@ -1,461 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.models.qwen3_dflash import (
|
||||
_add_global_draft_layer_exclusions,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_dflash2 import _grouped_conv, _score_edges
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import DFlash2Speculator
|
||||
|
||||
|
||||
@pytest.mark.parametrize("block_size", [5, 8])
|
||||
def test_grouped_conv_matches_reference(block_size: int):
|
||||
torch.manual_seed(0)
|
||||
batch, taps, num_groups, group_size = 3, 3, 4, 2
|
||||
hidden = torch.randn(batch * block_size, num_groups * group_size)
|
||||
delta = torch.randn(batch * block_size, taps, num_groups)
|
||||
base = torch.randn(taps, num_groups * group_size)
|
||||
|
||||
actual = _grouped_conv(
|
||||
hidden, delta, base, block_size, num_groups, group_size, taps
|
||||
)
|
||||
hidden_blocks = hidden.view(batch, block_size, num_groups, group_size)
|
||||
expected = torch.zeros_like(hidden_blocks)
|
||||
base = base.view(taps, num_groups, group_size)
|
||||
delta = delta.view(batch, block_size, taps, num_groups)
|
||||
for position in range(block_size):
|
||||
for tap in range(min(taps, position + 1)):
|
||||
expected[:, position] += (
|
||||
base[tap] + delta[:, position, tap, :, None]
|
||||
) * hidden_blocks[:, position - tap]
|
||||
|
||||
torch.testing.assert_close(actual, expected.flatten(0, 1).flatten(-2))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA")
|
||||
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
|
||||
@pytest.mark.parametrize(
|
||||
"batch,num_groups,group_size,block_size,taps",
|
||||
[
|
||||
(7, 13, 11, 5, 1),
|
||||
(7, 13, 11, 5, 3),
|
||||
(7, 13, 11, 8, 2),
|
||||
(16, 64, 16, 8, 2),
|
||||
(16, 160, 16, 8, 2),
|
||||
],
|
||||
)
|
||||
def test_grouped_conv_triton_matches_reference(
|
||||
dtype: torch.dtype,
|
||||
batch: int,
|
||||
num_groups: int,
|
||||
group_size: int,
|
||||
block_size: int,
|
||||
taps: int,
|
||||
):
|
||||
torch.manual_seed(0)
|
||||
rows = batch * block_size
|
||||
hidden = torch.randn(rows, num_groups * group_size, device="cuda", dtype=dtype)
|
||||
base = torch.randn(taps, num_groups * group_size, device="cuda", dtype=dtype)
|
||||
projected = torch.randn(rows, 2, taps, num_groups, device="cuda", dtype=dtype)
|
||||
delta = projected[:, 1]
|
||||
|
||||
actual = _grouped_conv(
|
||||
hidden, delta, base, block_size, num_groups, group_size, taps
|
||||
)
|
||||
|
||||
hidden_blocks = hidden.float().view(batch, block_size, num_groups, group_size)
|
||||
expected = torch.zeros_like(hidden_blocks)
|
||||
base_blocks = base.float().view(taps, num_groups, group_size)
|
||||
delta_blocks = delta.float().view(batch, block_size, taps, num_groups)
|
||||
for position in range(block_size):
|
||||
for tap in range(min(taps, position + 1)):
|
||||
expected[:, position] += (
|
||||
base_blocks[tap] + delta_blocks[:, position, tap, :, None]
|
||||
) * hidden_blocks[:, position - tap]
|
||||
|
||||
torch.testing.assert_close(
|
||||
actual,
|
||||
expected.flatten(0, 1).flatten(-2).to(dtype),
|
||||
rtol=1e-2 if dtype is torch.bfloat16 else 1e-5,
|
||||
atol=1e-2 if dtype is torch.bfloat16 else 1e-5,
|
||||
)
|
||||
|
||||
|
||||
def test_draft_quant_exclusions_include_global_layer_indices():
|
||||
quant_config = SimpleNamespace(
|
||||
exclude_modules=[
|
||||
"layers.0.mlp_conv*",
|
||||
"*layers.4.self_attn.q_proj",
|
||||
"layers.88.already_global",
|
||||
"lilicorr.layers.0.mlp.0",
|
||||
]
|
||||
)
|
||||
|
||||
_add_global_draft_layer_exclusions(quant_config, 88, 5)
|
||||
|
||||
assert "layers.88.mlp_conv*" in quant_config.exclude_modules
|
||||
assert "*layers.92.self_attn.q_proj" in quant_config.exclude_modules
|
||||
assert quant_config.exclude_modules.count("layers.88.already_global") == 1
|
||||
assert "lilicorr.layers.88.mlp.0" not in quant_config.exclude_modules
|
||||
|
||||
|
||||
def test_selector_edges_match_sequential_reference():
|
||||
torch.manual_seed(1)
|
||||
batch, steps, top_k, rank = 2, 4, 3, 5
|
||||
vocab = 17
|
||||
predecessors = torch.randn(vocab, rank)
|
||||
successors = torch.randn(vocab, rank)
|
||||
candidate_ids = torch.randint(vocab, (batch, steps, top_k))
|
||||
unary = torch.randn(batch, steps, top_k)
|
||||
hidden = torch.randn(batch, steps, rank)
|
||||
anchors = torch.randint(vocab, (batch,))
|
||||
|
||||
actual = _score_edges(
|
||||
predecessors,
|
||||
successors,
|
||||
candidate_ids,
|
||||
unary,
|
||||
hidden,
|
||||
anchors,
|
||||
top_k,
|
||||
)
|
||||
expected = torch.empty_like(actual)
|
||||
for step in range(steps):
|
||||
pred = (
|
||||
anchors[:, None].expand(-1, top_k)
|
||||
if step == 0
|
||||
else candidate_ids[:, step - 1]
|
||||
)
|
||||
expected[:, step] = unary[:, step, None] + torch.einsum(
|
||||
"bpr,bcr->bpc",
|
||||
predecessors[pred] * hidden[:, step, None],
|
||||
successors[candidate_ids[:, step]],
|
||||
)
|
||||
|
||||
torch.testing.assert_close(actual, expected)
|
||||
|
||||
|
||||
def _stub_base(monkeypatch, draft_logits):
|
||||
"""A DFlashSpeculator.__init__ that allocates only what the base class would.
|
||||
|
||||
The real base class fills draft_logits from draft_logits_spec, so callers
|
||||
pass a tensor already in that state.
|
||||
"""
|
||||
|
||||
def init_base(self, _vllm_config, device):
|
||||
self.draft_model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(dflash_config={"selector_top_k": 3})
|
||||
)
|
||||
self.max_num_reqs = 2
|
||||
self.num_query_per_req = 5
|
||||
self.num_speculative_steps = 4
|
||||
self.vocab_size = 17
|
||||
self.draft_tokens = torch.empty((2, 4), dtype=torch.int64, device=device)
|
||||
self.draft_logits = draft_logits
|
||||
|
||||
monkeypatch.setattr(DFlashSpeculator, "__init__", init_base)
|
||||
|
||||
|
||||
def test_selector_leaves_greedy_drafting_without_proposal_logits(monkeypatch):
|
||||
"""Greedy is the default, and it caches no proposal distribution.
|
||||
|
||||
The base class allocates draft_logits only for "probabilistic"; verification
|
||||
reads `draft_logits is None` to decide whether a distribution is on offer, so
|
||||
allocating one here would claim a proposal the walk never sampled from.
|
||||
"""
|
||||
_stub_base(monkeypatch, None)
|
||||
speculator = DFlash2Speculator(None, torch.device("cpu"))
|
||||
|
||||
assert speculator.draft_logits is None
|
||||
|
||||
|
||||
def test_selector_asks_for_fp32_proposal_logits():
|
||||
"""The spec the base class allocates from: fp32, filled -inf.
|
||||
|
||||
Not the head dtype -- rounding selector scores to bf16 moves the argmax of a
|
||||
candidate row often enough that the walk and the rejection sampler checking it
|
||||
would no longer read the same distribution.
|
||||
"""
|
||||
dtype, fill = DFlash2Speculator.draft_logits_spec(None, None)
|
||||
|
||||
assert dtype is torch.float32
|
||||
assert fill == float("-inf")
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
@pytest.mark.parametrize("variant", ["dflash2", "lilicorr", "lilicorr_plain"])
|
||||
def test_candidate_model_decoder_layer_cls(monkeypatch, variant):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3DecoderLayer
|
||||
from vllm.model_executor.models.qwen3_dflash2 import (
|
||||
DFlash2Qwen3DecoderLayer,
|
||||
DFlash2Qwen3Model,
|
||||
)
|
||||
|
||||
# 1. Mock get_current_vllm_config and TP groups
|
||||
mock_current_vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
block_size=16,
|
||||
user_specified_block_size=False,
|
||||
kv_cache_dtype_skip_layers=[],
|
||||
cache_dtype="auto",
|
||||
sliding_window=None,
|
||||
enable_prefix_caching=False,
|
||||
),
|
||||
kv_transfer_config=None,
|
||||
speculative_config=None,
|
||||
attention_config=SimpleNamespace(
|
||||
use_non_causal=False,
|
||||
backend=None,
|
||||
backend_per_kind={},
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=1,
|
||||
decode_context_parallel_size=1,
|
||||
),
|
||||
compilation_config=SimpleNamespace(
|
||||
compile_custom_ops=False,
|
||||
custom_ops="all",
|
||||
enabled_custom_ops=set(),
|
||||
static_forward_context={},
|
||||
mode=0, # CompilationMode.NONE is 0
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.float32,
|
||||
is_mm_prefix_lm=False,
|
||||
rswa_window=None,
|
||||
),
|
||||
kernel_config=SimpleNamespace(
|
||||
linear_backend="auto",
|
||||
),
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"get_attn_backend_cls",
|
||||
lambda *args, **kwargs: (
|
||||
"vllm.v1.attention.backends.cpu_attn.CPUAttentionBackend"
|
||||
),
|
||||
)
|
||||
|
||||
class MockGroup:
|
||||
rank_in_group = 0
|
||||
world_size = 1
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.parallel_state._TP",
|
||||
MockGroup(),
|
||||
)
|
||||
|
||||
# 2. Mock vllm_config
|
||||
hf_config = SimpleNamespace(
|
||||
vocab_size=1000,
|
||||
hidden_size=256,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=8,
|
||||
num_key_value_heads=2,
|
||||
max_position_embeddings=2048,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_parameters={},
|
||||
intermediate_size=512,
|
||||
hidden_act="silu",
|
||||
dflash_config={
|
||||
"selector_rank": 4,
|
||||
"selector_top_k": 3,
|
||||
"conv_kernel_size": 0 if variant == "lilicorr_plain" else 3,
|
||||
"conv_group_size": 0 if variant == "lilicorr_plain" else 2,
|
||||
"block_size": 5,
|
||||
"lilicorr_candidate_topk": 4,
|
||||
"lilicorr_hidden_size": 8,
|
||||
"lilicorr_num_layers": 2,
|
||||
"lilicorr_num_heads": 2,
|
||||
"lilicorr_mlp_ratio": 2.0,
|
||||
"lilicorr_factor_dim": 4,
|
||||
"lilicorr_vector_eps": 1e-6,
|
||||
"lilicorr_logit_scale": 3.0,
|
||||
"use_aux_hidden_state": False,
|
||||
},
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(
|
||||
hf_config=hf_config,
|
||||
quantization=None,
|
||||
),
|
||||
num_speculative_tokens=4,
|
||||
enable_adaptive_verification=False,
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.float32,
|
||||
is_mm_prefix_lm=False,
|
||||
),
|
||||
load_config=SimpleNamespace(
|
||||
quantization=None,
|
||||
quantization_param_path=None,
|
||||
),
|
||||
)
|
||||
mock_current_vllm_config.speculative_config = vllm_config.speculative_config
|
||||
vllm_config.compilation_config = mock_current_vllm_config.compilation_config
|
||||
|
||||
# 3. Instantiate the model under meta device to avoid parameter allocation issues
|
||||
with set_current_vllm_config(mock_current_vllm_config), torch.device("meta"):
|
||||
model_cls = DFlash2Qwen3Model if variant == "dflash2" else LiLiCorr
|
||||
model = model_cls(vllm_config=vllm_config)
|
||||
|
||||
# 4. Assert that the layers are DFlash2Qwen3DecoderLayer (the subclass)
|
||||
assert len(model.layers) == 2
|
||||
expected = (
|
||||
DFlashQwen3DecoderLayer
|
||||
if variant == "lilicorr_plain"
|
||||
else DFlash2Qwen3DecoderLayer
|
||||
)
|
||||
assert type(model.layers[0]) is expected
|
||||
|
||||
|
||||
def test_conv_projections_use_draft_quant_config(monkeypatch):
|
||||
from torch import nn
|
||||
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.model_executor.layers.quantization import modelopt
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3DecoderLayer
|
||||
from vllm.model_executor.models.qwen3_dflash2 import DFlash2Qwen3DecoderLayer
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_TP", SimpleNamespace(rank_in_group=0, world_size=1)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DFlashQwen3DecoderLayer,
|
||||
"__init__",
|
||||
lambda self, *a, **kw: nn.Module.__init__(self),
|
||||
)
|
||||
# Exercise the real quantized parameter allocation without selecting a GPU kernel.
|
||||
monkeypatch.setattr(
|
||||
modelopt,
|
||||
"select_linear_kernel",
|
||||
lambda *a, **kw: SimpleNamespace(input_quant_key=lambda: None),
|
||||
)
|
||||
quant_config = modelopt.ModelOptNvFp4Config(
|
||||
quant_method="W4A16_NVFP4", is_checkpoint_nvfp4_serialized=True
|
||||
)
|
||||
layer = DFlash2Qwen3DecoderLayer(
|
||||
SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=7),
|
||||
model_config=SimpleNamespace(dtype=torch.bfloat16),
|
||||
),
|
||||
config=SimpleNamespace(
|
||||
hidden_size=16,
|
||||
dflash_config={"conv_kernel_size": 2, "conv_group_size": 2},
|
||||
),
|
||||
layer_idx=0,
|
||||
prefix="model.layers.0",
|
||||
quant_config=quant_config,
|
||||
)
|
||||
for name in ("attention_conv", "mlp_conv"):
|
||||
module = getattr(layer, name)
|
||||
projection = module.kernel_projection
|
||||
assert projection.weight.dtype == torch.uint8
|
||||
assert projection.weight.shape == (32, 8)
|
||||
weight = torch.ones_like(projection.weight)
|
||||
AutoWeightsLoader(module).load_weights([("kernel_projection.weight", weight)])
|
||||
torch.testing.assert_close(projection.weight, weight)
|
||||
assert module.base_kernel.dtype == torch.bfloat16
|
||||
|
||||
|
||||
def test_context_kv_uses_quantized_projection_fallback(monkeypatch):
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.models import qwen3_dflash
|
||||
|
||||
class Projection(nn.Module):
|
||||
def __init__(self, packed_weight):
|
||||
super().__init__()
|
||||
self.register_buffer("packed_weight", packed_weight)
|
||||
self.quant_method = object()
|
||||
self.calls = 0
|
||||
|
||||
def forward(self, hidden_states):
|
||||
self.calls += 1
|
||||
return torch.nn.functional.linear(hidden_states, self.packed_weight), None
|
||||
|
||||
monkeypatch.setattr(
|
||||
qwen3_dflash.ops,
|
||||
"rms_norm",
|
||||
lambda output, hidden_states, weight, eps: output.copy_(hidden_states),
|
||||
)
|
||||
context_states = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
|
||||
projections = [
|
||||
Projection(
|
||||
torch.tensor(
|
||||
[
|
||||
[0.0, 0.0],
|
||||
[0.0, 0.0],
|
||||
[1.0, 0.0],
|
||||
[0.0, 1.0],
|
||||
[1.0, 1.0],
|
||||
[1.0, -1.0],
|
||||
]
|
||||
)
|
||||
),
|
||||
Projection(
|
||||
torch.tensor(
|
||||
[
|
||||
[0.0, 0.0],
|
||||
[0.0, 0.0],
|
||||
[2.0, 0.0],
|
||||
[0.0, 2.0],
|
||||
[-1.0, 0.0],
|
||||
[0.0, -1.0],
|
||||
]
|
||||
)
|
||||
),
|
||||
]
|
||||
model = SimpleNamespace(
|
||||
hidden_norm=SimpleNamespace(weight=nn.Parameter(torch.ones(2))),
|
||||
_rms_norm_eps=1e-6,
|
||||
)
|
||||
layers_attn = [
|
||||
SimpleNamespace(
|
||||
qkv_proj=projection,
|
||||
q_size=2,
|
||||
k_norm=SimpleNamespace(weight=nn.Parameter(torch.ones(2))),
|
||||
)
|
||||
for projection in projections
|
||||
]
|
||||
qwen3_dflash.DFlashQwen3Model._build_context_kv_buffers(
|
||||
model,
|
||||
layers_attn,
|
||||
has_bias=False,
|
||||
)
|
||||
assert model._fused_kv_weight is None
|
||||
assert all(not hasattr(projection, "weight") for projection in projections)
|
||||
|
||||
actual_k, actual_v = qwen3_dflash.DFlashQwen3Model._project_context_kv(
|
||||
model,
|
||||
context_states,
|
||||
num_ctx=2,
|
||||
num_layers=2,
|
||||
num_kv_heads=1,
|
||||
head_dim=2,
|
||||
)
|
||||
|
||||
expected_k = torch.tensor(
|
||||
[[[1.0, 2.0], [3.0, 4.0]], [[2.0, 4.0], [6.0, 8.0]]]
|
||||
).unsqueeze(2)
|
||||
expected_v = torch.tensor(
|
||||
[[[3.0, -1.0], [7.0, -1.0]], [[-1.0, -2.0], [-3.0, -4.0]]]
|
||||
).unsqueeze(2)
|
||||
torch.testing.assert_close(actual_k, expected_k)
|
||||
torch.testing.assert_close(actual_v, expected_v)
|
||||
assert [projection.calls for projection in projections] == [1, 1]
|
||||
@@ -1,127 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Config-only DFlash behavior.
|
||||
|
||||
``dflash_has_any_non_causal`` decides pre-build whether the draft needs a
|
||||
non-causal-capable backend, so its branch table (explicit override, SWA-derived
|
||||
per-layer causality, and the no-``layer_types`` fallback) is worth pinning.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.model_executor.models.qwen3_dflash import (
|
||||
_dflash_layer_causal,
|
||||
_get_dflash_fc_input_size,
|
||||
dflash_has_any_non_causal,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
|
||||
get_eagle3_aux_layers_from_config,
|
||||
)
|
||||
|
||||
|
||||
def _config(num_hidden_layers, layer_types=None, causal_override=None, is_causal=None):
|
||||
dflash_config = None if causal_override is None else {"causal": causal_override}
|
||||
return SimpleNamespace(
|
||||
num_hidden_layers=num_hidden_layers,
|
||||
layer_types=layer_types,
|
||||
dflash_config=dflash_config,
|
||||
is_causal=is_causal,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config,expected",
|
||||
[
|
||||
# Override forces causality on every layer, ignoring layer_types.
|
||||
(_config(2, layer_types=["full_attention"] * 2, causal_override=True), False),
|
||||
# Override forces non-causal on every layer.
|
||||
(
|
||||
_config(2, layer_types=["sliding_attention"] * 2, causal_override=False),
|
||||
True,
|
||||
),
|
||||
# DFlash2 stores the explicit attention semantics at the top level.
|
||||
(
|
||||
_config(
|
||||
2,
|
||||
layer_types=["sliding_attention"] * 2,
|
||||
is_causal=False,
|
||||
),
|
||||
True,
|
||||
),
|
||||
(
|
||||
_config(2, layer_types=["full_attention"] * 2, is_causal=True),
|
||||
False,
|
||||
),
|
||||
# SWA-derived: full-attention layers are non-causal.
|
||||
(_config(2, layer_types=["sliding_attention", "full_attention"]), True),
|
||||
# SWA-derived: all-sliding is fully causal.
|
||||
(_config(2, layer_types=["sliding_attention", "sliding_attention"]), False),
|
||||
# No layer_types -> non-causal fallback.
|
||||
(_config(2, layer_types=None), True),
|
||||
(_config(2, layer_types=[]), True),
|
||||
],
|
||||
)
|
||||
def test_dflash_has_any_non_causal(config, expected):
|
||||
assert dflash_has_any_non_causal(config) is expected
|
||||
|
||||
|
||||
def test_dflash_layer_causal_is_per_layer():
|
||||
config = _config(2, layer_types=["sliding_attention", "full_attention"])
|
||||
assert _dflash_layer_causal(config, 0) is True
|
||||
assert _dflash_layer_causal(config, 1) is False
|
||||
|
||||
|
||||
def test_dflash_layer_causal_honors_top_level_override():
|
||||
config = _config(
|
||||
2,
|
||||
layer_types=["sliding_attention", "full_attention"],
|
||||
is_causal=False,
|
||||
)
|
||||
assert _dflash_layer_causal(config, 0) is False
|
||||
assert _dflash_layer_causal(config, 1) is False
|
||||
|
||||
|
||||
def _vllm_config(**draft_config):
|
||||
config = SimpleNamespace(**draft_config)
|
||||
return SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(hf_config=config)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_dflash_fc_uses_aux_layer_count():
|
||||
vllm_config = _vllm_config(
|
||||
num_hidden_layers=5,
|
||||
hidden_size=4096,
|
||||
target_hidden_size=None,
|
||||
target_layer_ids=[1, 17, 32],
|
||||
)
|
||||
|
||||
assert _get_dflash_fc_input_size(vllm_config) == 3 * 4096
|
||||
|
||||
|
||||
def test_dflash_target_layers_map_to_post_layer_boundaries():
|
||||
vllm_config = _vllm_config(
|
||||
dflash_config={"target_layer_ids": [0, 16, 31]},
|
||||
)
|
||||
|
||||
assert get_eagle3_aux_layers_from_config(vllm_config.speculative_config) == (
|
||||
1,
|
||||
17,
|
||||
32,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_name", ["dflash_config", "eagle_config"])
|
||||
def test_eagle_aux_layers_preserves_legacy_layer_ids(config_name):
|
||||
layer_ids = [1, 17, 32]
|
||||
vllm_config = _vllm_config(
|
||||
**{config_name: {"layer_ids": layer_ids}},
|
||||
)
|
||||
|
||||
assert get_eagle3_aux_layers_from_config(vllm_config.speculative_config) == tuple(
|
||||
layer_ids
|
||||
)
|
||||
@@ -1,283 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptLinearMethod,
|
||||
resolve,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import (
|
||||
dequantize_to_dtype,
|
||||
nvfp4_gathered_bias,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_dspark import DSparkMarkovHead
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator
|
||||
|
||||
|
||||
def _markov_head(weight: torch.Tensor) -> DSparkMarkovHead:
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = nn.Linear(
|
||||
weight.shape[1], weight.shape[0], bias=False, dtype=weight.dtype
|
||||
)
|
||||
head.markov_w2.weight.data.copy_(weight)
|
||||
head.markov_w2._retain_weight_for_gather = False
|
||||
head.markov_w2.is_w4a16_nvfp4 = False
|
||||
return head
|
||||
|
||||
|
||||
def test_gathered_markov_bias_overwrites_dense_logits():
|
||||
weight = torch.arange(21, dtype=torch.float32).view(7, 3) / 10
|
||||
markov_embed = torch.tensor([[0.5, -1.0, 0.25], [1.0, 0.5, -0.5]])
|
||||
logits = torch.tensor(
|
||||
[
|
||||
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7],
|
||||
[0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1],
|
||||
]
|
||||
)
|
||||
values, index = logits.topk(3, dim=-1)
|
||||
values = torch.stack((values, torch.zeros_like(values)), dim=1)[:, 0]
|
||||
expected = values + torch.bmm(weight[index], markov_embed.unsqueeze(-1)).squeeze(-1)
|
||||
logits.fill_(float("-inf"))
|
||||
|
||||
result = _markov_head(weight).apply_bias_gathered(
|
||||
markov_embed, logits, values, index
|
||||
)
|
||||
|
||||
assert result is logits
|
||||
torch.testing.assert_close(result.gather(1, index), expected)
|
||||
selected = torch.zeros_like(result, dtype=torch.bool).scatter_(1, index, True)
|
||||
assert torch.isneginf(result.masked_select(~selected)).all()
|
||||
|
||||
|
||||
def test_gathered_markov_bias_matches_dense_at_full_vocab():
|
||||
weight = torch.arange(15, dtype=torch.float32).view(5, 3) / 10
|
||||
markov_embed = torch.tensor([[0.5, -1.0, 0.25]])
|
||||
logits = torch.tensor([[0.1, 0.4, -0.2, 0.3, 0.0]])
|
||||
original = logits.clone()
|
||||
values, index = logits.topk(logits.shape[-1], dim=-1)
|
||||
scale = 0.5
|
||||
logits.fill_(float("-inf"))
|
||||
|
||||
result = _markov_head(weight).apply_bias_gathered(
|
||||
markov_embed, logits, values, index, scale
|
||||
)
|
||||
|
||||
expected = original + markov_embed @ weight.T * scale
|
||||
torch.testing.assert_close(result, expected)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("use_fp64", [False, True])
|
||||
def test_dspark_revisited_position_uses_step_seed(use_fp64):
|
||||
"""A cached draft at a revisited position must use its current step."""
|
||||
device = torch.device("cuda")
|
||||
batch = 4096
|
||||
spec = DSparkSpeculator.__new__(DSparkSpeculator)
|
||||
spec.acceptance_estimator = None
|
||||
spec._d2t_scatter_index = None
|
||||
spec.draft_watermarker = None
|
||||
spec.use_fp64_gumbel = use_fp64
|
||||
spec.temperature = torch.ones(batch, device=device)
|
||||
spec.seeds = torch.arange(batch, dtype=torch.int64, device=device)
|
||||
spec._step_cols = torch.arange(2, dtype=torch.int32, device=device)
|
||||
spec.draft_logits = torch.empty(batch, 2, 2, device=device)
|
||||
logits = torch.tensor([0.7, 0.3], device=device).log().expand(batch, -1)
|
||||
mapping = torch.arange(batch, device=device)
|
||||
positions = torch.full((batch,), 22, dtype=torch.int64, device=device)
|
||||
|
||||
first = spec._sample_logits(logits, mapping, positions, 1)
|
||||
repeated = spec._sample_logits(logits, mapping, positions, 1)
|
||||
next_round = spec._sample_logits(logits, mapping, positions, 0)
|
||||
torch.testing.assert_close(first, repeated)
|
||||
expected = gumbel_sample(
|
||||
logits,
|
||||
mapping,
|
||||
spec.temperature,
|
||||
spec.seeds,
|
||||
positions - 1,
|
||||
apply_temperature=True,
|
||||
is_drafting=True,
|
||||
logits_cache=spec.draft_logits,
|
||||
logits_cache_col=spec._step_cols[0],
|
||||
use_fp64=use_fp64,
|
||||
)
|
||||
torch.testing.assert_close(next_round, expected)
|
||||
mismatch_rate = (first != next_round).float().mean().item()
|
||||
assert 0.35 < mismatch_rate < 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cuda_alike_platform", [False, True])
|
||||
def test_gathered_markov_bias_dequantizes_selected_w4a16_rows(
|
||||
monkeypatch, cuda_alike_platform
|
||||
):
|
||||
packed_weight = torch.tensor(
|
||||
[[0x00] * 8, [0x22] * 8, [0xAA] * 8, [0x31] * 8], dtype=torch.uint8
|
||||
)
|
||||
weight_scale = torch.ones((4, 1), dtype=torch.float8_e4m3fn)
|
||||
|
||||
layer = nn.Module()
|
||||
layer.weight = nn.Parameter(packed_weight, requires_grad=False)
|
||||
layer.weight_scale = nn.Parameter(weight_scale, requires_grad=False)
|
||||
layer.weight_scale_2 = nn.Parameter(torch.ones(1), requires_grad=False)
|
||||
layer._retain_weight_for_gather = True
|
||||
|
||||
spec, ctx, fmt = resolve("W4A16_NVFP4", type("Config", (), {"group_size": 16}), "")
|
||||
method = ModelOptLinearMethod(spec, ctx, fmt)
|
||||
|
||||
class RepackingKernel:
|
||||
@staticmethod
|
||||
def process_weights_after_loading(layer):
|
||||
layer.weight = nn.Parameter(
|
||||
torch.zeros((1, 1), dtype=torch.int32), requires_grad=False
|
||||
)
|
||||
layer.weight_scale = nn.Parameter(
|
||||
torch.zeros((1, 1), dtype=torch.float32), requires_grad=False
|
||||
)
|
||||
layer.weight_global_scale = nn.Parameter(
|
||||
torch.zeros(1, dtype=torch.float32), requires_grad=False
|
||||
)
|
||||
|
||||
method.kernel = RepackingKernel()
|
||||
method.process_weights_after_loading(layer)
|
||||
assert layer.is_w4a16_nvfp4
|
||||
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = layer
|
||||
markov_embed = torch.tensor([[1.0] * 16, [0.5, -0.5] * 8], dtype=torch.float32)
|
||||
index = torch.tensor([[1, 3], [2, 0]])
|
||||
values = torch.tensor([[0.25, -0.5], [1.0, 2.0]])
|
||||
original_values = values.clone()
|
||||
logits = torch.full((2, 4), float("-inf"))
|
||||
|
||||
# CPU tensors must use the fallback even on CUDA/ROCm hosts.
|
||||
monkeypatch.setattr(current_platform, "is_cuda_alike", lambda: cuda_alike_platform)
|
||||
result = head.apply_bias_gathered(markov_embed, logits, values, index)
|
||||
|
||||
dense_weight = torch.tensor([[0.0] * 16, [1.0] * 16, [-1.0] * 16, [0.5, 1.5] * 8])
|
||||
expected = original_values + torch.bmm(
|
||||
dense_weight[index], markov_embed.unsqueeze(-1)
|
||||
).squeeze(-1)
|
||||
torch.testing.assert_close(result.gather(1, index), expected)
|
||||
torch.testing.assert_close(values, original_values)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_nvfp4_gathered_bias_rejects_non_16_group_size():
|
||||
device = torch.device("cuda")
|
||||
rank = 32
|
||||
vocab_size = 2
|
||||
|
||||
with pytest.raises(ValueError, match="group size of 16"):
|
||||
nvfp4_gathered_bias(
|
||||
torch.zeros((1, rank), dtype=torch.bfloat16, device=device),
|
||||
torch.zeros((vocab_size, rank // 2), dtype=torch.uint8, device=device),
|
||||
torch.ones(
|
||||
(vocab_size, rank // 32), dtype=torch.float8_e4m3fn, device=device
|
||||
),
|
||||
torch.ones(1, dtype=torch.float32, device=device),
|
||||
torch.zeros((1, 1), dtype=torch.bfloat16, device=device),
|
||||
torch.zeros((1, 1), dtype=torch.int64, device=device),
|
||||
torch.full(
|
||||
(1, vocab_size), float("-inf"), dtype=torch.bfloat16, device=device
|
||||
),
|
||||
1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("batch_size", [1, 2, 4, 8])
|
||||
def test_nvfp4_gathered_markov_bias_kernel_matches_reference(batch_size: int):
|
||||
torch.manual_seed(0)
|
||||
device = torch.device("cuda")
|
||||
topk = 256
|
||||
rank = 512
|
||||
vocab_size = 512
|
||||
alpha = 0.75
|
||||
|
||||
packed_weight = torch.randint(
|
||||
0, 256, (vocab_size, rank // 2), dtype=torch.uint8, device=device
|
||||
)
|
||||
weight_scale = torch.full(
|
||||
(vocab_size, rank // 16),
|
||||
0.5,
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device=device,
|
||||
)
|
||||
global_scale = torch.tensor([0.25], dtype=torch.float32, device=device)
|
||||
|
||||
markov_storage = torch.randn(
|
||||
batch_size, 2, rank, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
values_storage = torch.randn(
|
||||
batch_size, 2, topk, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
index_storage = torch.empty(batch_size, 2, topk, dtype=torch.int64, device=device)
|
||||
for batch_idx in range(batch_size):
|
||||
index_storage[batch_idx, 0] = (
|
||||
torch.arange(topk, device=device) + batch_idx
|
||||
) % vocab_size
|
||||
logits_storage = torch.full(
|
||||
(batch_size, 2, vocab_size),
|
||||
float("-inf"),
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
|
||||
markov_embed = markov_storage[:, 0]
|
||||
values = values_storage[:, 0]
|
||||
index = index_storage[:, 0]
|
||||
logits = logits_storage[:, 0]
|
||||
|
||||
layer = nn.Module()
|
||||
layer.register_buffer("_nvfp4_weight_for_gather", packed_weight)
|
||||
layer.register_buffer("_nvfp4_weight_scale_for_gather", weight_scale)
|
||||
layer.register_buffer("_nvfp4_weight_global_scale_for_gather", global_scale)
|
||||
layer._nvfp4_group_size_for_gather = 16
|
||||
layer._retain_weight_for_gather = True
|
||||
layer.is_w4a16_nvfp4 = True
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = layer
|
||||
|
||||
flat_index = index.reshape(-1)
|
||||
selected_weight = dequantize_to_dtype(
|
||||
packed_weight.index_select(0, flat_index),
|
||||
weight_scale.index_select(0, flat_index),
|
||||
global_scale,
|
||||
dtype=torch.bfloat16,
|
||||
block_size=16,
|
||||
swizzle=False,
|
||||
).view(batch_size, topk, rank)
|
||||
expected = (
|
||||
values
|
||||
+ torch.bmm(selected_weight, markov_embed.unsqueeze(-1)).squeeze(-1) * alpha
|
||||
)
|
||||
|
||||
result = head.apply_bias_gathered(markov_embed, logits, values, index, alpha)
|
||||
|
||||
torch.testing.assert_close(
|
||||
result.gather(1, index), expected, rtol=1e-2, atol=6.25e-2
|
||||
)
|
||||
selected = torch.zeros_like(result, dtype=torch.bool).scatter_(1, index, True)
|
||||
assert torch.isneginf(result.masked_select(~selected)).all()
|
||||
|
||||
if batch_size == 1:
|
||||
logits.fill_(float("-inf"))
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
captured = head.apply_bias_gathered(
|
||||
markov_embed, logits, values, index, alpha
|
||||
)
|
||||
logits.fill_(float("-inf"))
|
||||
graph.replay()
|
||||
assert captured is logits
|
||||
torch.testing.assert_close(
|
||||
logits.gather(1, index), expected, rtol=1e-2, atol=6.25e-2
|
||||
)
|
||||
@@ -1,164 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""``get_top_tokens`` on the DeepSeek V4 MTP drafter.
|
||||
|
||||
The speculator opts into ``use_local_argmax_reduction`` by probing the draft
|
||||
model for ``get_top_tokens``, and expects it to select the same greedy draft
|
||||
token the full-vocab argmax would. V4 reaches its LM head through hc_head and
|
||||
the shared head's RMSNorm, so both methods have to share that transform.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mhc import HCHeadOp
|
||||
from vllm.model_executor.models.deepseek_mtp import SharedHead
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip(
|
||||
"get_top_tokens is implemented on the ROCm DeepSeek V4 MTP drafter only.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.models.deepseek_v4.amd.mtp import ( # noqa: E402
|
||||
DeepSeekV4MTP,
|
||||
DeepSeekV4MultiTokenPredictor,
|
||||
)
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
START_LAYER_IDX = 61
|
||||
HIDDEN_SIZE = 4096
|
||||
HC_MULT = 4
|
||||
RMS_NORM_EPS = 1e-6
|
||||
HC_EPS = 1e-6
|
||||
_EMBEDDING = "vllm.model_executor.layers.vocab_parallel_embedding"
|
||||
|
||||
|
||||
def _make_predictor(vocab_size: int) -> DeepSeekV4MultiTokenPredictor:
|
||||
config = PreTrainedConfig()
|
||||
config.hidden_size = HIDDEN_SIZE
|
||||
config.vocab_size = vocab_size
|
||||
config.rms_norm_eps = RMS_NORM_EPS
|
||||
|
||||
# A single vocab shard, so the reduction returns the local argmax without
|
||||
# touching the process group.
|
||||
with (
|
||||
mock.patch(f"{_EMBEDDING}.get_tensor_model_parallel_rank", return_value=0),
|
||||
mock.patch(
|
||||
f"{_EMBEDDING}.get_tensor_model_parallel_world_size", return_value=1
|
||||
),
|
||||
):
|
||||
shared_head = SharedHead(config=config, prefix="shared_head")
|
||||
|
||||
assert shared_head.head is not None
|
||||
generator = torch.Generator().manual_seed(7)
|
||||
with torch.no_grad():
|
||||
shared_head.head.weight.normal_(0.0, 0.02, generator=generator)
|
||||
# The default norm weight is all ones, and the argmax is invariant to
|
||||
# the norm's per-row rescale, so a uniform gain would hide a skipped
|
||||
# shared_head. Vary it so the comparison below can see one.
|
||||
shared_head.norm.weight.normal_(1.0, 0.5, generator=generator)
|
||||
shared_head = shared_head.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
hc_head_fn = torch.randn(
|
||||
HC_MULT, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
# Non-trivial gate scale and bias: hc_head mixes the hc_mult streams with
|
||||
# these, and defaults of 0 would make a skipped hc_head harder to see.
|
||||
hc_head_scale = torch.randn(1, dtype=torch.float32, generator=generator) * 0.1
|
||||
hc_head_base = torch.randn(HC_MULT, dtype=torch.float32, generator=generator) * 0.1
|
||||
|
||||
mtp_layer = SimpleNamespace(
|
||||
config=config,
|
||||
hc_mult=HC_MULT,
|
||||
hc_eps=HC_EPS,
|
||||
rms_norm_eps=RMS_NORM_EPS,
|
||||
hc_head_op=HCHeadOp(),
|
||||
hc_head_fn=(hc_head_fn * 1e-4).to(DEVICE_TYPE),
|
||||
hc_head_scale=hc_head_scale.to(DEVICE_TYPE),
|
||||
hc_head_base=hc_head_base.to(DEVICE_TYPE),
|
||||
shared_head=shared_head,
|
||||
)
|
||||
|
||||
# Only the attributes the two methods read; a real predictor would also
|
||||
# build the MLA/MoE draft block, which is irrelevant here.
|
||||
predictor = object.__new__(DeepSeekV4MultiTokenPredictor)
|
||||
torch.nn.Module.__init__(predictor)
|
||||
predictor.layers = {str(START_LAYER_IDX): mtp_layer}
|
||||
predictor.mtp_start_layer_idx = START_LAYER_IDX
|
||||
predictor.num_mtp_layers = 1
|
||||
predictor.logits_processor = LogitsProcessor(vocab_size)
|
||||
return predictor
|
||||
|
||||
|
||||
def _hidden_states(num_tokens: int, seed: int) -> torch.Tensor:
|
||||
"""The flat pre-hc_head residual the MTP layer returns."""
|
||||
generator = torch.Generator().manual_seed(seed)
|
||||
hidden_states = torch.randn(
|
||||
num_tokens, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
return hidden_states.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
|
||||
def _assert_selects_max_logit(top: torch.Tensor, logits: torch.Tensor) -> None:
|
||||
"""The selected token must carry the row's maximum logit.
|
||||
|
||||
hc_head emits bf16, so rows can tie for the maximum and then no single
|
||||
index is the right answer; compare the values the two paths select.
|
||||
"""
|
||||
assert top.shape == (logits.shape[0],)
|
||||
selected = logits.gather(1, top.unsqueeze(1)).squeeze(1)
|
||||
assert torch.equal(selected, logits.max(dim=-1).values)
|
||||
|
||||
|
||||
def test_get_top_tokens_matches_full_argmax(default_vllm_config):
|
||||
"""Same draft token as the path taken when the reduction is off.
|
||||
|
||||
``get_top_tokens`` has to run the same pre-head transform as
|
||||
``compute_logits``: hc_head over the (T, hc_mult, D) residual, then the
|
||||
shared head's RMSNorm. Dropping either one returns a different draft token
|
||||
instead of failing, which is what this comparison catches.
|
||||
"""
|
||||
predictor = _make_predictor(vocab_size=512)
|
||||
|
||||
for num_tokens in (1, 16, 128):
|
||||
hidden_states = _hidden_states(num_tokens, seed=11)
|
||||
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
assert top.dtype == torch.int64
|
||||
_assert_selects_max_logit(top, logits)
|
||||
|
||||
|
||||
def test_get_top_tokens_honors_padded_vocab(default_vllm_config):
|
||||
"""Padding entries above ``org_vocab_size`` must never win the argmax."""
|
||||
vocab_size = 500
|
||||
predictor = _make_predictor(vocab_size)
|
||||
head = predictor.layers[str(START_LAYER_IDX)].shared_head.head
|
||||
assert head.shard_indices.num_org_vocab_padding > 0
|
||||
|
||||
hidden_states = _hidden_states(32, seed=13)
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
_assert_selects_max_logit(top, logits)
|
||||
assert (top < vocab_size).all()
|
||||
|
||||
|
||||
def test_wrapper_forwards_spec_step_idx():
|
||||
"""``DeepSeekV4MTP`` is what the speculator probes, so it needs the method."""
|
||||
assert hasattr(DeepSeekV4MTP, "get_top_tokens")
|
||||
|
||||
hidden_states = torch.empty(0)
|
||||
wrapper = object.__new__(DeepSeekV4MTP)
|
||||
wrapper.model = SimpleNamespace(get_top_tokens=lambda *args: args)
|
||||
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states, 2) == (hidden_states, 2)
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states) == (hidden_states, 0)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,881 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import (
|
||||
CompilationConfig,
|
||||
CompilationMode,
|
||||
DeviceConfig,
|
||||
LoadConfig,
|
||||
VllmConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.model_executor.layers import logits_processor
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorrHead
|
||||
from vllm.transformers_utils.configs.eagle import EAGLEConfig
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import CandidateSampler
|
||||
from vllm.v1.worker.gpu.spec_decode.lilicorr.speculator import LiLiCorrSpeculator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def head_tp_metadata(monkeypatch):
|
||||
# Single-rank unit tests only need TP metadata.
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_TP", SimpleNamespace(rank_in_group=0, world_size=1)
|
||||
)
|
||||
|
||||
|
||||
def _config(**overrides):
|
||||
config = dict(
|
||||
candidate_topk=4,
|
||||
hidden_size=8,
|
||||
num_layers=2,
|
||||
num_heads=2,
|
||||
mlp_ratio=2.0,
|
||||
factor_dim=4,
|
||||
vector_eps=1e-6,
|
||||
logit_scale=3.0,
|
||||
)
|
||||
config.update(overrides)
|
||||
return {f"lilicorr_{key}": value for key, value in config.items()}
|
||||
|
||||
|
||||
def _reference_scores(head, embeddings, log_probs, hidden, anchor, valid):
|
||||
"""Unfused exported head: MHA attention, concatenated factors, separate edges."""
|
||||
batch, slots, top_k = log_probs.shape
|
||||
rank = torch.arange(top_k, device=log_probs.device) / max(top_k - 1, 1)
|
||||
top1 = (torch.arange(top_k, device=log_probs.device) == 0).float()
|
||||
features = torch.stack(
|
||||
(
|
||||
log_probs,
|
||||
log_probs.exp(),
|
||||
log_probs - log_probs.amax(-1, keepdim=True),
|
||||
rank.expand_as(log_probs),
|
||||
top1.expand_as(log_probs),
|
||||
),
|
||||
-1,
|
||||
)
|
||||
x = head.token_proj(embeddings) + head.pass_hidden_proj(hidden).unsqueeze(-2)
|
||||
features = head.feature_norm(features.to(x.dtype))
|
||||
x = x + head.feature_mlp.down_proj(F.silu(head.feature_mlp.up_proj(features)[0]))[0]
|
||||
x = x + head.slot_embedding[:, 0, :slots] + head.rank_embedding[:, 0]
|
||||
x = x.flatten(1, 2)
|
||||
positions = torch.arange(slots, device=x.device).repeat_interleave(top_k)
|
||||
relative = positions[:, None] - positions[None, :]
|
||||
bias = head.relative_slot_bias[:, relative + head.block_size - 1]
|
||||
bias = bias + (relative == 0) * head.same_slot_bias[:, None, None]
|
||||
bias = bias.repeat(batch, 1, 1)
|
||||
for layer in head.layers:
|
||||
attention = nn.MultiheadAttention(
|
||||
head.hidden_size,
|
||||
head.num_heads,
|
||||
batch_first=True,
|
||||
dtype=x.dtype,
|
||||
device=x.device,
|
||||
)
|
||||
attention.load_state_dict(layer.attn.state_dict())
|
||||
normalized = layer.attn_norm(x)
|
||||
x = (
|
||||
x
|
||||
+ attention(
|
||||
normalized, normalized, normalized, attn_mask=bias, need_weights=False
|
||||
)[0]
|
||||
)
|
||||
x = x + layer.mlp.down_proj(F.silu(layer.mlp.up_proj(layer.mlp_norm(x))[0]))[0]
|
||||
x = head.output_norm(x).view(batch, slots, top_k, -1)
|
||||
a = head.anchor_norm(head.context_proj(anchor) * valid[:, None])
|
||||
expanded = a[:, None, None].expand_as(x)
|
||||
factors = F.silu(head.factor_input_proj(torch.cat((x, expanded, x * expanded), -1)))
|
||||
incoming = F.normalize(head.in_head(factors), dim=-1, eps=head.vector_eps)
|
||||
outgoing = F.normalize(head.out_head(factors), dim=-1, eps=head.vector_eps)
|
||||
a = F.normalize(head.anchor_out_head(a), dim=-1, eps=head.vector_eps)
|
||||
start = (a[:, None] * incoming[:, 0]).sum(-1)
|
||||
pairs = outgoing[:, :-1] @ incoming[:, 1:].transpose(-1, -2)
|
||||
return (
|
||||
head.logit_scale
|
||||
* torch.cat((start[:, None, None].expand(-1, 1, top_k, -1), pairs), 1).float()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA or ROCm")
|
||||
@pytest.mark.parametrize(
|
||||
"head_width,slots,dtype",
|
||||
[
|
||||
pytest.param(8, 3, torch.float32, id="projected-multi-slot"),
|
||||
pytest.param(16, 1, torch.float32, id="identity-shortened-single-slot"),
|
||||
pytest.param(8, 2, torch.bfloat16, id="bf16-shortened-multi-slot"),
|
||||
],
|
||||
)
|
||||
def test_lilicorr_matches_exported_head(head_width, slots, dtype):
|
||||
device = torch.device("cuda")
|
||||
torch.manual_seed(7)
|
||||
with (
|
||||
torch.device(device),
|
||||
set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cuda"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
),
|
||||
):
|
||||
head = LiLiCorrHead(
|
||||
model_hidden_size=16,
|
||||
block_size=4,
|
||||
rms_norm_eps=1e-6,
|
||||
config=_config(hidden_size=head_width),
|
||||
).to(dtype)
|
||||
# vLLM linear parameters are initialized by the checkpoint loader.
|
||||
with torch.no_grad(), torch.device(device):
|
||||
for module in head.modules():
|
||||
if isinstance(module, LinearBase):
|
||||
for parameter in module.parameters():
|
||||
parameter.weight_loader(
|
||||
parameter, torch.randn_like(parameter) * 0.1
|
||||
)
|
||||
for layer in head.layers:
|
||||
layer.attn.in_proj_weight.normal_(std=0.1)
|
||||
layer.attn.in_proj_bias.normal_(std=0.1)
|
||||
head.relative_slot_bias.normal_(std=0.1)
|
||||
head.same_slot_bias.normal_(std=0.1)
|
||||
head.slot_embedding.normal_(std=0.1)
|
||||
head.rank_embedding.normal_(std=0.1)
|
||||
head.materialize_inference_buffers(device, dtype)
|
||||
inputs = (
|
||||
torch.randn(2, slots, 4, 16, dtype=dtype),
|
||||
torch.randn(2, slots, 23).log_softmax(-1).topk(4).values,
|
||||
torch.randn(2, slots, 16, dtype=dtype),
|
||||
torch.randn(2, 16, dtype=dtype),
|
||||
torch.tensor([True, False]),
|
||||
)
|
||||
actual = head(*inputs)
|
||||
expected = _reference_scores(head, *inputs)
|
||||
tolerance = 0.04 if dtype == torch.bfloat16 else 2e-6
|
||||
torch.testing.assert_close(actual, expected, atol=tolerance, rtol=tolerance)
|
||||
|
||||
|
||||
def test_runtime_length_keeps_trained_checkpoint_geometry(monkeypatch):
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3Model
|
||||
|
||||
def init_backbone(self, **kwargs):
|
||||
nn.Module.__init__(self)
|
||||
self.quant_config = None
|
||||
|
||||
monkeypatch.setattr(DFlashQwen3Model, "__init__", init_backbone)
|
||||
spec = SimpleNamespace(
|
||||
num_speculative_tokens=1,
|
||||
draft_model_config=SimpleNamespace(
|
||||
hf_config=SimpleNamespace(
|
||||
hidden_size=16,
|
||||
rms_norm_eps=1e-6,
|
||||
dflash_config=_config() | {"block_size": 4},
|
||||
)
|
||||
),
|
||||
)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
for slots in (1, 3):
|
||||
spec.num_speculative_tokens = slots
|
||||
head = LiLiCorr(
|
||||
vllm_config=SimpleNamespace(speculative_config=spec)
|
||||
).lilicorr
|
||||
assert head.slot_embedding.shape == (1, 1, 3, 1, 8)
|
||||
assert head.relative_slot_bias.shape == (2, 7)
|
||||
spec.draft_model_config.hf_config.dflash_config["lilicorr_enabled"] = False
|
||||
with pytest.raises(ValueError, match="lilicorr_enabled"):
|
||||
LiLiCorr(vllm_config=SimpleNamespace(speculative_config=spec))
|
||||
spec.draft_model_config.hf_config.dflash_config["lilicorr_enabled"] = True
|
||||
spec.num_speculative_tokens = 4
|
||||
with pytest.raises(ValueError, match="trained block_size"):
|
||||
LiLiCorr(vllm_config=SimpleNamespace(speculative_config=spec))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tp_size", [1, 2])
|
||||
def test_candidates_use_global_partition_and_exclude_padding(monkeypatch, tp_size):
|
||||
"""Candidate features must include mass outside top-k and on other TP ranks."""
|
||||
|
||||
class Gather:
|
||||
def __init__(self, calls):
|
||||
self.calls = calls
|
||||
self.index = 0
|
||||
|
||||
def __call__(self, value, dim=-1):
|
||||
expected_input, result = self.calls[self.index]
|
||||
assert dim == -1
|
||||
torch.testing.assert_close(value, expected_input)
|
||||
self.index += 1
|
||||
return result
|
||||
|
||||
shards = [
|
||||
torch.tensor([[1.0, 3.0, 2.0, 100.0], [4.0, 1.0, 2.0, 100.0]]),
|
||||
torch.tensor([[6.0, 5.0, 0.0, 100.0], [3.0, 6.0, 5.0, 100.0]]),
|
||||
][:tp_size]
|
||||
for rank in range(tp_size):
|
||||
fake = SimpleNamespace(
|
||||
scale=1.0,
|
||||
soft_cap=None,
|
||||
_apply_head=lambda *args, rank=rank: shards[rank].clone(),
|
||||
)
|
||||
lm_head = SimpleNamespace(
|
||||
tp_size=tp_size,
|
||||
shard_indices=SimpleNamespace(
|
||||
num_org_vocab_padding=1, org_vocab_start_index=rank * 3
|
||||
),
|
||||
)
|
||||
valid_shards = [shard[:, :3] for shard in shards]
|
||||
local_topk = [shard.topk(2) for shard in valid_shards]
|
||||
gather_calls = [
|
||||
(
|
||||
valid_shards[rank].logsumexp(-1, keepdim=True),
|
||||
torch.cat(
|
||||
[shard.logsumexp(-1, keepdim=True) for shard in valid_shards],
|
||||
-1,
|
||||
),
|
||||
),
|
||||
(
|
||||
local_topk[rank].values,
|
||||
torch.cat([topk.values for topk in local_topk], -1),
|
||||
),
|
||||
(
|
||||
local_topk[rank].indices + rank * 3,
|
||||
torch.cat(
|
||||
[
|
||||
topk.indices + shard_rank * 3
|
||||
for shard_rank, topk in enumerate(local_topk)
|
||||
],
|
||||
-1,
|
||||
),
|
||||
),
|
||||
]
|
||||
all_gather = Gather(gather_calls)
|
||||
|
||||
monkeypatch.setattr(
|
||||
logits_processor,
|
||||
"tensor_model_parallel_all_gather",
|
||||
all_gather,
|
||||
)
|
||||
monkeypatch.setattr(logits_processor, "_topk", lambda x, k: x.topk(k, dim=-1))
|
||||
ids, values = logits_processor.LogitsProcessor.get_top_k_tokens(
|
||||
fake,
|
||||
lm_head,
|
||||
torch.empty(2, 1),
|
||||
2,
|
||||
return_log_probs=True,
|
||||
)
|
||||
expected = torch.cat(valid_shards, -1).log_softmax(-1).topk(2)
|
||||
torch.testing.assert_close(ids, expected.indices)
|
||||
torch.testing.assert_close(values, expected.values)
|
||||
assert all_gather.index == (3 if tp_size > 1 else 0)
|
||||
|
||||
|
||||
def test_context_anchor_is_last_committed_normalized_feature():
|
||||
hidden = torch.arange(1, 25, dtype=torch.float32).view(6, 4)
|
||||
norm = nn.RMSNorm(4)
|
||||
spec = SimpleNamespace(
|
||||
hidden_states=hidden,
|
||||
model=SimpleNamespace(model=SimpleNamespace(hidden_norm=norm)),
|
||||
anchor_hidden=torch.full((4, 4), 123.0),
|
||||
anchor_valid=torch.ones(4, dtype=torch.bool),
|
||||
)
|
||||
LiLiCorrSpeculator.prepare_context_anchor(
|
||||
spec, 2, torch.tensor([0, 2, 6]), torch.tensor([0, 2])
|
||||
)
|
||||
torch.testing.assert_close(spec.anchor_hidden[:2], norm(hidden[[1, 3]]))
|
||||
assert spec.anchor_valid.tolist() == [True, True, False, False]
|
||||
assert not spec.anchor_hidden[2:].any()
|
||||
# A smaller reordered batch must not retain an old request's anchor.
|
||||
LiLiCorrSpeculator.prepare_context_anchor(
|
||||
spec, 1, torch.tensor([0, 3]), torch.tensor([1])
|
||||
)
|
||||
torch.testing.assert_close(spec.anchor_hidden[0], norm(hidden[1]))
|
||||
assert not spec.anchor_hidden[1:].any()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_captured_context_anchor_rereads_fixed_inputs():
|
||||
"""The anchor runs in the draft's FULL graph: each replay must re-read its
|
||||
fixed-address inputs and ignore a padded request's stale rejected count."""
|
||||
dev = torch.device("cuda")
|
||||
query_start_loc = torch.zeros(3, dtype=torch.int32, device=dev)
|
||||
num_rejected = torch.zeros(2, dtype=torch.int32, device=dev)
|
||||
spec = SimpleNamespace(
|
||||
hidden_states=torch.randn(8, 2, device=dev),
|
||||
model=SimpleNamespace(model=SimpleNamespace(hidden_norm=lambda x: 2 * x)),
|
||||
anchor_hidden=torch.zeros(2, 2, device=dev),
|
||||
anchor_valid=torch.zeros(2, dtype=torch.bool, device=dev),
|
||||
)
|
||||
args = (spec, 2, query_start_loc, num_rejected)
|
||||
LiLiCorrSpeculator.prepare_context_anchor(*args)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
LiLiCorrSpeculator.prepare_context_anchor(*args)
|
||||
# One live request padded to two; the second case anchors on a prefill row
|
||||
# past the graph's context rows, stored eagerly before replay.
|
||||
for loc, rejected, row in (([0, 2, 2], [1, 5], 0), ([0, 7, 7], [0, 0], 6)):
|
||||
query_start_loc.copy_(torch.tensor(loc))
|
||||
num_rejected.copy_(torch.tensor(rejected))
|
||||
graph.replay()
|
||||
torch.testing.assert_close(spec.anchor_hidden[0], 2 * spec.hidden_states[row])
|
||||
assert spec.anchor_valid.tolist() == [True, False]
|
||||
assert not spec.anchor_hidden[1].any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lilicorr", [False, True])
|
||||
def test_candidate_generation_routes_scores_and_adaptive_inputs(monkeypatch, lilicorr):
|
||||
"""Both heads share the walk, including a padded request and adaptive scores."""
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import DFlash2Speculator
|
||||
|
||||
key = "lilicorr_candidate_topk" if lilicorr else "selector_top_k"
|
||||
|
||||
def init_base(self, config, device):
|
||||
self.draft_model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(hidden_size=4, dflash_config={key: 4})
|
||||
)
|
||||
self.max_num_reqs = 3
|
||||
self.num_speculative_steps = 2
|
||||
self.num_query_per_req = 3
|
||||
self.dtype = torch.float32
|
||||
|
||||
monkeypatch.setattr(DFlashSpeculator, "__init__", init_base)
|
||||
cls = LiLiCorrSpeculator if lilicorr else DFlash2Speculator
|
||||
spec = cls(None, torch.device("cpu"))
|
||||
hidden = torch.arange(36).float().view(9, 4)
|
||||
spec._run_model = lambda *args: hidden
|
||||
spec.sample_indices = torch.tensor([1, 2, 4, 5, 7, 8])
|
||||
spec.sample_pos = torch.arange(6)
|
||||
spec.sample_idx_mapping = torch.tensor([1, 1, 0, 0, -1, -1])
|
||||
spec.sample_col = torch.tensor([0, 1, 0, 1, 0, 1])
|
||||
spec.temperature = torch.ones(3)
|
||||
spec.seeds = torch.arange(3)
|
||||
spec.draft_tokens = torch.empty(3, 2, dtype=torch.long)
|
||||
spec.draft_logits = None
|
||||
spec.use_fp64_gumbel = False
|
||||
spec.enable_adaptive_verification = True
|
||||
spec.input_buffers = SimpleNamespace(input_ids=torch.arange(9))
|
||||
candidates = torch.arange(24).view(6, 4)
|
||||
log_probs = candidates.float().log_softmax(-1)
|
||||
scores = torch.randn(3, 2, 4, 4)
|
||||
scoring_inputs: list[torch.Tensor] = []
|
||||
sampling_inputs: list[Any] = []
|
||||
adaptive_inputs: list[torch.Tensor] = []
|
||||
|
||||
def score(*args):
|
||||
scoring_inputs.extend(args)
|
||||
return scores
|
||||
|
||||
def sample(*args):
|
||||
sampling_inputs.extend(args)
|
||||
spec.candidate_sampler.scores.copy_(scores[:, :, 0])
|
||||
|
||||
spec.model = SimpleNamespace(
|
||||
compute_candidates=lambda h: (candidates, log_probs),
|
||||
model=SimpleNamespace(lilicorr=score, candidate_selector=score),
|
||||
)
|
||||
if lilicorr:
|
||||
assert isinstance(spec, LiLiCorrSpeculator)
|
||||
monkeypatch.setattr(
|
||||
spec,
|
||||
"target_embeddings",
|
||||
lambda ids: ids.float().unsqueeze(-1).expand(*ids.shape, 4),
|
||||
raising=False,
|
||||
)
|
||||
spec.anchor_hidden.copy_(torch.arange(12).view(3, 4))
|
||||
spec.anchor_valid[:2] = True
|
||||
monkeypatch.setattr(spec.candidate_sampler, "sample", sample)
|
||||
monkeypatch.setattr(
|
||||
spec, "_maybe_predict_acceptance", lambda *args: adaptive_inputs.extend(args)
|
||||
)
|
||||
spec._generate_draft(3, 9, None, None, None)
|
||||
|
||||
expected_ids = candidates.view(3, 2, 4)
|
||||
expected_first = (
|
||||
spec.target_embeddings(expected_ids)
|
||||
if isinstance(spec, LiLiCorrSpeculator)
|
||||
else expected_ids
|
||||
)
|
||||
torch.testing.assert_close(scoring_inputs[0], expected_first)
|
||||
torch.testing.assert_close(scoring_inputs[1], log_probs.view(3, 2, 4))
|
||||
torch.testing.assert_close(
|
||||
scoring_inputs[2], hidden[spec.sample_indices].view(3, 2, 4)
|
||||
)
|
||||
if lilicorr:
|
||||
assert isinstance(spec, LiLiCorrSpeculator)
|
||||
torch.testing.assert_close(scoring_inputs[3], spec.anchor_hidden)
|
||||
torch.testing.assert_close(scoring_inputs[4], spec.anchor_valid)
|
||||
else:
|
||||
torch.testing.assert_close(scoring_inputs[3], torch.tensor([0, 3, 6]))
|
||||
torch.testing.assert_close(sampling_inputs[0], expected_ids)
|
||||
assert sampling_inputs[1] is scores
|
||||
assert sampling_inputs[4] is spec.sample_idx_mapping
|
||||
torch.testing.assert_close(adaptive_inputs[0], scores[:, :, 0].flatten(0, 1))
|
||||
torch.testing.assert_close(adaptive_inputs[1], spec.sample_idx_mapping)
|
||||
torch.testing.assert_close(adaptive_inputs[2], spec.sample_col)
|
||||
|
||||
|
||||
def test_lilicorr_config_preserves_architecture():
|
||||
from transformers import Qwen3Config
|
||||
|
||||
config = Qwen3Config(architectures=["LiLiCorrDraftModel"])
|
||||
wrapped = EAGLEConfig(config, method="dflash")
|
||||
assert wrapped.architectures == ["LiLiCorrDraftModel"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("probabilistic", [False, True])
|
||||
def test_candidate_walk_preserves_conditional_scores_and_padding(probabilistic):
|
||||
"""Check the shared sampler's actual q, stale support, and graph padding."""
|
||||
device = torch.device("cuda")
|
||||
batch, steps, top_k, vocab = 3, 3, 4, 32
|
||||
sampler = CandidateSampler(batch, steps, top_k, device)
|
||||
candidates = (
|
||||
torch.arange(steps * top_k, device=device)
|
||||
.view(1, steps, top_k)
|
||||
.repeat(batch, 1, 1)
|
||||
)
|
||||
scores = torch.randn(batch, steps, top_k, top_k, device=device)
|
||||
tokens = torch.full((batch, steps), -1, dtype=torch.long, device=device)
|
||||
cache = (
|
||||
torch.full((batch, steps, vocab), -float("inf"), device=device)
|
||||
if probabilistic
|
||||
else None
|
||||
)
|
||||
positions = torch.arange(batch * steps * 2, device=device)[::2]
|
||||
mappings = torch.tensor(
|
||||
[2] * steps + [0] * steps + [-1] * steps, device=device
|
||||
).repeat_interleave(2)[::2]
|
||||
temperature = torch.tensor([0.0, 1.0, 0.8], device=device)
|
||||
seeds = torch.tensor([11, 22, 33], device=device)
|
||||
|
||||
def run():
|
||||
sampler.sample(
|
||||
candidates,
|
||||
scores,
|
||||
batch,
|
||||
positions,
|
||||
mappings,
|
||||
temperature,
|
||||
seeds,
|
||||
tokens,
|
||||
cache,
|
||||
False,
|
||||
)
|
||||
|
||||
run()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
run()
|
||||
old_candidates = candidates.clone()
|
||||
candidates.add_(12)
|
||||
graph.replay()
|
||||
for row, state in ((0, 2), (1, 0)):
|
||||
previous = 0
|
||||
for step in range(steps):
|
||||
realized = scores[row, step, previous]
|
||||
torch.testing.assert_close(sampler.scores[row, step], realized)
|
||||
index = (candidates[row, step] == tokens[row, step]).nonzero().item()
|
||||
if not probabilistic or temperature[state] == 0:
|
||||
assert index == realized.argmax().item()
|
||||
if cache is not None:
|
||||
torch.testing.assert_close(
|
||||
cache[state, step, candidates[row, step]], realized
|
||||
)
|
||||
assert cache[state, step, old_candidates[row, step]].isneginf().all()
|
||||
previous = index
|
||||
assert (tokens[2] == -1).all()
|
||||
if cache is not None:
|
||||
assert cache[1].isneginf().all()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("use_fp64", [False, True])
|
||||
def test_candidate_walk_revisited_position_matches_step_seed(use_fp64):
|
||||
"""The candidate walk must use the same step key as ordinary draft sampling."""
|
||||
device = torch.device("cuda")
|
||||
batch, steps, top_k = 4096, 2, 2
|
||||
sampler = CandidateSampler(batch, steps, top_k, device)
|
||||
candidates = torch.arange(top_k, device=device).expand(batch, steps, top_k)
|
||||
logits = torch.tensor([0.7, 0.3], device=device).log()
|
||||
scores = logits.expand(batch, steps, top_k, top_k)
|
||||
mapping = torch.arange(batch, device=device)
|
||||
temperature = torch.ones(batch, device=device)
|
||||
seeds = mapping.to(torch.int64)
|
||||
positions = torch.arange(21, 21 + steps, device=device).repeat(batch)
|
||||
tokens = torch.empty(batch, steps, dtype=torch.int64, device=device)
|
||||
cache = torch.empty(batch, steps, top_k, device=device)
|
||||
first_round = None
|
||||
for start in (21, 22):
|
||||
positions.view(batch, steps).copy_(
|
||||
torch.arange(start, start + steps, device=device)
|
||||
)
|
||||
sampler.sample(
|
||||
candidates,
|
||||
scores,
|
||||
batch,
|
||||
positions,
|
||||
mapping.repeat_interleave(steps),
|
||||
temperature,
|
||||
seeds,
|
||||
tokens,
|
||||
cache,
|
||||
use_fp64,
|
||||
)
|
||||
for step in range(steps):
|
||||
expected = gumbel_sample(
|
||||
logits.expand(batch, -1),
|
||||
mapping,
|
||||
temperature,
|
||||
seeds,
|
||||
positions.view(batch, steps)[:, step] - 1,
|
||||
apply_temperature=True,
|
||||
is_drafting=True,
|
||||
logits_cache=cache,
|
||||
logits_cache_col=torch.tensor(step, device=device),
|
||||
use_fp64=use_fp64,
|
||||
)
|
||||
torch.testing.assert_close(tokens[:, step], expected)
|
||||
if first_round is None:
|
||||
first_round = tokens.clone()
|
||||
else:
|
||||
mismatch_rate = (first_round[:, 1] != tokens[:, 0]).float().mean().item()
|
||||
assert 0.35 < mismatch_rate < 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("convolution", "mismatch", "quantized"),
|
||||
[
|
||||
pytest.param(False, None, False, id="valid-plain"),
|
||||
pytest.param(True, None, False, id="valid-convolution"),
|
||||
pytest.param(False, "missing_head", False, id="missing-head"),
|
||||
pytest.param(False, "extra_head", False, id="extra-head"),
|
||||
pytest.param(True, "missing_conv", False, id="missing-convolution"),
|
||||
pytest.param(False, "extra_conv", False, id="unexpected-convolution"),
|
||||
pytest.param(False, None, True, id="optional-w4a16-input-scale"),
|
||||
pytest.param(False, "missing_weight", True, id="missing-quantized-weight"),
|
||||
pytest.param(False, "missing_bias", True, id="missing-quantized-bias"),
|
||||
pytest.param(False, "missing_weight_scale", True, id="missing-block-scale"),
|
||||
pytest.param(False, "missing_weight_scale_2", True, id="missing-global-scale"),
|
||||
],
|
||||
)
|
||||
def test_checkpoint_coverage_rejects_incomplete_or_wrong_heads(
|
||||
monkeypatch, convolution, mismatch, quantized
|
||||
):
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr, LiLiCorrForCausalLM
|
||||
|
||||
wrapper = LiLiCorrForCausalLM.__new__(LiLiCorrForCausalLM) # type: ignore[type-abstract]
|
||||
nn.Module.__init__(wrapper)
|
||||
wrapper.model = LiLiCorr.__new__(LiLiCorr)
|
||||
nn.Module.__init__(wrapper.model)
|
||||
wrapper.has_own_lm_head = False
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
wrapper.model.lilicorr = LiLiCorrHead(
|
||||
model_hidden_size=16, block_size=4, rms_norm_eps=1e-6, config=_config()
|
||||
)
|
||||
layer = nn.Module()
|
||||
if convolution:
|
||||
layer.attention_conv = nn.Linear(2, 2, bias=False)
|
||||
wrapper.model.layers = nn.ModuleList([layer])
|
||||
if quantized:
|
||||
from vllm.config.quantization import QuantSpec
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
CkptCtx,
|
||||
ModelOptLinearMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kNvfp4Static,
|
||||
)
|
||||
|
||||
# Match the W4A16 NVFP4 checkpoint contract without GPU kernel setup.
|
||||
projection = wrapper.model.lilicorr.pass_hidden_proj
|
||||
projection.quant_method = ModelOptLinearMethod(
|
||||
QuantSpec(weight=kNvfp4Static, activation=None), CkptCtx(group_size=16)
|
||||
)
|
||||
projection.weight = nn.Parameter(
|
||||
torch.zeros(8, 8, dtype=torch.uint8), requires_grad=False
|
||||
)
|
||||
for name, value in (
|
||||
("weight_scale", torch.ones(8, 1).to(torch.float8_e4m3fn)),
|
||||
("weight_scale_2", torch.ones(1)),
|
||||
("input_scale", torch.full((1,), torch.nan)),
|
||||
):
|
||||
projection.register_parameter(
|
||||
name, nn.Parameter(value, requires_grad=False)
|
||||
)
|
||||
weights = dict(wrapper.model.state_dict())
|
||||
if quantized:
|
||||
del weights["lilicorr.pass_hidden_proj.input_scale"]
|
||||
if mismatch == "missing_head":
|
||||
del weights["lilicorr.slot_embedding"]
|
||||
elif mismatch in (
|
||||
"missing_weight",
|
||||
"missing_bias",
|
||||
"missing_weight_scale",
|
||||
"missing_weight_scale_2",
|
||||
):
|
||||
del weights[f"lilicorr.pass_hidden_proj.{mismatch.removeprefix('missing_')}"]
|
||||
elif mismatch == "extra_head":
|
||||
weights["lilicorr.untrained.weight"] = torch.zeros(1)
|
||||
elif mismatch == "missing_conv":
|
||||
del weights["layers.0.attention_conv.weight"]
|
||||
elif mismatch == "extra_conv":
|
||||
weights["layers.0.mlp_conv.untrained"] = torch.zeros(1)
|
||||
|
||||
# Keep production loading and mapping, bypass only backbone GPU KV setup.
|
||||
wrapper.model.use_aux_hidden_state = True
|
||||
wrapper.model.has_separate_mask_embedding = False
|
||||
monkeypatch.setattr(wrapper, "_read_mask_embedding", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
wrapper.model, "_build_fused_kv_buffers", lambda: None, raising=False
|
||||
)
|
||||
supplied = [("model." + name, value) for name, value in weights.items()]
|
||||
if mismatch:
|
||||
message = (
|
||||
"no module or parameter"
|
||||
if mismatch.startswith("extra")
|
||||
else "coverage mismatch"
|
||||
)
|
||||
with pytest.raises(ValueError, match=message):
|
||||
wrapper.load_weights(supplied)
|
||||
else:
|
||||
wrapper.load_weights(supplied)
|
||||
assert wrapper.model.lilicorr._attn_bias is not None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owned_head_model(monkeypatch):
|
||||
from vllm.model_executor.layers.quantization import modelopt
|
||||
from vllm.model_executor.models import qwen3_dflash
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorrForCausalLM
|
||||
|
||||
quant_config = modelopt.ModelOptNvFp4Config(
|
||||
quant_method="W4A16_NVFP4", is_checkpoint_nvfp4_serialized=True
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
modelopt,
|
||||
"select_linear_kernel",
|
||||
lambda *a, **kw: SimpleNamespace(input_quant_key=lambda: None),
|
||||
)
|
||||
monkeypatch.setattr(qwen3_dflash, "get_draft_quant_config", lambda _: quant_config)
|
||||
|
||||
class Backbone(nn.Module):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__()
|
||||
self.quant_config = quant_config
|
||||
self.use_aux_hidden_state = True
|
||||
self.has_separate_mask_embedding = False
|
||||
self.lilicorr = LiLiCorrHead(
|
||||
model_hidden_size=16, block_size=4, rms_norm_eps=1e-6, config=_config()
|
||||
)
|
||||
|
||||
def _build_fused_kv_buffers(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(LiLiCorrForCausalLM, "model_cls", Backbone)
|
||||
monkeypatch.setattr(LiLiCorrForCausalLM, "_read_mask_embedding", lambda _: None)
|
||||
|
||||
def build(owned=True):
|
||||
config = SimpleNamespace(
|
||||
vocab_size=64,
|
||||
draft_vocab_size=64,
|
||||
hidden_size=16,
|
||||
has_own_lm_head=owned,
|
||||
num_hidden_layers=0,
|
||||
dflash_config={},
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(hf_config=config),
|
||||
draft_load_config=None,
|
||||
attention_backend=None,
|
||||
kv_cache_dtype=None,
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
get_total_num_hidden_layers=lambda: 0,
|
||||
get_vocab_size=lambda: 64,
|
||||
),
|
||||
attention_config=SimpleNamespace(),
|
||||
cache_config=SimpleNamespace(),
|
||||
load_config=LoadConfig(),
|
||||
)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
model = LiLiCorrForCausalLM(vllm_config=vllm_config)
|
||||
return model, vllm_config
|
||||
|
||||
return build
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", [None, "weight", "weight_scale", "weight_scale_2"])
|
||||
def test_owned_nvfp4_lm_head_loads_required_checkpoint_tensors(
|
||||
owned_head_model, missing
|
||||
):
|
||||
model, _ = owned_head_model()
|
||||
assert model.lm_head.weight.dtype == torch.uint8
|
||||
assert model.lm_head.weight.shape == (64, 8)
|
||||
weights = {
|
||||
name: torch.ones_like(value) for name, value in model.state_dict().items()
|
||||
}
|
||||
del weights["lm_head.input_scale"] # Deprecated and unused for W4A16.
|
||||
if missing:
|
||||
del weights[f"lm_head.{missing}"]
|
||||
with pytest.raises(ValueError, match=f"lm_head.{missing}"):
|
||||
model.load_weights(weights.items())
|
||||
else:
|
||||
model.load_weights(weights.items())
|
||||
assert model.has_own_lm_head
|
||||
for name in ("weight", "weight_scale", "weight_scale_2"):
|
||||
torch.testing.assert_close(
|
||||
getattr(model.lm_head, name), weights[f"lm_head.{name}"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owned", [False, True])
|
||||
def test_selected_lm_head_survives_dflash_and_lilicorr_sharing(
|
||||
monkeypatch, owned_head_model, owned
|
||||
):
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash import utils as dflash_utils
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle import utils as eagle_utils
|
||||
|
||||
model, config = owned_head_model(owned)
|
||||
own_head = model.lm_head
|
||||
target_head = owned_head_model(owned)[0].lm_head
|
||||
# Identical packed bytes do not imply identical quantized heads.
|
||||
with torch.no_grad():
|
||||
own_head.weight.fill_(1)
|
||||
target_head.weight.fill_(1)
|
||||
if owned:
|
||||
own_head.weight_scale_2.fill_(1)
|
||||
target_head.weight_scale_2.fill_(2)
|
||||
embedding = VocabParallelEmbedding(64, 16)
|
||||
target = SimpleNamespace(
|
||||
model=SimpleNamespace(embed_tokens=embedding), lm_head=target_head
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
eagle_utils, "get_pp_group", lambda: SimpleNamespace(world_size=1)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dflash_utils, "replace", lambda obj, **kw: SimpleNamespace(**(vars(obj) | kw))
|
||||
)
|
||||
monkeypatch.setattr(dflash_utils, "get_pp_safe_draft_load_config", lambda c: c)
|
||||
monkeypatch.setattr(dflash_utils, "get_model", lambda **kw: model)
|
||||
if owned:
|
||||
|
||||
def no_weight_comparison(*args):
|
||||
raise AssertionError("Explicit ownership must bypass raw-weight comparison")
|
||||
|
||||
monkeypatch.setattr(dflash_utils, "_should_share", no_weight_comparison)
|
||||
spec = LiLiCorrSpeculator.__new__(LiLiCorrSpeculator)
|
||||
spec.vllm_config = config
|
||||
assert spec.load_draft_model(target, set()) is model
|
||||
assert model.lm_head is (own_head if owned else target_head)
|
||||
assert spec.target_embeddings is embedding
|
||||
if owned:
|
||||
target.lm_head = None
|
||||
assert spec.load_draft_model(target, set()).lm_head is own_head
|
||||
|
||||
|
||||
def test_quantized_head_calls_methods_without_reading_packed_weights(monkeypatch):
|
||||
from vllm.model_executor.layers import linear
|
||||
from vllm.model_executor.layers.linear import UnquantizedLinearMethod
|
||||
|
||||
calls = []
|
||||
configured = []
|
||||
quant_config = object()
|
||||
|
||||
class PackedMethod(UnquantizedLinearMethod):
|
||||
def apply(self, layer, x, bias=None):
|
||||
calls.append(layer.prefix)
|
||||
# Packed storage has a different name/dtype from the activations.
|
||||
assert x.dtype == torch.float32
|
||||
return F.linear(x, layer.packed_weight.float() * layer.weight_scale, bias)
|
||||
|
||||
def resolve(config, layer, prefix):
|
||||
assert config is quant_config
|
||||
configured.append(prefix)
|
||||
return PackedMethod()
|
||||
|
||||
monkeypatch.setattr(linear, "resolve_quant_method", resolve)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
head = LiLiCorrHead(
|
||||
model_hidden_size=16,
|
||||
block_size=4,
|
||||
rms_norm_eps=1e-6,
|
||||
config=_config(hidden_size=8),
|
||||
quant_config=quant_config,
|
||||
prefix="model.lilicorr",
|
||||
)
|
||||
with torch.no_grad():
|
||||
for module in head.modules():
|
||||
if isinstance(module, LinearBase):
|
||||
if module.quant_config is None:
|
||||
module.weight.normal_(std=0.1)
|
||||
module.bias.zero_()
|
||||
continue
|
||||
module.register_parameter(
|
||||
"packed_weight",
|
||||
nn.Parameter(
|
||||
torch.randint(-4, 5, module.weight.shape, dtype=torch.int8),
|
||||
requires_grad=False,
|
||||
),
|
||||
)
|
||||
module.register_parameter(
|
||||
"weight_scale",
|
||||
nn.Parameter(
|
||||
torch.tensor(0.05),
|
||||
requires_grad=False,
|
||||
),
|
||||
)
|
||||
del module.weight
|
||||
module.bias.zero_()
|
||||
for layer in head.layers:
|
||||
layer.attn.in_proj_weight.normal_(std=0.1)
|
||||
layer.attn.in_proj_bias.zero_()
|
||||
head.materialize_inference_buffers(torch.device("cpu"), torch.float32)
|
||||
result = head(
|
||||
torch.randn(2, 3, 4, 16),
|
||||
torch.randn(2, 3, 4).log_softmax(-1),
|
||||
torch.randn(2, 3, 16),
|
||||
torch.randn(2, 16),
|
||||
torch.tensor([True, False]),
|
||||
)
|
||||
assert result.shape == (2, 3, 4, 4)
|
||||
assert torch.isfinite(result).all()
|
||||
for name in ("factor_input_proj", "out_head", "in_head"):
|
||||
assert getattr(head, name).quant_config is None
|
||||
assert f"model.lilicorr.{name}" not in configured
|
||||
assert set(calls) == set(configured)
|
||||
assert len(configured) == len(set(configured))
|
||||
for name, module in head.named_modules():
|
||||
if isinstance(module, LinearBase):
|
||||
assert module.prefix == f"model.lilicorr.{name}"
|
||||
@@ -1,239 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
create_standard_kv_cache_spec,
|
||||
try_get_attention_backend,
|
||||
)
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
DeviceConfig,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
SpeculativeConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.model_executor.models.llama import LlamaForCausalLM
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.spec_decode.eagle import EagleProposer
|
||||
|
||||
mimo_7b_dir = "XiaomiMiMo/MiMo-7B-Base"
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
def test_glm_mtp_defers_lm_head(default_vllm_config):
|
||||
from vllm.model_executor.models import deepseek_mtp
|
||||
from vllm.models.glm5next.common import mtp
|
||||
|
||||
config = mock.MagicMock(
|
||||
hidden_size=16,
|
||||
rms_norm_eps=1e-5,
|
||||
index_topk=8,
|
||||
index_kpool=4,
|
||||
)
|
||||
vllm_config = mock.MagicMock()
|
||||
vllm_config.speculative_config.draft_model_config.hf_text_config = config
|
||||
vllm_config.scheduler_config.max_num_batched_tokens = 4
|
||||
|
||||
with (
|
||||
mock.patch.object(mtp, "Glm5NextDecoderLayer", return_value=nn.Identity()),
|
||||
mock.patch.object(deepseek_mtp, "ParallelLMHead") as parallel_lm_head,
|
||||
mock.patch.object(mtp.current_platform, "device_type", "cpu"),
|
||||
):
|
||||
layer = mtp.Glm5NextMultiTokenPredictorLayer(vllm_config, "model.layers.1")
|
||||
|
||||
parallel_lm_head.assert_not_called()
|
||||
assert layer.shared_head.head is None
|
||||
|
||||
|
||||
def _create_mtp_proposer(num_speculative_tokens: int) -> EagleProposer:
|
||||
"""Create an MTP proposer with unified model configuration."""
|
||||
model_config = ModelConfig(
|
||||
model=mimo_7b_dir, runner="generate", max_model_len=100, trust_remote_code=True
|
||||
)
|
||||
|
||||
speculative_config = SpeculativeConfig(
|
||||
target_model_config=model_config,
|
||||
target_parallel_config=ParallelConfig(),
|
||||
model=mimo_7b_dir,
|
||||
method="mtp",
|
||||
num_speculative_tokens=num_speculative_tokens,
|
||||
)
|
||||
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
cache_config=CacheConfig(),
|
||||
speculative_config=speculative_config,
|
||||
device_config=DeviceConfig(device=DEVICE_TYPE),
|
||||
parallel_config=ParallelConfig(),
|
||||
load_config=LoadConfig(),
|
||||
scheduler_config=SchedulerConfig(
|
||||
max_model_len=model_config.max_model_len,
|
||||
is_encoder_decoder=model_config.is_encoder_decoder,
|
||||
),
|
||||
)
|
||||
|
||||
return EagleProposer(vllm_config=vllm_config, device=DEVICE_TYPE)
|
||||
|
||||
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_pp_group")
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_layers_from_vllm_config")
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_model")
|
||||
def test_mtp_load_model_unified(mock_get_model, mock_get_layers, mock_get_pp_group):
|
||||
"""Test MTP-specific model loading with unified model approach."""
|
||||
# Setup mocks
|
||||
mock_model = mock.MagicMock()
|
||||
mock_model.model.embed_tokens.weight.shape = (131072, 4096)
|
||||
mock_get_model.return_value = mock_model
|
||||
# MTP does not have its own embed_tokens or lm_head
|
||||
# so it should share them with the target model
|
||||
mock_model.has_own_embed_tokens = False
|
||||
mock_model.has_own_lm_head = False
|
||||
|
||||
target_attn_layers = {"target_attn_1": mock.MagicMock()}
|
||||
all_attn_layers = {**target_attn_layers, "draft_attn_1": mock.MagicMock()}
|
||||
|
||||
mock_get_layers.side_effect = [target_attn_layers, all_attn_layers]
|
||||
|
||||
mock_pp_group = mock.MagicMock()
|
||||
mock_pp_group.world_size = 1
|
||||
mock_get_pp_group.return_value = mock_pp_group
|
||||
|
||||
# Create target model
|
||||
class _TargetModelStub(LlamaForCausalLM):
|
||||
model: mock.MagicMock
|
||||
lm_head: mock.MagicMock
|
||||
|
||||
target_model = mock.create_autospec(_TargetModelStub, instance=True)
|
||||
target_model.model = mock.MagicMock()
|
||||
target_model.model.embed_tokens.weight.shape = (131072, 4096)
|
||||
target_model.lm_head = mock.MagicMock()
|
||||
|
||||
# Create MTP proposer
|
||||
proposer = _create_mtp_proposer(num_speculative_tokens=4)
|
||||
proposer.load_model(target_model)
|
||||
|
||||
# Verify MTP-specific behavior:
|
||||
# Model is loaded
|
||||
mock_get_model.assert_called_once()
|
||||
# MTP shares lm_head with target model
|
||||
assert proposer.model.lm_head == target_model.lm_head
|
||||
# MTP shares embed_tokens with target model
|
||||
assert proposer.model.model.embed_tokens == target_model.model.embed_tokens
|
||||
assert proposer._draft_attn_layer_names == {"draft_attn_1"}
|
||||
assert all_attn_layers["draft_attn_1"].is_draft_layer is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_speculative_tokens", [1])
|
||||
def test_mtp_propose(num_speculative_tokens, monkeypatch):
|
||||
"""Test that MTP's forward method returns hidden states directly."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
batch_size = 2
|
||||
seq_lens = [5, 3]
|
||||
total_tokens = sum(seq_lens)
|
||||
vocab_size = 100
|
||||
|
||||
proposer = _create_mtp_proposer(num_speculative_tokens)
|
||||
hidden_size = proposer.hidden_size
|
||||
|
||||
# Mock the MTP model to verify it returns hidden states directly
|
||||
model_mock = mock.MagicMock()
|
||||
|
||||
# MTP returns hidden states directly
|
||||
if num_speculative_tokens == 1:
|
||||
model_mock.return_value = torch.zeros(total_tokens, hidden_size, device=device)
|
||||
else:
|
||||
# Multiple forward passes for multi-token speculation
|
||||
forward_returns = []
|
||||
for i in range(num_speculative_tokens):
|
||||
if i == 0:
|
||||
h_states = torch.zeros(total_tokens, hidden_size, device=device)
|
||||
else:
|
||||
h_states = torch.zeros(batch_size, hidden_size, device=device)
|
||||
forward_returns.append(h_states)
|
||||
model_mock.side_effect = forward_returns
|
||||
|
||||
# Mock compute_logits
|
||||
def create_deterministic_logits(batch_size, vocab_size, token_offset):
|
||||
logits = torch.full((batch_size, vocab_size), -100.0, device=device)
|
||||
logits[:, token_offset] = 100.0
|
||||
return logits
|
||||
|
||||
if num_speculative_tokens == 1:
|
||||
model_mock.compute_logits.return_value = create_deterministic_logits(
|
||||
batch_size, vocab_size, 42
|
||||
)
|
||||
else:
|
||||
logits_returns = [
|
||||
create_deterministic_logits(batch_size, vocab_size, 42 + i)
|
||||
for i in range(num_speculative_tokens)
|
||||
]
|
||||
model_mock.compute_logits.side_effect = logits_returns
|
||||
|
||||
proposer.model = model_mock
|
||||
proposer._draft_attn_layer_names = {"layer.0"}
|
||||
|
||||
# Prepare inputs
|
||||
batch_spec = BatchSpec(seq_lens=seq_lens, query_lens=seq_lens)
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch_spec, block_size=16, device=device
|
||||
)
|
||||
|
||||
target_token_ids = torch.randint(0, vocab_size, (total_tokens,), device=device)
|
||||
target_positions = torch.cat(
|
||||
[
|
||||
torch.arange(seq_lens[0], device=device),
|
||||
torch.arange(seq_lens[1], device=device),
|
||||
]
|
||||
)
|
||||
target_hidden_states = torch.randn(total_tokens, hidden_size, device=device)
|
||||
next_token_ids = torch.randint(
|
||||
0, vocab_size, (batch_size,), dtype=torch.int32, device=device
|
||||
)
|
||||
sampling_metadata = mock.MagicMock()
|
||||
|
||||
# Setup attention metadata
|
||||
attn_metadata_builder_cls, _ = try_get_attention_backend(
|
||||
AttentionBackendEnum.FLASH_ATTN
|
||||
)
|
||||
|
||||
attn_metadata_builder = attn_metadata_builder_cls(
|
||||
kv_cache_spec=create_standard_kv_cache_spec(proposer.vllm_config),
|
||||
layer_names=list(proposer._draft_attn_layer_names),
|
||||
vllm_config=proposer.vllm_config,
|
||||
device=device,
|
||||
)
|
||||
|
||||
mock_attn_group = mock.MagicMock()
|
||||
mock_attn_group.get_metadata_builder.return_value = attn_metadata_builder
|
||||
mock_attn_group.layer_names = list(proposer._draft_attn_layer_names)
|
||||
mock_attn_group.kv_cache_spec = attn_metadata_builder.kv_cache_spec
|
||||
proposer.draft_attn_groups = [mock_attn_group]
|
||||
|
||||
# Run propose
|
||||
result = proposer.propose(
|
||||
num_speculative_tokens=num_speculative_tokens,
|
||||
target_token_ids=target_token_ids,
|
||||
target_positions=target_positions,
|
||||
target_hidden_states=target_hidden_states,
|
||||
next_token_ids=next_token_ids,
|
||||
token_indices_to_sample=None,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
sampling_metadata=sampling_metadata,
|
||||
)
|
||||
|
||||
# Verify the model was called correctly
|
||||
assert model_mock.called
|
||||
# Verify output shape
|
||||
assert result.shape == (batch_size, num_speculative_tokens)
|
||||
@@ -1,884 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Padded-page handling in create_kv_cache_views.
|
||||
|
||||
Guards that a page_size_padded spec strides the block dimension by the padded page
|
||||
while keeping per-block content compact, so padding bytes at the end of each page are
|
||||
never addressed by the logical view.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.v1.hisparse.binding as attn_utils_module
|
||||
import vllm.v1.hisparse.runtime as hisparse_runtime_module
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
dense_kv_cache_views,
|
||||
)
|
||||
from vllm.config.compilation import CompilationConfig, CUDAGraphMode
|
||||
from vllm.v1.attention.backend import AttentionBackend, AttentionCGSupport, MultipleOf
|
||||
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
|
||||
from vllm.v1.hisparse.binding import allocate_hisparse_kv_caches
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
HiSparseResidentSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheTensor,
|
||||
MLAAttentionSpec,
|
||||
SparseCacheRole,
|
||||
compute_layout_strides,
|
||||
)
|
||||
from vllm.v1.worker.gpu import attn_utils
|
||||
from vllm.v1.worker.gpu.attn_utils import (
|
||||
FastPrefillHelper,
|
||||
get_attn_cg_support,
|
||||
get_query_lens_mismatch_unsupported_backend,
|
||||
)
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
|
||||
from vllm.v1.worker.utils import (
|
||||
AttentionGroup,
|
||||
allocate_kv_cache,
|
||||
copy_kv_cache_blocks_inplace,
|
||||
customize_attention_spec,
|
||||
map_kv_caches_to_kernel_blocks,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("enabled", "block_size", "main_sizes", "indexer_sizes", "expected"),
|
||||
[
|
||||
(True, 256, [64], [64], 64),
|
||||
(True, 64, [32, 64], [16, 32], 32),
|
||||
(True, 64, [MultipleOf(16)], [32], 32),
|
||||
(True, 64, [64], [32], None),
|
||||
(False, 256, [64], [64], 256),
|
||||
],
|
||||
)
|
||||
def test_get_kv_cache_spec_resolves_hisparse_block_size(
|
||||
monkeypatch, enabled, block_size, main_sizes, indexer_sizes, expected
|
||||
):
|
||||
"""Resolve shared MLA geometry before planning; leave other specs alone."""
|
||||
specs = {
|
||||
"main": MLAAttentionSpec(
|
||||
block_size=block_size, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
|
||||
),
|
||||
"indexer": MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
cache_role=SparseCacheRole.INDEXER,
|
||||
),
|
||||
"dense": FullAttentionSpec(
|
||||
block_size=block_size, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
|
||||
),
|
||||
}
|
||||
layers = {}
|
||||
for name, sizes in zip(specs, [main_sizes, indexer_sizes, [block_size]]):
|
||||
backend = SimpleNamespace(
|
||||
get_name=lambda name=name: name,
|
||||
customize_spec=AttentionBackend.customize_spec,
|
||||
get_supported_kernel_block_sizes=lambda _=None, sizes=sizes: sizes,
|
||||
)
|
||||
layers[name] = SimpleNamespace(
|
||||
get_kv_cache_spec=lambda _, spec=specs[name]: spec,
|
||||
get_attn_backend=lambda backend=backend: backend,
|
||||
is_draft_layer=False,
|
||||
)
|
||||
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)
|
||||
monkeypatch.setattr(
|
||||
attn_utils_module, "get_hisparse_kv_cache_groups", lambda *_: []
|
||||
)
|
||||
config = SimpleNamespace(
|
||||
attention_config=SimpleNamespace(hisparse_config=object() if enabled else None)
|
||||
)
|
||||
if expected is None:
|
||||
with pytest.raises(ValueError, match="supported by every sparse"):
|
||||
attn_utils.get_kv_cache_spec(config)
|
||||
return
|
||||
|
||||
resolved = attn_utils.get_kv_cache_spec(config)
|
||||
assert resolved["main"].block_size == resolved["indexer"].block_size == expected
|
||||
dense_backend = layers["dense"].get_attn_backend()
|
||||
assert resolved["dense"] == customize_attention_spec(dense_backend, specs["dense"])
|
||||
assert all(spec.block_size == block_size for spec in specs.values())
|
||||
|
||||
|
||||
def test_get_kv_cache_spec_tags_draft_layers(monkeypatch):
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
|
||||
)
|
||||
backend = SimpleNamespace(
|
||||
customize_spec=AttentionBackend.customize_spec,
|
||||
get_supported_kernel_block_sizes=lambda _=None: [16],
|
||||
)
|
||||
layers = {
|
||||
name: SimpleNamespace(
|
||||
get_kv_cache_spec=lambda _: spec,
|
||||
get_attn_backend=lambda: backend,
|
||||
is_draft_layer=name == "draft",
|
||||
)
|
||||
for name in ("target", "draft")
|
||||
}
|
||||
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)
|
||||
config = SimpleNamespace(attention_config=SimpleNamespace(hisparse_config=None))
|
||||
|
||||
specs = attn_utils.get_kv_cache_spec(config)
|
||||
assert specs["draft"].is_draft and not specs["target"].is_draft
|
||||
|
||||
|
||||
class _FakeMetadataBuilder:
|
||||
def __init__(self, support: AttentionCGSupport, varlen_bound: int | None = None):
|
||||
self.support = support
|
||||
self.varlen_bound = varlen_bound
|
||||
|
||||
def get_cudagraph_support(self, *_args):
|
||||
return self.support
|
||||
|
||||
def get_varlen_cudagraph_max_query_len(self, *_args):
|
||||
return self.varlen_bound
|
||||
|
||||
|
||||
class _TargetBackend:
|
||||
@classmethod
|
||||
def supports_device_cpu_query_lens_mismatch(cls) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
class _DraftBackend:
|
||||
@classmethod
|
||||
def supports_device_cpu_query_lens_mismatch(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def test_attention_checks_preserve_global_and_target_scoped_support():
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
target_group = AttentionGroup(
|
||||
_TargetBackend,
|
||||
["target"],
|
||||
spec,
|
||||
0,
|
||||
)
|
||||
target_group.metadata_builders = [
|
||||
_FakeMetadataBuilder(AttentionCGSupport.ALWAYS) # type: ignore[list-item]
|
||||
]
|
||||
draft_group = AttentionGroup(
|
||||
_DraftBackend,
|
||||
["draft"],
|
||||
spec,
|
||||
0,
|
||||
)
|
||||
draft_group.metadata_builders = [
|
||||
_FakeMetadataBuilder(AttentionCGSupport.UNIFORM_BATCH) # type: ignore[list-item]
|
||||
]
|
||||
groups = [[target_group, draft_group]]
|
||||
|
||||
# The runner-wide execution mode must still honor the drafter's limit.
|
||||
unfiltered = get_attn_cg_support(groups, None)
|
||||
assert unfiltered.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
|
||||
assert unfiltered.min_cg_attn_backend == "_DraftBackend"
|
||||
|
||||
# Adaptive verification validates only the target's varlen graphs.
|
||||
target_only = get_attn_cg_support(
|
||||
groups,
|
||||
None,
|
||||
checked_layer_names={"target"},
|
||||
)
|
||||
assert target_only.min_cg_support == AttentionCGSupport.ALWAYS
|
||||
assert target_only.min_cg_attn_backend is None
|
||||
assert (
|
||||
get_query_lens_mismatch_unsupported_backend(
|
||||
groups,
|
||||
checked_layer_names={"target"},
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
# Shared target/draft groups still participate in target-scoped checks.
|
||||
draft_group.layer_names.append("target")
|
||||
target_with_shared_group = get_attn_cg_support(
|
||||
groups,
|
||||
None,
|
||||
checked_layer_names={"target"},
|
||||
)
|
||||
assert target_with_shared_group.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
|
||||
assert (
|
||||
get_query_lens_mismatch_unsupported_backend(
|
||||
groups,
|
||||
checked_layer_names={"target"},
|
||||
)
|
||||
== "_DraftBackend"
|
||||
)
|
||||
|
||||
|
||||
def test_varlen_cudagraph_unsupported_backend_checks_scoped_bounds():
|
||||
"""ALWAYS passes without a bound, other builders need one at least as wide as
|
||||
the requested length, and NEVER fails whatever bound a builder reports."""
|
||||
config: Any = SimpleNamespace()
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
def group(
|
||||
backend: Any,
|
||||
layer_name: str,
|
||||
support: AttentionCGSupport,
|
||||
bound: int | None = None,
|
||||
):
|
||||
builder: Any = _FakeMetadataBuilder(support, bound)
|
||||
attn_group = AttentionGroup(backend, [layer_name], spec, 0)
|
||||
attn_group.metadata_builders = [builder]
|
||||
return attn_group
|
||||
|
||||
target = group(_TargetBackend, "target", AttentionCGSupport.ALWAYS)
|
||||
draft = group(_DraftBackend, "draft", AttentionCGSupport.UNIFORM_BATCH, 8)
|
||||
never = group(_DraftBackend, "never", AttentionCGSupport.NEVER, 8)
|
||||
|
||||
unsupported = attn_utils.get_varlen_cudagraph_unsupported_backend
|
||||
assert unsupported([[target, draft]], config, 8) is None
|
||||
assert unsupported([[target, draft]], config, 9) == ("_DraftBackend", 8)
|
||||
assert (
|
||||
unsupported([[target, draft]], config, 9, checked_layer_names={"target"})
|
||||
is None
|
||||
)
|
||||
assert unsupported([[target, never]], config, 1) == ("_DraftBackend", None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_speculative_tokens", [0, 7])
|
||||
def test_flashinfer_sparse_full_graphs_exclude_prefill_keep_varlen_decode(
|
||||
num_speculative_tokens,
|
||||
):
|
||||
"""Prefill must fall back without disabling adaptive verification graphs."""
|
||||
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
|
||||
FlashInferMLASparseTRTLLMBackend,
|
||||
)
|
||||
|
||||
backend = FlashInferMLASparseTRTLLMBackend
|
||||
config: Any = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
num_speculative_tokens=num_speculative_tokens, parallel_drafting=False
|
||||
),
|
||||
use_v2_model_runner=True,
|
||||
)
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=64, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
|
||||
)
|
||||
group = AttentionGroup(backend, ["target"], spec, 0)
|
||||
group.metadata_builders = [object.__new__(backend.get_builder_cls())]
|
||||
groups = [[group]]
|
||||
support = get_attn_cg_support(groups, config)
|
||||
compilation = CompilationConfig(cudagraph_mode=CUDAGraphMode.FULL)
|
||||
mode = compilation.resolve_cudagraph_mode_and_sizes(
|
||||
support.min_cg_support,
|
||||
support.min_cg_attn_backend,
|
||||
uniform_decode_query_len=1 + num_speculative_tokens,
|
||||
use_v2_model_runner=True,
|
||||
)
|
||||
assert mode.mixed_mode() != CUDAGraphMode.FULL
|
||||
assert mode.decode_mode() == CUDAGraphMode.FULL
|
||||
assert get_query_lens_mismatch_unsupported_backend(groups) is None
|
||||
unsupported = attn_utils.get_varlen_cudagraph_unsupported_backend
|
||||
assert unsupported(groups, config, 1 + num_speculative_tokens) is None
|
||||
assert unsupported(groups, config, 2 + num_speculative_tokens) == (
|
||||
backend.__name__,
|
||||
1 + num_speculative_tokens,
|
||||
)
|
||||
|
||||
|
||||
def test_get_kv_sharing_fast_prefill_eligible_layers(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Fast prefill applies to the contiguous suffix of KV-sharing layers.
|
||||
|
||||
Draft-model layers register after the target model's and may share KV, so
|
||||
they must not extend (or break) the target's eligible suffix.
|
||||
"""
|
||||
|
||||
def check(
|
||||
layer_names: list[str],
|
||||
shared: dict[str, str],
|
||||
draft_layer_names: set[str] | None = None,
|
||||
) -> set[str]:
|
||||
monkeypatch.setattr(
|
||||
attn_utils,
|
||||
"get_layers_from_vllm_config",
|
||||
lambda *a, **k: {name: None for name in layer_names},
|
||||
)
|
||||
monkeypatch.setattr(attn_utils, "get_shared_kv_cache_layers", lambda *a: shared)
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(kv_sharing_fast_prefill=True)
|
||||
)
|
||||
return attn_utils.get_kv_sharing_fast_prefill_eligible_layers(
|
||||
vllm_config, draft_layer_names
|
||||
)
|
||||
|
||||
# No KV sharing: nothing is eligible.
|
||||
assert check(["t0", "t1"], {}) == set()
|
||||
|
||||
# Trailing run of sharing layers (YOCO-style second half).
|
||||
assert check(["t0", "t1", "t2", "t3"], {"t2": "t1", "t3": "t1"}) == {"t2", "t3"}
|
||||
|
||||
# A non-sharing layer after a sharing one breaks the suffix.
|
||||
assert check(["t0", "t1", "t2", "t3"], {"t1": "t0", "t3": "t0"}) == {"t3"}
|
||||
|
||||
# KV-sharing draft layers at the end are collected without an exclusion...
|
||||
assert check(
|
||||
["t0", "t1", "t2", "t3", "d0", "d1"],
|
||||
{"t2": "t1", "t3": "t1", "d0": "t1", "d1": "t1"},
|
||||
) == {"t2", "t3", "d0", "d1"}
|
||||
|
||||
# ...so the runner excludes them: skipped, not collected, and they do not
|
||||
# break the target's trailing run.
|
||||
assert check(
|
||||
["t0", "t1", "t2", "t3", "d0", "d1"],
|
||||
{"t2": "t1", "t3": "t1", "d0": "t1", "d1": "t1"},
|
||||
draft_layer_names={"d0", "d1"},
|
||||
) == {"t2", "t3"}
|
||||
|
||||
# Feature flag off: nothing is eligible even with sharing layers.
|
||||
monkeypatch.setattr(
|
||||
attn_utils, "get_layers_from_vllm_config", lambda *a, **k: {"t0": None}
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
attn_utils, "get_shared_kv_cache_layers", lambda *a: {"t0": "t0"}
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(kv_sharing_fast_prefill=False)
|
||||
)
|
||||
assert attn_utils.get_kv_sharing_fast_prefill_eligible_layers(vllm_config) == set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"num_tokens", [1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128]
|
||||
)
|
||||
@pytest.mark.parametrize("num_active_loras", [1, 2, 4])
|
||||
def test_fast_prefill_dispatch_preserves_active_lora_count(
|
||||
num_tokens: int, num_active_loras: int
|
||||
):
|
||||
"""Fast-prefill padding must match the main dispatch's LoRA variant."""
|
||||
|
||||
class FakeCudaGraphManager:
|
||||
device = "cpu"
|
||||
|
||||
def __init__(self):
|
||||
self.dispatch_calls = []
|
||||
|
||||
def dispatch(self, **kwargs):
|
||||
self.dispatch_calls.append(kwargs)
|
||||
# A captured no-LoRA graph is padded to 8 tokens, while the
|
||||
# active-LoRA path stays eager at the unpadded token count.
|
||||
if kwargs["num_active_loras"] == 0:
|
||||
num_tokens = 8
|
||||
mode = CUDAGraphMode.PIECEWISE
|
||||
else:
|
||||
num_tokens = kwargs["num_tokens"]
|
||||
mode = CUDAGraphMode.NONE
|
||||
return BatchExecutionDescriptor(
|
||||
cg_mode=mode,
|
||||
num_tokens=num_tokens,
|
||||
num_reqs=kwargs["num_reqs"],
|
||||
num_active_loras=kwargs["num_active_loras"],
|
||||
num_ubatches=1,
|
||||
)
|
||||
|
||||
manager = FakeCudaGraphManager()
|
||||
helper = FastPrefillHelper(manager, max_num_tokens=max(32, num_tokens))
|
||||
metadata = helper.prepare(
|
||||
torch.arange(num_tokens, dtype=torch.int32),
|
||||
num_reqs=1,
|
||||
cu_num_logits_np=np.array([0, num_tokens], dtype=np.int32),
|
||||
has_prefill=True,
|
||||
batch_desc=BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.NONE,
|
||||
num_tokens=num_tokens,
|
||||
num_reqs=1,
|
||||
num_active_loras=num_active_loras,
|
||||
num_ubatches=1,
|
||||
),
|
||||
num_active_loras=num_active_loras,
|
||||
)
|
||||
|
||||
assert metadata is not None
|
||||
assert metadata.num_logits_indices == num_tokens
|
||||
assert metadata.logits_indices_padded.shape[0] == num_tokens
|
||||
assert metadata.max_logits_per_req == num_tokens
|
||||
assert manager.dispatch_calls[-1]["num_active_loras"] == num_active_loras
|
||||
|
||||
|
||||
class _FakeSharedHostRegion:
|
||||
def __init__(self) -> None:
|
||||
self.cleanup_calls = 0
|
||||
self.base_tensor = torch.empty(1, dtype=torch.int8)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self.cleanup_calls += 1
|
||||
|
||||
|
||||
def test_profiling_cleanup_keeps_host_pool_for_real_kv_cache(monkeypatch):
|
||||
"""The real KV cache must reuse the profiling host pool, not pin it again."""
|
||||
pinned = torch.empty(8, dtype=torch.int8)
|
||||
allocate_pinned = MagicMock(return_value=(pinned, pinned))
|
||||
monkeypatch.setattr(
|
||||
hisparse_runtime_module, "allocate_pinned_host_pool", allocate_pinned
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
hisparse_runtime_module, "check_hisparse_host_memory", lambda size: None
|
||||
)
|
||||
vllm_config = SimpleNamespace(instance_id="profiling-reuse")
|
||||
kv_cache_config = SimpleNamespace(hisparse_shared_host_pool=False)
|
||||
pool = attn_utils_module.get_hisparse_host_pool(vllm_config, kv_cache_config)
|
||||
backing = pool.allocate(8)
|
||||
runtime = SimpleNamespace(
|
||||
_host_cache=backing, registered_host_pool=pinned, hot_backing=object()
|
||||
)
|
||||
forward_context = {
|
||||
"layer": SimpleNamespace(hisparse_cache=SimpleNamespace(runtime=runtime))
|
||||
}
|
||||
|
||||
attn_utils_module.release_hisparse_profiling_cache(forward_context)
|
||||
|
||||
assert not hasattr(runtime, "_host_cache")
|
||||
reused = attn_utils_module.get_hisparse_host_pool(vllm_config, kv_cache_config)
|
||||
assert reused is pool
|
||||
assert reused.allocate(8) is backing
|
||||
allocate_pinned.assert_called_once_with(8)
|
||||
hisparse_runtime_module.drop_hisparse_host_pool(vllm_config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure_phase", ["allocation", "binding", "buffers"])
|
||||
@pytest.mark.parametrize("shared", [False, True])
|
||||
def test_init_hisparse_rolls_back_host_pool(monkeypatch, failure_phase, shared):
|
||||
"""Failed initialization must release shared or private registrations."""
|
||||
region = _FakeSharedHostRegion()
|
||||
registered = torch.empty(4096, dtype=torch.int8)
|
||||
cudart = MagicMock()
|
||||
cudart.cudaHostUnregister.return_value.value = 0
|
||||
monkeypatch.setattr(torch.accelerator, "synchronize", lambda: None)
|
||||
monkeypatch.setattr(torch.cuda, "cudart", lambda: cudart)
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC
|
||||
),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=1),
|
||||
instance_id="rollback",
|
||||
)
|
||||
pools = []
|
||||
|
||||
def allocate(*args):
|
||||
pools.append(args[-1])
|
||||
if shared:
|
||||
args[-1].shared_region = region
|
||||
else:
|
||||
args[-1].registered = registered
|
||||
args[-1].backing = registered[:8]
|
||||
if failure_phase == "allocation":
|
||||
raise RuntimeError("initialization failed")
|
||||
return {}
|
||||
|
||||
def bind(**kwargs):
|
||||
if failure_phase == "binding":
|
||||
raise RuntimeError("initialization failed")
|
||||
return []
|
||||
|
||||
def buffers(*args, **kwargs):
|
||||
raise RuntimeError("initialization failed")
|
||||
|
||||
monkeypatch.setattr(attn_utils_module, "allocate_hisparse_kv_caches", allocate)
|
||||
monkeypatch.setattr(attn_utils_module, "bind_hisparse_kv_caches", bind)
|
||||
monkeypatch.setattr(
|
||||
attn_utils_module, "initialize_hisparse_runtime_buffers", buffers
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="initialization failed"):
|
||||
attn_utils_module.init_hisparse_kv_cache(
|
||||
SimpleNamespace(),
|
||||
torch.device("cpu"),
|
||||
[],
|
||||
vllm_config,
|
||||
{},
|
||||
SimpleNamespace(),
|
||||
)
|
||||
assert region.cleanup_calls == int(shared)
|
||||
if shared:
|
||||
cudart.cudaHostUnregister.assert_not_called()
|
||||
else:
|
||||
cudart.cudaHostUnregister.assert_called_once_with(registered.data_ptr())
|
||||
assert attn_utils_module.get_hisparse_host_pool(vllm_config, None) is not pools[0]
|
||||
hisparse_runtime_module.drop_hisparse_host_pool(vllm_config)
|
||||
|
||||
|
||||
def test_reshape_padded_kv_cache_strides_by_padded_page():
|
||||
num_blocks = 3
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=1,
|
||||
head_size=2,
|
||||
dtype=torch.float32,
|
||||
page_size_padded=384,
|
||||
)
|
||||
assert spec.real_page_size_bytes == 256
|
||||
|
||||
raw = torch.zeros(spec.page_size_bytes * num_blocks, dtype=torch.int8)
|
||||
(kv_cache,) = dense_kv_cache_views(raw, spec, num_blocks, 1, KVCacheLayout.LBHNC)
|
||||
|
||||
elem_size = 4 # float32
|
||||
# Content dim packs K and V: 2 * head_size.
|
||||
assert kv_cache.shape == (num_blocks, 1, 16, 2 * spec.head_size)
|
||||
assert kv_cache.dtype == spec.dtype
|
||||
assert kv_cache.stride(0) == spec.page_size_padded // elem_size
|
||||
assert kv_cache[1].storage_offset() == spec.page_size_padded // elem_size
|
||||
# Within one block the (unpadded) content stays compact.
|
||||
assert kv_cache[0].is_contiguous()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"kernel_block_sizes",
|
||||
"expected_num_blocks",
|
||||
"expected_num_states",
|
||||
),
|
||||
[
|
||||
(None, 4, 64),
|
||||
([256], 4, 64),
|
||||
([64], 16, 16),
|
||||
],
|
||||
)
|
||||
def test_allocate_compressed_mla_cache(
|
||||
kernel_block_sizes: list[int] | None,
|
||||
expected_num_blocks: int,
|
||||
expected_num_states: int,
|
||||
):
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
)
|
||||
num_pages = 4
|
||||
config = KVCacheConfig(
|
||||
num_blocks=num_pages,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=num_pages * spec.page_size_bytes,
|
||||
layers=["layer.0"],
|
||||
layer_stride=num_pages * spec.page_size_bytes,
|
||||
block_stride=spec.page_size_bytes,
|
||||
)
|
||||
],
|
||||
kv_cache_groups=[KVCacheGroupSpec(["layer.0"], spec)],
|
||||
)
|
||||
|
||||
caches = allocate_kv_cache(
|
||||
config, torch.device("cpu"), KVCacheLayout.LBHNC, kernel_block_sizes
|
||||
)
|
||||
|
||||
assert caches["layer.0"].shape == (expected_num_blocks, 1, expected_num_states, 128)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout", list(KVCacheLayout))
|
||||
def test_copy_kv_cache_blocks_shared_storage(layout: KVCacheLayout):
|
||||
num_blocks = 4
|
||||
num_layers = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=2,
|
||||
head_size=2,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
|
||||
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
|
||||
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
for block_idx in range(num_blocks):
|
||||
cache[block_idx].fill_(10 * layer_idx + block_idx)
|
||||
|
||||
expected = [[cache[i].clone() for i in range(num_blocks)] for cache in caches]
|
||||
copies = [KVCacheBlockCopy(src_block_id=0, dst_block_id=2)]
|
||||
|
||||
copy_kv_cache_blocks_inplace(caches, num_blocks, copies)
|
||||
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
torch.testing.assert_close(cache[2], expected[layer_idx][0])
|
||||
torch.testing.assert_close(cache[1], expected[layer_idx][1])
|
||||
|
||||
|
||||
def test_fixed_block_stride_propagates_outward_in_lhbnc():
|
||||
num_blocks = 3
|
||||
num_layers = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=2,
|
||||
head_size=2,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
natural = compute_layout_strides(spec, num_blocks, num_layers, KVCacheLayout.LHBNC)
|
||||
block_stride = natural[1] + 8
|
||||
|
||||
strides = compute_layout_strides(
|
||||
spec,
|
||||
num_blocks,
|
||||
num_layers,
|
||||
KVCacheLayout.LHBNC,
|
||||
fixed_strides=(None, block_stride, None, None, None),
|
||||
)
|
||||
|
||||
assert strides[1] == block_stride
|
||||
assert strides[2] == block_stride * num_blocks
|
||||
assert strides[0] == strides[2] * spec.num_heads
|
||||
|
||||
|
||||
def test_copy_kv_cache_blocks_separate_head_groups():
|
||||
# LHBNC stores each head group separately, so a block's bytes are scattered
|
||||
# across L*H regions.
|
||||
layout = KVCacheLayout.LHBNC
|
||||
num_blocks = 4
|
||||
num_layers = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=2,
|
||||
head_size=2,
|
||||
dtype=torch.float32,
|
||||
num_head_slots=2,
|
||||
state_content_bytes=2 * 2 * 4,
|
||||
)
|
||||
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
|
||||
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
|
||||
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
for block_idx in range(num_blocks):
|
||||
for head_idx in range(cache.shape[1]):
|
||||
cache[block_idx, head_idx].fill_(
|
||||
100 * layer_idx + 10 * head_idx + block_idx
|
||||
)
|
||||
|
||||
expected = [[cache[i].clone() for i in range(num_blocks)] for cache in caches]
|
||||
copy_kv_cache_blocks_inplace(
|
||||
caches,
|
||||
num_blocks,
|
||||
[KVCacheBlockCopy(src_block_id=0, dst_block_id=2)],
|
||||
)
|
||||
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
torch.testing.assert_close(cache[2], expected[layer_idx][0])
|
||||
torch.testing.assert_close(cache[1], expected[layer_idx][1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layout,num_layers",
|
||||
[
|
||||
(KVCacheLayout.LBHNC, 2),
|
||||
# Splitting needs a manager block to be one dense page, which a
|
||||
# block-outermost layout only gives when the block holds one layer.
|
||||
(KVCacheLayout.BLHNC, 1),
|
||||
],
|
||||
)
|
||||
def test_copy_kv_cache_blocks_with_virtual_block_splitting(
|
||||
layout: KVCacheLayout, num_layers: int
|
||||
):
|
||||
num_blocks = 4
|
||||
physical_per_logical = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=2,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
|
||||
caches = dense_kv_cache_views(
|
||||
raw,
|
||||
spec,
|
||||
num_blocks,
|
||||
num_layers,
|
||||
layout,
|
||||
kernel_block_size=spec.block_size // physical_per_logical,
|
||||
)
|
||||
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
for block_idx in range(cache.shape[0]):
|
||||
cache[block_idx].fill_(100 * layer_idx + block_idx)
|
||||
expected = [[cache[i].clone() for i in range(cache.shape[0])] for cache in caches]
|
||||
|
||||
copy_kv_cache_blocks_inplace(
|
||||
caches,
|
||||
num_blocks,
|
||||
[KVCacheBlockCopy(src_block_id=0, dst_block_id=2)],
|
||||
)
|
||||
|
||||
dst_start = 2 * physical_per_logical
|
||||
for layer_idx, cache in enumerate(caches):
|
||||
for physical_idx in range(physical_per_logical):
|
||||
torch.testing.assert_close(
|
||||
cache[dst_start + physical_idx], expected[layer_idx][physical_idx]
|
||||
)
|
||||
|
||||
|
||||
def test_allocate_hisparse_kv_caches_host_pool_and_view_less_specs():
|
||||
"""Host tensors get their own backing; view-less specs keep the raw one."""
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2, num_kv_heads=1, head_size=4, dtype=torch.float32
|
||||
)
|
||||
page = spec.page_size_bytes
|
||||
resident_spec = HiSparseResidentSpec(block_size=2, page_size=page)
|
||||
device_size = 4 * page
|
||||
config = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
hisparse_host_num_blocks=3,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=3 * page,
|
||||
layers=["source"],
|
||||
layer_stride=3 * page,
|
||||
block_stride=page,
|
||||
host_resident=True,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=device_size,
|
||||
layers=["indexer"],
|
||||
layer_stride=device_size,
|
||||
block_stride=page,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=device_size,
|
||||
layers=["resident"],
|
||||
layer_stride=device_size,
|
||||
block_stride=page,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["source"], spec, host_resident=True),
|
||||
KVCacheGroupSpec(["indexer"], spec),
|
||||
KVCacheGroupSpec(["resident"], resident_spec),
|
||||
],
|
||||
)
|
||||
host_buffers: list[torch.Tensor] = []
|
||||
|
||||
def host_allocator(size: int) -> torch.Tensor:
|
||||
host_buffers.append(torch.zeros(size, dtype=torch.int8))
|
||||
return host_buffers[-1]
|
||||
|
||||
caches = allocate_hisparse_kv_caches(
|
||||
config,
|
||||
torch.device("cpu"),
|
||||
KVCacheLayout.LBHNC,
|
||||
[2, 2, 2],
|
||||
SimpleNamespace(allocate=host_allocator),
|
||||
)
|
||||
assert len(config.kv_cache_tensors) == 3
|
||||
|
||||
assert [buf.numel() for buf in host_buffers] == [3 * page]
|
||||
assert caches["source"].shape[0] == 3
|
||||
assert (
|
||||
caches["source"].untyped_storage().data_ptr()
|
||||
== host_buffers[0].untyped_storage().data_ptr()
|
||||
)
|
||||
assert caches["indexer"].shape[0] == 4
|
||||
backing = caches["resident"]
|
||||
assert backing.dtype == torch.int8 and backing.numel() >= device_size
|
||||
assert (
|
||||
backing.untyped_storage().data_ptr()
|
||||
== caches["indexer"].untyped_storage().data_ptr()
|
||||
)
|
||||
|
||||
|
||||
class _TableBuilder:
|
||||
requires_block_table_width = False
|
||||
supports_update_block_table = False
|
||||
|
||||
def __init__(self, kv_cache_spec, layer_names, vllm_config, device):
|
||||
self.kv_cache_spec = kv_cache_spec
|
||||
|
||||
def build(self, common_prefix_len, common_attn_metadata, fast_build=False):
|
||||
return common_attn_metadata.block_table_tensor
|
||||
|
||||
|
||||
_VLLM_CONFIG = SimpleNamespace(
|
||||
model_config=SimpleNamespace(max_model_len=8192),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=4),
|
||||
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
|
||||
)
|
||||
|
||||
|
||||
def _packed_group(tokens_per_state, row_bytes, supported_sizes):
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1024,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.uint8,
|
||||
state_content_bytes=row_bytes,
|
||||
tokens_per_state=tokens_per_state,
|
||||
)
|
||||
backend = SimpleNamespace(
|
||||
get_builder_cls=lambda: _TableBuilder,
|
||||
get_supported_kernel_block_sizes=lambda _=None: supported_sizes,
|
||||
get_name=lambda: "FAKE",
|
||||
customize_spec=lambda spec: spec,
|
||||
)
|
||||
return AttentionGroup(backend, ["layer.0"], spec, 0)
|
||||
|
||||
|
||||
def test_packed_compressed_group_gets_kernel_block_table():
|
||||
"""A packed indexer cache whose kernel needs 64-state pages gets a table and
|
||||
a bound view in kernel blocks that address the same packed-block rows."""
|
||||
row, stride_rows = 132, 5 * 64
|
||||
group = _packed_group(4, row, [128, 256])
|
||||
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=1024)
|
||||
assert group.get_metadata_builder().kv_cache_spec.block_size == 256
|
||||
|
||||
backing = torch.arange(3 * stride_rows).repeat_interleave(row)
|
||||
manager = backing.view(3, 1, stride_rows, row)[:, :, :256]
|
||||
pages = map_kv_caches_to_kernel_blocks({"layer.0": manager}, [group])["layer.0"]
|
||||
metadata = create_common_attn_metadata(BatchSpec([2048], [1]), 1024, "cpu")
|
||||
metadata.block_table_tensor = torch.tensor([[0, 2]], dtype=torch.int32)
|
||||
table = group.build_metadata(metadata)
|
||||
assert table.tolist() == [[0, 1, 2, 3, 10, 11, 12, 13]]
|
||||
assert torch.equal(pages[table[0, 4:], 0].flatten(0, 1), manager[2, 0])
|
||||
|
||||
|
||||
def test_split_group_maps_manager_block_table():
|
||||
"""Groups split in a dense layout keep manager block tables; builders get
|
||||
b * blocks_per_kv_block + j against the view allocated in kernel blocks."""
|
||||
group = _packed_group(4, 132, [128, 256])
|
||||
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=256)
|
||||
kernel_view = torch.zeros(12, 1, 64, 132)
|
||||
bound = map_kv_caches_to_kernel_blocks({"layer.0": kernel_view}, [group])
|
||||
assert bound["layer.0"] is kernel_view
|
||||
|
||||
metadata = create_common_attn_metadata(BatchSpec([2048], [1]), 1024, "cpu")
|
||||
metadata.block_table_tensor = torch.tensor([[0, 2]], dtype=torch.int32)
|
||||
table = group.build_metadata(metadata)
|
||||
assert table.tolist() == [[0, 1, 2, 3, 8, 9, 10, 11]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("block_size", "page_states"), [(1024, 64), (384, 32), (256, 0)]
|
||||
)
|
||||
def test_split_blocks_align_to_kernel_blocks(block_size, page_states):
|
||||
"""Backends taking only fixed kernel blocks align packed blocks to the kernel
|
||||
block the final block size is split into, and not at all when unsplit."""
|
||||
group = _packed_group(4, 132, [128, 256])
|
||||
spec = customize_attention_spec(group.backend, group.kv_cache_spec)
|
||||
spec = spec.copy_with_new_block_size(block_size)
|
||||
assert spec.get_block_stride_alignment() == max(page_states * 132, 1)
|
||||
|
||||
|
||||
def test_packed_token_cache_cannot_be_split():
|
||||
group = _packed_group(1, 1152, [64])
|
||||
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=1024)
|
||||
packed = torch.zeros(3, 1, 2048, 1152, dtype=torch.uint8)[:, :, :1024]
|
||||
with pytest.raises(ValueError, match="cannot be split"):
|
||||
map_kv_caches_to_kernel_blocks({"layer.0": packed}, [group])
|
||||
@@ -1,206 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.model_executor.models.interfaces import EagleModelMixin
|
||||
from vllm.model_executor.models.mimo import MiMoModel
|
||||
from vllm.models.minimax_m3.nvidia import model as minimax_m3
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
|
||||
requires_aux_hidden_states,
|
||||
reserve_aux_intermediate_tensor_slots,
|
||||
verify_supports_aux_hidden_states_over_pp,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "hf_config", "expected"),
|
||||
[
|
||||
("eagle3", {"eagle_config": {"use_aux_hidden_state": False}}, False),
|
||||
("eagle3", {"eagle_config": {"use_aux_hidden_state": True}}, True),
|
||||
("eagle3", {"eagle_config": {}}, True),
|
||||
("eagle3", {"eagle_config": None}, True),
|
||||
("eagle3", {}, True),
|
||||
("dflash", {"eagle_config": {"use_aux_hidden_state": False}}, True),
|
||||
("dspark", {"eagle_config": {"use_aux_hidden_state": False}}, True),
|
||||
("extract_hidden_states", {}, True),
|
||||
("mtp", {}, False),
|
||||
],
|
||||
)
|
||||
def test_aux_hidden_state_requirement_respects_eagle3_config(
|
||||
method, hf_config, expected
|
||||
):
|
||||
spec_config = SimpleNamespace(
|
||||
method=method,
|
||||
draft_model_config=SimpleNamespace(hf_config=SimpleNamespace(**hf_config)),
|
||||
)
|
||||
assert requires_aux_hidden_states(spec_config) is expected
|
||||
|
||||
|
||||
def test_aux_layers_are_sorted_and_deduplicated():
|
||||
model = EagleModelMixin()
|
||||
model._set_aux_hidden_state_layers((48, 3, 90, 24, 48))
|
||||
assert model.aux_hidden_state_layers == (3, 24, 48, 90)
|
||||
|
||||
|
||||
def test_mimo_does_not_inherit_aux_hidden_state_pp_support():
|
||||
inner = MiMoModel.__new__(MiMoModel)
|
||||
target = SimpleNamespace(model=inner)
|
||||
|
||||
assert not inner.supports_aux_hidden_states_over_pp
|
||||
with pytest.raises(ValueError, match="does not support eagle3"):
|
||||
verify_supports_aux_hidden_states_over_pp(target, "eagle3")
|
||||
|
||||
|
||||
class _PPAuxLayer(torch.nn.Module):
|
||||
"""Aliases and mutates residual in place like MiniMaxM3DecoderLayer."""
|
||||
|
||||
ffn_all_reduce_deferred = False
|
||||
|
||||
def __init__(self, index):
|
||||
super().__init__()
|
||||
self.index = index
|
||||
|
||||
def forward(self, positions, hidden_states, residual):
|
||||
total = hidden_states if residual is None else hidden_states + residual
|
||||
residual = hidden_states if residual is None else residual
|
||||
residual.copy_(total + self.index + 1)
|
||||
return torch.full_like(hidden_states, 10 * (self.index + 1)), residual
|
||||
|
||||
|
||||
class _PPAuxNorm(torch.nn.Module):
|
||||
"""Clobbers its inputs so aux taps that alias them would fail."""
|
||||
|
||||
def forward(self, hidden_states, residual):
|
||||
output = hidden_states + residual
|
||||
hidden_states.fill_(-101)
|
||||
residual.fill_(-103)
|
||||
return output, residual
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def minimax_pp_stage(monkeypatch):
|
||||
"""Use the real MiniMax constructor/forward and aux helpers on CPU tensors."""
|
||||
group = SimpleNamespace(world_size=2, is_first_rank=True, is_last_rank=False)
|
||||
bounds = [0, 3]
|
||||
monkeypatch.setattr(minimax_m3, "get_pp_group", lambda: group)
|
||||
monkeypatch.setattr(parallel_state, "get_pp_group", lambda: group)
|
||||
monkeypatch.setattr(parallel_state, "model_parallel_is_initialized", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
minimax_m3,
|
||||
"VocabParallelEmbedding",
|
||||
lambda *args, **kwargs: torch.nn.Identity(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
minimax_m3, "MiniMAXGemmaRMSNorm", lambda *args, **kwargs: _PPAuxNorm()
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
minimax_m3,
|
||||
"MiniMaxM3DecoderLayer",
|
||||
lambda **kwargs: _PPAuxLayer(int(kwargs["prefix"].rsplit(".", 1)[1])),
|
||||
)
|
||||
|
||||
def make_layers(num_layers, build, prefix):
|
||||
return (
|
||||
*bounds,
|
||||
torch.nn.ModuleList(
|
||||
build(f"{prefix}.{index}")
|
||||
if bounds[0] <= index < bounds[1]
|
||||
else torch.nn.Identity()
|
||||
for index in range(num_layers)
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(minimax_m3, "make_layers", make_layers)
|
||||
|
||||
def make_stage(start, end, taps, world_size=2):
|
||||
bounds[:] = [start, end]
|
||||
group.world_size = world_size
|
||||
group.is_first_rank = start == 0
|
||||
group.is_last_rank = end == 6
|
||||
config = SimpleNamespace(
|
||||
vocab_size=16, hidden_size=6144, num_hidden_layers=6, rms_norm_eps=1e-6
|
||||
)
|
||||
model = minimax_m3.MiniMaxM3Model(
|
||||
vllm_config=SimpleNamespace(
|
||||
model_config=SimpleNamespace(hf_text_config=config),
|
||||
quant_config=None,
|
||||
speculative_config=None,
|
||||
use_v2_model_runner=True,
|
||||
)
|
||||
)
|
||||
model._set_aux_hidden_state_layers(taps)
|
||||
target = SimpleNamespace(
|
||||
model=model,
|
||||
make_empty_intermediate_tensors=model.make_empty_intermediate_tensors,
|
||||
)
|
||||
reserve_aux_intermediate_tensor_slots(target)
|
||||
return model, target
|
||||
|
||||
return make_stage
|
||||
|
||||
|
||||
# Input 7; _PPAuxLayer i adds 11 * (i + 1) to hidden + residual.
|
||||
def _expected_aux_value(tap):
|
||||
return 7 + 11 * tap * (tap + 1) // 2
|
||||
|
||||
|
||||
def _pp_aux_state(value):
|
||||
return torch.full((2, 6144), float(value), device="cpu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("taps", [(0, 3, 6), (0, 1, 3), (4, 5, 6)])
|
||||
def test_minimax_pp2_preserves_ordered_global_aux_taps(minimax_pp_stage, taps):
|
||||
first, _ = minimax_pp_stage(0, 3, taps)
|
||||
sent = first(None, None, None, _pp_aux_state(7))
|
||||
last, target = minimax_pp_stage(3, 6, taps)
|
||||
reserved = target.make_empty_intermediate_tensors(2, torch.float32, "cpu")
|
||||
assert set(sent.tensors) == set(reserved.tensors)
|
||||
result = last(None, None, sent)
|
||||
assert isinstance(result, tuple)
|
||||
output, aux = result
|
||||
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
|
||||
for hidden, tap in zip(aux, taps, strict=True):
|
||||
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
|
||||
|
||||
|
||||
def test_minimax_missing_upstream_aux_slot_is_not_silently_dropped(minimax_pp_stage):
|
||||
model, _ = minimax_pp_stage(3, 6, (0, 3, 6))
|
||||
incoming = IntermediateTensors(
|
||||
{
|
||||
"hidden_states": _pp_aux_state(30),
|
||||
"residual": _pp_aux_state(43),
|
||||
"aux_hidden_states_0": _pp_aux_state(7),
|
||||
}
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="Missing aux_hidden_states_1"):
|
||||
model(None, None, incoming)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("taps", [(), (0, 3, 6)])
|
||||
def test_minimax_pp1_output_and_aux_taps(minimax_pp_stage, taps):
|
||||
model, _ = minimax_pp_stage(0, 6, taps, world_size=1)
|
||||
output = model(None, None, None, _pp_aux_state(7))
|
||||
if taps:
|
||||
output, aux = output
|
||||
for hidden, tap in zip(aux, taps, strict=True):
|
||||
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
|
||||
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
|
||||
|
||||
|
||||
def test_minimax_pp2_without_aux_keeps_hidden_and_residual_transport(minimax_pp_stage):
|
||||
first, _ = minimax_pp_stage(0, 3, ())
|
||||
sent = first(None, None, None, _pp_aux_state(7))
|
||||
assert set(sent.tensors) == {"hidden_states", "residual"}
|
||||
torch.testing.assert_close(sent["hidden_states"], _pp_aux_state(30))
|
||||
torch.testing.assert_close(sent["residual"], _pp_aux_state(43))
|
||||
last, target = minimax_pp_stage(3, 6, ())
|
||||
assert set(
|
||||
target.make_empty_intermediate_tensors(12, torch.bfloat16, "cpu").tensors
|
||||
) == {"hidden_states", "residual"}
|
||||
output = last(None, None, sent)
|
||||
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
|
||||
@@ -1,408 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(),
|
||||
reason="requires CUDA",
|
||||
)
|
||||
|
||||
|
||||
def test_block_tables_apply_staged_writes_fuses_kv_groups(monkeypatch):
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[16, 32, 8],
|
||||
max_num_reqs=4,
|
||||
max_num_batched_tokens=64,
|
||||
max_num_blocks_per_group=[8, 8, 8],
|
||||
device=device,
|
||||
)
|
||||
|
||||
def fail_if_apply_write_called():
|
||||
pytest.fail("multi-group writes should use the fused apply kernel")
|
||||
|
||||
for block_table in block_tables.block_tables:
|
||||
monkeypatch.setattr(block_table, "apply_write", fail_if_apply_write_called)
|
||||
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([1, 2], [10, 11], []),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.append_block_ids(
|
||||
req_index=1,
|
||||
new_block_ids=([3], [12], [5, 6]),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[0].gpu[0, :2],
|
||||
torch.tensor([1, 2], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[1].gpu[0, :2],
|
||||
torch.tensor([10, 11], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[0].gpu[1, :1],
|
||||
torch.tensor([3], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[1].gpu[1, :1],
|
||||
torch.tensor([12], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[2].gpu[1, :2],
|
||||
torch.tensor([5, 6], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert block_tables.num_blocks.np[0, 0] == 2
|
||||
assert block_tables.num_blocks.np[1, 0] == 2
|
||||
assert block_tables.num_blocks.np[2, 0] == 0
|
||||
assert block_tables.num_blocks.np[0, 1] == 1
|
||||
assert block_tables.num_blocks.np[1, 1] == 1
|
||||
assert block_tables.num_blocks.np[2, 1] == 2
|
||||
assert torch.equal(
|
||||
block_tables.num_blocks.gpu[:, :2],
|
||||
torch.tensor([[2, 1], [2, 1], [0, 2]], dtype=torch.int32, device=device),
|
||||
)
|
||||
|
||||
for block_table in block_tables.block_tables:
|
||||
assert not block_table._staged_write_indices
|
||||
assert not block_table._staged_write_starts
|
||||
assert not block_table._staged_write_contents
|
||||
assert not block_table._staged_write_cu_lens
|
||||
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([7], [13], [8]),
|
||||
overwrite=False,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[0].gpu[0, :3],
|
||||
torch.tensor([1, 2, 7], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[1].gpu[0, :3],
|
||||
torch.tensor([10, 11, 13], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[2].gpu[0, :1],
|
||||
torch.tensor([8], dtype=torch.int32, device=device),
|
||||
)
|
||||
assert block_tables.num_blocks.np[0, 0] == 3
|
||||
assert block_tables.num_blocks.np[1, 0] == 3
|
||||
assert block_tables.num_blocks.np[2, 0] == 1
|
||||
|
||||
|
||||
def test_block_tables_apply_staged_writes_single_group():
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[16],
|
||||
max_num_reqs=2,
|
||||
max_num_batched_tokens=16,
|
||||
max_num_blocks_per_group=[4],
|
||||
device=device,
|
||||
)
|
||||
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([1, 2],),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.equal(
|
||||
block_tables.block_tables[0].gpu[0, :2],
|
||||
torch.tensor([1, 2], dtype=torch.int32, device=device),
|
||||
)
|
||||
|
||||
|
||||
def test_block_tables_skip_custom_slot_mapping_groups():
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[8, 262144],
|
||||
max_num_reqs=1,
|
||||
max_num_batched_tokens=4,
|
||||
max_num_blocks_per_group=[1, 1],
|
||||
device=device,
|
||||
slot_mapping_enabled=[False, True],
|
||||
)
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([7], [12]),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
|
||||
idx_mapping = torch.tensor([0], dtype=torch.int32, device=device)
|
||||
query_start_loc = torch.tensor([0, 2], dtype=torch.int32, device=device)
|
||||
positions = torch.tensor([153797, 165757], dtype=torch.int64, device=device)
|
||||
slot_mappings = block_tables.compute_slot_mappings(
|
||||
idx_mapping,
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_tokens_padded=2,
|
||||
)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert slot_mappings[0].tolist() == [-1, -1]
|
||||
assert slot_mappings[1].tolist() == [
|
||||
12 * 262144 + 153797,
|
||||
12 * 262144 + 165757,
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cp_rank", range(4))
|
||||
def test_dcp_slot_mapping_only_shards_sharded_groups(cp_rank: int):
|
||||
"""Only sharded groups use DCP interleave in logical-block coordinates."""
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[128, 128],
|
||||
max_num_reqs=1,
|
||||
max_num_batched_tokens=1024,
|
||||
max_num_blocks_per_group=[2, 8],
|
||||
device=device,
|
||||
dcp_sharded=[True, False],
|
||||
cp_size=4,
|
||||
cp_rank=cp_rank,
|
||||
cp_interleave=128,
|
||||
)
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([5, 9], list(range(10, 18))),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
|
||||
idx_mapping = torch.zeros(1, dtype=torch.int32, device=device)
|
||||
query_start_loc = torch.tensor([0, 1024], dtype=torch.int32, device=device)
|
||||
positions = torch.arange(1024, dtype=torch.int64, device=device)
|
||||
actual = block_tables.compute_slot_mappings(
|
||||
idx_mapping,
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_tokens_padded=1024,
|
||||
)
|
||||
|
||||
expected = torch.full((1024,), -1, dtype=torch.int64, device=device)
|
||||
first_start = cp_rank * 128
|
||||
second_start = 512 + first_start
|
||||
expected[first_start : first_start + 128] = torch.arange(
|
||||
5 * 128, 6 * 128, dtype=torch.int64, device=device
|
||||
)
|
||||
expected[second_start : second_start + 128] = torch.arange(
|
||||
9 * 128, 10 * 128, dtype=torch.int64, device=device
|
||||
)
|
||||
assert torch.equal(actual[0], expected)
|
||||
assert torch.equal(actual[1], positions + 10 * 128)
|
||||
|
||||
|
||||
def test_v1_block_table_move_row_clears_vacated_row():
|
||||
"""condense() moves the last row into a freed slot; the vacated row must
|
||||
not keep stale block ids. Padded dummy-run batches dereference stale rows
|
||||
as mamba state slots (bypassing the NULL_BLOCK_ID fill of real decode
|
||||
padding) and write state in place there — corrupting the blocks' new
|
||||
owner once they are reallocated, e.g. to an in-flight NIXL load."""
|
||||
from vllm.v1.worker.block_table import BlockTable
|
||||
|
||||
block_table = BlockTable(
|
||||
block_size=16,
|
||||
max_num_reqs=4,
|
||||
max_num_blocks_per_req=8,
|
||||
max_num_batched_tokens=64,
|
||||
pin_memory=False,
|
||||
device=torch.device("cuda"),
|
||||
cp_kv_cache_interleave_size=1,
|
||||
)
|
||||
block_table.add_row([7, 8, 9], row_idx=0)
|
||||
block_table.add_row([4, 5], row_idx=1)
|
||||
|
||||
block_table.move_row(1, 0)
|
||||
|
||||
assert block_table.block_table.np[0, :2].tolist() == [4, 5]
|
||||
assert block_table.num_blocks_per_row[0] == 2
|
||||
# The vacated source row routes to the reserved null block.
|
||||
assert block_table.num_blocks_per_row[1] == 0
|
||||
assert (block_table.block_table.np[1] == 0).all()
|
||||
|
||||
|
||||
def test_get_dummy_block_tables_returns_zeroed_rows():
|
||||
"""Dummy runs bypass the gather, so the persistent input_block_tables
|
||||
hold the previous real step's rows. Mamba/GDN metadata routes in-place
|
||||
state writes through block_table[:, 0] (dummy slot mappings are
|
||||
PAD-filled, state indices are not), so stale rows would direct dummy
|
||||
state writes at freed — possibly reallocated — blocks.
|
||||
get_dummy_block_tables must hand out zeroed (null block) rows while
|
||||
preserving the persistent storage address for CUDA graphs."""
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[16],
|
||||
max_num_reqs=4,
|
||||
max_num_batched_tokens=64,
|
||||
max_num_blocks_per_group=[8],
|
||||
device=device,
|
||||
)
|
||||
# Simulate a real step: stage a request's blocks and gather them into
|
||||
# the persistent input block tables.
|
||||
block_tables.append_block_ids(req_index=0, new_block_ids=([1, 2],), overwrite=True)
|
||||
block_tables.apply_staged_writes()
|
||||
idx_mapping = torch.zeros(1, dtype=torch.int32, device=device)
|
||||
block_tables.gather_block_tables(idx_mapping, num_reqs_padded=1)
|
||||
torch.accelerator.synchronize()
|
||||
assert block_tables.input_block_tables[0][0, 0].item() == 1
|
||||
|
||||
dummy = block_tables.get_dummy_block_tables(num_reqs=1)
|
||||
torch.accelerator.synchronize()
|
||||
assert (dummy[0] == 0).all()
|
||||
# CUDA graph invariant: same persistent tensor, not a fresh allocation.
|
||||
assert dummy[0].data_ptr() == block_tables.input_block_tables[0].data_ptr()
|
||||
|
||||
|
||||
def test_dummy_request_slot_mapping_is_pad():
|
||||
"""idx_mapping == -1 marks a dummy (or CUDA-graph padding) request.
|
||||
|
||||
A dummy draft decode step must not resolve slots through the persistent
|
||||
block-table row of a real request slot, which may be stale and point at
|
||||
blocks that are now in the prefix cache.
|
||||
"""
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[4],
|
||||
max_num_reqs=2,
|
||||
max_num_batched_tokens=16,
|
||||
max_num_blocks_per_group=[4],
|
||||
device=device,
|
||||
)
|
||||
block_tables.append_block_ids(req_index=0, new_block_ids=([7, 8],), overwrite=True)
|
||||
block_tables.apply_staged_writes()
|
||||
query_start_loc = torch.tensor([0, 3], dtype=torch.int32, device=device)
|
||||
positions = torch.tensor([1, 2, 3], dtype=torch.int64, device=device)
|
||||
|
||||
real = block_tables.compute_slot_mappings(
|
||||
torch.tensor([0], dtype=torch.int32, device=device),
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_tokens_padded=3,
|
||||
)
|
||||
assert real[0].tolist() == [7 * 4 + 1, 7 * 4 + 2, 7 * 4 + 3]
|
||||
|
||||
dummy = block_tables.compute_slot_mappings(
|
||||
torch.tensor([-1], dtype=torch.int32, device=device),
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_tokens_padded=3,
|
||||
)
|
||||
assert dummy[0].tolist() == [PAD_SLOT_ID] * 3
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def populated_block_tables():
|
||||
tables = BlockTables([16, 32], 8, 64, [3, 5], torch.device("cuda"))
|
||||
for req_index in range(8):
|
||||
tables.append_block_ids(
|
||||
req_index, ([req_index + 1] * 3, [req_index + 1] * 5), overwrite=True
|
||||
)
|
||||
tables.apply_staged_writes()
|
||||
tables.gather_block_tables(torch.arange(8, device="cuda"), num_reqs_padded=8)
|
||||
return tables
|
||||
|
||||
|
||||
@pytest.mark.parametrize("previous_dummy", [False, True])
|
||||
@pytest.mark.parametrize("next_dummy", [False, True])
|
||||
def test_shared_block_tables_clear_rows_from_larger_batch(
|
||||
populated_block_tables, previous_dummy, next_dummy
|
||||
):
|
||||
"""A smaller target batch must leave no stale rows for larger draft graphs."""
|
||||
tables = populated_block_tables
|
||||
if previous_dummy:
|
||||
for table in tables.get_dummy_block_tables(8):
|
||||
table.fill_(99) # Profiling supplies valid context/state slots.
|
||||
ptrs = [table.data_ptr() for table in tables.input_block_tables]
|
||||
idx = torch.tensor([7, 2, 0, 5, 1], device="cuda")
|
||||
for num_reqs in (3, 5, 0):
|
||||
if next_dummy:
|
||||
out = tables.get_dummy_block_tables(num_reqs)
|
||||
num_rows = num_reqs
|
||||
else:
|
||||
num_rows = num_reqs + 1
|
||||
out = tables.gather_block_tables(idx[:num_reqs], num_rows)
|
||||
for table, view, ptr in zip(tables.input_block_tables, out, ptrs):
|
||||
assert view.shape == (num_rows, table.shape[1])
|
||||
assert table.data_ptr() == ptr
|
||||
if num_rows:
|
||||
assert view.data_ptr() == ptr
|
||||
assert torch.count_nonzero(table[num_reqs:]).item() == 0
|
||||
if next_dummy:
|
||||
assert torch.count_nonzero(view).item() == 0
|
||||
view.fill_(99)
|
||||
else:
|
||||
expected = (idx[:num_reqs, None] + 1).expand(-1, table.shape[1])
|
||||
torch.testing.assert_close(view[:num_reqs], expected.to(torch.int32))
|
||||
|
||||
|
||||
def test_external_block_table_output_preserves_shared_rows(populated_block_tables):
|
||||
"""PCP-local gathers must neither clear shared rows nor reset their tracking."""
|
||||
tables = populated_block_tables
|
||||
previous = [table.clone() for table in tables.input_block_tables]
|
||||
out = tuple(torch.full_like(table[:3], -1) for table in previous)
|
||||
out_ptrs = torch.tensor(
|
||||
[table.data_ptr() for table in out], dtype=torch.uint64, device="cuda"
|
||||
)
|
||||
idx = torch.tensor([7, 2], device="cuda")
|
||||
result = tables.gather_block_tables(idx, 3, out=out, out_ptrs=out_ptrs)
|
||||
for table, before, view in zip(tables.input_block_tables, previous, result):
|
||||
torch.testing.assert_close(table, before)
|
||||
assert view[:, 0].tolist() == [8, 3, 0]
|
||||
tables.gather_block_tables(idx[:1], num_reqs_padded=1)
|
||||
for table in tables.input_block_tables:
|
||||
assert torch.count_nonzero(table[1:]).item() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_cuda_graph", [False, True])
|
||||
def test_larger_draft_batch_uses_null_kpool_slots(
|
||||
populated_block_tables, use_cuda_graph
|
||||
):
|
||||
"""Draft padding must not resolve to another request's physical KPool slots."""
|
||||
from vllm.v1.attention.backends.mla.indexer import compute_kpool_tail_slot_mapping
|
||||
|
||||
tables = populated_block_tables
|
||||
idx = torch.tensor([2, 0, 4, 1, 3], device="cuda")
|
||||
query_start_loc = torch.arange(9, dtype=torch.int32, device="cuda").clamp_max_(5)
|
||||
slot_mapping = torch.full((8,), -1, dtype=torch.int64, device="cuda")
|
||||
positions = torch.arange(8, dtype=torch.int64, device="cuda")
|
||||
|
||||
def compute_slots():
|
||||
return compute_kpool_tail_slot_mapping(
|
||||
slot_mapping,
|
||||
tables.input_block_tables[0],
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_actual_tokens=8,
|
||||
num_reqs=8,
|
||||
kpool=8,
|
||||
)
|
||||
|
||||
if use_cuda_graph:
|
||||
compute_slots()
|
||||
torch.accelerator.synchronize()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
slots = compute_slots()
|
||||
tables.gather_block_tables(idx, num_reqs_padded=5)
|
||||
if use_cuda_graph:
|
||||
graph.replay()
|
||||
else:
|
||||
slots = compute_slots()
|
||||
assert slots.tolist() == [24, 9, 42, 19, 36, -1, -1, -1]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,668 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.model_executor.models import supports_multimodal_embeddings
|
||||
from vllm.model_executor.models.exaone4_5_mtp import Exaone4_5_MTP
|
||||
from vllm.model_executor.models.llama4_eagle import EagleLlama4ForCausalLM
|
||||
from vllm.model_executor.models.llama_eagle3 import Eagle3LlamaForCausalLM
|
||||
from vllm.model_executor.models.mistral_eagle import EagleMistralForCausalLM
|
||||
from vllm.model_executor.models.mistral_large_3_eagle import (
|
||||
EagleMistralLarge3ForCausalLM,
|
||||
)
|
||||
from vllm.v1.attention.backends import flash_attn as flash_attn_module
|
||||
from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadata
|
||||
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
|
||||
from vllm.v1.worker.gpu.pcp_manager import PCPManager
|
||||
from vllm.v1.worker.gpu.spec_decode import speculator as base_spec_module
|
||||
from vllm.v1.worker.gpu.spec_decode.multi_module_mtp.speculator import (
|
||||
MultiModuleMTPSpeculator,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar import speculator as spec_module
|
||||
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
|
||||
TargetDependentARSpeculator,
|
||||
)
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
|
||||
class _TestSpeculator(TargetDependentARSpeculator):
|
||||
def load_draft_model(self, target_model, target_attn_layer_names):
|
||||
return self.test_draft_model
|
||||
|
||||
|
||||
class _DraftModel(torch.nn.Module):
|
||||
def __init__(self, output: torch.Tensor | tuple[torch.Tensor, torch.Tensor]):
|
||||
super().__init__()
|
||||
self.output = output
|
||||
|
||||
def forward(self, **kwargs):
|
||||
return self.output
|
||||
|
||||
|
||||
class _MultimodalDraftModel(torch.nn.Module):
|
||||
supports_multimodal_embeddings = True
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids,
|
||||
multimodal_embeddings=None,
|
||||
*,
|
||||
is_multimodal=None,
|
||||
):
|
||||
raise AssertionError("embed_input_ids should not be called during loading")
|
||||
|
||||
|
||||
class _TextOnlyDraftModel(torch.nn.Module):
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids,
|
||||
multimodal_embeddings=None,
|
||||
*,
|
||||
is_multimodal=None,
|
||||
):
|
||||
raise AssertionError("embed_input_ids should not be called during loading")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cg_mode", [CUDAGraphMode.NONE, CUDAGraphMode.FULL])
|
||||
def test_pcp_draft_metadata_keeps_graph_padding_in_decode(cg_mode):
|
||||
def build(common_prefix_len, common_attn_metadata):
|
||||
return split_decodes_and_prefills(
|
||||
common_attn_metadata,
|
||||
decode_threshold=1,
|
||||
require_uniform=True,
|
||||
treat_short_extends_as_decodes=False,
|
||||
)
|
||||
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.arange_np = torch.arange(5, dtype=torch.int32).numpy()
|
||||
speculator.max_model_len = speculator.draft_max_seq_len = 32
|
||||
speculator.draft_is_prefilling = torch.zeros(4, dtype=torch.bool)
|
||||
speculator.input_buffers = SimpleNamespace(
|
||||
positions=torch.arange(4, dtype=torch.int64),
|
||||
query_start_loc=torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([11, 21, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
speculator.dcp_size = 1
|
||||
speculator.block_tables = SimpleNamespace(
|
||||
cp_size=1,
|
||||
input_block_tables=[torch.zeros(4, 1, dtype=torch.int32)],
|
||||
slot_mappings=torch.tensor([[10, 20, -1, -1]]),
|
||||
)
|
||||
speculator.kv_cache_config = SimpleNamespace(kv_cache_groups=[object()])
|
||||
speculator.attn_groups = [
|
||||
[
|
||||
SimpleNamespace(
|
||||
get_metadata_builder=lambda _: SimpleNamespace(
|
||||
build=build, supports_update_block_table=False
|
||||
),
|
||||
build_metadata=lambda cm, ubatch_idx=0, **_: build(0, cm),
|
||||
layer_names=["draft"],
|
||||
)
|
||||
]
|
||||
]
|
||||
num_reqs_padded = 4 if cg_mode == CUDAGraphMode.FULL else 2
|
||||
metadata = speculator._build_uniform_attn_metadata(
|
||||
batch_desc=BatchExecutionDescriptor(cg_mode, 4, num_reqs_padded),
|
||||
num_reqs=2,
|
||||
num_query_per_req=1,
|
||||
seq_lens_cpu_upper_bound=torch.tensor([10, 20], dtype=torch.int32),
|
||||
step=1,
|
||||
)
|
||||
assert metadata["draft"] == (num_reqs_padded, 0, num_reqs_padded, 0)
|
||||
|
||||
|
||||
def _mock_base_model_load(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
base_spec_module,
|
||||
"get_layers_from_vllm_config",
|
||||
lambda *args, **kwargs: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DraftModelSpeculator,
|
||||
"_validate_local_argmax_reduction",
|
||||
lambda self: None,
|
||||
)
|
||||
|
||||
|
||||
def _make_speculator(
|
||||
monkeypatch,
|
||||
output: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
) -> _TestSpeculator:
|
||||
monkeypatch.setattr(
|
||||
spec_module,
|
||||
"set_forward_context",
|
||||
lambda *args, **kwargs: nullcontext(),
|
||||
)
|
||||
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.supports_mm_inputs = False
|
||||
speculator.pcp_manager = None
|
||||
speculator.vllm_config = None
|
||||
speculator.input_buffers = SimpleNamespace(
|
||||
input_ids=torch.arange(4),
|
||||
positions=torch.arange(4),
|
||||
)
|
||||
speculator.hidden_states = torch.zeros(4, 3)
|
||||
speculator.model = _DraftModel(output)
|
||||
return speculator
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("hc_mult", "expected"), [(None, 64), (4, 256)])
|
||||
def test_speculator_uses_draft_model_hidden_size(monkeypatch, hc_mult, expected):
|
||||
# Qwen4Exp targets expose multi-stream HC residuals to the drafter.
|
||||
monkeypatch.setattr(base_spec_module, "_target_feeds_hc_residual", lambda _: True)
|
||||
hf_config = SimpleNamespace()
|
||||
if hc_mult is not None:
|
||||
hf_config.hc_mult = hc_mult
|
||||
draft_model_config = SimpleNamespace(
|
||||
hf_config=hf_config,
|
||||
get_hidden_size=lambda: 64,
|
||||
get_vocab_size=lambda: 32,
|
||||
)
|
||||
speculative_config = SimpleNamespace(
|
||||
method="mtp",
|
||||
num_speculative_tokens=3,
|
||||
draft_model_config=draft_model_config,
|
||||
use_local_argmax_reduction=False,
|
||||
draft_sample_method="greedy",
|
||||
enable_adaptive_verification=False,
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
speculative_config=speculative_config,
|
||||
scheduler_config=SimpleNamespace(
|
||||
max_num_seqs=2,
|
||||
max_num_batched_tokens=8,
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
max_model_len=32,
|
||||
dtype=torch.float32,
|
||||
use_fp64_gumbel=False,
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_size=1,
|
||||
data_parallel_rank=0,
|
||||
decode_context_parallel_size=1,
|
||||
),
|
||||
)
|
||||
|
||||
speculator = _TestSpeculator(vllm_config, torch.device("cpu"))
|
||||
|
||||
assert speculator.hidden_size == expected
|
||||
|
||||
|
||||
def test_mm_support_configured_after_model_load(monkeypatch):
|
||||
checked_configs = []
|
||||
|
||||
class _ModelConfig:
|
||||
@property
|
||||
def supports_multimodal_inputs(self):
|
||||
checked_configs.append(self)
|
||||
return True
|
||||
|
||||
target_model_config = _ModelConfig()
|
||||
draft_model_config = _ModelConfig()
|
||||
vllm_config = SimpleNamespace(model_config=target_model_config)
|
||||
draft_model = _MultimodalDraftModel()
|
||||
|
||||
def init_base(speculator, vllm_config, device):
|
||||
speculator.vllm_config = vllm_config
|
||||
speculator.device = device
|
||||
speculator.max_num_tokens = 4
|
||||
speculator.max_num_reqs = 2
|
||||
speculator.hidden_size = 3
|
||||
speculator.dtype = torch.float32
|
||||
speculator.draft_model_config = draft_model_config
|
||||
speculator.supports_mm_inputs = False
|
||||
speculator.use_acceptance_estimator = False
|
||||
|
||||
monkeypatch.setattr(DraftModelSpeculator, "__init__", init_base)
|
||||
_mock_base_model_load(monkeypatch)
|
||||
|
||||
speculator = _TestSpeculator(vllm_config, torch.device("cpu"))
|
||||
|
||||
assert checked_configs == []
|
||||
assert not speculator.supports_mm_inputs
|
||||
assert speculator.inputs_embeds is None
|
||||
|
||||
speculator.test_draft_model = draft_model
|
||||
speculator.load_model(torch.nn.Module())
|
||||
|
||||
assert checked_configs == [target_model_config]
|
||||
assert speculator.supports_mm_inputs
|
||||
assert speculator.inputs_embeds is not None
|
||||
assert speculator.inputs_embeds.shape == (4, 3)
|
||||
|
||||
|
||||
def test_load_model_keeps_mm_support_for_capable_drafter(monkeypatch):
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.supports_mm_inputs = False
|
||||
speculator.inputs_embeds = None
|
||||
speculator.use_acceptance_estimator = False
|
||||
speculator.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(supports_multimodal_inputs=True)
|
||||
)
|
||||
speculator.max_num_tokens = 4
|
||||
speculator.hidden_size = 3
|
||||
speculator.dtype = torch.float32
|
||||
speculator.device = torch.device("cpu")
|
||||
draft_model = _MultimodalDraftModel()
|
||||
speculator.test_draft_model = draft_model
|
||||
_mock_base_model_load(monkeypatch)
|
||||
|
||||
speculator.load_model(torch.nn.Module())
|
||||
|
||||
assert speculator.supports_mm_inputs
|
||||
assert speculator.inputs_embeds is not None
|
||||
|
||||
|
||||
def test_load_model_disables_mm_support_for_text_only_drafter(monkeypatch):
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.supports_mm_inputs = False
|
||||
speculator.inputs_embeds = None
|
||||
speculator.use_acceptance_estimator = False
|
||||
speculator.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(supports_multimodal_inputs=True)
|
||||
)
|
||||
draft_model = _TextOnlyDraftModel()
|
||||
speculator.test_draft_model = draft_model
|
||||
warning_messages = []
|
||||
_mock_base_model_load(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
base_spec_module.logger,
|
||||
"warning_once",
|
||||
lambda message, *args: warning_messages.append(message % args),
|
||||
)
|
||||
|
||||
speculator.load_model(torch.nn.Module())
|
||||
|
||||
assert not speculator.supports_mm_inputs
|
||||
assert warning_messages == [
|
||||
(
|
||||
"Draft model _TextOnlyDraftModel does not support external multimodal "
|
||||
"embeddings. Embeddings from the target model will not be passed to the "
|
||||
"drafter; using text-only draft inputs instead."
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_multi_module_mm_support_configured_after_model_load(monkeypatch):
|
||||
speculator = object.__new__(MultiModuleMTPSpeculator)
|
||||
speculator.supports_mm_inputs = False
|
||||
speculator.inputs_embeds = None
|
||||
speculator.use_acceptance_estimator = False
|
||||
speculator.cached_draft_input_embeds = None
|
||||
speculator.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(supports_multimodal_inputs=True)
|
||||
)
|
||||
speculator.max_num_tokens = 4
|
||||
speculator.max_num_reqs = 2
|
||||
speculator.num_speculative_steps = 3
|
||||
speculator.hidden_size = 3
|
||||
speculator.dtype = torch.float32
|
||||
speculator.device = torch.device("cpu")
|
||||
draft_model = _MultimodalDraftModel()
|
||||
_mock_base_model_load(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
MultiModuleMTPSpeculator,
|
||||
"load_draft_model",
|
||||
lambda self, target_model, target_attn_layer_names: draft_model,
|
||||
)
|
||||
|
||||
speculator.load_model(torch.nn.Module())
|
||||
|
||||
assert speculator.supports_mm_inputs
|
||||
assert speculator.inputs_embeds is not None
|
||||
assert speculator.inputs_embeds.shape == (4, 3)
|
||||
assert speculator.cached_draft_input_embeds is not None
|
||||
assert speculator.cached_draft_input_embeds.shape == (2, 2, 3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model_cls", "expected"),
|
||||
[
|
||||
(EagleLlama4ForCausalLM, True),
|
||||
(EagleMistralForCausalLM, True),
|
||||
(EagleMistralLarge3ForCausalLM, True),
|
||||
(Exaone4_5_MTP, True),
|
||||
(Eagle3LlamaForCausalLM, False),
|
||||
],
|
||||
)
|
||||
def test_draft_model_multimodal_embedding_capability(model_cls, expected):
|
||||
assert supports_multimodal_embeddings(model_cls) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_cls", [EagleLlama4ForCausalLM, EagleMistralLarge3ForCausalLM]
|
||||
)
|
||||
def test_mm_capable_drafter_merges_multimodal_embeddings(model_cls):
|
||||
"""Drafters advertising multimodal embeddings must embed text ids and
|
||||
scatter the multimodal embeddings themselves; they do not inherit
|
||||
SupportsMultiModal's helpers."""
|
||||
table = torch.arange(8, dtype=torch.float32).repeat(3, 1).T # [8, 3]
|
||||
drafter = object.__new__(model_cls)
|
||||
drafter.model = SimpleNamespace(embed_input_ids=lambda ids: table[ids])
|
||||
input_ids = torch.tensor([1, 5, 6, 2])
|
||||
|
||||
text_only = model_cls.embed_input_ids(drafter, input_ids)
|
||||
assert torch.equal(text_only, table[input_ids])
|
||||
|
||||
mm_embeds = [torch.full((2, 3), -1.0)]
|
||||
is_multimodal = torch.tensor([False, True, True, False])
|
||||
merged = model_cls.embed_input_ids(
|
||||
drafter, input_ids, mm_embeds, is_multimodal=is_multimodal
|
||||
)
|
||||
assert torch.equal(merged[[0, 3]], table[[1, 2]])
|
||||
assert torch.equal(merged[[1, 2]], mm_embeds[0])
|
||||
|
||||
|
||||
def test_run_model_unpacks_tuple_return_for_mtp(monkeypatch):
|
||||
logits_hidden = torch.full((4, 3), 1.0)
|
||||
feedback_hidden = torch.full((4, 3), 2.0)
|
||||
speculator = _make_speculator(monkeypatch, (logits_hidden, feedback_hidden))
|
||||
|
||||
actual_logits_hidden, actual_feedback_hidden = speculator._run_model(
|
||||
4,
|
||||
attn_metadata=None,
|
||||
slot_mappings=None,
|
||||
num_tokens_across_dp=None,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
)
|
||||
|
||||
assert actual_logits_hidden is logits_hidden
|
||||
assert actual_feedback_hidden is feedback_hidden
|
||||
|
||||
|
||||
def test_run_model_reuses_tensor_return_for_mtp(monkeypatch):
|
||||
hidden = torch.full((4, 3), 1.0)
|
||||
speculator = _make_speculator(monkeypatch, hidden)
|
||||
|
||||
actual_logits_hidden, actual_feedback_hidden = speculator._run_model(
|
||||
4,
|
||||
attn_metadata=None,
|
||||
slot_mappings=None,
|
||||
num_tokens_across_dp=None,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
)
|
||||
|
||||
assert actual_logits_hidden is hidden
|
||||
assert actual_feedback_hidden is hidden
|
||||
|
||||
|
||||
@pytest.mark.parametrize("partitioned", [False, True])
|
||||
def test_run_model_uses_complete_pcp_padding(monkeypatch, partitioned):
|
||||
hidden = torch.full((4, 3), 1.0)
|
||||
speculator = _make_speculator(monkeypatch, hidden)
|
||||
gathered_is_padding = torch.tensor(
|
||||
[False, False, False, True, False, False, True, True]
|
||||
)
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
max_num_tokens=4,
|
||||
moe_gathers_tokens=True,
|
||||
)
|
||||
if partitioned:
|
||||
manager.draft_prefill_batch = SimpleNamespace(
|
||||
input_ids=torch.arange(4),
|
||||
positions=torch.arange(4),
|
||||
is_padding=gathered_is_padding,
|
||||
)
|
||||
else:
|
||||
local_is_padding = torch.tensor([False, False, False, True])
|
||||
speculator.input_buffers.is_padding = local_is_padding
|
||||
gathered_is_padding = torch.cat([local_is_padding, local_is_padding])
|
||||
seen = {}
|
||||
monkeypatch.setattr(
|
||||
spec_module,
|
||||
"set_forward_context",
|
||||
lambda *args, **kwargs: (seen.update(kwargs), nullcontext())[1],
|
||||
)
|
||||
speculator.pcp_manager = manager
|
||||
|
||||
speculator._run_model(
|
||||
4,
|
||||
attn_metadata=None,
|
||||
slot_mappings=None,
|
||||
num_tokens_across_dp=None,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(seen["is_padding"], gathered_is_padding)
|
||||
if partitioned:
|
||||
assert seen["is_padding"] is gathered_is_padding
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"method_name",
|
||||
"cg_mode",
|
||||
"num_speculative_steps",
|
||||
"expected_eager_calls",
|
||||
"expected_graph_replays",
|
||||
),
|
||||
[
|
||||
("_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
|
||||
("_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 3),
|
||||
("_fused_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
|
||||
("_fused_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 1),
|
||||
("_multi_step_decode", CUDAGraphMode.FULL, 3, 0, 2),
|
||||
],
|
||||
)
|
||||
def test_multi_step_decode_replays_captured_graph_as_expected(
|
||||
method_name,
|
||||
cg_mode,
|
||||
num_speculative_steps,
|
||||
expected_eager_calls,
|
||||
expected_graph_replays,
|
||||
):
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.num_speculative_steps = 4
|
||||
speculator.current_draft_step = torch.tensor(0)
|
||||
speculator.slot_mapping_observer = None
|
||||
speculator.host_mirror_forward_observer = None
|
||||
speculator.input_buffers = SimpleNamespace(
|
||||
positions=torch.arange(2),
|
||||
query_start_loc=torch.arange(3),
|
||||
)
|
||||
speculator.idx_mapping = torch.arange(2)
|
||||
speculator.attn_groups = []
|
||||
speculator.block_tables = SimpleNamespace(input_block_tables=[])
|
||||
generate_draft = Mock()
|
||||
speculator._generate_draft = generate_draft
|
||||
run_fullgraph = Mock()
|
||||
speculator.decode_cudagraph_manager = SimpleNamespace(run_fullgraph=run_fullgraph)
|
||||
batch_desc = BatchExecutionDescriptor(
|
||||
cg_mode=cg_mode,
|
||||
num_tokens=2,
|
||||
num_reqs=2,
|
||||
)
|
||||
|
||||
getattr(speculator, method_name)(
|
||||
num_reqs=2,
|
||||
skip_attn=True,
|
||||
batch_desc=batch_desc,
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
num_tokens_across_dp=None,
|
||||
num_speculative_steps=num_speculative_steps,
|
||||
)
|
||||
|
||||
assert generate_draft.call_count == expected_eager_calls
|
||||
assert run_fullgraph.call_count == expected_graph_replays
|
||||
|
||||
|
||||
def test_fused_full_graph_maps_split_group_block_tables():
|
||||
"""The fused FULL replay skips build(), so split groups' tables are mapped first."""
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1024, num_kv_heads=1, head_size=128, dtype=torch.uint8
|
||||
)
|
||||
group = AttentionGroup(
|
||||
SimpleNamespace(),
|
||||
["layer.0"],
|
||||
spec,
|
||||
0,
|
||||
kernel_block_size=256,
|
||||
kernel_block_table=torch.zeros(1, 4, 32, dtype=torch.int32),
|
||||
kernel_block_offsets=torch.arange(4, dtype=torch.int32),
|
||||
)
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.input_buffers = SimpleNamespace(
|
||||
positions=torch.arange(2), query_start_loc=torch.arange(3)
|
||||
)
|
||||
speculator.idx_mapping = torch.arange(2)
|
||||
speculator.attn_groups = [[group]]
|
||||
speculator.block_tables = SimpleNamespace(
|
||||
input_block_tables=[torch.tensor([[1, 2], [0, 3]], dtype=torch.int32)]
|
||||
)
|
||||
replayed_tables = []
|
||||
speculator.decode_cudagraph_manager = SimpleNamespace(
|
||||
run_fullgraph=lambda _: replayed_tables.append(
|
||||
group.kernel_block_table[0, :2, :8].tolist()
|
||||
)
|
||||
)
|
||||
|
||||
speculator._fused_multi_step_decode(
|
||||
num_reqs=2,
|
||||
skip_attn=False,
|
||||
batch_desc=BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.FULL, num_tokens=2, num_reqs=2
|
||||
),
|
||||
num_tokens_across_dp=None,
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
num_speculative_steps=4,
|
||||
)
|
||||
|
||||
assert replayed_tables == [
|
||||
[[4, 5, 6, 7, 8, 9, 10, 11], [0, 1, 2, 3, 12, 13, 14, 15]]
|
||||
]
|
||||
|
||||
|
||||
def test_update_draft_decode_metadata_updates_fa3_scheduler_metadata(
|
||||
monkeypatch,
|
||||
):
|
||||
builder = object.__new__(flash_attn_module.FlashAttentionMetadataBuilder)
|
||||
builder.aot_schedule = True
|
||||
builder.use_full_cuda_graph = True
|
||||
builder.scheduler_metadata = torch.zeros(8, dtype=torch.int32)
|
||||
builder.cache_config = SimpleNamespace(cache_dtype="bfloat16")
|
||||
builder.kv_cache_dtype = torch.bfloat16
|
||||
builder.num_heads_q = 2
|
||||
builder.num_heads_kv = 1
|
||||
builder.headdim = 128
|
||||
builder.block_size = 16
|
||||
builder.dcp_world_size = 1
|
||||
builder.dcp_rank = 0
|
||||
builder.cp_kv_cache_interleave_size = 1
|
||||
builder.aot_sliding_window = None
|
||||
|
||||
expected = torch.tensor([7, 8, 9], dtype=torch.int32)
|
||||
|
||||
def fake_get_scheduler_metadata(**kwargs):
|
||||
return expected
|
||||
|
||||
monkeypatch.setattr(builder, "_get_scheduler_metadata", fake_get_scheduler_metadata)
|
||||
|
||||
metadata = FlashAttentionMetadata(
|
||||
num_actual_tokens=3,
|
||||
max_query_len=2,
|
||||
query_start_loc=torch.tensor([0, 1, 3], dtype=torch.int32),
|
||||
max_seq_len=8,
|
||||
seq_lens=torch.tensor([5, 6], dtype=torch.int32),
|
||||
block_table=torch.zeros((2, 1), dtype=torch.int32),
|
||||
slot_mapping=torch.zeros(3, dtype=torch.int32),
|
||||
max_dcp_context_kv_len=None,
|
||||
dcp_context_kv_lens=None,
|
||||
num_decode_reqs=2,
|
||||
num_prefill_reqs=0,
|
||||
num_decode_tokens=3,
|
||||
num_prefill_tokens=0,
|
||||
scheduler_metadata=torch.tensor([-1, -1, -1], dtype=torch.int32),
|
||||
max_num_splits=4,
|
||||
causal=True,
|
||||
mm_prefix_query_range_tensor=None,
|
||||
rswa_prefix_lens=None,
|
||||
rswa_window=None,
|
||||
rswa_window_tensor=None,
|
||||
)
|
||||
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
assert torch.equal(metadata.scheduler_metadata, expected)
|
||||
assert torch.equal(builder.scheduler_metadata[:3], expected)
|
||||
|
||||
|
||||
def test_update_draft_decode_metadata_skips_without_scheduler_metadata(monkeypatch):
|
||||
builder = object.__new__(flash_attn_module.FlashAttentionMetadataBuilder)
|
||||
builder.aot_schedule = True
|
||||
builder.use_full_cuda_graph = True
|
||||
builder.scheduler_metadata = torch.zeros(4, dtype=torch.int32)
|
||||
|
||||
called = False
|
||||
|
||||
def fake_get_scheduler_metadata(**kwargs):
|
||||
nonlocal called
|
||||
called = True
|
||||
return torch.tensor([1], dtype=torch.int32)
|
||||
|
||||
monkeypatch.setattr(builder, "_get_scheduler_metadata", fake_get_scheduler_metadata)
|
||||
|
||||
metadata = FlashAttentionMetadata(
|
||||
num_actual_tokens=1,
|
||||
max_query_len=1,
|
||||
query_start_loc=torch.tensor([0, 1], dtype=torch.int32),
|
||||
max_seq_len=1,
|
||||
seq_lens=torch.tensor([1], dtype=torch.int32),
|
||||
block_table=torch.zeros((1, 1), dtype=torch.int32),
|
||||
slot_mapping=torch.zeros(1, dtype=torch.int32),
|
||||
max_dcp_context_kv_len=None,
|
||||
dcp_context_kv_lens=None,
|
||||
num_decode_reqs=1,
|
||||
num_prefill_reqs=0,
|
||||
num_decode_tokens=1,
|
||||
num_prefill_tokens=0,
|
||||
scheduler_metadata=None,
|
||||
max_num_splits=1,
|
||||
causal=True,
|
||||
mm_prefix_query_range_tensor=None,
|
||||
rswa_prefix_lens=None,
|
||||
rswa_window=None,
|
||||
rswa_window_tensor=None,
|
||||
)
|
||||
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
assert not called
|
||||
assert metadata.scheduler_metadata is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("num_speculative_steps", "expected"), [(1, False), (3, True)])
|
||||
def test_decode_metadata_update_needs_draft_decode_steps(
|
||||
num_speculative_steps, expected
|
||||
):
|
||||
"""One speculative step runs no draft decodes, so the in-place metadata
|
||||
update (and its fallback log) does not apply even on a capable backend."""
|
||||
speculator = object.__new__(_TestSpeculator)
|
||||
speculator.num_speculative_steps = num_speculative_steps
|
||||
speculator.attn_groups = [
|
||||
[
|
||||
SimpleNamespace(
|
||||
supports_draft_decode_metadata_update=True,
|
||||
backend=SimpleNamespace(get_name=lambda: "CAPABLE"),
|
||||
)
|
||||
]
|
||||
]
|
||||
|
||||
speculator._configure_decode_metadata_update()
|
||||
|
||||
assert speculator.supports_decode_metadata_update is expected
|
||||
@@ -1,468 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import create_new_process_for_each_test
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.mem_constants import GiB_bytes
|
||||
from vllm.v1.worker import gpu_worker, startup_plan
|
||||
from vllm.v1.worker.gpu_worker import maybe_rocm_profiling_fallback
|
||||
from vllm.v1.worker.startup_plan import (
|
||||
maybe_apply_startup_plan,
|
||||
maybe_save_startup_plan,
|
||||
)
|
||||
|
||||
|
||||
def test_sleep_preservation_restores_private_draft_not_shared_target():
|
||||
target = torch.nn.Linear(2, 2, bias=False)
|
||||
draft = torch.nn.Module()
|
||||
draft.private = torch.nn.Linear(2, 2, bias=False)
|
||||
draft.shared = target.weight
|
||||
expected = draft.private.weight.detach().clone()
|
||||
pointer = draft.private.weight.data_ptr()
|
||||
worker = object.__new__(gpu_worker.Worker)
|
||||
worker.get_draft_model = lambda: draft
|
||||
assert set(worker._get_sleep_parameters(target)) == {
|
||||
"weight",
|
||||
"draft.private.weight",
|
||||
}
|
||||
worker._sleep_saved_parameters = {"draft.private.weight": expected}
|
||||
with torch.no_grad():
|
||||
target.weight.fill_(3.0)
|
||||
draft.private.weight.zero_()
|
||||
worker._restore_sleep_parameters(target)
|
||||
torch.testing.assert_close(draft.private.weight, expected)
|
||||
assert draft.private.weight.data_ptr() == pointer
|
||||
assert torch.all(target.weight == 3.0)
|
||||
assert worker._sleep_saved_parameters == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_shared_draft", [False, True])
|
||||
def test_sleep_preservation_allows_empty_draft_but_rejects_target_typo(
|
||||
has_shared_draft,
|
||||
):
|
||||
target = torch.nn.Linear(2, 2, bias=False)
|
||||
draft = torch.nn.Module() if has_shared_draft else None
|
||||
if draft is not None:
|
||||
draft.shared = target.weight
|
||||
worker = object.__new__(gpu_worker.Worker)
|
||||
worker.get_draft_model = lambda: draft
|
||||
worker.model_config = SimpleNamespace(sleep_preserve_parameter_names=["draft.*"])
|
||||
worker._save_sleep_parameters(target)
|
||||
assert worker._sleep_saved_parameters == {}
|
||||
worker.model_config.sleep_preserve_parameter_names = ["missing"]
|
||||
with pytest.raises(ValueError, match="No parameter matches sleep retention"):
|
||||
worker._save_sleep_parameters(target)
|
||||
|
||||
|
||||
def test_load_model_preserves_compiled_graphs_at_runtime(monkeypatch):
|
||||
"""Profiling must use serving's thread count to keep Dynamo guards valid."""
|
||||
from torch._dynamo.testing import CompileCounter
|
||||
|
||||
monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
|
||||
monkeypatch.setattr(gpu_worker, "has_ec_transfer", lambda: False)
|
||||
monkeypatch.setattr(
|
||||
gpu_worker, "set_current_vllm_config", lambda config: nullcontext()
|
||||
)
|
||||
loading_threads = []
|
||||
worker = SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(weight_transfer_config=None),
|
||||
model_runner=SimpleNamespace(
|
||||
load_model=lambda **kwargs: loading_threads.append(torch.get_num_threads())
|
||||
),
|
||||
_maybe_get_memory_pool_context=lambda **kwargs: nullcontext(),
|
||||
_scoped_allocator_max_split=lambda **kwargs: nullcontext(),
|
||||
)
|
||||
original_threads = torch.get_num_threads()
|
||||
try:
|
||||
torch.set_num_threads(2)
|
||||
gpu_worker.Worker.load_model(worker)
|
||||
assert loading_threads == [2]
|
||||
|
||||
counter = CompileCounter()
|
||||
compiled = torch.compile(lambda x: x + 1, backend=counter, fullgraph=True)
|
||||
x = torch.ones(2)
|
||||
compiled(x)
|
||||
gpu_worker.set_torch_threads_for_runtime()
|
||||
torch.testing.assert_close(compiled(x), x + 1)
|
||||
assert counter.frame_count == 1
|
||||
finally:
|
||||
torch.set_num_threads(original_threads)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike()
|
||||
or not torch.accelerator.is_available()
|
||||
or torch.cuda.memory.get_allocator_backend() != "native",
|
||||
reason="needs the native CUDA or ROCm allocator",
|
||||
)
|
||||
# A fresh allocator: blocks cached by earlier tests could serve the large buffer.
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_scoped_max_split_keeps_freed_large_blocks_releasable():
|
||||
"""A small allocation made after a large buffer is freed must not pin the
|
||||
buffer's segment: the profiling run (determine_available_memory) grows
|
||||
workspaces this way, and a pinned segment survives empty_cache() and is
|
||||
counted as consumed memory."""
|
||||
large = 512 * 1024 * 1024
|
||||
small = 2 * 1024 * 1024 # large pool, so it is served by splitting cached blocks
|
||||
|
||||
def reserved_while_small_is_live(scope) -> int:
|
||||
torch.accelerator.empty_cache()
|
||||
with scope:
|
||||
buf = torch.empty(large, dtype=torch.uint8, device="cuda")
|
||||
del buf
|
||||
tensor = torch.empty(small, dtype=torch.uint8, device="cuda")
|
||||
torch.accelerator.empty_cache()
|
||||
reserved = torch.accelerator.memory_reserved()
|
||||
del tensor
|
||||
torch.accelerator.empty_cache()
|
||||
return reserved
|
||||
|
||||
baseline = torch.accelerator.memory_reserved()
|
||||
# Without the limit the small tensor is split off the freed block and pins it.
|
||||
assert reserved_while_small_is_live(nullcontext()) - baseline >= large
|
||||
scoped = gpu_worker.Worker._scoped_allocator_max_split(
|
||||
SimpleNamespace(), max_split_size_mb=20
|
||||
)
|
||||
assert reserved_while_small_is_live(scoped) - baseline < large
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike()
|
||||
or not torch.accelerator.is_available()
|
||||
or torch.cuda.memory.get_allocator_backend() != "native",
|
||||
reason="needs the native CUDA or ROCm allocator",
|
||||
)
|
||||
@pytest.mark.parametrize("fail", [False, True])
|
||||
@pytest.mark.parametrize("snapshot_fallback", [False, True])
|
||||
@pytest.mark.parametrize("suffix", ["", ", "])
|
||||
def test_scoped_max_split_preserves_allocator_settings(
|
||||
monkeypatch, fail, snapshot_fallback, suffix
|
||||
):
|
||||
"""Preserve allocator settings across successful and failed profiling runs."""
|
||||
if snapshot_fallback:
|
||||
monkeypatch.delattr(
|
||||
torch._C, "_accelerator_getAllocatorSettings", raising=False
|
||||
)
|
||||
|
||||
def settings():
|
||||
return torch.cuda.memory._snapshot()["allocator_settings"]
|
||||
|
||||
original = settings()["PYTORCH_CUDA_ALLOC_CONF"]
|
||||
configured = (
|
||||
"max_split_size_mb:128,garbage_collection_threshold:0.8,"
|
||||
"roundup_power2_divisions:[256:1,512:2,>:4],max_non_split_rounding_mb:32"
|
||||
)
|
||||
try:
|
||||
torch._C._accelerator_setAllocatorSettings(configured + suffix)
|
||||
before = settings()
|
||||
expected_error = pytest.raises(RuntimeError, match="profiling failed")
|
||||
with (
|
||||
expected_error if fail else nullcontext(),
|
||||
gpu_worker.Worker._scoped_allocator_max_split(SimpleNamespace(), 20),
|
||||
):
|
||||
scoped = settings()
|
||||
assert scoped["max_split_size"] == 20 * 1024 * 1024
|
||||
for key in ("garbage_collection_threshold", "roundup_power2_divisions"):
|
||||
assert scoped[key] == before[key]
|
||||
if fail:
|
||||
raise RuntimeError("profiling failed")
|
||||
assert settings() == before
|
||||
finally:
|
||||
torch._C._accelerator_setAllocatorSettings(original)
|
||||
|
||||
|
||||
def test_scoped_max_split_ignores_async_allocator(monkeypatch):
|
||||
"""Async allocators ignore max_split and may not support memory snapshots."""
|
||||
monkeypatch.setattr(current_platform, "is_cuda_alike", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
torch.cuda.memory, "get_allocator_backend", lambda: "cudaMallocAsync"
|
||||
)
|
||||
with (
|
||||
patch.object(torch.cuda.memory, "_snapshot") as snapshot,
|
||||
patch.object(torch._C, "_accelerator_setAllocatorSettings") as set_settings,
|
||||
gpu_worker.Worker._scoped_allocator_max_split(SimpleNamespace(), 20),
|
||||
):
|
||||
pass
|
||||
snapshot.assert_not_called()
|
||||
set_settings.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_memory_bytes", [None, 1])
|
||||
def test_memory_profile_bounds_decode_logits_rows(monkeypatch, kv_cache_memory_bytes):
|
||||
"""ROCm decode workspace uses max_num_seqs during startup profiling."""
|
||||
from vllm.config import get_current_vllm_config_or_none
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _max_decode_logits_rows
|
||||
|
||||
config = SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=16),
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=5),
|
||||
)
|
||||
|
||||
class Profiled(Exception):
|
||||
pass
|
||||
|
||||
def profile_run(*, randomize_inputs=False):
|
||||
assert randomize_inputs is True
|
||||
# Without the config context, the helper falls back to all 32768
|
||||
# batched tokens, which would reserve 128 GiB at 1M context.
|
||||
assert _max_decode_logits_rows(32768) == 16 * (1 + 5)
|
||||
raise Profiled
|
||||
|
||||
worker = SimpleNamespace(
|
||||
vllm_config=config,
|
||||
randomize_dummy_inputs=True,
|
||||
cache_config=SimpleNamespace(kv_cache_memory_bytes=kv_cache_memory_bytes),
|
||||
model_runner=SimpleNamespace(profile_run=profile_run, model_memory_usage=0),
|
||||
init_snapshot=SimpleNamespace(free_memory=2),
|
||||
_scoped_allocator_max_split=lambda **kwargs: nullcontext(),
|
||||
)
|
||||
monkeypatch.setattr(gpu_worker, "maybe_apply_startup_plan", lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
gpu_worker, "memory_profiling", lambda *args, **kwargs: nullcontext()
|
||||
)
|
||||
|
||||
assert get_current_vllm_config_or_none() is None
|
||||
with pytest.raises(Profiled):
|
||||
gpu_worker.Worker.determine_available_memory(worker)
|
||||
assert get_current_vllm_config_or_none() is None
|
||||
|
||||
|
||||
# Startup-plan persistence (vllm/v1/worker/startup_plan.py), applied and
|
||||
# saved by Worker.determine_available_memory / compile_or_warm_up_model.
|
||||
|
||||
|
||||
def _plan_worker(config_hash="abc123", free_memory=78 * GiB_bytes, kv_bytes=None):
|
||||
"""The minimal Worker surface the startup-plan entry points touch."""
|
||||
return SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(compute_hash=lambda: config_hash),
|
||||
rank=0,
|
||||
parallel_config=SimpleNamespace(world_size=1),
|
||||
init_snapshot=SimpleNamespace(free_memory=free_memory),
|
||||
cache_config=SimpleNamespace(kv_cache_memory_bytes=kv_bytes),
|
||||
)
|
||||
|
||||
|
||||
def _plan_platform(name="NVIDIA H100 PCIe"):
|
||||
return SimpleNamespace(
|
||||
get_device_name=lambda device_id=0: name,
|
||||
get_device_total_memory=lambda device_id=0: 80 * GiB_bytes,
|
||||
get_device_capability=lambda device_id=0: (9, 0),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plan_env(monkeypatch: pytest.MonkeyPatch, tmp_path):
|
||||
"""Enable the startup plan, isolated under a tmp cache root."""
|
||||
monkeypatch.setenv("VLLM_ENABLE_STARTUP_PLAN", "1")
|
||||
monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path))
|
||||
with patch.object(startup_plan, "current_platform", _plan_platform()):
|
||||
yield
|
||||
|
||||
|
||||
def test_startup_plan_fingerprint_sensitivity(plan_env):
|
||||
"""The fingerprint is the OOM-safety key: stable for identical inputs,
|
||||
different for anything the profiled value depends on."""
|
||||
fp = startup_plan.compute_plan_fingerprint
|
||||
base = fp(_plan_worker().vllm_config, 0, 1)
|
||||
assert base == fp(_plan_worker().vllm_config, 0, 1)
|
||||
assert base != fp(_plan_worker("other").vllm_config, 0, 1)
|
||||
assert base != fp(_plan_worker().vllm_config, 1, 2)
|
||||
with patch.object(startup_plan, "current_platform", _plan_platform("NVIDIA A100")):
|
||||
assert base != fp(_plan_worker().vllm_config, 0, 1)
|
||||
with patch("vllm.__version__", "0.0.0+plan-test"):
|
||||
assert base != fp(_plan_worker().vllm_config, 0, 1)
|
||||
|
||||
|
||||
def test_startup_plan_apply_gate(plan_env):
|
||||
"""Only a fingerprint-matching, memory-safe plan is ever applied."""
|
||||
maybe_save_startup_plan(_plan_worker(), 50 * GiB_bytes)
|
||||
|
||||
applied = _plan_worker()
|
||||
maybe_apply_startup_plan(applied)
|
||||
assert applied.cache_config.kv_cache_memory_bytes == 50 * GiB_bytes
|
||||
|
||||
less_memory = _plan_worker(free_memory=60 * GiB_bytes)
|
||||
other_config = _plan_worker(config_hash="zzz999")
|
||||
for refused in (less_memory, other_config):
|
||||
maybe_apply_startup_plan(refused)
|
||||
assert refused.cache_config.kv_cache_memory_bytes is None
|
||||
|
||||
# An explicit --kv-cache-memory is never overridden.
|
||||
explicit = _plan_worker(kv_bytes=7 * GiB_bytes)
|
||||
maybe_apply_startup_plan(explicit)
|
||||
assert explicit.cache_config.kv_cache_memory_bytes == 7 * GiB_bytes
|
||||
|
||||
|
||||
# Memory accounting of the profiling run (Worker.determine_available_memory).
|
||||
|
||||
# The fallback reads only the sign of the measured drop and this process's torch
|
||||
# reservation; free memory is only logged, so no amount here is a device size.
|
||||
ANY_FREE_MEMORY = 8 * GiB_bytes
|
||||
MEASURED_DROP = 4 * GiB_bytes
|
||||
TORCH_RESERVED = 3 * GiB_bytes
|
||||
RELEASED_BY_OTHERS = 2 * GiB_bytes
|
||||
|
||||
|
||||
def _snapshot(free_memory, torch_memory=0):
|
||||
return SimpleNamespace(free_memory=free_memory, torch_memory=torch_memory)
|
||||
|
||||
|
||||
def _profile_result(consumed, reserved_before=0, reserved_after=0):
|
||||
"""A result whose free-memory readings agree with `consumed`, which
|
||||
`memory_profiling` derives as the drop in free memory, negative when it grew."""
|
||||
return SimpleNamespace(
|
||||
total_consumed=consumed,
|
||||
transient_peak_headroom=0,
|
||||
before_create=_snapshot(ANY_FREE_MEMORY, reserved_before),
|
||||
after_profile=_snapshot(ANY_FREE_MEMORY - consumed, reserved_after),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rocm(request):
|
||||
with patch.object(
|
||||
gpu_worker, "current_platform", SimpleNamespace(is_rocm=lambda: request.param)
|
||||
):
|
||||
yield request.param
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rocm", [True, False], indirect=True)
|
||||
def test_profiling_fallback_declines_when_free_memory_dropped(rocm):
|
||||
"""The profiling measurement is kept as-is whenever free memory dropped."""
|
||||
result = _profile_result(consumed=MEASURED_DROP)
|
||||
|
||||
assert maybe_rocm_profiling_fallback(result) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rocm", [True], indirect=True)
|
||||
def test_profiling_fallback_replaces_a_released_measurement(rocm):
|
||||
"""A negative measurement describes the rest of the device, so it is replaced
|
||||
by this process's reservation, which the rest of the device cannot move."""
|
||||
result = _profile_result(
|
||||
consumed=-RELEASED_BY_OTHERS,
|
||||
reserved_after=TORCH_RESERVED,
|
||||
)
|
||||
|
||||
assert maybe_rocm_profiling_fallback(result) == TORCH_RESERVED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rocm", [True], indirect=True)
|
||||
def test_profiling_fallback_never_returns_a_negative_amount(rocm):
|
||||
"""A reservation that shrank across the run cannot become negative usage."""
|
||||
result = _profile_result(
|
||||
consumed=-RELEASED_BY_OTHERS,
|
||||
reserved_before=TORCH_RESERVED,
|
||||
reserved_after=0,
|
||||
)
|
||||
|
||||
assert maybe_rocm_profiling_fallback(result) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rocm", [False], indirect=True)
|
||||
def test_profiling_fallback_declines_off_rocm(rocm):
|
||||
"""Platforms that account frees eagerly keep reporting the error, so the
|
||||
caller's assertion stays reachable there."""
|
||||
result = _profile_result(consumed=-RELEASED_BY_OTHERS)
|
||||
|
||||
assert maybe_rocm_profiling_fallback(result) is None
|
||||
|
||||
|
||||
class _OrderedHandle:
|
||||
"""Send handle that logs when it is waited."""
|
||||
|
||||
def __init__(self, log: list[str], name: str):
|
||||
self.log = log
|
||||
self.name = name
|
||||
|
||||
def is_completed(self) -> bool:
|
||||
return True
|
||||
|
||||
def wait(self) -> None:
|
||||
self.log.append(f"wait:{self.name}")
|
||||
|
||||
|
||||
def test_execute_model_waits_previous_pp_send_before_forward(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""Previous device handles are waited before the forward pass; the
|
||||
metadata handle is left to the GroupCoordinator's reaper."""
|
||||
import torch
|
||||
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
log: list[str] = []
|
||||
previous_tensor_send = _OrderedHandle(log, "prev-tensor")
|
||||
metadata_handle = _OrderedHandle(log, "meta")
|
||||
tensor_handle = _OrderedHandle(log, "tensor")
|
||||
|
||||
def isend_tensor_dict(tensors, all_gather_group=None, all_gather_tensors=None):
|
||||
log.append("isend")
|
||||
return [metadata_handle, tensor_handle]
|
||||
|
||||
pp_group = SimpleNamespace(
|
||||
is_first_rank=True,
|
||||
is_last_rank=False,
|
||||
isend_tensor_dict=isend_tensor_dict,
|
||||
)
|
||||
monkeypatch.setattr(gpu_worker, "get_pp_group", lambda: pp_group)
|
||||
monkeypatch.setattr(gpu_worker, "get_tp_group", lambda: SimpleNamespace())
|
||||
|
||||
def run_model(scheduler_output, intermediate_tensors):
|
||||
log.append("forward")
|
||||
return IntermediateTensors({"hidden_states": torch.zeros(1)})
|
||||
|
||||
worker = SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
pipeline_parallel_size=2, distributed_executor_backend="mp"
|
||||
),
|
||||
),
|
||||
use_v2_model_runner=True,
|
||||
model_runner=SimpleNamespace(execute_model=run_model, is_pooling_model=False),
|
||||
annotate_profile=lambda scheduler_output: nullcontext(),
|
||||
_pp_send_work=[previous_tensor_send],
|
||||
)
|
||||
scheduler_output = SimpleNamespace(
|
||||
total_num_scheduled_tokens=4, num_scheduled_tokens={"r0": 4}
|
||||
)
|
||||
|
||||
assert gpu_worker.Worker.execute_model(worker, scheduler_output) is None
|
||||
|
||||
assert log == ["wait:prev-tensor", "forward", "isend"]
|
||||
assert worker._pp_send_work == [tensor_handle]
|
||||
|
||||
|
||||
def test_jit_monitor_activation_follows_enable_jit_warmup(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""The post-warmup JIT monitor must stay off when JIT warmup is disabled
|
||||
(e.g. by enforce_eager): runtime compilation is then expected, and
|
||||
warning/erroring on it would be noise."""
|
||||
from vllm.utils import jit_monitor
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr(jit_monitor, "activate", lambda **kwargs: calls.append(kwargs))
|
||||
|
||||
def worker(enable_jit_warmup):
|
||||
return SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
kernel_config=SimpleNamespace(enable_jit_warmup=enable_jit_warmup)
|
||||
),
|
||||
observability_config=SimpleNamespace(
|
||||
jit_monitor_mode="warn", jit_monitor_verbose=False
|
||||
),
|
||||
)
|
||||
|
||||
gpu_worker.Worker._maybe_activate_jit_monitor(worker(True))
|
||||
assert calls == [{"mode": "warn", "verbose": False}]
|
||||
|
||||
calls.clear()
|
||||
gpu_worker.Worker._maybe_activate_jit_monitor(worker(False))
|
||||
assert calls == []
|
||||
@@ -1,172 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from contextlib import AbstractContextManager
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.v1.hisparse.binding as hisparse_binding
|
||||
import vllm.v1.worker.gpu.attn_utils as attn_utils
|
||||
import vllm.v1.worker.gpu_model_runner as gpu_model_runner
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
|
||||
class _AllocationScope(AbstractContextManager):
|
||||
def __init__(self) -> None:
|
||||
self.active = False
|
||||
|
||||
def __enter__(self):
|
||||
assert not self.active
|
||||
self.active = True
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: Any) -> None:
|
||||
assert self.active
|
||||
self.active = False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hisparse", [False, True])
|
||||
def test_mrv2_kv_pool_only_wraps_backing_allocation(monkeypatch, hisparse) -> None:
|
||||
scope = _AllocationScope()
|
||||
kv_caches = {"layer": torch.empty(0)}
|
||||
|
||||
def allocate(*args, **kwargs):
|
||||
assert scope.active
|
||||
return kv_caches
|
||||
|
||||
def bind(*args, **kwargs):
|
||||
assert not scope.active
|
||||
|
||||
monkeypatch.setattr(attn_utils, "allocate_kv_cache", allocate)
|
||||
monkeypatch.setattr(attn_utils, "bind_kv_cache_to_layers", bind)
|
||||
monkeypatch.setattr(attn_utils, "get_shared_kv_cache_layers", lambda config: {})
|
||||
|
||||
hisparse_bindings = []
|
||||
if hisparse:
|
||||
host_pool = SimpleNamespace()
|
||||
|
||||
def bind_hisparse(**kwargs):
|
||||
hisparse_bindings.append(kwargs)
|
||||
assert scope.active
|
||||
assert kwargs["kv_caches"] is kv_caches
|
||||
assert kwargs["host_pool"] is host_pool
|
||||
return [
|
||||
SimpleNamespace(
|
||||
view=SimpleNamespace(cache=torch.empty(1, 1, 1), block_size=1),
|
||||
runtime=SimpleNamespace(),
|
||||
)
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
hisparse_binding,
|
||||
"get_hisparse_host_pool",
|
||||
lambda vllm_config, kv_cache_config: host_pool,
|
||||
)
|
||||
monkeypatch.setattr(hisparse_binding, "allocate_hisparse_kv_caches", allocate)
|
||||
monkeypatch.setattr(hisparse_binding, "bind_hisparse_kv_caches", bind_hisparse)
|
||||
|
||||
config = SimpleNamespace(
|
||||
attention_config=SimpleNamespace(
|
||||
hisparse_config=object() if hisparse else None
|
||||
),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=1, max_num_batched_tokens=1),
|
||||
cache_config=SimpleNamespace(get_resolved_kv_cache_layout=lambda: None),
|
||||
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type="test")),
|
||||
)
|
||||
result = attn_utils.init_kv_cache(
|
||||
{},
|
||||
SimpleNamespace(kv_cache_groups=[]),
|
||||
torch.device("cpu"),
|
||||
[],
|
||||
config,
|
||||
kv_cache_allocation_context=scope,
|
||||
block_tables=SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert len(hisparse_bindings) == int(hisparse)
|
||||
assert result is kv_caches
|
||||
assert not scope.active
|
||||
|
||||
|
||||
def test_mrv1_kv_pool_only_wraps_backing_allocation(monkeypatch) -> None:
|
||||
scope = _AllocationScope()
|
||||
kv_caches = {"layer": torch.empty(0)}
|
||||
|
||||
def allocate(*args, **kwargs):
|
||||
assert scope.active
|
||||
return kv_caches
|
||||
|
||||
def bind(*args, **kwargs):
|
||||
assert not scope.active
|
||||
|
||||
monkeypatch.setattr(gpu_model_runner, "allocate_kv_cache", allocate)
|
||||
monkeypatch.setattr(gpu_model_runner, "bind_kv_cache", bind)
|
||||
|
||||
runner = SimpleNamespace(
|
||||
device=torch.device("cpu"),
|
||||
cache_config=SimpleNamespace(get_resolved_kv_cache_layout=lambda: None),
|
||||
shared_kv_cache_layers={},
|
||||
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type="test")),
|
||||
compilation_config=SimpleNamespace(static_forward_context={}),
|
||||
kv_caches=[],
|
||||
attn_groups=[],
|
||||
speculative_config=None,
|
||||
)
|
||||
result = gpu_model_runner.GPUModelRunner.initialize_kv_cache_tensors(
|
||||
runner,
|
||||
SimpleNamespace(kv_cache_groups=[]),
|
||||
[],
|
||||
kv_cache_allocation_context=scope,
|
||||
)
|
||||
|
||||
assert result is kv_caches
|
||||
assert not scope.active
|
||||
|
||||
|
||||
def test_kv_wake_does_not_run_model_runner_recovery() -> None:
|
||||
model = torch.nn.Module()
|
||||
model.register_buffer("_k_scale", torch.tensor(0.5))
|
||||
model.register_buffer("_v_scale", torch.tensor(0.25))
|
||||
|
||||
class Runner:
|
||||
def __init__(self) -> None:
|
||||
self.model = model
|
||||
self.layout_tensors = tuple(torch.tensor([i]) for i in range(5))
|
||||
self.recovery_calls = 0
|
||||
|
||||
def post_kv_cache_wake_up(self) -> None:
|
||||
self.recovery_calls += 1
|
||||
self.model.get_buffer("_k_scale").fill_(1.0)
|
||||
self.model.get_buffer("_v_scale").fill_(1.0)
|
||||
self.layout_tensors = tuple(torch.tensor([i]) for i in range(5))
|
||||
|
||||
runner = Runner()
|
||||
worker = cast(
|
||||
Worker,
|
||||
SimpleNamespace(
|
||||
sleep_mode_backend=SimpleNamespace(resume=lambda tags: None),
|
||||
_sleep_saved_buffers={},
|
||||
_sleep_saved_draft_buffers={},
|
||||
model_runner=runner,
|
||||
synchronize_device=lambda: None,
|
||||
vllm_config=SimpleNamespace(
|
||||
model_config=SimpleNamespace(enable_nccl_comm_suspend=False)
|
||||
),
|
||||
),
|
||||
)
|
||||
layout_tensors = runner.layout_tensors
|
||||
layout_ptrs = tuple(t.data_ptr() for t in layout_tensors)
|
||||
|
||||
Worker.wake_up(worker, tags=["kv_cache"])
|
||||
|
||||
assert runner.recovery_calls == 0
|
||||
assert model.get_buffer("_k_scale").item() == 0.5
|
||||
assert model.get_buffer("_v_scale").item() == 0.25
|
||||
assert all(
|
||||
actual is expected
|
||||
for actual, expected in zip(runner.layout_tensors, layout_tensors, strict=True)
|
||||
)
|
||||
assert tuple(t.data_ptr() for t in runner.layout_tensors) == layout_ptrs
|
||||
@@ -1,305 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.entrypoints.pooling.scoring.utils import compute_maxsim_score
|
||||
from vllm.pooling_params import LateInteractionParams, PoolingParams
|
||||
from vllm.v1.pool.late_interaction import (
|
||||
LATE_INTERACTION_MODE_CACHE_QUERY,
|
||||
build_late_interaction_doc_params,
|
||||
build_late_interaction_query_params,
|
||||
compute_maxsim_score_batched,
|
||||
)
|
||||
from vllm.v1.pool.late_interaction_runner import LateInteractionRunner
|
||||
|
||||
|
||||
def _make_pooling_params(
|
||||
late_interaction_params: LateInteractionParams,
|
||||
) -> PoolingParams:
|
||||
return PoolingParams(
|
||||
task="token_embed",
|
||||
late_interaction_params=late_interaction_params,
|
||||
)
|
||||
|
||||
|
||||
def test_postprocess_scores_and_releases_query_cache():
|
||||
runner = LateInteractionRunner()
|
||||
query_key = "query-0"
|
||||
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
doc_emb = torch.tensor([[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]], dtype=torch.float32)
|
||||
|
||||
query_params = _make_pooling_params(
|
||||
build_late_interaction_query_params(query_key=query_key, query_uses=1)
|
||||
)
|
||||
query_output = runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[query_params],
|
||||
req_ids=["query-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
assert isinstance(query_output, list)
|
||||
assert query_output[0] is not None
|
||||
assert query_output[0].shape == torch.Size([])
|
||||
|
||||
doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key=query_key)
|
||||
)
|
||||
doc_output = runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[doc_emb],
|
||||
pooling_params=[doc_params],
|
||||
req_ids=["doc-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
assert isinstance(doc_output, list)
|
||||
assert doc_output[0] is not None
|
||||
assert torch.allclose(doc_output[0], compute_maxsim_score(query_emb, doc_emb))
|
||||
|
||||
with pytest.raises(ValueError, match="query cache miss"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[doc_emb],
|
||||
pooling_params=[doc_params],
|
||||
req_ids=["doc-req-2"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
|
||||
def test_postprocess_scores_docs_in_batch():
|
||||
runner = LateInteractionRunner()
|
||||
query_key = "query-batch"
|
||||
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
doc_emb_1 = torch.tensor([[1.0, 0.0], [0.5, 0.5]], dtype=torch.float32)
|
||||
doc_emb_2 = torch.tensor([[0.0, 1.0], [0.3, 0.7], [1.0, 0.0]], dtype=torch.float32)
|
||||
|
||||
query_params = _make_pooling_params(
|
||||
build_late_interaction_query_params(query_key=query_key, query_uses=2)
|
||||
)
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[query_params],
|
||||
req_ids=["query-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key=query_key)
|
||||
)
|
||||
doc_output = runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[doc_emb_1, doc_emb_2],
|
||||
pooling_params=[doc_params, doc_params],
|
||||
req_ids=["doc-req-1", "doc-req-2"],
|
||||
finished_mask=[True, True],
|
||||
)
|
||||
assert isinstance(doc_output, list)
|
||||
assert doc_output[0] is not None
|
||||
assert doc_output[1] is not None
|
||||
assert torch.allclose(doc_output[0], compute_maxsim_score(query_emb, doc_emb_1))
|
||||
assert torch.allclose(doc_output[1], compute_maxsim_score(query_emb, doc_emb_2))
|
||||
|
||||
with pytest.raises(ValueError, match="query cache miss"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[doc_emb_1],
|
||||
pooling_params=[doc_params],
|
||||
req_ids=["doc-req-3"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
|
||||
def test_finished_request_releases_unscored_doc_use():
|
||||
runner = LateInteractionRunner()
|
||||
query_key = "query-cancel"
|
||||
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
doc_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
|
||||
query_params = _make_pooling_params(
|
||||
build_late_interaction_query_params(query_key=query_key, query_uses=1)
|
||||
)
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[query_params],
|
||||
req_ids=["query-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key=query_key)
|
||||
)
|
||||
runner.register_request("doc-req", doc_params)
|
||||
runner.on_requests_finished({"doc-req"})
|
||||
|
||||
with pytest.raises(ValueError, match="query cache miss"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[doc_emb],
|
||||
pooling_params=[doc_params],
|
||||
req_ids=["doc-req-retry"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_release_queries_is_targeted_and_idempotent():
|
||||
runner = LateInteractionRunner()
|
||||
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
|
||||
for query_key in ("query-release", "query-keep"):
|
||||
query_params = _make_pooling_params(
|
||||
build_late_interaction_query_params(query_key=query_key, query_uses=1)
|
||||
)
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[query_params],
|
||||
req_ids=[f"{query_key}-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
released_doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key="query-release")
|
||||
)
|
||||
kept_doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key="query-keep")
|
||||
)
|
||||
runner.register_request("released-doc", released_doc_params)
|
||||
runner.register_request("kept-doc", kept_doc_params)
|
||||
|
||||
runner.release_queries(["query-release"])
|
||||
runner.release_queries(["query-release"])
|
||||
|
||||
with pytest.raises(ValueError, match="query cache miss"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[released_doc_params],
|
||||
req_ids=["released-doc"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
kept_output = runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[kept_doc_params],
|
||||
req_ids=["kept-doc"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
assert isinstance(kept_output, list)
|
||||
assert kept_output[0] is not None
|
||||
|
||||
|
||||
def test_invalid_query_uses_raises():
|
||||
runner = LateInteractionRunner()
|
||||
bad_meta = LateInteractionParams(
|
||||
mode=LATE_INTERACTION_MODE_CACHE_QUERY,
|
||||
query_key="query-bad",
|
||||
)
|
||||
bad_meta.query_uses = "bad-int"
|
||||
bad_query_params = _make_pooling_params(bad_meta)
|
||||
|
||||
with pytest.raises(ValueError, match="must be an integer value"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[torch.ones((2, 2), dtype=torch.float32)],
|
||||
pooling_params=[bad_query_params],
|
||||
req_ids=["query-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fused Triton scoring path (PR #40337).
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
|
||||
def test_score_flash_matches_fp64_oracle():
|
||||
"""Shared-query scoring through the fused kernel must match a per-pair
|
||||
fp64 MaxSim oracle on ragged doc lengths, including length-1 docs."""
|
||||
torch.manual_seed(0)
|
||||
d = 128
|
||||
q = torch.randn(32, d, device="cuda", dtype=torch.float16)
|
||||
doc_lengths = [180, 37, 512, 1, 300, 64, 1030, 256]
|
||||
docs = [
|
||||
torch.randn(ld, d, device="cuda", dtype=torch.float16) for ld in doc_lengths
|
||||
]
|
||||
|
||||
runner = LateInteractionRunner()
|
||||
assert runner._flash_enabled
|
||||
scores = runner._score([q] * len(docs), docs)
|
||||
assert runner._flash_enabled, "kernel path must not have fallen back"
|
||||
|
||||
for i, doc in enumerate(docs):
|
||||
ref = (q.double() @ doc.double().T).max(dim=1).values.sum().float()
|
||||
torch.testing.assert_close(
|
||||
scores[i].to(torch.float32), ref, atol=5e-2, rtol=1e-3
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
|
||||
def test_score_multi_query_uses_reference_path():
|
||||
"""Distinct queries per pair route to the reference scorer and agree
|
||||
with it exactly (no kernel dispatch for the N:N pattern)."""
|
||||
torch.manual_seed(1)
|
||||
d = 128
|
||||
queries = [torch.randn(16, d, device="cuda") for _ in range(3)]
|
||||
docs = [torch.randn(ld, d, device="cuda") for ld in (50, 3, 77)]
|
||||
|
||||
runner = LateInteractionRunner()
|
||||
scores = runner._score(queries, docs)
|
||||
ref = compute_maxsim_score_batched(queries, docs)
|
||||
for s, r in zip(scores, ref):
|
||||
torch.testing.assert_close(s, r)
|
||||
|
||||
|
||||
def test_score_flash_failure_disables_and_falls_back(monkeypatch):
|
||||
"""A kernel failure must serve the batch via the reference scorer and
|
||||
disable the kernel path for the rest of the process."""
|
||||
runner = LateInteractionRunner()
|
||||
runner._flash_enabled = True
|
||||
|
||||
def _boom(query, docs):
|
||||
raise RuntimeError("synthetic kernel failure")
|
||||
|
||||
monkeypatch.setattr(runner, "_score_flash_shared_query", _boom)
|
||||
q = torch.randn(8, 32)
|
||||
docs = [torch.randn(5, 32), torch.randn(7, 32)]
|
||||
# CPU tensors already skip the kernel; force the dispatch condition.
|
||||
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
|
||||
scores = runner._score([q, q], docs)
|
||||
assert not runner._flash_enabled
|
||||
ref = compute_maxsim_score_batched([q, q], docs)
|
||||
for s, r in zip(scores, ref):
|
||||
torch.testing.assert_close(s, r)
|
||||
|
||||
|
||||
def test_disabled_flag_uses_reference_path():
|
||||
runner = LateInteractionRunner(enable_flash=False)
|
||||
assert not runner._flash_enabled
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Autotune config pruning.
|
||||
# ---------------------------------------------------------------------------
|
||||
def _prune(monkeypatch, budget: int, named_args: dict):
|
||||
from vllm.v1.pool.flash_maxsim import _common
|
||||
|
||||
monkeypatch.setattr(_common, "_smem_budget", lambda: budget)
|
||||
return _common._prune_configs(_common._get_configs(), named_args)
|
||||
|
||||
|
||||
def _est(cfg, d_pad: int) -> int:
|
||||
bq, bd = cfg.kwargs["BLOCK_Q"], cfg.kwargs["BLOCK_D"]
|
||||
return (bq * d_pad + bd * d_pad) * 2 + bq * bd * 4
|
||||
|
||||
|
||||
def test_prune_configs_uses_padded_dim(monkeypatch):
|
||||
"""d=513 pads to 1024: survivors must fit the budget at d_pad, not at
|
||||
the un-padded d (which would admit ~2x-oversized tiles)."""
|
||||
budget = 166_912 # A100 opt-in
|
||||
survivors = _prune(monkeypatch, budget, {"Lq": 1024, "d": 513, "d_pad": 1024})
|
||||
assert survivors
|
||||
assert all(_est(c, 1024) <= budget for c in survivors)
|
||||
|
||||
|
||||
def test_prune_configs_no_rejected_fallback(monkeypatch):
|
||||
"""When nothing fits, the fallback is the single smallest-footprint
|
||||
config — never a slice of rejected configs."""
|
||||
from vllm.v1.pool.flash_maxsim import _common
|
||||
|
||||
survivors = _prune(monkeypatch, 10_000, {"Lq": 1024, "d_pad": 1024})
|
||||
assert len(survivors) == 1
|
||||
smallest = min(_common._get_configs(), key=lambda c: _est(c, 1024))
|
||||
assert survivors[0].kwargs == smallest.kwargs
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user