Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
@@ -194,6 +194,77 @@ def test_fused_recurrent_kda_rejects_unaddressable_layouts():
run_kernel(broken, state)
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="The large-grid fix is NVIDIA-only"
)
@pytest.mark.parametrize("num_seqs,num_heads", [(1024, 64), (2048, 48)])
def test_fused_recurrent_kda_more_than_65535_programs(num_seqs: int, num_heads: int):
"""Regression test for the launch grid.
GLM-5.3-Flash has 64 KDA value heads; at TP=1 (every DP rank) a decode
batch of 1024 sequences needs 1024 * 64 = 65536 (sequence, head)
programs. The kernel used to put that product into gridDim.z, whose CUDA
limit is 65535, so the launch failed with ``Triton Error [CUDA]: invalid
argument`` at CUDA-graph capture and DP deployments could not start. The
grid now carries the product in gridDim.x. Small head dims keep the test
cheap; the shape that matters is the number of programs. Every (sequence,
head) pair is independent, so the full batch must be bitwise identical to
the same batch run in two halves.
"""
torch.manual_seed(0)
dev = torch.device("cuda")
head_dim = 16
pool = num_seqs + 8
q = torch.randn(1, num_seqs, num_heads, head_dim, device=dev, dtype=torch.bfloat16)
k = torch.randn_like(q)
v = torch.randn_like(q)
g = torch.randn_like(q)
beta = torch.randn(1, num_seqs, num_heads, device=dev, dtype=torch.bfloat16)
state = torch.randn(
pool, num_heads, head_dim, head_dim, device=dev, dtype=torch.float32
)
cu = torch.arange(0, num_seqs + 1, device=dev, dtype=torch.int32)
# slot 0 is NULL_BLOCK_ID and is skipped by the kernel: use slots 1..
idx = (torch.randperm(pool - 1, device=dev)[:num_seqs] + 1).to(torch.int32)
a_log = torch.randn(num_heads, device=dev, dtype=torch.float32)
g_bias = torch.randn(num_heads, head_dim, device=dev, dtype=torch.float32)
def run(sl: slice, cu_: torch.Tensor, st: torch.Tensor, out: torch.Tensor):
fused_recurrent_kda(
q=q[:, sl],
k=k[:, sl],
v=v[:, sl],
g=g[:, sl],
beta=beta[:, sl],
initial_state=st,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_,
ssm_state_indices=idx[sl],
sigmoid_beta=True,
a_log=a_log,
g_bias=g_bias,
compute_gate=True,
lower_bound=-5.0,
out=out,
)
full_state = state.clone()
full_out = torch.zeros_like(k)
run(slice(0, num_seqs), cu, full_state, full_out)
half = num_seqs // 2
ref_state = state.clone()
ref_out = torch.zeros_like(k)
for s, e in ((0, half), (half, num_seqs)):
cu_h = torch.arange(0, e - s + 1, device=dev, dtype=torch.int32)
part = torch.zeros_like(k[:, s:e])
run(slice(s, e), cu_h, ref_state, part)
ref_out[:, s:e] = part
torch.accelerator.synchronize()
assert torch.equal(full_out, ref_out)
assert torch.equal(full_state, ref_state)
@pytest.mark.parametrize("offset", [16, 144, 256])
@pytest.mark.parametrize("dim_first", [False, True])
@pytest.mark.parametrize("num_spec", [0, 3])
+103
View File
@@ -191,3 +191,106 @@ def test_amd_attn_res_fused_contract(
original_blocks[:, block_write_idx].copy_(expected_prefix)
torch.testing.assert_close(blocks, original_blocks, atol=0, rtol=0)
assert actual.is_contiguous()
@pytest.mark.parametrize(
"num_tokens,num_blocks,has_delta,write_block",
[
(0, 0, False, False),
(1, 0, True, True),
(17, 4, True, True),
(320, 8, False, False),
],
)
def test_amd_attn_res_fp8_preserves_prefix_and_quantized_output(
num_tokens,
num_blocks,
has_delta,
write_block,
default_vllm_config,
):
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
torch.manual_seed(41)
hidden_size = 7168
prefix = _randn_with_row_padding(num_tokens, hidden_size, padding=7)
delta = _randn_with_row_padding(num_tokens, hidden_size) if has_delta else None
blocks = _randn_with_row_padding(num_tokens, 9, hidden_size, padding=13)
norm = 1 + torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) * 0.1
score = torch.randn_like(norm) / hidden_size**0.5
out_norm = 1 + torch.randn_like(norm) * 0.1
ref_prefix, ref_blocks = prefix.clone(), blocks.clone()
kwargs = dict(
num_blocks=num_blocks,
block_write_idx=num_blocks if write_block else -1,
eps=1e-5,
output_norm_eps=1e-5,
)
reference = attn_res(ref_prefix, delta, ref_blocks, norm, score, out_norm, **kwargs)
output, scale = attn_res(
prefix,
delta,
blocks,
norm,
score,
out_norm,
quant_dtype=current_platform.fp8_dtype(),
**kwargs,
)
assert output.dtype == current_platform.fp8_dtype()
assert scale.shape == (num_tokens, 1)
if num_tokens:
# Keep reference rounding independent of Inductor's fused quantization.
quant = QuantFP8(
static=False, group_shape=GroupShape.PER_TOKEN, compile_native=False
)
ref_output, ref_scale = quant(reference)
torch.testing.assert_close(scale, ref_scale, atol=1e-7, rtol=1e-6)
# Floating-point fusion can move values at FP8 rounding midpoints.
# Bound each change to the adjacent code and bound how often it occurs.
# Codes are sign-magnitude, so order them by value to keep a step
# across zero adjacent.
def ordinal(x: torch.Tensor) -> torch.Tensor:
code = x.view(torch.uint8).to(torch.int16)
return torch.where(code >= 0x80, 0x80 - code, code)
code_delta = (ordinal(output) - ordinal(ref_output)).abs()
assert code_delta.max().item() <= 1
assert (code_delta != 0).float().mean().item() < 1e-4
torch.testing.assert_close(prefix, ref_prefix, atol=0, rtol=0)
torch.testing.assert_close(blocks, ref_blocks, atol=0, rtol=0)
@pytest.mark.parametrize(
"matching,requires_unquantized", [(True, False), (False, False), (True, True)]
)
def test_mla_input_quant_requires_all_consumers(matching, requires_unquantized):
from types import SimpleNamespace
from torch import nn
from vllm.model_executor.layers.fusion.quant_activation import (
expose_input_quant_key,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8DynamicTokenSym,
)
from vllm.models.kimi_k3.amd.mla import KimiK3MultiHeadLatentAttentionWrapper
attention = object.__new__(KimiK3MultiHeadLatentAttentionWrapper)
nn.Module.__init__(attention)
attention.indexer = None
attention.q_lora_rank = 1536
attention.fused_qkv_a_proj = nn.Identity()
attention.g_proj = nn.Identity()
kernel = SimpleNamespace(input_quant_key=lambda: kFp8DynamicTokenSym)
expose_input_quant_key(attention.fused_qkv_a_proj, kernel)
if matching:
expose_input_quant_key(attention.g_proj, kernel)
attention.g_proj.requires_unquantized_input = requires_unquantized
actual = attention.get_input_quant_key()
assert actual == (
kFp8DynamicTokenSym if matching and not requires_unquantized else None
)
@@ -75,7 +75,7 @@ def _builder(
vllm_config.cache_config.prefix_match_unit = prefix_match_unit
if num_spec:
vllm_config.speculative_config = _StubSpeculativeConfig(num_spec)
return KimiK3ROCmKDAMetadataBuilder(
builder = KimiK3ROCmKDAMetadataBuilder(
kv_cache_spec=MambaSpec(
block_size=block_size,
shapes=((16, 64),),
@@ -91,6 +91,11 @@ def _builder(
vllm_config=vllm_config,
device=torch.device("cuda"),
)
vllm_config.cache_config.hash_block_size = prefix_match_unit or block_size
vllm_config.cache_config.cache_hit_alignment_tokens = (
prefix_match_unit or block_size
)
return builder
def _build(batch: BatchSpec, block_size: int = BLOCK_SIZE, **kw):
@@ -22,7 +22,7 @@ from tests.utils import (
from vllm.distributed import get_tp_group
from vllm.model_executor.layers.fused_moe.runner import moe_runner
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.linear import ColumnParallelLinear, ReplicatedLinear
from vllm.models.kimi_k3.amd import latent_moe_runner
from vllm.models.kimi_k3.amd.latent_moe_runner import ROCmLatentMoERunner
from vllm.models.kimi_k3.amd.linear import KimiRoutedOutputTransform
@@ -40,20 +40,42 @@ EPS = 1e-5
DTYPE = torch.bfloat16
def _build_transform(device: torch.device) -> KimiRoutedOutputTransform:
def _build_transform(
device: torch.device, *, row_sharded: bool = False
) -> tuple[KimiRoutedOutputTransform, torch.Tensor]:
norm = RMSNorm(LATENT_SIZE, eps=EPS).to(device=device, dtype=DTYPE)
up_proj = ReplicatedLinear(
LATENT_SIZE,
HIDDEN_SIZE,
bias=False,
params_dtype=DTYPE,
prefix="routed_expert_up_proj",
).to(device=device)
torch.manual_seed(0)
norm.weight.data.copy_(1 + 0.1 * torch.randn_like(norm.weight))
up_proj.weight.data.copy_(torch.randn_like(up_proj.weight) / LATENT_SIZE**0.5)
return KimiRoutedOutputTransform(norm, up_proj)
full_weight = (
torch.randn(HIDDEN_SIZE, LATENT_SIZE, device=device, dtype=DTYPE)
/ LATENT_SIZE**0.5
)
up_proj: ReplicatedLinear | ColumnParallelLinear
if row_sharded:
up_proj = ColumnParallelLinear(
LATENT_SIZE,
HIDDEN_SIZE,
bias=False,
gather_output=True,
params_dtype=DTYPE,
prefix="routed_expert_up_proj",
).to(device=device)
up_proj.weight_loader(up_proj.weight, full_weight)
else:
up_proj = ReplicatedLinear(
LATENT_SIZE,
HIDDEN_SIZE,
bias=False,
params_dtype=DTYPE,
prefix="routed_expert_up_proj",
).to(device=device)
up_proj.weight.data.copy_(full_weight)
return (
KimiRoutedOutputTransform(norm, up_proj, row_sharded=row_sharded),
full_weight,
)
def _tail_runner(
@@ -72,6 +94,7 @@ def _tail_runner(
runner = object.__new__(ROCmLatentMoERunner)
attrs = {
"routed_output_transform": transform,
"_up_proj_preshard": bool(getattr(transform, "row_sharded", False)),
"_up_proj_shard_size": HIDDEN_SIZE // tp_world,
"_logged_sharded_tail": False,
"moe_config": SimpleNamespace(
@@ -101,9 +124,13 @@ def _rank_partials(
def _check_matches_replicated(
device: torch.device, tp_world: int, rank: int, use_ep: bool = False
device: torch.device,
tp_world: int,
rank: int,
use_ep: bool = False,
row_sharded: bool = False,
) -> None:
transform = _build_transform(device)
transform, up_weight = _build_transform(device, row_sharded=row_sharded)
runner = _tail_runner(transform, tp_world, use_ep)
group = get_tp_group().device_group
@@ -118,7 +145,7 @@ def _check_matches_replicated(
transform.norm.weight,
EPS,
),
transform.up_proj.weight,
up_weight,
)
expected.add_(_all_reduced(shared_output, group))
@@ -136,12 +163,37 @@ def _check_matches_replicated_under_ep(
_check_matches_replicated(device, tp_world, rank, use_ep=True)
def _check_presharded_matches_replicated(
device: torch.device, tp_world: int, rank: int
) -> None:
_check_matches_replicated(device, tp_world, rank, row_sharded=True)
def _check_unfused_tail_gathers_full_hidden(
device: torch.device, tp_world: int, rank: int
) -> None:
transform, up_weight = _build_transform(device, row_sharded=True)
assert transform.up_proj.weight.shape[0] == HIDDEN_SIZE // tp_world
# all-gather reconstructs the full projection when all ranks feed the same
# input, so use one seed for all ranks.
torch.manual_seed(1234)
latent = torch.randn(4, LATENT_SIZE, device=device, dtype=DTYPE).mul_(0.01)
torch.testing.assert_close(
transform(latent),
F.linear(transform.norm(latent), up_weight),
atol=8e-2,
rtol=3e-2,
)
def _check_writes_only_its_own_shard(
device: torch.device, tp_world: int, rank: int
) -> None:
"""Two ranks that swapped both weight rows and write offsets still sum to
the right total, so inspect each slice before the final collective."""
transform = _build_transform(device)
transform, up_weight = _build_transform(device)
runner = _tail_runner(transform, tp_world)
group = get_tp_group().device_group
@@ -169,7 +221,7 @@ def _check_writes_only_its_own_shard(
shard = HIDDEN_SIZE // tp_world
start, end = rank * shard, (rank + 1) * shard
local = captured["states"]
projected = F.linear(latent, transform.up_proj.weight[start:end])
projected = F.linear(latent, up_weight[start:end])
torch.testing.assert_close(
local[:, start:end], before[:, start:end] + projected, atol=8e-2, rtol=3e-2
@@ -181,6 +233,8 @@ def _check_writes_only_its_own_shard(
_CHECKS = {
"matches_replicated": _check_matches_replicated,
"matches_replicated_ep": _check_matches_replicated_under_ep,
"presharded_matches_replicated": _check_presharded_matches_replicated,
"unfused_gathers": _check_unfused_tail_gathers_full_hidden,
"own_shard_only": _check_writes_only_its_own_shard,
}
@@ -219,6 +273,16 @@ def test_sharded_tail_tp8_ep8_matches_replicated_projection() -> None:
_run_ranks("matches_replicated_ep", 8)
@multi_gpu_test(num_gpus=4)
def test_presharded_tail_tp4_matches_replicated_projection() -> None:
_run_ranks("presharded_matches_replicated", 4)
@multi_gpu_test(num_gpus=4)
def test_presharded_unfused_tail_gathers_the_full_hidden_dim() -> None:
_run_ranks("unfused_gathers", 4)
@multi_gpu_test(num_gpus=4)
def test_sharded_tail_tp4_writes_only_its_own_shard() -> None:
_run_ranks("own_shard_only", 4)
@@ -1,6 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from torch import nn
@@ -36,3 +39,81 @@ def test_mla_self_attention_returns_projection_storage_directly() -> None:
assert output is projected
assert output.data_ptr() == projected.data_ptr()
@pytest.mark.parametrize("quantized", [False, True])
@pytest.mark.parametrize("fused_decode", [False, True])
def test_mla_forward_preserves_output_shape_with_fp8_input(
monkeypatch, quantized: bool, fused_decode: bool
) -> None:
"""Both MLA paths accept producer-quantized input after decode fusion."""
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8DynamicTokenSym,
)
from vllm.models.kimi_k3.amd.mla import KimiK3MultiHeadLatentAttentionWrapper
hidden_states = torch.randn(4, 8, dtype=torch.bfloat16)
if quantized:
hidden_states = QuantizedActivation(
hidden_states.to(kFp8DynamicTokenSym.dtype),
torch.ones(4, 1),
hidden_states.dtype,
hidden_states.shape,
kFp8DynamicTokenSym,
)
projected = torch.randn(4, 8, dtype=torch.bfloat16)
paths = []
def input_projection(value):
assert value is hidden_states
return torch.zeros(4, 8, dtype=torch.bfloat16), None
def attention_output(path, output_shape):
assert output_shape == projected.shape
paths.append(path)
return projected
attention = SimpleNamespace(
q_lora_rank=2,
kv_lora_rank=4,
qk_rope_head_dim=2,
qk_head_dim=4,
num_heads=2,
v_head_dim=4,
fused_qkv_a_proj=input_projection,
q_a_layernorm=nn.Identity(),
_normalize_q_kv=lambda q, kv: (q, kv),
q_b_proj=lambda q: (torch.zeros(4, 8, dtype=q.dtype), None),
rotary_emb=None,
indexer=None,
dcp_q_replicate=False,
_fused_qk_prep=fused_decode,
_fused_decode=lambda q, kv, pe, pos, shape, *args: attention_output(
"fused", shape
),
g_proj=None,
o_proj=lambda value: (value, None),
)
if fused_decode:
attention.mla_attn = SimpleNamespace(layer_name="test")
monkeypatch.setattr(
"vllm.models.kimi_k3.amd.mla.get_attention_context",
lambda _: (
SimpleNamespace(num_actual_tokens=4, num_decode_tokens=4),
None,
torch.zeros(1),
torch.arange(4),
),
)
else:
attention.mla_attn = lambda q, kv, pe, **kwargs: attention_output(
"regular", kwargs["output_shape"]
)
output = KimiK3MultiHeadLatentAttentionWrapper.forward(
attention, torch.arange(4), hidden_states
)
assert output is projected
assert paths == ["fused" if fused_decode else "regular"]
+3 -7
View File
@@ -4,7 +4,7 @@
import sys
from collections.abc import Callable
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock, patch
from unittest.mock import patch
import pytest
@@ -91,9 +91,7 @@ def test_int4_per_group_32_is_not_an_online_moe_method():
QuantizationConfigArgs(moe={"weight": "int4_per_group_32"})
)
assert (
config.resolve_quant_method_cls(
Mock(spec=RoutedExperts), "model.layers.0.mlp.experts"
)
config.resolve_quant_method_cls(RoutedExperts, "model.layers.0.mlp.experts")
is None
)
@@ -103,6 +101,4 @@ def test_unknown_online_moe_weight_still_raises():
QuantizationConfigArgs(moe={"weight": "fp8_per_token"})
)
with pytest.raises(ValueError, match="online quantization"):
config.resolve_quant_method_cls(
Mock(spec=RoutedExperts), "model.layers.0.mlp.experts"
)
config.resolve_quant_method_cls(RoutedExperts, "model.layers.0.mlp.experts")
+53 -9
View File
@@ -100,6 +100,8 @@ def _make_builder(
prefix_match_unit: int | None = None,
use_eagle: bool = False,
disable_eagle_block_drop: bool = False,
cache_hit_alignment_tokens: int | None = None,
hash_block_size: int | None = None,
) -> AttentionMetadataBuilder:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B",
@@ -122,6 +124,11 @@ def _make_builder(
vllm_config.cache_config.use_replayssm = use_recoverssm
vllm_config.cache_config.use_recoverssm = use_recoverssm
vllm_config.cache_config.prefix_match_unit = prefix_match_unit
hash_block_size = hash_block_size or prefix_match_unit or mamba_block_size
vllm_config.cache_config.hash_block_size = hash_block_size
vllm_config.cache_config.cache_hit_alignment_tokens = (
cache_hit_alignment_tokens or hash_block_size
)
builder = builder_cls(
kv_cache_spec=MambaSpec(
block_size=mamba_block_size,
@@ -220,6 +227,8 @@ def test_kda_recoverssm_startup_metadata_flow_without_model(monkeypatch):
vllm_config=builder_config,
device=DEVICE,
)
builder_config.cache_config.hash_block_size = BLOCK_SIZE
builder_config.cache_config.cache_hit_alignment_tokens = BLOCK_SIZE
# An all-prefill speculative batch used to leave an all-false spec mask
# alive, then access active_non_spec_mask_cpu before it was initialized.
@@ -287,18 +296,45 @@ def test_kda_recoverssm_startup_metadata_flow_without_model(monkeypatch):
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_internal_checkpoint_metadata_targets_last_aligned_boundary():
@pytest.mark.parametrize(
"batch,prefix_match_unit,hit_alignment,expected_offsets,expected_states",
[
(
BatchSpec(seq_lens=[50, 32], query_lens=[50, 16]),
None,
16,
[48, 0],
[2, NULL_BLOCK_ID],
),
(
BatchSpec(seq_lens=[50, 32], query_lens=[50, 16]),
16,
16,
[48, 0],
[2, NULL_BLOCK_ID],
),
(BatchSpec(seq_lens=[530], query_lens=[530]), None, 128, [512], [32]),
(BatchSpec(seq_lens=[530], query_lens=[50]), None, 128, [32], [32]),
(BatchSpec(seq_lens=[530], query_lens=[530]), 16, 16, [528], [32]),
(BatchSpec(seq_lens=[530], query_lens=[50]), 16, 16, [48], [32]),
],
)
def test_internal_checkpoint_metadata_targets_last_aligned_boundary(
batch, prefix_match_unit, hit_alignment, expected_offsets, expected_states
):
device = torch.device("cuda")
batch = BatchSpec(seq_lens=[50, 32], query_lens=[50, 16])
common_attn_metadata = create_common_attn_metadata(
batch, BLOCK_SIZE, device, arange_block_indices=True
).replace(is_prefilling=torch.tensor([True, True]))
).replace(is_prefilling=torch.tensor([True] * len(batch.seq_lens)))
builder = _make_builder(
KimiK3KDAMetadataBuilder,
num_speculative_tokens=0,
full_cuda_graph=False,
mamba_cache_mode="align",
num_prefill_checkpoint_blocks=1,
prefix_match_unit=prefix_match_unit,
cache_hit_alignment_tokens=hit_alignment,
hash_block_size=16,
device=device,
)
assert isinstance(builder, KimiK3KDAMetadataBuilder)
@@ -313,26 +349,33 @@ def test_internal_checkpoint_metadata_targets_last_aligned_boundary():
assert actual.checkpoint is not None
torch.testing.assert_close(
actual.checkpoint.state_indices,
torch.tensor([2, NULL_BLOCK_ID], dtype=torch.int32, device=device),
torch.tensor(expected_states, dtype=torch.int32, device=device),
)
torch.testing.assert_close(
actual.checkpoint.checkpoint_offsets,
torch.tensor([48, 0], dtype=torch.int32, device=device),
torch.tensor(expected_offsets, dtype=torch.int32, device=device),
)
@pytest.mark.parametrize(
("disable_eagle_block_drop", "prefix_match_unit", "expected_offset"),
[(False, 16, 80), (True, 16, 96), (False, 8, None)],
("seq_len", "disable_eagle_block_drop", "prefix_match_unit", "expected_offset"),
[
(100, False, 16, 80),
(100, True, 16, 96),
(100, False, 8, None),
(96, False, 16, 80),
(96, True, 16, 80),
],
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_spec_internal_checkpoint_metadata_targets_replay_boundary(
seq_len: int,
disable_eagle_block_drop: bool,
prefix_match_unit: int,
expected_offset: int | None,
) -> None:
device = torch.device("cuda")
batch = BatchSpec(seq_lens=[100], query_lens=[100])
batch = BatchSpec(seq_lens=[seq_len], query_lens=[seq_len])
common_attn_metadata = create_common_attn_metadata(
batch, BLOCK_SIZE, device, arange_block_indices=True
)
@@ -390,6 +433,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
full_cuda_graph=False,
mamba_cache_mode="align",
num_prefill_checkpoint_blocks=1,
prefix_match_unit=16,
device=device,
)
assert isinstance(builder, KimiK3KDAMetadataBuilder)
@@ -447,7 +491,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
2,
False,
[False, False],
None,
1,
id="no-scheduled-draft-tokens",
),
pytest.param(
@@ -13,8 +13,10 @@ from types import SimpleNamespace
import pytest
import torch
import vllm.model_executor.layers.attention.mla_attention as mla_attention
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonBaseImpl,
MLACommonImpl,
MLACommonPrefillMetadata,
build_mla_chunked_context_metadata,
)
@@ -317,3 +319,115 @@ def test_fused_context_rejects_an_unquantized_query() -> None:
)
with pytest.raises(AssertionError, match="new-token epilogue"):
layer._compute_prefill_context(q, SimpleNamespace(prefill=prefill))
# --------------------------------------------------------------------------
# Decode context parallelism: the generic impl keeps its loop (allgather +
# reorg) and only the per-chunk K/V pack is handed to the layer's fused kernel.
# --------------------------------------------------------------------------
_DCP = 2
_DCP_TOKENS = 48
def _run_dcp_context_loop(monkeypatch, *, q_data_type, fused_mla_kv_concat_fn):
"""Drive ``MLACommonImpl._context_parallel_compute_prefill_context`` on one
chunk with the collective pieces (gather, allgather, reorg) stubbed out."""
torch.manual_seed(0)
device = torch.device("cuda")
kv_b_proj = _KVBProj(device, weight_dtype=torch.bfloat16)
workspace = torch.randn(
(_DCP_TOKENS * (_DCP + 1), _ENTRY), dtype=torch.bfloat16, device=device
)
impl = SimpleNamespace(
kv_cache_dtype="auto",
kv_lora_rank=_KV_LORA_RANK,
qk_rope_head_dim=_QK_ROPE,
qk_nope_head_dim=_QK_NOPE,
v_head_dim=_V_HEAD_DIM,
num_heads=_NUM_HEADS,
kv_b_proj=kv_b_proj,
_use_flashinfer_concat_mla_k=False,
)
impl._concat_k_nope_k_pe = MLACommonImpl._concat_k_nope_k_pe.__get__(impl)
monkeypatch.setattr(mla_attention.ops, "cp_gather_cache", lambda **_: None)
monkeypatch.setattr(mla_attention, "_get_kv_b_proj_input_dtype", lambda *_: None)
monkeypatch.setattr(
mla_attention,
"reorg_kvcache",
lambda kv_c, k_pe, **_: (kv_c[:_DCP_TOKENS].squeeze(1), k_pe[:_DCP_TOKENS]),
)
chunk = SimpleNamespace(
index=0,
padded_local_seq_lens=[_DCP_TOKENS],
local_context_lens_allranks=[[_DCP_TOKENS // _DCP] * _DCP],
padded_local_cu_seq_lens=torch.tensor([0, _DCP_TOKENS], device=device),
padded_local_token_to_seq=torch.zeros(
_DCP_TOKENS, dtype=torch.int32, device=device
),
local_starts=[0],
num_local_context_tokens=_DCP_TOKENS,
request_slice=slice(0, 1),
num_requests=1,
starts=torch.tensor([0], device=device),
num_context_tokens=_DCP_TOKENS,
max_seq_len=_DCP_TOKENS,
token_slice=slice(0, 4),
)
backend = _RecordingPrefillBackend()
attn_metadata = SimpleNamespace(
prefill=SimpleNamespace(
prefill_backend=backend,
chunked_context=SimpleNamespace(
workspace=workspace,
chunks=[chunk],
empty_token_slices=False,
dcp_manager=SimpleNamespace(kv_gather=lambda dst, src: None),
),
q_data_type=q_data_type,
block_table=torch.zeros((1, 1), dtype=torch.int32, device=device),
)
)
q = torch.randn(
(4, _NUM_HEADS, _QK_NOPE + _QK_ROPE), dtype=torch.bfloat16, device=device
)
out, lse = MLACommonImpl._context_parallel_compute_prefill_context(
impl,
q,
torch.empty(0, device=device),
attn_metadata,
k_scale=torch.ones(1, device=device),
dcp_world_size=_DCP,
fused_mla_kv_concat_fn=fused_mla_kv_concat_fn,
)
return backend, out, lse
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
@torch.inference_mode()
def test_dcp_context_fused_pack_matches_generic_tail(
monkeypatch, kv_cache_dtype: str
) -> None:
"""Under DCP the layer's fused K/V pack must feed the prefill backend exactly
what the generic impl's cast + split + concat tail feeds it."""
q_data_type = (
current_platform.fp8_dtype() if kv_cache_dtype == "fp8" else torch.bfloat16
)
layer = SimpleNamespace(qk_nope_head_dim=_QK_NOPE, v_head_dim=_V_HEAD_DIM)
fused_fn = MultiHeadLatentAttention._fused_mla_kv_concat.__get__(layer)
backend_ref, ref_out, ref_lse = _run_dcp_context_loop(
monkeypatch, q_data_type=q_data_type, fused_mla_kv_concat_fn=None
)
backend_fused, fused_out, fused_lse = _run_dcp_context_loop(
monkeypatch, q_data_type=q_data_type, fused_mla_kv_concat_fn=fused_fn
)
assert len(backend_ref.calls) == len(backend_fused.calls) == 1
for name, fused_t, ref_t in zip(
("q", "k", "v"), backend_fused.calls[0], backend_ref.calls[0], strict=True
):
torch.testing.assert_close(
fused_t, ref_t, atol=0, rtol=0, msg=lambda m, n=name: f"{n} differs: {m}"
)
torch.testing.assert_close(fused_out, ref_out, atol=0, rtol=0)
torch.testing.assert_close(fused_lse, ref_lse, atol=0, rtol=0)
+40
View File
@@ -8,6 +8,7 @@ import random
from collections.abc import Iterator
from dataclasses import dataclass
from math import lcm
from uuid import uuid4
import pytest
import requests
@@ -353,6 +354,45 @@ def _format(turns: list[Turn]) -> str:
return "\n".join(rows)
@pytest.mark.parametrize(
"prompt_len",
[
# Blocks=6144, PMU=128. P=7040 is PMU-aligned but not block-aligned:
# ensure lookup reads the cached attention proof at 7040 despite
# the final hit limit of 7039, then applies EAGLE's 128-token drop.
pytest.param(7040, id="eagle-proof-scan"),
# Blocks=6144, PMU=128. P=7296 is an exact PMU multiple:
# ensure the Mamba checkpoint is 7168, not 7040 from applying both
# the P - 1 cap and EAGLE's 128-token drop.
pytest.param(7296, id="eagle-double-cap"),
],
)
def test_dspark_exact_resend_reuses_prompt_checkpoint(prompt_len: int) -> None:
"""Resends reuse the Mamba checkpoint and its companion EAGLE attention proof."""
mode = Mode(128, True)
salt = str(uuid4())
rng = random.Random(0)
prompt = [rng.randint(1000, 150000) for _ in range(prompt_len)]
deployment = DEPLOYMENTS["plain"]
with _serve(deployment, mode) as servers:
url = servers[0].url_root
cold = _complete(url, prompt, salt, max_tokens=1)
resend = _complete(url, prompt, salt, max_tokens=1)
recompute = _complete(url, prompt, f"{salt}-recompute", max_tokens=1)
# EAGLE's dropped hash unit already leaves tokens to recompute on resend.
expected = (prompt_len // 128 - 1) * 128
actual = _cached(resend)
assert _cached(cold) == _cached(recompute) == 0
assert actual == expected, f"{prompt_len=}: {actual=}, {expected=}"
check_logprobs_close(
outputs_0_lst=[_tokens_text_logprobs(recompute)],
outputs_1_lst=[_tokens_text_logprobs(resend)],
name_0="recompute",
name_1="resend",
)
@pytest.mark.parametrize(
"name, mode", [_case(name, mode) for name in DEPLOYMENTS for mode in MODES]
)
@@ -301,6 +301,27 @@ def test_shard_sequence_parallel_mlp_gating(
)
@pytest.mark.parametrize(
("moe_backend", "all2all_backend", "expected"),
[
("deep_gemm_mega_moe", "naive", True),
("auto", "deepep_v2", True),
("auto", "deepep_low_latency", False),
],
)
def test_shared_expert_sharding_backend_gate(
moe_backend: str,
all2all_backend: str,
expected: bool,
):
vllm_config = SimpleNamespace(
kernel_config=SimpleNamespace(moe_backend=moe_backend),
parallel_config=SimpleNamespace(all2all_backend=all2all_backend),
)
assert kimi_model.can_shard_sequence_parallel_shared_expert(vllm_config) is expected
def test_sharded_sequence_parallel_mlp_matches_replicated(default_vllm_config):
"""Sharded SP MLP must reproduce the replicated result for every token.
@@ -0,0 +1,95 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import mteb
import numpy as np
import pytest
import torch
from torch.utils.data import DataLoader
from tests.conftest import HfRunner
from tests.models.utils import RerankModelInfo
from .mteb_score_utils import MtebCrossEncoderMixin, mteb_test_rerank_models
RERANK_MODELS = [
RerankModelInfo(
"polaria-tech/zerank-2-reranker-vllm",
architecture="Qwen3ForSequenceClassification",
chat_template_name="zerank2.jinja",
seq_pooling_type="LAST",
attn_type="decoder",
is_prefix_caching_supported=True,
is_chunked_prefill_supported=True,
mteb_score=0.34305,
mteb_tol=1e-2,
enable_test=True,
),
]
class ZerankHfRunner(MtebCrossEncoderMixin, HfRunner):
# The converted checkpoint has no lm_head, so the reference is the original
# causal LM: the logit of the "Yes" token at the last position. The converted
# checkpoint returns sigmoid(logit / 5), which ranks documents identically.
original_model = "zeroentropy/zerank-2-reranker"
def __init__(
self, model_name: str, dtype: str = "auto", *args: Any, **kwargs: Any
) -> None:
from transformers import AutoModelForCausalLM, AutoTokenizer
HfRunner.__init__(
self,
model_name=self.original_model,
auto_cls=AutoModelForCausalLM,
dtype=dtype,
**kwargs,
)
self.tokenizer = AutoTokenizer.from_pretrained(
self.original_model, padding_side="left"
)
self.token_true_id = self.tokenizer.convert_tokens_to_ids("Yes")
@torch.no_grad
def predict(
self,
inputs1: DataLoader[mteb.types.BatchedInput],
inputs2: DataLoader[mteb.types.BatchedInput],
*args,
**kwargs,
) -> np.ndarray:
queries = [text for batch in inputs1 for text in batch["text"]]
corpus = [text for batch in inputs2 for text in batch["text"]]
tokenizer = self.tokenizer
prompts = []
for query, document in zip(queries, corpus):
conversation = [
{"role": "query", "content": query},
{"role": "document", "content": document},
]
prompt = tokenizer.apply_chat_template(
conversation=conversation,
tools=None,
chat_template=self.chat_template,
tokenize=False,
)
prompts.append(prompt)
scores = []
for prompt in prompts:
inputs = tokenizer([prompt], return_tensors="pt")
inputs = self.wrap_device(inputs)
logits = self.model(**inputs).logits[:, -1, :]
scores.append(logits[0, self.token_true_id].item())
return torch.Tensor(scores)
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", RERANK_MODELS)
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
mteb_test_rerank_models(vllm_runner, model_info, hf_runner=ZerankHfRunner)
@@ -9,14 +9,12 @@ from collections import defaultdict
from pathlib import PosixPath
import pytest
from packaging.version import Version
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForImageTextToText,
AutoModelForTextToWaveform,
)
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.platforms import current_platform
from vllm.utils.func_utils import identity
@@ -818,8 +816,7 @@ VLM_TEST_SETTINGS = {
patch_hf_runner=model_utils.paddleocr_vl_patch_hf_runner,
image_size_factors=[(0.25,)],
marks=[
pytest.mark.skipif(
Version(TRANSFORMERS_VERSION) >= Version("5.0.0"),
pytest.mark.skip(
reason="Model's custom code uses ROPE_INIT_FUNCTIONS"
"['default'] which was removed in transformers v5",
),
@@ -104,7 +104,16 @@ def run_test(
)
@pytest.mark.parametrize("model", ["nvidia/NVIDIA-Nemotron-Parse-v1.2"])
@pytest.mark.parametrize(
"model",
[
"nvidia/NVIDIA-Nemotron-Parse-v1.2",
# v2.0's checkpoint ties lm_head to the decoder's input embeddings
# instead of shipping a separate lm_head.weight tensor; this
# exercises that path (see tie_weights() in nemotron_parse.py).
"nvidia/NVIDIA-Nemotron-Parse-2.0",
],
)
@pytest.mark.parametrize("dtype", ["bfloat16"])
@pytest.mark.parametrize("num_logprobs", [5])
def test_models(
@@ -36,6 +36,7 @@ VIDEO_MODEL_SETTINGS: dict[str, dict[str, Any]] = {
"<|VISION_START|><|VIDEO_PAD|><|VISION_END|>Describe this video."
"<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>"
),
"patch_hf_runner": model_utils.cohere_compass_patch_hf_runner,
},
"Qwen/Qwen2.5-VL-3B-Instruct": {
"prompt": (
@@ -88,6 +89,9 @@ def test_transformers_video_generation(
model_id, dtype="bfloat16", auto_cls=AutoModelForImageTextToText
) as hf_model:
hf_model = model_utils.qwen3_vl_patch_hf_runner(hf_model)
patch_hf_runner = VIDEO_MODEL_SETTINGS[model_id].get("patch_hf_runner")
if patch_hf_runner is not None:
hf_model = patch_hf_runner(hf_model)
hf_outputs = hf_model.generate_greedy_logprobs_limit(
[prompt], 128, num_logprobs=10, videos=[video]
)
@@ -146,10 +146,6 @@ def test_online_serving(vllm_runner, audio_assets: AudioTestAssets):
)
@pytest.mark.skip(
reason="VoxtralProcessor.apply_chat_template() in transformers v5 "
"doesn't resolve chat_template=None to the default template"
)
def test_hf_reference(hf_runner, vllm_runner, audio_assets: AudioTestAssets):
"""Compare vLLM Mistral-format output against HF Transformers reference.
@@ -157,9 +153,6 @@ def test_hf_reference(hf_runner, vllm_runner, audio_assets: AudioTestAssets):
attention backends), we compare per-token logprobs using the standard
check_logprobs_close helper: when tokens diverge at a position, each
runner's chosen token must appear in the other's top-k logprobs.
Marked xfail(strict=False) so remaining edge-case mismatches
don't block CI.
"""
question = f"What's happening in these {len(audio_assets)} audio clips?"
max_tokens = 10
@@ -106,7 +106,8 @@ def tokenizer() -> MistralTokenizer:
@pytest_asyncio.fixture
async def async_engine():
async def async_engine(request):
engine_config = {**ENGINE_CONFIG, **getattr(request, "param", {})}
gpu_memory_utilization = ENGINE_CONFIG.get("gpu_memory_utilization", 0.9)
from vllm.platforms import current_platform
@@ -115,7 +116,7 @@ async def async_engine():
wait_for_memory_to_settle(threshold_ratio=1.0 - gpu_memory_utilization)
engine_args = AsyncEngineArgs(**ENGINE_CONFIG)
engine_args = AsyncEngineArgs(**engine_config)
llm = AsyncLLM.from_engine_args(engine_args)
try:
yield llm
@@ -275,3 +276,82 @@ async def test_voxtral_realtime_generator(audio_assets, tokenizer, async_engine)
f" got: {got!r}\n"
f" expected: {expected!r}"
)
@pytest.mark.asyncio
async def test_voxtral_realtime_buffer_stops_at_max_model_len(tokenizer):
from vllm.model_executor.models.voxtral_realtime import VoxtralRealtimeBuffer
audio_config = tokenizer.instruct_tokenizer.audio_encoder.audio_config
audio = Audio.from_file(AudioAsset("winning_call").get_local_path(), strict=False)
req = TranscriptionRequest(
streaming=StreamingMode.OFFLINE,
audio=audio.to_base64(audio.format),
language=None,
)
audio_enc = tokenizer.encode_transcription(req)
max_model_len = 64
buffer = VoxtralRealtimeBuffer(
audio_config, audio_enc.tokens, max_model_len=max_model_len
)
await buffer.append_audio(audio_enc.audios[0].audio_array)
await buffer.append_audio(None)
# Unlimited feedback tokens so only the length cap can stop the stream.
await buffer.append_tokens([0] * max_model_len)
n_tokens = 0
async for prompt in buffer.get_input_stream():
n_tokens += len(prompt["prompt_token_ids"])
assert len(audio_enc.tokens) < n_tokens < max_model_len
@pytest.mark.asyncio
@pytest.mark.parametrize("async_engine", [{"max_model_len": 128}], indirect=True)
async def test_voxtral_realtime_generator_max_model_len(
audio_assets, tokenizer, async_engine
):
# Lazy import to avoid CUDA-reinitialization error
from vllm.model_executor.models.voxtral_realtime import VoxtralRealtimeBuffer
max_model_len = async_engine.model_config.max_model_len
sampling_params = SamplingParams(temperature=0.0, max_tokens=1)
audio_config = tokenizer.instruct_tokenizer.audio_encoder.audio_config
async def input_stream(audio_buffer):
async for prompt in audio_buffer.get_input_stream():
parsed_prompt = parse_model_prompt(async_engine.model_config, prompt)
(engine_input,) = await async_engine.renderer.render_cmpl_async(
[parsed_prompt]
)
yield StreamingInput(prompt=engine_input)
# winning_call is ~300 tokens long, well past max_model_len.
audio = Audio.from_file(audio_assets[1].get_local_path(), strict=False)
req = TranscriptionRequest(
streaming=StreamingMode.OFFLINE,
audio=audio.to_base64(audio.format),
language=None,
)
audio_enc = tokenizer.encode_transcription(req)
buffer = VoxtralRealtimeBuffer(
audio_config, audio_enc.tokens, max_model_len=max_model_len
)
await buffer.append_audio(audio_enc.audios[0].audio_array)
await buffer.append_audio(None)
output_tokens = []
async for resp in async_engine.generate(
prompt=input_stream(buffer),
sampling_params=sampling_params,
request_id="session-max-len",
):
tokens = resp.outputs[0].token_ids[-1:]
output_tokens.extend(tokens)
await buffer.append_tokens(tokens)
assert resp.finished
assert 0 < len(output_tokens) < max_model_len
# The engine is still healthy after the session hit the cap.
assert not async_engine.errored
@@ -1111,6 +1111,19 @@ def qwen3_vl_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
return hf_model
def cohere_compass_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
"""Declare the video modality that CohereCompass omits upstream.
Without it ``generate`` leaves ``pixel_values_videos`` unconsumed and the
forward pass rejects it, see huggingface/transformers#49320. Drop this once
the pinned transformers declares the modality itself.
"""
model = hf_model.model
if "video" not in model.input_modalities:
model.input_modalities = (*model.input_modalities, "video")
return hf_model
def voxtral_patch_hf_runner(hf_model: "HfRunner") -> "HfRunner":
"""Patch HfRunner for Voxtral's conversation-based processor.
@@ -0,0 +1,660 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import ast
import inspect
import os
import textwrap
import pytest
import torch
MODEL = os.environ.get("EG2_MODEL_PATH")
needs_model = pytest.mark.skipif(not MODEL, reason="EG2_MODEL_PATH not set")
TEXT_COS, MM_COS = 0.999, 0.999
def _cos(a, b):
return torch.nn.functional.cosine_similarity(
torch.tensor(a, dtype=torch.float32),
torch.tensor(b, dtype=torch.float32),
dim=-1,
)
def _ensure_synthetic_video(
path: str, duration: float, fps: float, width: int, height: int
) -> str:
if os.path.exists(path):
os.remove(path)
import cv2
import numpy as np
fourcc_fn = getattr(cv2, "VideoWriter_fourcc", cv2.VideoWriter.fourcc)
fourcc = fourcc_fn(*"mp4v")
num_frames = int(duration * fps)
writer = cv2.VideoWriter(path, fourcc, fps, (width, height))
y_coords, x_coords = np.mgrid[0:height, 0:width]
for i in range(num_frames):
# Spatially varying color pattern that evolves dynamically over frames
frame: np.ndarray = np.zeros((height, width, 3), dtype=np.uint8)
frame[..., 0] = ((x_coords * 255 // max(1, width)) + i * 17) % 256
frame[..., 1] = ((y_coords * 255 // max(1, height)) + i * 29) % 256
frame[..., 2] = (x_coords + y_coords + i * 13) % 256
writer.write(frame)
writer.release()
return path
@pytest.fixture(scope="module")
def st_model():
from sentence_transformers import SentenceTransformer
return SentenceTransformer(
MODEL, device="cuda", model_kwargs={"torch_dtype": torch.bfloat16}
)
@needs_model
def test_structure(vllm_runner, monkeypatch):
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
def probe(model):
lm = model.language_model
win = [layer.self_attn.attn.impl.sliding_window for layer in lm.layers]
return win, model.config.text_config.sliding_window
win, cfg_w = vm.apply_model(probe)[0]
assert (cfg_w, cfg_w) in win # (512, 512) == W-1 with W = 513
@needs_model
@pytest.mark.parametrize(
"prompt",
[
"short query",
"task: search result | query: what is vllm",
"word " * 700, # > 512: crosses sliding window
"word " * 1500, # > 1024
],
)
def test_text_parity(vllm_runner, st_model, prompt):
ref = st_model.encode([prompt], normalize_embeddings=True)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed([prompt])
sim = _cos(out, ref).min().item()
assert sim >= TEXT_COS, (
f"Text cosine {sim} < {TEXT_COS} for prompt len {len(prompt)}"
)
@needs_model
def test_mm_recipe(vllm_runner, st_model):
from PIL import Image
img = Image.new("RGB", (224, 224), color=(255, 0, 0))
prompt = "Describe this image: <|image|>"
# SentenceTransformer multimodal encode
ref = st_model.encode([{"image": img, "text": prompt}], normalize_embeddings=True)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed([{"prompt": prompt, "multi_modal_data": {"image": img}}])
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Image cosine {sim} < {MM_COS}"
@needs_model
def test_natural_image_parity(vllm_runner, st_model):
from PIL import Image
img_path = "/projects/gemma4-vllm/images/cat.jpg"
if not os.path.exists(img_path):
pytest.skip(f"Test asset {img_path} not found")
img = Image.open(img_path)
prompt = "What is this image? <|image|>"
ref = st_model.encode([{"image": img, "text": prompt}], normalize_embeddings=True)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed([{"prompt": prompt, "multi_modal_data": {"image": img}}])
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Natural image cosine {sim} < {MM_COS}"
@needs_model
def test_audio_parity(vllm_runner, st_model):
import torchaudio
audio_path = "/projects/gemma4-vllm/audio/tellMeAboutTheSun.wav"
if not os.path.exists(audio_path):
pytest.skip(f"Test asset {audio_path} not found")
wav, sr = torchaudio.load(audio_path)
mono_wav = wav.mean(dim=0).numpy()
prompt = "Describe this audio: <|audio|>"
ref = st_model.encode(
[{"audio": audio_path, "text": prompt}], normalize_embeddings=True
)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[{"prompt": prompt, "multi_modal_data": {"audio": (mono_wav, sr)}}]
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Audio cosine {sim} < {MM_COS}"
@needs_model
def test_mixed_parity(vllm_runner, st_model):
import torchaudio
from PIL import Image
img_path = "/projects/gemma4-vllm/images/cat.jpg"
audio_path = "/projects/gemma4-vllm/audio/tellMeAboutTheSun.wav"
if not os.path.exists(img_path) or not os.path.exists(audio_path):
pytest.skip("Test assets for mixed parity not found")
img = Image.open(img_path)
wav, sr = torchaudio.load(audio_path)
mono_wav = wav.mean(dim=0).numpy()
prompt = "Describe image <|image|> and audio <|audio|>"
ref = st_model.encode(
[{"image": img, "audio": audio_path, "text": prompt}],
normalize_embeddings=True,
)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[
{
"prompt": prompt,
"multi_modal_data": {
"image": img,
"audio": (mono_wav, sr),
},
}
]
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Mixed cosine {sim} < {MM_COS}"
@needs_model
def test_video_parity_uniform_overflow(vllm_runner, st_model):
from transformers.video_utils import load_video
video_path = _ensure_synthetic_video(
"/tmp/test_40s.mp4", duration=40.0, fps=10.0, width=160, height=120
)
frames, meta = load_video(video_path, backend="opencv")
prompt = "Describe this video: <|video|>"
ref = st_model.encode(
[{"video": video_path, "text": prompt}], normalize_embeddings=True
)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[{"prompt": prompt, "multi_modal_data": {"video": (frames, meta)}}]
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"40s video cosine {sim} < {MM_COS}"
@needs_model
def test_video_parity_portrait(vllm_runner, st_model):
from transformers.video_utils import load_video
video_path = _ensure_synthetic_video(
"/tmp/test_portrait.mp4", duration=3.0, fps=10.0, width=120, height=160
)
frames, meta = load_video(video_path, backend="opencv")
prompt = "Describe this video: <|video|>"
ref = st_model.encode(
[{"video": video_path, "text": prompt}], normalize_embeddings=True
)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[{"prompt": prompt, "multi_modal_data": {"video": (frames, meta)}}]
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Portrait video cosine {sim} < {MM_COS}"
@needs_model
def test_tower_skip(vllm_runner, monkeypatch):
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
def nparams(m):
return sum(p.numel() for p in m.parameters()) / 1e6
with vllm_runner(
MODEL,
runner="pooling",
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "audio": 0, "video": 0},
) as vm:
p_text = vm.apply_model(nparams)[0]
assert abs(p_text - 271.00) <= 0.05, (
f"Expected 271.00M text params, got {p_text}M"
)
with vllm_runner(MODEL, runner="pooling", max_model_len=2048) as vm:
p_full = vm.apply_model(nparams)[0]
assert abs(p_full - 744.37) <= 0.05, (
f"Expected 744.37M full params, got {p_full}M"
)
def test_encoder_contract():
from vllm.model_executor.models.embedding_gemma2 import EmbeddingGemma2Model
from vllm.model_executor.models.gemma4_mm import (
Gemma4ForConditionalGeneration as G,
)
borrowed_methods = [
"_parse_and_validate_multimodal_inputs",
"_parse_and_validate_image_input",
"_parse_and_validate_video_input",
"_parse_and_validate_audio_input",
"_process_image_input",
"_process_video_input",
"_process_audio_input",
"embed_multimodal",
"_encoder_chunk",
]
for name in borrowed_methods:
# Check method identity (L-F6 + T-F4)
assert getattr(EmbeddingGemma2Model, name) is getattr(G, name)
# AST checks: verify no zero-arg super() calls in borrowed methods
func = getattr(EmbeddingGemma2Model, name)
src = textwrap.dedent(inspect.getsource(func))
tree = ast.parse(src)
for node in ast.walk(tree):
if (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == "super"
):
assert len(node.args) > 0, (
f"Zero-arg super() call found in borrowed method {name}"
)
# AST check: all self.<attr> non-callable accesses are assigned in __init__
init_src = inspect.getsource(EmbeddingGemma2Model.__init__)
for name in borrowed_methods:
func = getattr(EmbeddingGemma2Model, name)
src = textwrap.dedent(inspect.getsource(func))
tree = ast.parse(src)
for node in ast.walk(tree):
if (
isinstance(node, ast.Attribute)
and isinstance(node.value, ast.Name)
and node.value.id == "self"
):
attr = node.attr
assert hasattr(EmbeddingGemma2Model, attr) or attr in init_src, (
f"Attribute {attr} accessed on self in {name} is neither "
f"defined on class nor in __init__"
)
@needs_model
def test_instance_attribute_access(vllm_runner):
"""Check self.<attr> accesses on a real model instance."""
from vllm.model_executor.models.embedding_gemma2 import EmbeddingGemma2Model
borrowed_methods = [
"_parse_and_validate_multimodal_inputs",
"_parse_and_validate_image_input",
"_parse_and_validate_video_input",
"_parse_and_validate_audio_input",
"_process_image_input",
"_process_video_input",
"_process_audio_input",
"embed_multimodal",
"_encoder_chunk",
]
attrs_accessed = set()
for name in borrowed_methods:
func = getattr(EmbeddingGemma2Model, name)
src = textwrap.dedent(inspect.getsource(func))
tree = ast.parse(src)
for node in ast.walk(tree):
if (
isinstance(node, ast.Attribute)
and isinstance(node.value, ast.Name)
and node.value.id == "self"
):
attrs_accessed.add(node.attr)
def check_attrs(model):
for attr in attrs_accessed:
assert hasattr(model, attr), (
f"Real instance of EmbeddingGemma2Model is missing attribute '{attr}' "
f"accessed by borrowed method"
)
return True
with vllm_runner(MODEL, runner="pooling", max_model_len=2048) as vm:
res = vm.apply_model(check_attrs)
assert res[0] is True
@needs_model
def test_video_loader_real_video(vllm_runner, st_model):
"""Decode a real MP4 file through EmbeddingGemma2VideoBackend.load_bytes
and VideoMediaIO / MediaConnector with default num_frames=32.
"""
from vllm.multimodal.media import MediaConnector
from vllm.multimodal.media.video import VideoMediaIO
from vllm.multimodal.video import VIDEO_LOADER_REGISTRY
video_path = "/projects/gemma4-vllm/videos/test_intel.mp4"
backend_cls = VIDEO_LOADER_REGISTRY.name2class["embedding_gemma2"]
with open(video_path, "rb") as f:
data = f.read()
# Direct backend load
frames, meta = backend_cls.load_bytes(data)
# VideoMediaIO with default num_frames=32 (VideoMediaIO passes num_frames=32)
video_io = VideoMediaIO(image_io=None, video_backend="embedding_gemma2")
loaded = video_io.load_bytes(data)
frames_io, meta_io = loaded.media
assert len(frames_io) == len(frames)
assert meta_io.get("do_sample_frames") is False
# MediaConnector with video_processor="EmbeddingGemma2VideoProcessor"
connector = MediaConnector(allowed_local_media_path="/projects/gemma4-vllm/videos")
fetched = connector.fetch_video(
f"file://{video_path}",
video_processor="EmbeddingGemma2VideoProcessor",
)
frames_conn, meta_conn = fetched.media
assert len(frames_conn) == 32
assert meta_conn.get("do_sample_frames") is False
prompt = "Describe this video: <|video|>"
ref = st_model.encode(
[{"video": video_path, "text": prompt}], normalize_embeddings=True
)
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[
{
"prompt": prompt,
"multi_modal_data": {"video": (frames_conn, meta_conn)},
}
]
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Real video loader cosine {sim} < {MM_COS}"
@needs_model
def test_video_loader_duplicate_expansion_e2e(vllm_runner, st_model):
"""End-to-end duplicate expansion test with low-fps clip."""
import numpy as np
from vllm.multimodal.video import VIDEO_LOADER_REGISTRY
backend_cls = VIDEO_LOADER_REGISTRY.name2class["embedding_gemma2"]
# 4s clip at 0.5 fps = 2 unique frames
lowfps_path = "/tmp/test_lowfps_05.mp4"
_ensure_synthetic_video(lowfps_path, duration=4.0, fps=0.5, width=64, height=48)
with open(lowfps_path, "rb") as f:
data = f.read()
# Default fps=1.0 -> 4 frames expanding 2 unique frames to [0, 0, 1, 1]
frames, meta = backend_cls.load_bytes(data)
assert frames.shape[0] == 4
# Compare returned frames directly, not only indices
assert np.array_equal(frames[0], frames[1])
assert not np.array_equal(frames[0], frames[2])
assert np.array_equal(frames[2], frames[3])
prompt = "Describe this video: <|video|>"
with vllm_runner(MODEL, runner="pooling", max_model_len=8192) as vm:
out = vm.embed(
[{"prompt": prompt, "multi_modal_data": {"video": (frames, meta)}}]
)
ref = st_model.encode(
[{"video": lowfps_path, "text": prompt}], normalize_embeddings=True
)
sim = _cos(out, ref).min().item()
assert sim >= MM_COS, f"Duplicate expansion cosine {sim} < {MM_COS}"
assert len(out) == 1
assert len(out[0]) == 768
def test_video_loader_indices():
from transformers.models.embedding_gemma2.video_processing_embedding_gemma2 import (
EmbeddingGemma2VideoProcessor,
)
from transformers.video_utils import VideoMetadata
from vllm.multimodal.video import (
VIDEO_LOADER_REGISTRY,
VideoSourceMetadata,
VideoTargetMetadata,
)
backend_cls = VIDEO_LOADER_REGISTRY.name2class["embedding_gemma2"]
hf_proc = EmbeddingGemma2VideoProcessor()
# Case 1: clip shorter than 32s (e.g. 5s @ 24fps = 120 frames)
src_5s = VideoSourceMetadata(total_frames_num=120, original_fps=24.0, duration=5.0)
tgt = VideoTargetMetadata(num_frames=-1, fps=1.0, max_duration=300)
vllm_indices = backend_cls.compute_frames_index_to_sample(src_5s, tgt)
hf_meta_5s = VideoMetadata(fps=24.0, duration=5.0, total_num_frames=120)
hf_indices_5s = hf_proc.sample_frames(
hf_meta_5s, fps=1.0, max_frames=32, overflow_strategy="uniform"
).tolist()
assert vllm_indices == hf_indices_5s
# Case 2: clip shorter than 1s (e.g. 0.5s @ 24fps = 12 frames)
src_sub1s = VideoSourceMetadata(
total_frames_num=12, original_fps=24.0, duration=0.5
)
vllm_sub1s = backend_cls.compute_frames_index_to_sample(src_sub1s, tgt)
hf_meta_sub1s = VideoMetadata(fps=24.0, duration=0.5, total_num_frames=12)
hf_indices_sub1s = hf_proc.sample_frames(
hf_meta_sub1s, fps=1.0, max_frames=32, overflow_strategy="uniform"
).tolist()
assert vllm_sub1s == hf_indices_sub1s
# Case 3: clip longer than 32s (e.g. 40s @ 10fps = 400 frames)
# -> uniform overflow cap 32 frames
src_40s = VideoSourceMetadata(
total_frames_num=400, original_fps=10.0, duration=40.0
)
vllm_40s = backend_cls.compute_frames_index_to_sample(src_40s, tgt)
hf_meta_40s = VideoMetadata(fps=10.0, duration=40.0, total_num_frames=400)
hf_indices_40s = hf_proc.sample_frames(
hf_meta_40s, fps=1.0, max_frames=32, overflow_strategy="uniform"
).tolist()
assert vllm_40s == hf_indices_40s
assert len(vllm_40s) == 32
# Case 4: default target fps (target.fps <= 0 defaults to 1.0)
tgt_default_fps = VideoTargetMetadata(num_frames=-1, fps=-1.0, max_duration=300)
vllm_def = backend_cls.compute_frames_index_to_sample(src_5s, tgt_default_fps)
assert vllm_def == hf_indices_5s
# Case 5 (NEW-2): 60 fps / 300 s (18000 frames) vs HF sample_frames
src_300s = VideoSourceMetadata(
total_frames_num=18000, original_fps=60.0, duration=300.0
)
v_300s = backend_cls.compute_frames_index_to_sample(
src_300s, VideoTargetMetadata(num_frames=-1, fps=60.0, max_duration=300)
)
h_300s = hf_proc.sample_frames(
VideoMetadata(fps=60.0, duration=300.0, total_num_frames=18000),
fps=60.0,
max_frames=32,
overflow_strategy="uniform",
).tolist()
assert v_300s == h_300s, f"60fps/300s mismatch: {v_300s[-3:]} vs {h_300s[-3:]}"
# Case 6 (NEW-2): 1 fps / 4 h (432000 frames @ 30 native fps) vs HF sample_frames
src_4h = VideoSourceMetadata(
total_frames_num=432000, original_fps=30.0, duration=14400.0
)
v_4h = backend_cls.compute_frames_index_to_sample(
src_4h, VideoTargetMetadata(num_frames=-1, fps=1.0, max_duration=300)
)
h_4h = hf_proc.sample_frames(
VideoMetadata(fps=30.0, duration=14400.0, total_num_frames=432000),
fps=1.0,
max_frames=32,
overflow_strategy="uniform",
).tolist()
assert v_4h == h_4h, f"1fps/4h mismatch: {v_4h[-2:]} vs {h_4h[-2:]}"
def test_video_loader_duplicate_expansion():
from transformers.models.embedding_gemma2.video_processing_embedding_gemma2 import (
EmbeddingGemma2VideoProcessor,
)
from transformers.video_utils import VideoMetadata
from vllm.multimodal.video import (
VIDEO_LOADER_REGISTRY,
VideoSourceMetadata,
VideoTargetMetadata,
)
backend_cls = VIDEO_LOADER_REGISTRY.name2class["embedding_gemma2"]
hf_proc = EmbeddingGemma2VideoProcessor()
# 4s clip @ 0.5fps = 2 frames total. Requested target fps = 1.0 -> 4 frames.
# Source has fewer frames than requested sampled frames, requiring duplicates.
src_lowfps = VideoSourceMetadata(total_frames_num=2, original_fps=0.5, duration=4.0)
tgt = VideoTargetMetadata(num_frames=-1, fps=1.0, max_duration=300)
vllm_indices = backend_cls.compute_frames_index_to_sample(src_lowfps, tgt)
hf_meta = VideoMetadata(fps=0.5, duration=4.0, total_num_frames=2)
hf_indices = hf_proc.sample_frames(
hf_meta, fps=1.0, max_frames=32, overflow_strategy="uniform"
).tolist()
assert vllm_indices == hf_indices
assert len(vllm_indices) == 4
assert vllm_indices == [0, 0, 1, 1]
def test_video_media_io_embedding_gemma2():
"""Verify VideoMediaIO with default num_frames=32 loads video bytes for
EmbeddingGemma2 without error.
"""
import os
from unittest.mock import MagicMock
from vllm.multimodal.media import MediaConnector
from vllm.multimodal.media.video import VideoMediaIO
video_path = "/projects/gemma4-vllm/videos/test_intel.mp4"
if not os.path.exists(video_path):
return
with open(video_path, "rb") as f:
data = f.read()
# VideoMediaIO defaults to num_frames=32
video_io = VideoMediaIO(image_io=MagicMock(), video_backend="embedding_gemma2")
loaded = video_io.load_bytes(data)
frames, meta = loaded.media
assert len(frames) == 32
assert meta.get("do_sample_frames") is False
# MediaConnector path
connector = MediaConnector(allowed_local_media_path="/projects/gemma4-vllm/videos")
fetched = connector.fetch_video(
f"file://{video_path}",
video_processor="EmbeddingGemma2VideoProcessor",
)
frames_conn, meta_conn = fetched.media
assert len(frames_conn) == 32
assert meta_conn.get("do_sample_frames") is False
def test_config_capping_and_explicit_limits():
"""Verify EmbeddingGemma2ModelConfig backend selection, default capping,
and preservation of explicit limits.
"""
from types import SimpleNamespace
from unittest.mock import patch
from vllm.model_executor.models.config import (
EmbeddingGemma2ModelConfig,
Gemma4Config,
)
from vllm.v1.attention.backends.registry import AttentionBackendEnum
# (a) When attention backend is None, default to TRITON_ATTN,
# and default capping: max_model_len > 8192 without explicit limit capped to 8192
cfg_default = SimpleNamespace(
attention_config=SimpleNamespace(backend=None),
model_config=SimpleNamespace(
max_model_len=262144,
original_max_model_len=None,
),
)
with patch.object(Gemma4Config, "verify_and_update_config"):
EmbeddingGemma2ModelConfig.verify_and_update_config(cfg_default)
assert cfg_default.attention_config.backend == AttentionBackendEnum.TRITON_ATTN
assert cfg_default.model_config.max_model_len == 8192
# (b) Default capping with original_max_model_len == -1
cfg_default_minus1 = SimpleNamespace(
attention_config=SimpleNamespace(backend=None),
model_config=SimpleNamespace(
max_model_len=131072,
original_max_model_len=-1,
),
)
with patch.object(Gemma4Config, "verify_and_update_config"):
EmbeddingGemma2ModelConfig.verify_and_update_config(cfg_default_minus1)
assert cfg_default_minus1.model_config.max_model_len == 8192
# (c) Explicit limit 4096 preserved
cfg_explicit_4k = SimpleNamespace(
attention_config=SimpleNamespace(backend=None),
model_config=SimpleNamespace(
max_model_len=4096,
original_max_model_len=4096,
),
)
with patch.object(Gemma4Config, "verify_and_update_config"):
EmbeddingGemma2ModelConfig.verify_and_update_config(cfg_explicit_4k)
assert cfg_explicit_4k.model_config.max_model_len == 4096
# (d) Explicit limit 16384 preserved and explicit backend preserved
cfg_explicit_16k = SimpleNamespace(
attention_config=SimpleNamespace(backend=AttentionBackendEnum.FLASH_ATTN),
model_config=SimpleNamespace(
max_model_len=16384,
original_max_model_len=16384,
),
)
with patch.object(Gemma4Config, "verify_and_update_config"):
EmbeddingGemma2ModelConfig.verify_and_update_config(cfg_explicit_16k)
assert cfg_explicit_16k.attention_config.backend == AttentionBackendEnum.FLASH_ATTN
assert cfg_explicit_16k.model_config.max_model_len == 16384
def test_sentence_transformer_tokenizer_config_max_seq_length(tmp_path):
"""Verify get_sentence_transformer_tokenizer_config accepts config
with only max_seq_length.
"""
import json
from vllm.transformers_utils.config import (
get_sentence_transformer_tokenizer_config,
)
# 1. Synthetic model directory with only max_seq_length in sentence_bert_config.json
cfg_file = tmp_path / "sentence_bert_config.json"
cfg_file.write_text(json.dumps({"max_seq_length": 8192}))
loaded = get_sentence_transformer_tokenizer_config(str(tmp_path))
assert loaded is not None
assert loaded["max_seq_length"] == 8192
@@ -0,0 +1,81 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import numpy as np
import pytest
import torch
from PIL import Image
from transformers import AutoImageProcessor
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.platforms import current_platform
from vllm.transformers_utils.processors.kimi_k25_vision_fused import (
KimiK25FusedVisionProcessor,
)
from ...utils import build_model_context
_MODEL_ID = "moonshotai/Kimi-K3"
@pytest.fixture(scope="module")
def image_processors():
ctx = build_model_context(_MODEL_ID, limit_mm_per_prompt={"image": 1})
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
k25_fused = processor.info.image_processor
assert isinstance(k25_fused, KimiK25FusedVisionProcessor)
k3_hf = AutoImageProcessor.from_pretrained(_MODEL_ID, trust_remote_code=True)
return k25_fused, k3_hf
def _noise_image(width: int, height: int) -> Image.Image:
rng = np.random.default_rng(0)
return Image.fromarray(rng.integers(0, 256, (height, width, 3), dtype=np.uint8))
@pytest.mark.parametrize(
("width", "height"),
[(310, 470), (7300, 30), (13, 9)],
)
def test_fused_image_processor_matches_hf(image_processors, width: int, height: int):
fused, hf = image_processors
image = _noise_image(width, height)
expected = hf.preprocess([{"type": "image", "image": image}], return_tensors="pt")
actual = fused.preprocess([{"type": "image", "image": image}], return_tensors="pt")
torch.testing.assert_close(actual["grid_thws"], expected["grid_thws"])
torch.testing.assert_close(actual["pixel_values"], expected["pixel_values"])
assert fused.media_tokens_calculator(
{"type": "image", "image": image}
) == hf.media_tokens_calculator({"type": "image", "image": image})
@pytest.mark.usefixtures("default_vllm_config")
def test_mm_device_do_normalize():
device = current_platform.device_type
ctx = build_model_context(_MODEL_ID, limit_mm_per_prompt={"image": 2})
assert ctx.model_config.multimodal_config.mm_device_do_normalize
ctx.model_config.multimodal_config.mm_device_do_normalize = False
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
images = [
Image.new("RGB", (310, 470), color=(17, 89, 231)),
Image.new("RGB", (480, 320), color=(201, 13, 127)),
]
prompt = processor.info.get_hf_config().image_placeholder * len(images)
mm_items = processor.info.parse_mm_data({"image": images})
normalized_inputs = processor(prompt, mm_items=mm_items)
normalized_values = normalized_inputs["mm_kwargs"].get_data()["pixel_values"]
ctx.model_config.multimodal_config.mm_device_do_normalize = True
raw_inputs = processor(prompt, mm_items=mm_items)
raw_values = raw_inputs["mm_kwargs"].get_data()["pixel_values"]
assert raw_values.dtype == torch.uint8
input_norm = build_mm_input_norm(ctx.model_config).to(device)
output = input_norm(raw_values.flatten(1).to(device), normalized_values.dtype)
torch.testing.assert_close(
output, normalized_values.flatten(1).to(device), rtol=1.6e-2, atol=1e-5
)
@@ -249,9 +249,9 @@ def test_repeated_image_hits_the_processor_cache():
"BAAI/Emu3-Chat-hf",
"<image> and more text",
marks=pytest.mark.xfail(
reason="Emu3Processor prepends its BOS token only when images are "
"passed, so the unexpanded prompt vLLM tokenizes never "
"gets one. Fixed by huggingface/transformers#47924, unreleased.",
reason="Emu3Processor prepends the BOS token itself because the "
"tokenizer doesn't, so the unexpanded prompt vLLM tokenizes "
"never gets one.",
strict=False,
),
),
+64 -4
View File
@@ -32,6 +32,7 @@ from vllm.model_executor.layers.quantization.modelopt import (
ModelOptNvFp4Config,
)
from vllm.model_executor.layers.quantization.online.base import OnlineQuantizationConfig
from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig
from vllm.models.qwen4_exp.amd import ple_layer as amd_ple_layer
from vllm.models.qwen4_exp.amd.ple_layer import (
Qwen4ExpPLELayer as Qwen4ExpPLELayerAMD,
@@ -51,6 +52,7 @@ from vllm.models.qwen4_exp.nvidia.ngram_embedding import (
Qwen4ExpPLEUnquantizedEmbeddingMethod,
)
from vllm.models.qwen4_exp.nvidia.ple_layer import Qwen4ExpPLELayer
from vllm.platforms import current_platform
from vllm.utils.torch_utils import weak_ref_tensor
from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionMetadata,
@@ -592,6 +594,16 @@ def test_ple_embedding_respects_inc_layer_config() -> None:
Qwen4ExpPLEEmbeddingMethod.from_quant_config(quant_config, prefix)
def test_ple_embedding_is_unquantized_under_quark() -> None:
prefix = "model.layers.1.ple.ple_embedding.ngram_embedding"
quant_config = QuarkConfig({"exclude": [], "global_quant_config": {}})
assert isinstance(
Qwen4ExpPLEEmbeddingMethod.from_quant_config(quant_config, prefix),
Qwen4ExpPLEUnquantizedEmbeddingMethod,
)
def test_ple_embedding_dtype_overrides_modelopt_exclusion() -> None:
prefix = "model.layers.1.ple.ple_embedding.ngram_embedding"
quant_config = ModelOptNvFp4Config(exclude_modules=[prefix])
@@ -1442,7 +1454,7 @@ def test_fused_ngram_ids_correctness(
contexts: list[list[int]],
first_token_id: int,
) -> None:
from vllm.models.qwen4_exp.nvidia.ops.ple import ple_ngram_ids
from vllm.models.qwen4_exp.common.ops.ple import ple_ngram_ids
device = torch.device("cuda")
query_start_loc = torch.tensor(
@@ -2197,15 +2209,20 @@ def _make_conv_metadata(
),
],
)
@pytest.mark.parametrize(
"layer_cls", [Qwen4ExpPLELayer, Qwen4ExpPLELayerAMD], ids=["nvidia", "amd"]
)
def test_fused_conv_correctness(
case: _ConvBatchCase,
state_layout: str,
layer_cls: type[nn.Module],
) -> None:
device = torch.device("cuda")
metadata, num_real_tokens = _make_conv_metadata(case, device)
if case.state_index_stride > 1:
assert metadata.state_indices_tensor.stride(0) == case.state_index_stride
module = Qwen4ExpPLELayer.__new__(Qwen4ExpPLELayer)
# layer_cls is type[nn.Module], so layer_cls.__new__ is type.__new__.
module = object.__new__(layer_cls)
nn.Module.__init__(module)
module.conv_state_len = (case.kernel_size - 1) * case.dilation
module.short_conv_dilation = case.dilation
@@ -2278,7 +2295,7 @@ def test_fused_conv_correctness(
def test_fused_gate_correctness(num_tokens: int, strided_kv: bool) -> None:
import math
from vllm.models.qwen4_exp.nvidia.ops.ple import ple_gate
from vllm.models.qwen4_exp.common.ops.ple import ple_gate
device = torch.device("cuda")
hc, h = 4, 2560
@@ -2378,7 +2395,6 @@ def _build_amd_ngram_embedding(
embedding_dim=config.ple_embed_dim,
ple_dense_layer_id=0,
max_total_tokens=4,
max_num_reqs=2,
prefix="test.ple_embedding",
layer_name="test.ple",
quant_config=(
@@ -2564,3 +2580,47 @@ def test_amd_pinned_embedding_output_written_under_cudagraph_capture(
expected = loaded_weight[ngram_ids.cpu()].to(device="cuda:0").flatten(-2)
torch.testing.assert_close(output.float(), expected.float(), rtol=0, atol=0)
@pytest.mark.skipif(
not current_platform.is_rocm(),
reason="only the ROCm backend runs the n-gram embedding under torch.compile",
)
@pytest.mark.parametrize(
("query_lens", "contexts"),
[([3, 1], [[5, 6], [0, 7]]), ([1, 0, 2], [[1, 2], [3, 4], [0, 0]])],
ids=["two-requests", "empty-request"],
)
def test_amd_ngram_embedding_matches_reference_under_compile(
monkeypatch: pytest.MonkeyPatch,
query_lens: list[int],
contexts: list[list[int]],
) -> None:
"""The AMD n-gram ID op must run under Dynamo with a symbolic request count."""
module, loaded_weight = _build_amd_ngram_embedding(
monkeypatch, device="cuda:0", cpu_offload=False, fp8_checkpoint=False
)
device = torch.device("cuda:0")
query_start_loc = torch.tensor(
[0, *accumulate(query_lens)], dtype=torch.int32, device=device
)
input_ids = torch.tensor(
[9, 0, 11, 12][: sum(query_lens)], dtype=torch.int32, device=device
)
ngram_context = torch.tensor(contexts, dtype=torch.int32, device=device)
compiled = torch.compile(module, fullgraph=True, dynamic=True)
output = compiled(input_ids, query_start_loc, ngram_context)
ngram_ids = _reference_ngram_ids(
input_ids,
query_start_loc,
ngram_context,
module.layer_multipliers,
module.ngram_heads_vocab_sizes,
module.ngram_heads_offsets,
module.eos_token_id,
module.heads_per_ngram,
)
expected = loaded_weight[ngram_ids.cpu()].flatten(-2).to(device)
torch.testing.assert_close(output.float(), expected.float(), rtol=0, atol=0)
+196
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import inspect
import math
from types import SimpleNamespace
from typing import Any
@@ -9,15 +10,21 @@ import pytest
import torch
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
from vllm.models.qwen4_exp.amd import indexer_qsa
from vllm.models.qwen4_exp.amd import (
model as _qwen4_exp_model, # noqa: F401
)
from vllm.models.qwen4_exp.amd import ple_layer as ple_layer_module
from vllm.models.qwen4_exp.amd.indexer_qsa import (
QSAIndexer,
apply_qsa_rmsnorm,
apply_qsa_rope,
)
from vllm.models.qwen4_exp.amd.ops import qsa as qsa_ops
from vllm.models.qwen4_exp.amd.ops.qsa_prepare import (
qsa_prepare,
supports_fused_pre_indexer,
)
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
@@ -120,6 +127,195 @@ def test_qsa_rmsnorm_uses_portable_implementation(default_vllm_config) -> None:
torch.testing.assert_close(output, norm.forward_native(tensor))
def _make_attn(*, use_fused: bool) -> SimpleNamespace:
"""The main-attention fields the fused QSA prepare reads from its owner."""
return SimpleNamespace(
use_fused_qsa_prepare=use_fused,
kv_cache=torch.zeros(1, 2, 16, 8),
q_norm=GemmaRMSNorm(4, eps=1e-6),
k_norm=GemmaRMSNorm(4, eps=1e-6),
_k_scale_float=1.0,
_v_scale_float=1.0,
)
def _make_indexer(*, use_fused: bool, num_tokens: int = 2) -> QSAIndexer:
"""A QSAIndexer whose unfused path runs for real, with no projection weights.
Both branches have to be reachable: a fused-path test is only meaningful if
the unfused one it replaces would otherwise have executed.
"""
heads, head_dim = 2, 4
indexer = QSAIndexer.__new__(QSAIndexer)
torch.nn.Module.__init__(indexer)
indexer.index_n_heads = heads
indexer.index_kv_heads = 1
indexer.index_head_dim = head_dim
indexer.compress_ratio = 2
indexer.use_fused_pre_indexer = use_fused
indexer.skip_topk = True
indexer.index_qk_proj = lambda hidden_states: (
torch.zeros(hidden_states.shape[0], (heads + 1) * head_dim),
None,
)
indexer.q_layernorm = GemmaRMSNorm(head_dim, eps=1e-6)
indexer.k_layernorm = GemmaRMSNorm(head_dim, eps=1e-6)
indexer.rotary_emb = SimpleNamespace(
cos_sin_cache=torch.zeros(16, head_dim),
rotary_dim=head_dim // 2,
apply_rotary_emb=lambda tensor, cos, sin: tensor,
_match_cos_sin_cache_dtype=lambda _: torch.zeros(16, head_dim),
)
# The raw cache's full width carries the MRoPE position tail that the fused
# kernel writes; key_cache is only the leading key columns.
indexer.raw_key_cache = SimpleNamespace(
kv_cache=torch.zeros(1, 4, 1, head_dim + 12),
key_cache=torch.zeros(1, 4, 1, head_dim),
cache_rope_positions=True,
rope_position_offset=head_dim,
)
indexer.compressed_key_cache = SimpleNamespace(
kv_cache=torch.zeros(1, 2, 1, head_dim)
)
raw_metadata = SimpleNamespace(
num_actual_tokens=num_tokens,
slot_mapping=torch.arange(num_tokens),
block_table=torch.zeros(1, 1, dtype=torch.int32),
query_start_loc=torch.tensor([0, num_tokens], dtype=torch.int32),
logical_positions=torch.arange(num_tokens),
token_to_req=torch.zeros(num_tokens, dtype=torch.int32),
)
compressed_metadata = SimpleNamespace(
num_actual_tokens=num_tokens,
slot_mapping=torch.arange(num_tokens),
k_work_metadata=torch.zeros(1, 2, dtype=torch.int32),
)
indexer._metadata = lambda: (raw_metadata, compressed_metadata)
indexer.test_metadata = (raw_metadata, compressed_metadata)
return indexer
@pytest.mark.usefixtures("default_vllm_config")
def test_qsa_fused_prepare_replaces_the_unfused_chain(
monkeypatch: pytest.MonkeyPatch,
) -> None:
indexer = _make_indexer(use_fused=True)
attn = _make_attn(use_fused=True)
calls = []
main_outputs = (torch.empty(0), torch.empty(0))
def fake_prepare(*args, **kwargs):
calls.append((args, kwargs))
return main_outputs
monkeypatch.setattr(indexer_qsa, "qsa_prepare", fake_prepare)
monkeypatch.setattr(
QSAIndexer,
"_update_and_compress",
lambda *args, **kwargs: pytest.fail("fused path ran the unfused chain"),
)
rows = torch.tensor([[3, 1, -1], [5, 2, 0]], dtype=torch.int32)
qkv = torch.zeros(4, 16)
slot_mapping = torch.arange(4)
gate_out = torch.empty(4, 1, 4)
actual, actual_main = QSAIndexer.forward(
indexer,
torch.zeros(2, 8),
torch.tensor([7, 8]),
rows,
attn=attn,
qkv=qkv,
slot_mapping=slot_mapping,
gate_out=gate_out,
)
assert actual is rows
assert actual_main is main_outputs
assert len(calls) == 1
args, kwargs = calls[0]
passed = inspect.signature(qsa_prepare).bind(*args, **kwargs).arguments
_, compressed_metadata = indexer.test_metadata
# The kernel addresses the raw cache at its full width and writes the MRoPE
# position tail itself, so it needs kv_cache, not the key_cache view.
assert passed["state_cache"] is indexer.raw_key_cache.kv_cache
assert passed["compressed_cache"] is indexer.compressed_key_cache.kv_cache
assert passed["k_work_metadata"] is compressed_metadata.k_work_metadata
assert passed["compress_ratio"] == indexer.compress_ratio
assert passed["rope_pos_offset"] == indexer.index_head_dim
# Main attention: only the real tokens, the vLLM cache viewed per token,
# and the gate landing in the caller's buffer.
assert passed["main_qkv"].shape[0] == 2
assert passed["main_qkv"].data_ptr() == qkv.data_ptr()
assert passed["main_slot_mapping"].shape == (2,)
assert passed["main_kv_cache"].shape == (1, 16, 2, 8)
assert passed["main_kv_cache"].data_ptr() == attn.kv_cache.data_ptr()
assert passed["main_gate_out"].shape[0] == 2
assert passed["main_gate_out"].data_ptr() == gate_out.data_ptr()
assert passed["main_q_norm_weight"] is attn.q_norm.weight
assert passed["main_k_norm_weight"] is attn.k_norm.weight
@pytest.mark.usefixtures("default_vllm_config")
def test_qsa_unsupported_config_keeps_the_unfused_chain(
monkeypatch: pytest.MonkeyPatch,
) -> None:
indexer = _make_indexer(use_fused=False)
monkeypatch.setattr(
indexer_qsa,
"qsa_prepare",
lambda *args, **kwargs: pytest.fail("unfused path ran the fused kernel"),
)
updates = []
monkeypatch.setattr(
QSAIndexer,
"_update_and_compress",
lambda *args, **kwargs: updates.append(args),
)
rows = torch.tensor([[3, 1, -1], [5, 2, 0]], dtype=torch.int32)
actual, main_outputs = QSAIndexer.forward(
indexer,
torch.zeros(2, 8),
torch.tensor([7, 8]),
rows,
attn=_make_attn(use_fused=False),
)
assert actual is rows
assert main_outputs is None
assert len(updates) == 1
@pytest.mark.parametrize(
("overrides", "expected"),
[
pytest.param({}, True, id="qwen3_8_flash_next"),
pytest.param({"is_neox_style": False}, False, id="not-neox"),
pytest.param({"rotary_dim": 128}, False, id="rotary-dim"),
pytest.param({"mrope_interleaved": False}, False, id="mrope-not-interleaved"),
pytest.param({"mrope_section": (11, 11, 10, 0)}, False, id="mrope-section-len"),
],
)
def test_fused_pre_indexer_gate_is_config_shaped(overrides, expected) -> None:
# Qwen3.8-Flash-Next's indexer geometry, which both vendors satisfy.
rotary = SimpleNamespace(
rotary_dim=64,
is_neox_style=True,
mrope_section=(11, 11, 10),
mrope_interleaved=True,
)
for name, value in overrides.items():
setattr(rotary, name, value)
assert (
supports_fused_pre_indexer(
rotary, head_dim=128, num_kv_heads=1, compress_ratio=4
)
is expected
)
def test_qsa_selection_uses_portable_topk_on_rocm(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -0,0 +1,418 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Correctness tests for the AMD fused QSA prepare kernel."""
import pytest
import torch
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
from vllm.models.qwen4_exp.amd.indexer_qsa import apply_qsa_rope
from vllm.models.qwen4_exp.amd.ops.qsa import (
qsa_compress_groups_with_ratio,
qsa_store_cache_rows,
)
from vllm.models.qwen4_exp.amd.ops.qsa_prepare import qsa_prepare
from vllm.models.qwen4_exp.common.qsa_cache import (
canonical_qsa_rope_positions,
circular_qsa_slot_mapping,
compressed_qsa_slot_mapping,
)
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
requires_qsa_kernels = pytest.mark.skipif(
not current_platform.is_rocm() or not HAS_TRITON,
reason="the AMD QSA kernels require ROCm and Triton",
)
def _reference_gemma_rmsnorm(
x: torch.Tensor,
weight: torch.Tensor,
eps: float,
) -> torch.Tensor:
"""The unfused Gemma RMSNorm the AMD reference path actually runs."""
norm = GemmaRMSNorm(weight.shape[-1], eps=eps).to(
device=weight.device, dtype=weight.dtype
)
with torch.no_grad():
norm.weight.copy_(weight)
return norm.forward_native(x)
HQ, D = 4, 128
CR = 4
MROPE_SECTION = (11, 11, 10)
EPS = 1e-6
BLOCK_SIZE = 16
COMP_PAGE = BLOCK_SIZE // CR
ROPE_POS_OFFSET = D
RTOL = 1.6e-2
ATOL = 1e-2
MIXED_BATCH = ([260, 259, 138], [1, 1, 37], [8, 8, 8])
MAIN_HQ, MAIN_HK, MAIN_D, MAIN_PAGE = 6, 2, 256, 16
def _make_block_table(block_counts):
# Block 0 is the null block, which no request owns.
num_blocks = sum(block_counts) + 1
table = torch.full((len(block_counts), max(block_counts)), -1, dtype=torch.int32)
physical_blocks = torch.randperm(sum(block_counts)) + 1
offset = 0
for request, count in enumerate(block_counts):
table[request, :count] = physical_blocks[offset : offset + count]
offset += count
return table, num_blocks
def assert_fp8_within_one_ulp(actual: torch.Tensor, expected: torch.Tensor) -> None:
# e4m3 is sign-magnitude, so within a sign the uint8 code order matches the
# value order and one ulp is one code step. The two paths' intermediates
# differ in the pooling accumulation order, which at denormal magnitudes
# (absolute grid step 2^-9) shows up as up to 2 code steps.
code_diff = (
actual.view(torch.uint8).int() - expected.view(torch.uint8).int()
).abs()
abs_diff = (actual.float() - expected.float()).abs()
assert bool(((code_diff <= 1) | (abs_diff <= 2**-8)).all())
def _make_main_inputs(num_tokens: int) -> dict:
"""Random main-attention arguments with a paged BF16 cache in vLLM's layout."""
num_blocks = num_tokens // MAIN_PAGE + 2
cache = torch.zeros(
num_blocks,
MAIN_HK,
MAIN_PAGE,
2 * MAIN_D,
dtype=torch.bfloat16,
device="cuda",
).transpose(1, 2)
slots = torch.randperm(num_blocks * MAIN_PAGE, device="cuda")[:num_tokens]
slots[-1] = -1
norm_weights = torch.randn(2, MAIN_D, dtype=torch.bfloat16, device="cuda") * 0.2
return dict(
main_qkv=torch.randn(
num_tokens,
2 * (MAIN_HQ + MAIN_HK) * MAIN_D,
dtype=torch.bfloat16,
device="cuda",
),
main_q_norm_weight=norm_weights[0],
main_k_norm_weight=norm_weights[1],
main_eps=EPS,
main_kv_cache=cache,
main_slot_mapping=slots,
main_k_scale=1.0,
main_v_scale=1.0,
# The AMD op hands the gate back through a buffer it does not own.
main_gate_out=torch.empty(
num_tokens, MAIN_HQ, MAIN_D, dtype=torch.bfloat16, device="cuda"
),
)
def _check_main_outputs(main: dict, q_out, gate_out, rope, positions) -> None:
"""Compare with the AMD layer's unfused split, QK-norm, RoPE and cache write."""
from vllm._custom_ops import reshape_and_cache_flash
num_tokens = main["main_qkv"].shape[0]
q_gate, k, v = main["main_qkv"].split(
[2 * MAIN_HQ * MAIN_D, MAIN_HK * MAIN_D, MAIN_HK * MAIN_D], dim=-1
)
q, gate = torch.chunk(q_gate.view(num_tokens, MAIN_HQ, -1), 2, dim=-1)
q = _reference_gemma_rmsnorm(
q.reshape(-1, MAIN_D), main["main_q_norm_weight"], EPS
).view(num_tokens, -1)
k = _reference_gemma_rmsnorm(
k.reshape(-1, MAIN_D), main["main_k_norm_weight"], EPS
).view(num_tokens, -1)
q, k = rope(positions, q, k)
kv_cache = main["main_kv_cache"]
cache = torch.zeros_like(kv_cache)
key_cache, value_cache = cache.split(MAIN_D, dim=-1)
scale = torch.tensor(1.0, device="cuda")
reshape_and_cache_flash(
k.view(-1, MAIN_HK, MAIN_D),
v.view(-1, MAIN_HK, MAIN_D),
key_cache,
value_cache,
main["main_slot_mapping"],
"auto",
scale,
scale,
)
torch.testing.assert_close(q_out.flatten(1), q, rtol=RTOL, atol=ATOL)
assert torch.equal(gate_out, gate)
torch.testing.assert_close(kv_cache, cache, rtol=RTOL, atol=ATOL)
@requires_qsa_kernels
@pytest.mark.usefixtures("default_vllm_config")
@pytest.mark.parametrize("indexer_dtype", [torch.bfloat16, torch.float8_e4m3fn])
@pytest.mark.parametrize(
"mrope,is_2d_positions,cache_rope_positions,state_size,seq_lens,query_lens,history_lens",
[
pytest.param(True, True, True, 4, *MIXED_BATCH, id="mrope"),
pytest.param(False, False, False, 4, *MIXED_BATCH, id="text"),
pytest.param(True, False, True, 8, *MIXED_BATCH, id="mrope-model-1d"),
pytest.param(True, True, False, 4, *MIXED_BATCH, id="mrope-no-position-cache"),
pytest.param(
True,
False,
False,
8,
*MIXED_BATCH,
id="mrope-model-1d-no-position-cache",
),
pytest.param(
False, False, True, 4, *MIXED_BATCH, id="text-with-position-cache"
),
pytest.param(True, True, True, 4, [37], [37], [0], id="fresh"),
pytest.param(True, True, True, 4, [4097], [4097], [0], id="tiled"),
],
)
def test_qsa_fused_prepare_matches_unfused(
indexer_dtype,
mrope,
is_2d_positions,
cache_rope_positions,
state_size,
seq_lens,
query_lens,
history_lens,
) -> None:
from vllm.model_executor.layers.rotary_embedding import get_rope
if indexer_dtype == torch.float8_e4m3fn:
pytest.skip("the AMD QSA indexer cache is bf16-only")
# The FP8 comparison below is a one-ulp bound on data this test generates,
# so an unseeded run decides for itself whether it reproduces a rounding
# difference. Seed it, or the kernel's bit-exactness is only sampled.
torch.manual_seed(0)
device = "cuda"
rope_params = {
"partial_rotary_factor": 0.25,
"rope_theta": 10000000,
"rope_type": "default",
}
if mrope:
rope_params["mrope_interleaved"] = True
rope_params["mrope_section"] = list(MROPE_SECTION)
with torch.device(device):
rope = get_rope(
head_size=256,
max_position=32768,
rope_parameters=rope_params,
dtype=torch.bfloat16,
)
token_to_req = torch.cat(
[
torch.full((length,), request, dtype=torch.int32)
for request, length in enumerate(query_lens)
]
).to(device)
logical_positions = torch.cat(
[
torch.arange(seq_len - query_len, seq_len, dtype=torch.int64)
for seq_len, query_len in zip(seq_lens, query_lens)
]
).to(device)
num_tokens = logical_positions.numel()
query_start_loc = torch.tensor(
[0, *torch.tensor(query_lens).cumsum(0).tolist()], dtype=torch.int32
).to(device)
positions = (
torch.stack(
[
logical_positions,
logical_positions // 7 + 3,
logical_positions // 13 + 11,
]
)
if is_2d_positions
else logical_positions
)
position_rows = (
canonical_qsa_rope_positions(positions)
if cache_rope_positions
else logical_positions.view(-1, 1, 1).expand(-1, 1, 3)
)
compressed_block_counts = [
(seq_len // CR + COMP_PAGE - 1) // COMP_PAGE for seq_len in seq_lens
]
raw_block_table, num_raw_blocks = _make_block_table([1] * len(seq_lens))
compressed_block_table, num_compressed_blocks = _make_block_table(
compressed_block_counts
)
raw_block_table = raw_block_table.to(device)
raw_slots = circular_qsa_slot_mapping(
raw_block_table,
token_to_req,
logical_positions,
state_size,
query_start_loc,
)
compressed_slots = compressed_qsa_slot_mapping(
compressed_block_table.to(device),
token_to_req,
logical_positions,
COMP_PAGE,
CR,
)
group_counts = torch.tensor(
[
seq_len // CR - (seq_len - query_len) // CR
for seq_len, query_len in zip(seq_lens, query_lens)
],
dtype=torch.int32,
device=device,
)
k_work_counts = torch.maximum(group_counts, torch.ones_like(group_counts))
k_start_loc = torch.cat([k_work_counts.new_zeros(1), k_work_counts.cumsum(0)])
work_requests = torch.repeat_interleave(
torch.arange(len(query_lens), dtype=torch.int32, device=device),
k_work_counts,
)
local_work = torch.arange(
int(k_start_loc[-1]), dtype=torch.int32, device=device
) - torch.repeat_interleave(k_start_loc[:-1], k_work_counts)
max_k_work = (num_tokens + (CR - 1) * len(query_lens)) // CR
k_work_metadata = torch.full((max_k_work, 2), -1, dtype=torch.int32, device=device)
k_work_metadata[: work_requests.numel()] = torch.stack(
(work_requests, local_work), dim=1
)
raw_width = D + 12 if cache_rope_positions else D
# Match vLLM's padded-page cache layout: rows are contiguous, while physical
# blocks have a larger stride than their logical contents.
raw_page_elements = state_size * raw_width
fused_raw_storage = torch.zeros(
num_raw_blocks,
raw_page_elements + 16,
dtype=torch.bfloat16,
device=device,
)
fused_raw = torch.as_strided(
fused_raw_storage,
(num_raw_blocks, state_size, 1, raw_width),
(raw_page_elements + 16, raw_width, raw_width, 1),
)
for request, history_len in enumerate(history_lens):
history_end = seq_lens[request] - query_lens[request]
for position in range(history_end - history_len, history_end):
block = int(raw_block_table[request, 0])
row = fused_raw[block, position % state_size, 0]
row[:D] = torch.randn(D, dtype=torch.bfloat16, device=device)
if cache_rope_positions:
row[ROPE_POS_OFFSET:].view(torch.int64).copy_(
torch.tensor(
[position, position // 7 + 3, position // 13 + 11],
dtype=torch.int64,
device=device,
)
)
unfused_raw = fused_raw.clone()
compressed_page_elements = COMP_PAGE * D
fused_compressed_storage = torch.zeros(
num_compressed_blocks,
compressed_page_elements + 16,
dtype=indexer_dtype,
device=device,
)
fused_compressed = torch.as_strided(
fused_compressed_storage,
(num_compressed_blocks, COMP_PAGE, 1, D),
(compressed_page_elements + 16, D, D, 1),
)
unfused_compressed = fused_compressed.clone()
projected_qk = torch.randn(
num_tokens, (HQ + 1) * D, dtype=torch.bfloat16, device=device
)
q_weight = torch.randn(D, dtype=torch.bfloat16, device=device) * 0.2
k_weight = torch.randn(D, dtype=torch.bfloat16, device=device) * 0.2
fused_query = torch.empty(num_tokens, HQ, D, dtype=indexer_dtype, device=device)
main = _make_main_inputs(num_tokens)
main_q_out, main_gate_out = qsa_prepare(
projected_qk[:, : HQ * D],
projected_qk[:, HQ * D :],
positions,
rope.cos_sin_cache,
q_weight,
k_weight,
EPS,
fused_query,
fused_raw,
raw_slots,
raw_block_table,
query_start_loc,
logical_positions,
fused_compressed,
compressed_slots,
k_work_metadata,
compress_ratio=CR,
mrope_section=MROPE_SECTION if mrope else None,
rope_pos_offset=ROPE_POS_OFFSET if cache_rope_positions else None,
**main,
)
assert main_gate_out is main["main_gate_out"]
_check_main_outputs(main, main_q_out, main_gate_out, rope, positions)
unfused_query = projected_qk[:, : HQ * D].reshape(num_tokens, HQ, D)
unfused_query = _reference_gemma_rmsnorm(
unfused_query.reshape(-1, D), q_weight, EPS
).reshape_as(unfused_query)
unfused_query = apply_qsa_rope(rope, positions, unfused_query)
raw_keys = unfused_raw[..., :D]
rope_positions = (
unfused_raw[..., ROPE_POS_OFFSET:].view(torch.int64)
if cache_rope_positions
else None
)
pooled, first_positions = qsa_compress_groups_with_ratio(
projected_qk[:, HQ * D :].reshape(-1, 1, D),
position_rows,
raw_keys,
raw_block_table,
token_to_req,
query_start_loc,
logical_positions,
compressed_slots,
CR,
rope_positions,
)
compressed_rows = _reference_gemma_rmsnorm(
pooled.reshape(-1, D), k_weight, EPS
).reshape(-1, 1, D)
group_positions = (
first_positions.transpose(0, 1) if mrope else first_positions[:, 0]
)
compressed_rows = apply_qsa_rope(rope, group_positions, compressed_rows)
qsa_store_cache_rows(unfused_compressed, compressed_slots, compressed_rows)
qsa_store_cache_rows(raw_keys, raw_slots, projected_qk[:, HQ * D :])
if rope_positions is not None:
qsa_store_cache_rows(rope_positions, raw_slots, position_rows)
if indexer_dtype == torch.float8_e4m3fn:
# Both paths round the same ~bf16 intermediates to e4m3. Bitwise
# equality (the dsv4 indexer test's bar) does not hold here: the 1D
# reference rope (forward_cuda) differs from _norm_rope by up to 1
# bf16 ulp, and even the MRoPE pair flips a code occasionally.
unfused_query = unfused_query.to(indexer_dtype)
assert_fp8_within_one_ulp(fused_query, unfused_query)
else:
torch.testing.assert_close(fused_query, unfused_query, rtol=RTOL, atol=ATOL)
assert torch.equal(fused_raw.view(torch.int16), unfused_raw.view(torch.int16))
if indexer_dtype == torch.float8_e4m3fn:
assert_fp8_within_one_ulp(fused_compressed, unfused_compressed)
else:
torch.testing.assert_close(
fused_compressed, unfused_compressed, rtol=RTOL, atol=ATOL
)
+25 -7
View File
@@ -15,6 +15,7 @@ from vllm.models.qwen4_exp.nvidia import (
)
from vllm.models.qwen4_exp.nvidia.ops import qsa as qsa_ops
from vllm.models.qwen4_exp.nvidia.ops import qsa_indexer as qsa_indexer_ops
from vllm.models.qwen4_exp.nvidia.qsa import qsa_kv_cache_dtype
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
from vllm.v1.worker.utils import clear_layer_kv_caches
@@ -314,7 +315,7 @@ def test_qsa_circular_buffer_metadata_keeps_only_each_requests_suffix() -> None:
builder.k_work_metadata_buffer = torch.empty(0, 2, dtype=torch.int32, device=device)
query_start_loc = torch.tensor([0, 7, 13, 13], dtype=torch.int32, device=device)
token_to_req = torch.tensor([0] * 7 + [1] * 6 + [0] * 3, device=device)
block_table = torch.tensor([[1], [0], [2]], dtype=torch.int32, device=device)
block_table = torch.tensor([[1], [3], [2]], dtype=torch.int32, device=device)
common = SimpleNamespace(
num_actual_tokens=16,
num_reqs=3,
@@ -339,10 +340,10 @@ def test_qsa_circular_buffer_metadata_keeps_only_each_requests_suffix() -> None:
4,
-1,
-1,
3,
0,
1,
2,
15,
12,
13,
14,
-1,
-1,
-1,
@@ -350,6 +351,10 @@ def test_qsa_circular_buffer_metadata_keeps_only_each_requests_suffix() -> None:
assert metadata.slot_mapping.tolist() == expected
# A dummy batch puts every request on the null block, which owns no ring.
block_table.zero_()
assert builder.build(0, common).slot_mapping.tolist() == [-1] * 16
@pytest.mark.parametrize("chunk_start", list(range(8)))
def test_qsa_circular_buffer_survives_one_speculative_step(chunk_start: int) -> None:
@@ -366,7 +371,7 @@ def test_qsa_circular_buffer_survives_one_speculative_step(chunk_start: int) ->
query_len = num_spec + 1
slots = qsa_cache.circular_qsa_slot_mapping(
torch.tensor([[0]], dtype=torch.int32),
torch.tensor([[1]], dtype=torch.int32),
torch.zeros(query_len, dtype=torch.int32),
torch.arange(chunk_start, chunk_start + query_len),
capacity,
@@ -374,7 +379,7 @@ def test_qsa_circular_buffer_survives_one_speculative_step(chunk_start: int) ->
)
committed = torch.arange(chunk_start - chunk_start % compress_ratio, chunk_start)
assert set(slots.tolist()).isdisjoint((committed % capacity).tolist())
assert set((slots % capacity).tolist()).isdisjoint((committed % capacity).tolist())
def _qsa_key_cache(
@@ -448,6 +453,19 @@ def test_qsa_ring_capacity_covers_one_speculative_step(
assert spec.block_size == expected
def test_qsa_kv_cache_dtype_honors_skip_layers() -> None:
"""``--kv-cache-dtype-skip-layers`` keeps the listed QSA layers unquantized.
The MTP layer's own attention is the one that matters on Flash-Next: FP8
there cuts draft acceptance at depth while the target layers stay FP8.
"""
cache_config = SimpleNamespace(cache_dtype="fp8", kv_cache_dtype_skip_layers=["48"])
assert qsa_kv_cache_dtype(cache_config, "mtp.layers.48.self_attn") == "auto"
assert qsa_kv_cache_dtype(cache_config, "model.layers.47.self_attn") == "fp8"
cache_config.kv_cache_dtype_skip_layers = []
assert qsa_kv_cache_dtype(cache_config, "mtp.layers.48.self_attn") == "fp8"
@requires_qsa_kernels
def test_qsa_compressed_metadata_keeps_dummy_slots_inert() -> None:
device = torch.device("cuda")
+6 -10
View File
@@ -581,6 +581,10 @@ _EMBEDDING_EXAMPLE_MODELS = {
trust_remote_code=True,
hf_overrides={"model_type": "deepseek_v3", "auto_map": None},
),
"EmbeddingGemma2Model": _HfExamplesInfo(
"google/embeddinggemma-2",
is_available_online=False,
),
"Gemma2Model": _HfExamplesInfo("BAAI/bge-multilingual-gemma2"),
"Gemma3TextModel": _HfExamplesInfo("google/embeddinggemma-300m"),
"GteModel": _HfExamplesInfo(
@@ -771,10 +775,7 @@ _MULTIMODAL_EXAMPLE_MODELS = {
# [Decoder-only]
"AriaForConditionalGeneration": _HfExamplesInfo("rhymes-ai/Aria"),
"AudioFlamingo3ForConditionalGeneration": _HfExamplesInfo(
"nvidia/audio-flamingo-3-hf",
transformers_version_reason={
"vllm": "Needs https://github.com/huggingface/transformers/pull/43538"
},
"nvidia/audio-flamingo-3-hf"
),
"BagelForConditionalGeneration": _HfExamplesInfo("ByteDance-Seed/BAGEL-7B-MoT"),
"BailingMoeV3VLForConditionalGeneration": _HfExamplesInfo(
@@ -813,12 +814,7 @@ _MULTIMODAL_EXAMPLE_MODELS = {
"nvidia/Cosmos3-Edge",
max_model_len=4096,
use_original_num_layers=True,
hf_overrides={
"text_config": {
"num_hidden_layers": 2,
"hybrid_override_pattern": "*-",
}
},
hf_overrides={"text_config": {"layers_block_type": ["full_attention", "mlp"]}},
),
"DeepseekVLV2ForCausalLM": _HfExamplesInfo(
"deepseek-ai/deepseek-vl2-tiny",
@@ -2,15 +2,26 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DecoderReplayLayers runs the replay layers on the forward's replay batch."""
from unittest.mock import MagicMock
import pytest
import torch
from vllm.config import CompilationConfig, CUDAGraphMode
from vllm.forward_context import (
BatchDescriptor,
ForwardContext,
get_forward_context,
override_forward_context,
)
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.models.deepseek_v41.decoder_replay_layers import (
DecoderReplayLayers,
ReplayBatch,
)
from vllm.models.deepseek_v41.nvidia.decoder_replay_cudagraph import (
DecoderReplayCudaGraphManager,
)
from vllm.v1.worker.gpu import cudagraph_utils
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
@@ -32,9 +43,9 @@ def _context(metadata):
def _set_replay_batch(layers, rows, metadata):
layers.rows = torch.tensor(rows, device=DEVICE)
layers.forward_context = ForwardContext(
no_compile_layers={}, attn_metadata=metadata, slot_mapping={}
layers.replay_batch = ReplayBatch(
torch.tensor(rows, device=DEVICE),
ForwardContext(no_compile_layers={}, attn_metadata=metadata, slot_mapping={}),
)
@@ -56,10 +67,8 @@ def _states(num_tokens: int):
)
def test_run_gathers_states_and_realigns_shared_indexer_buffers():
topk = torch.arange(NUM_TOKENS * 4, device=DEVICE).view(NUM_TOKENS, 4).int()
candidates = torch.arange(NUM_TOKENS * 3, device=DEVICE).view(NUM_TOKENS, 3).int()
topk_before, candidates_before = topk.clone(), candidates.clone()
def test_run_gathers_states():
"""Every row's KV is written first; the layers then run on the replay rows."""
seen = {}
def run_layers(hidden_states, positions, input_ids, pre_mix, post, res, residual):
@@ -69,7 +78,8 @@ def test_run_gathers_states_and_realigns_shared_indexer_buffers():
seen["is_padding"] = replay_context.is_padding
return residual, pre_mix
layers = DecoderReplayLayers(WINDOW, run_layers, [topk, candidates])
write_batch_kv = MagicMock()
layers = DecoderReplayLayers(WINDOW, run_layers, write_batch_kv, set(), "swa")
states = _states(NUM_TOKENS)
hidden, residual = states[0], states[-1]
full, sub = object(), object()
@@ -79,11 +89,10 @@ def test_run_gathers_states_and_realigns_shared_indexer_buffers():
outputs = layers(*states)
assert get_forward_context() is context
write_batch_kv.assert_called_once_with(*states)
rows = torch.tensor(REPLAY_ROWS, device=DEVICE)
assert torch.equal(seen["hidden_states"], hidden[rows])
assert seen["attn_metadata"] is sub and seen["is_padding"] is None
assert torch.equal(topk[: len(REPLAY_ROWS)], topk_before[rows])
assert torch.equal(candidates[: len(REPLAY_ROWS)], candidates_before[rows])
assert len(outputs) == 2 and outputs[0].shape == residual.shape
assert torch.equal(outputs[0][rows], residual[rows])
assert outputs[0][1:173].abs().sum() == 0
@@ -96,9 +105,77 @@ def test_no_replay_batch_runs_the_whole_batch():
seen["attn_metadata"] = get_forward_context().attn_metadata
return (hidden_states,)
layers = DecoderReplayLayers(WINDOW, run_layers, [])
write_batch_kv = MagicMock()
layers = DecoderReplayLayers(WINDOW, run_layers, write_batch_kv, set(), "swa")
states = _states(NUM_TOKENS)
full = object()
with override_forward_context(_context(full)):
(output,) = layers(*states)
assert output is states[0] and seen["attn_metadata"] is full
write_batch_kv.assert_not_called()
def _graph_context(num_tokens):
return ForwardContext(
no_compile_layers={},
attn_metadata={},
slot_mapping={},
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
batch_descriptor=BatchDescriptor(num_tokens=num_tokens),
)
def test_piecewise_graphs_break_out_by_size():
"""A PIECEWISE graph's KV write and break are fixed at capture, when no replay
batch is set, so both follow the graph's size rather than the replay batch."""
write_batch_kv = MagicMock()
layers = DecoderReplayLayers(
WINDOW, lambda *states: ("whole",), write_batch_kv, set(), "swa"
)
layers._run_in_graph_break = lambda *states: ("break",) # type: ignore[method-assign]
states = _states(NUM_TOKENS)
with override_forward_context(_graph_context(1024)):
assert layers(*states) == ("whole",) # no threshold: no break
layers.trim_threshold = 768
assert layers(*states) == ("break",)
_set_replay_batch(layers, REPLAY_ROWS, object())
with override_forward_context(_graph_context(576)):
assert not layers.uses_replay_batch() # a replay batch alone does not break out
write_batch_kv.assert_called_once_with(*states)
def test_replay_graph_matches_eager(monkeypatch):
"""The replay graph of the next captured size pads and runs the rows."""
monkeypatch.setattr(cudagraph_utils, "get_pp_group", MagicMock)
capture = torch.cuda.stream(torch.cuda.Stream())
monkeypatch.setattr(cudagraph_utils, "graph_capture", lambda device: capture)
compilation = CompilationConfig(decoder_replay_cudagraph_capture_sizes=[4])
cfg = MagicMock(compilation_config=compilation, speculative_config=None)
# Mocking it true would capture into the cuMem pool, which breaks on ROCm.
cfg.use_cumem_cudagraph_pool = False
cfg.scheduler_config = MagicMock(max_num_seqs=2, max_num_batched_tokens=64)
cfg.cache_config.use_kda_recoverssm = False
cfg.model_config.hf_config = MagicMock(hc_mult=HC, hidden_size=HIDDEN)
cfg.model_config.dtype = torch.float32
def run_layers(hidden, positions, ids, pre, post, mix, residual):
return residual + hidden[:, None] + positions[:, None, None], pre + ids[:, None]
layers = DecoderReplayLayers(4, run_layers, MagicMock(), set(), "swa")
manager = DecoderReplayCudaGraphManager(cfg, DEVICE, layers)
def prepare(desc):
rows = torch.arange(desc.num_tokens)
layers.replay_batch = ReplayBatch(rows, _graph_context(desc.num_tokens))
manager.capture_replay_graphs(prepare)
states = [
torch.randn(12, *b.shape[1:], device=DEVICE).to(b.dtype)
for b in manager.input_buffers
]
rows = torch.tensor([11, 2, 7], device=DEVICE)
desc = manager.dispatch(2, 3, None, 0)
with override_forward_context(_graph_context(desc.num_tokens)):
actual = manager.run(rows, states)
for a, e in zip(actual, run_layers(*(t[rows] for t in states))):
torch.testing.assert_close(a, e, rtol=0, atol=0)
+63 -17
View File
@@ -11,7 +11,14 @@ import pytest
import torch
from vllm.config import CUDAGraphMode
from vllm.forward_context import (
BatchDescriptor,
ForwardContext,
override_forward_context,
)
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.models.deepseek_v41.nvidia.model_state import DeepseekV41ModelState
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
@@ -57,7 +64,8 @@ def state(monkeypatch):
cfg.scheduler_config.max_num_batched_tokens = 1024
cfg.parallel_config.data_parallel_size = 1
cfg.compilation_config.fast_moe_cold_start = False
layers = SimpleNamespace(window=WINDOW, rows=None, forward_context=None)
cfg.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
layers = DecoderReplayLayers(WINDOW, MagicMock(), MagicMock(), set(), "swa_first")
model = SimpleNamespace(token_lookback_depth=0, decoder_replay_layers=layers)
builds: list = []
@@ -70,7 +78,7 @@ def state(monkeypatch):
attn_metadata=object(),
)
builds.append(build)
return {"swa": build.attn_metadata}
return {"swa": build.attn_metadata, "swa_first": build.attn_metadata}
monkeypatch.setattr(DefaultModelState, "prepare_attn", prepare_attn)
state = DeepseekV41ModelState(cfg, model, None, DEVICE)
@@ -118,7 +126,8 @@ def _slot_mappings(num_tokens: int) -> torch.Tensor:
def _prepare(state, batch, cg_mode):
"""Runs prepare_attn; returns the replay batch and the replay build's inputs."""
"""Runs prepare_attn; returns the replay batch and the replay build's inputs.
The first replay layer's sliding-window build follows the replay build."""
state.prepare_attn(
batch,
cg_mode,
@@ -127,13 +136,8 @@ def _prepare(state, batch, cg_mode):
[],
GROUPS,
)
layers = state.decoder_replay_layers
if layers.rows is None:
assert layers.forward_context is None
return None, None
return SimpleNamespace(
rows=layers.rows, forward_context=layers.forward_context
), state.builds[-1]
replay = state.decoder_replay_layers.replay_batch
return (None, None) if replay is None else (replay, state.builds[-2])
def test_replay_batch_keeps_each_request_window(state):
@@ -154,8 +158,16 @@ def test_replay_batch_keeps_each_request_window(state):
assert build.replay_start.tolist() == [0, 300 - WINDOW, 50]
assert torch.equal(sub.positions, batch.positions[rows])
assert torch.equal(build.slot_mappings, _slot_mappings(401)[:, rows])
# The first replay layer keeps the encoder-side window starts: it wrote
# every row's window KV.
first = state.builds[-1]
assert first.batch is sub and first.cg_mode == CUDAGraphMode.NONE
assert first.replay_start.tolist() == [0, 0, 50]
context = replay.forward_context
assert context.attn_metadata == {"swa": build.attn_metadata}
assert context.attn_metadata == {
"swa": build.attn_metadata,
"swa_first": first.attn_metadata,
}
assert torch.equal(context.slot_mapping["mla"], _slot_mappings(401)[1, rows])
assert context.dp_metadata is None and context.is_padding is None
@@ -191,9 +203,10 @@ def test_replay_batch_keeps_adaptive_verification_query_bound(state):
assert replay is not None and build.batch.max_query_len == 200
def test_only_eager_steps_trim(state):
"""A CUDA graph keeps the layers on its whole batch; an eager step trims a
padded batch to its real rows."""
def test_graph_steps_trim_only_piecewise_at_threshold(state):
"""A CUDA graph keeps the layers on its whole batch, unless it is a PIECEWISE
one at the trim threshold or above, as its capture decided; an eager step
trims a batch to its rows."""
batch = _input_batch(QUERY_LENS, SEQ_LENS, PREFILLING, num_tokens_after_padding=512)
for cg_mode in (CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL):
assert _prepare(state, batch, cg_mode) == (None, None)
@@ -202,6 +215,23 @@ def test_only_eager_steps_trim(state):
assert replay.rows.tolist() == REPLAY_ROWS
assert build.cg_mode == CUDAGraphMode.NONE
assert build.batch.num_tokens_after_padding == len(REPLAY_ROWS)
layers = state.decoder_replay_layers
graph = ForwardContext(
no_compile_layers={},
attn_metadata={},
slot_mapping={},
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
batch_descriptor=BatchDescriptor(num_tokens=512),
)
for threshold in (513, 512):
layers.trim_threshold = threshold
replay, _ = _prepare(state, batch, CUDAGraphMode.PIECEWISE)
with override_forward_context(graph): # the capture's decision
assert (
layers.uses_replay_batch() == (replay is not None) == (threshold == 512)
)
assert replay is not None and replay.rows.tolist() == REPLAY_ROWS
assert _prepare(state, batch, CUDAGraphMode.FULL) == (None, None)
def test_whole_batch_forwards_get_no_replay_batch(state):
@@ -251,9 +281,25 @@ def test_dp_ranks_replay_together(dp_state):
def test_idle_dp_rank_dummy_trims_with_its_peers(dp_state):
dummy = _input_batch([512], [512], [False])
"""An idle rank's dummy keeps one row, so peers do not wait on its replay."""
dummy = _input_batch([256, 256], [256, 256], [False, False])
dp_state.other = (True, 129)
replay, _ = _prepare(dp_state, dummy, CUDAGraphMode.NONE)
assert replay is not None and replay.rows.shape[0] == WINDOW
assert replay is not None and replay.rows.shape[0] == 1
dp_metadata = replay.forward_context.dp_metadata
assert dp_metadata.num_tokens_across_dp_cpu.tolist() == [WINDOW, 129]
assert dp_metadata.num_tokens_across_dp_cpu.tolist() == [1, 129]
def test_dp_ranks_pad_to_one_replay_graph(dp_state):
"""Every rank pads its replay batch to the graph fitting the largest rank's."""
dp_state.replay_cudagraphs = MagicMock()
dp_state.replay_cudagraphs.dispatch.return_value = BatchExecutionDescriptor(
CUDAGraphMode.PIECEWISE, 512, None
)
dp_state.other = (True, 300)
batch = _input_batch(QUERY_LENS, SEQ_LENS, PREFILLING)
replay, _ = _prepare(dp_state, batch, CUDAGraphMode.NONE)
assert dp_state.replay_cudagraphs.dispatch.call_args.args[:2] == (3, 300)
assert replay.forward_context.batch_descriptor.num_tokens == 512
dp_metadata = replay.forward_context.dp_metadata
assert dp_metadata.num_tokens_across_dp_cpu.tolist() == [512, 512]
@@ -0,0 +1,186 @@
# 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.fused_moe import (
fused_moe_make_expert_params_mapping,
)
from vllm.models.deepseek_v4.amd import mega_moe as mega_moe_module
from vllm.models.deepseek_v4.amd.mega_moe import (
DeepseekV4AiterMegaMoEExperts,
)
from vllm.models.deepseek_v4.amd.model import DeepseekV4MoE
from vllm.platforms import current_platform
HIDDEN = 64
INTER = 64
def _make_experts(
monkeypatch,
*,
ep_rank=0,
ep_size=1,
num_experts=2,
intermediate_size=INTER,
max_num_batched_tokens=3000,
swiglu_limit=None,
):
monkeypatch.setattr(
mega_moe_module,
"get_ep_group",
lambda: SimpleNamespace(
rank_in_group=ep_rank, world_size=ep_size, cpu_group="ep"
),
)
vllm_config = SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_batched_tokens=max_num_batched_tokens)
)
return DeepseekV4AiterMegaMoEExperts(
vllm_config,
num_experts=num_experts,
top_k=2,
hidden_size=HIDDEN,
intermediate_size=intermediate_size,
swiglu_limit=swiglu_limit,
)
@pytest.mark.cpu_test
def test_experts_load_into_local_slots(monkeypatch):
model = torch.nn.Module()
model.ffn = torch.nn.Module()
model.ffn.experts = _make_experts(monkeypatch, ep_rank=1, ep_size=2, num_experts=4)
params = dict(model.named_parameters())
mapping = fused_moe_make_expert_params_mapping(
model,
ckpt_gate_proj_name="w1",
ckpt_down_proj_name="w2",
ckpt_up_proj_name="w3",
num_experts=4,
routed_experts_prefix="",
)
shapes = {
("w1", "weight"): (INTER, HIDDEN // 2),
("w3", "weight"): (INTER, HIDDEN // 2),
("w2", "weight"): (HIDDEN, INTER // 2),
("w1", "weight_scale"): (INTER, HIDDEN // 32),
("w3", "weight_scale"): (INTER, HIDDEN // 32),
("w2", "weight_scale"): (HIDDEN, INTER // 32),
}
shard_value = {"w1": 1, "w3": 2, "w2": 3}
loaded = {}
for expert in range(4):
for (shard, suffix), shape in shapes.items():
name = f"ffn.experts.{expert}.{shard}.{suffix}"
weight = torch.full(
shape, 10 * expert + shard_value[shard], dtype=torch.uint8
)
for param_name, weight_name, expert_id, shard_id in mapping:
if weight_name not in name:
continue
mapped = name.replace(weight_name, param_name)
param = params[mapped]
if param.weight_loader(
param,
weight,
mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
):
loaded[name] = mapped
break
assert sorted({n.split(".")[2] for n in loaded}) == ["2", "3"]
assert len(loaded) == 2 * len(shapes)
for slot, expert in enumerate((2, 3)):
for suffix in ("weight", "weight_scale"):
w13 = params[f"ffn.experts.w13_{suffix}"][slot]
w2 = params[f"ffn.experts.w2_{suffix}"][slot]
assert torch.all(w13[:INTER] == 10 * expert + 1)
assert torch.all(w13[INTER:] == 10 * expert + 2)
assert torch.all(w2 == 10 * expert + 3)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="Requires ROCm")
@pytest.mark.parametrize("hash_routing", [False, True])
@pytest.mark.parametrize("num_tokens", [1, 37])
def test_mega_moe_routing_matches_reference(monkeypatch, hash_routing, num_tokens):
num_experts, top_k, vocab = 16, 4, 64
scaling = 2.5
device = "cuda"
torch.manual_seed(0)
class Gate(torch.nn.Module):
def __init__(self):
super().__init__()
self.weight = torch.randn(num_experts, HIDDEN, device=device) * 0.1
self.e_score_correction_bias = (
None if hash_routing else torch.randn(num_experts, device=device)
)
self.tid2eid = (
torch.stack(
[
torch.randperm(num_experts, device=device)[:top_k]
for _ in range(vocab)
]
).to(torch.int32)
if hash_routing
else None
)
self.bias_vl = None
def forward(self, x):
return x.float() @ self.weight.t(), None
captured = {}
def experts(x, topk_weights, topk_ids):
captured["weights"], captured["ids"] = topk_weights, topk_ids
return 2 * x
moe = DeepseekV4MoE.__new__(DeepseekV4MoE)
torch.nn.Module.__init__(moe)
moe.gate = Gate()
moe.experts = experts
moe.shared_experts = lambda x: 3 * x
moe.scoring_func = "sqrtsoftplus"
moe.n_activated_experts = top_k
moe.renormalize = True
moe.routed_scaling_factor = scaling
moe.image_sentinel_lo = 0
x = torch.randn(num_tokens, HIDDEN, device=device, dtype=torch.bfloat16)
input_ids = torch.randint(0, vocab, (num_tokens,), device=device)
out = moe._forward_mega_moe(x, input_ids)
ids, weights = captured["ids"], captured["weights"]
assert ids.dtype == torch.int32 and ids.is_contiguous()
assert weights.dtype == torch.float32 and weights.is_contiguous()
scores = torch.nn.functional.softplus(x.float() @ moe.gate.weight.t()).sqrt()
if hash_routing:
expected_ids = moe.gate.tid2eid[input_ids].long()
else:
expected_ids = (scores + moe.gate.e_score_correction_bias).topk(top_k).indices
expected_weights = scores.gather(1, expected_ids)
expected_weights *= scaling / expected_weights.sum(dim=-1, keepdim=True)
order = ids.long().sort(dim=-1).indices
expected_order = expected_ids.sort(dim=-1).indices
torch.testing.assert_close(
ids.long().gather(1, order), expected_ids.gather(1, expected_order)
)
torch.testing.assert_close(
weights.gather(1, order),
expected_weights.gather(1, expected_order),
rtol=1e-3,
atol=1e-4,
)
torch.testing.assert_close(out, 5 * x)
+4 -1
View File
@@ -15,7 +15,10 @@ def _make_uninitialized_model(confidence_head):
object.__setattr__(
model,
"model",
SimpleNamespace(confidence_head=confidence_head),
SimpleNamespace(
confidence_head=confidence_head,
layers=[SimpleNamespace(ffn=SimpleNamespace(use_mega_moe=False))],
),
)
return model
+40 -9
View File
@@ -6,9 +6,15 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.layers.fused_moe.deep_gemm_mega_moe import (
DeepGemmSm100MegaMoEBackend,
)
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
bind_routed_experts_capturer,
)
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
deepgemm_post_process_weight_scale_block,
)
from vllm.models.deepseek_v4.nvidia.dspark import DSparkDeepseekV4ForCausalLM
from vllm.models.deepseek_v4.nvidia.model import (
DeepseekV4ForCausalLM,
@@ -23,6 +29,7 @@ from vllm.models.deepseek_v41.common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
from vllm.models.deepseek_v41.nvidia.model import DeepseekV4MoE as DeepseekV41MoE
from vllm.platforms import current_platform
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
from vllm.utils.deep_gemm import is_deep_gemm_supported
from vllm.utils.torch_utils import set_default_torch_dtype
pytestmark = pytest.mark.skipif(
@@ -447,7 +454,9 @@ def test_deepseek_v4_mega_moe_preserves_checkpoint_dimensions(
):
param.data.random_(1, 128)
originals.append(param.data.clone())
monkeypatch.setattr(experts, "_check_runtime_supported", lambda: None)
monkeypatch.setattr(
experts, "_ensure_backend", lambda: DeepGemmSm100MegaMoEBackend()
)
monkeypatch.setattr(
"vllm.utils.deep_gemm._import_deep_gemm",
lambda: SimpleNamespace(
@@ -473,19 +482,23 @@ def test_deepseek_v4_mega_moe_preserves_checkpoint_dimensions(
@pytest.mark.parametrize(
"hidden_size,intermediate_size,block_size,mxfp8",
"hidden_size,intermediate_size,block_size,mxfp8,packed",
[
pytest.param(128, 512, 128, False, id="aligned-block128"),
pytest.param(128, 512, 128, True, id="aligned-block128-mxfp8"),
pytest.param(5120, 2304, 32, False, id="deepseek-v41-flash"),
pytest.param(128, 2304, 128, False, id="native-block128"),
pytest.param(5120, 2304, 32, True, id="deepseek-v41-flash-mxfp8"),
pytest.param(128, 512, 128, False, False, id="aligned-block128"),
pytest.param(128, 512, 128, False, True, id="aligned-block128-packed"),
pytest.param(128, 512, 128, True, False, id="aligned-block128-mxfp8"),
pytest.param(5120, 2304, 32, False, False, id="deepseek-v41-flash"),
pytest.param(128, 2304, 128, False, False, id="native-block128"),
pytest.param(128, 2304, 128, False, True, id="native-block128-packed"),
pytest.param(5120, 2304, 32, True, False, id="deepseek-v41-flash-mxfp8"),
],
)
def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
monkeypatch, hidden_size, intermediate_size, block_size, mxfp8
monkeypatch, hidden_size, intermediate_size, block_size, mxfp8, packed
):
"""Shared fusion preserves checkpoint weights and scales at native widths."""
if packed and not is_deep_gemm_supported():
pytest.skip("Packing the shared scales requires DeepGEMM")
class FakeDeepGemm:
transformed_dims: list[tuple[int, int]] = []
@@ -539,7 +552,9 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
intermediate_size=intermediate_size,
num_shared_experts=1,
)
experts._check_runtime_supported = lambda: None
monkeypatch.setattr(
experts, "_ensure_backend", lambda: DeepGemmSm100MegaMoEBackend()
)
def fp8_parameter(*shape):
return torch.nn.Parameter(
@@ -593,6 +608,18 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
.repeat_interleave(block_k // 32, dim=1)
)
originals.append((linear.weight.view(torch.uint8).clone(), scale_1x32))
if packed:
linear.weight_scale_inv = torch.nn.Parameter(
deepgemm_post_process_weight_scale_block(
scale.data.cuda().unsqueeze(0),
*linear.weight.shape,
quant_block_shape=linear.weight_block_size,
num_groups=1,
)
.squeeze(0)
.cpu(),
requires_grad=False,
)
monkeypatch.setattr("vllm.utils.deep_gemm._import_deep_gemm", lambda: FakeDeepGemm)
original_gate_up_ptr = shared_experts.gate_up_proj.weight.data_ptr()
@@ -644,6 +671,10 @@ def test_deepseek_v4_mega_moe_does_not_double_add_fused_shared_expert(
class FakeExperts(torch.nn.Module):
has_fused_shared_experts = fused
_backend = DeepGemmSm100MegaMoEBackend()
def _ensure_backend(self):
return self._backend
def forward(self, hidden_states, *args, **kwargs):
return torch.ones_like(hidden_states)
+3 -1
View File
@@ -7,7 +7,7 @@ import pytest
import torch
from torch import nn
from vllm.config import ParallelConfig
from vllm.config import KernelConfig, ParallelConfig
from vllm.model_executor.models.utils import WeightsMapper
from vllm.platforms import current_platform
@@ -58,6 +58,7 @@ def test_rocm_moe_routing_and_shared_experts_match_reference(
model_config=SimpleNamespace(hf_config=config),
quant_config=None,
parallel_config=ParallelConfig(),
kernel_config=default_vllm_config.kernel_config,
),
prefix="model.layers.0.ffn",
)
@@ -230,6 +231,7 @@ def test_rocm_moe_wires_vision_routing_on_hash_and_regular_layers(
model_config=SimpleNamespace(hf_config=config),
quant_config=None,
parallel_config=ParallelConfig(),
kernel_config=KernelConfig(),
)
hash_moe = rocm_model.DeepseekV4MoE(vllm_config, prefix="model.layers.0.ffn")
+34
View File
@@ -85,6 +85,7 @@ def test_dspark_markov_head_is_replicated(
assert head.markov_w2.tp_size == 1
assert head.markov_w1.weight.shape == (128, 8)
assert head.markov_w2.weight.shape == (128, 8)
head.markov_w2.quant_method.process_weights_after_loading(head.markov_w2)
def fail_collective(*args, **kwargs):
raise AssertionError("replicated Markov head must not invoke TP collectives")
@@ -335,3 +336,36 @@ def test_dsv4_context_kv_uses_one_stacked_wkv_projection(monkeypatch):
assert torch.equal(calls[1][1], stacked_output.view(2, 3, 4)[:, 2] + 2)
assert calls[0][3] is slot_mappings[0]
assert calls[1][3] is slot_mappings[2]
@pytest.mark.cpu_test
def test_k3_dspark_mla_kv_cache_spec_groups_with_target_mla():
"""The draft's MLA layers must share a KV cache group with the target's."""
from vllm.model_executor.layers.attention.mla_attention import MLAAttention
from vllm.models.kimi_k3.nvidia.mla import MultiHeadLatentAttention
from vllm.v1.core.kv_cache_utils import _get_kv_cache_groups_uniform_page_size
vllm_config = SimpleNamespace(
model_config=None, cache_config=SimpleNamespace(block_size=64)
)
target_attn = SimpleNamespace(
kv_cache_dtype="fp8",
head_size=576,
sliding_window=None,
indexer=None,
non_causal_multi_token_decode=False,
attn_backend=SimpleNamespace(get_name=lambda: "ROCM_AITER_MLA"),
_uses_flat_kv_cache=lambda: False,
)
draft_attn = SimpleNamespace(
kv_cache_dtype="fp8", head_size=576, non_causal_multi_token_decode=True
)
target_spec = MLAAttention.get_kv_cache_spec(target_attn, vllm_config)
draft_spec = MultiHeadLatentAttention.get_kv_cache_spec(draft_attn, vllm_config)
kv_cache_spec = {f"model.layers.{i}.attn": target_spec for i in range(24)}
kv_cache_spec |= {f"draft.layers.{i}.attn": draft_spec for i in range(5)}
groups = _get_kv_cache_groups_uniform_page_size(kv_cache_spec)
assert len(groups) == 1
assert len(groups[0].layer_names) == 29
@@ -7,6 +7,9 @@
is set and the symbol exists, and otherwise falls back to
`vllm.model_executor.layers.<module>`. These tests pin that contract and the
logging that reports which source was used.
CPU-only: no engine is built. The end-to-end counterpart that serves a model
through `vllm_runner` lives in `test_layer_registry_e2e.py` (GPU job).
"""
import logging
@@ -14,7 +17,6 @@ import sys
import types
import pytest
import torch
from vllm.model_executor.models.transformers import layers
@@ -42,16 +44,16 @@ def test_falls_back_to_vllm_when_disabled(monkeypatch, fake_hw_layernorm):
assert layers._resolve("layernorm", "RMSNorm") is VllmRMSNorm
def test_uses_hw_agnostic_when_enabled(monkeypatch, fake_hw_layernorm, caplog):
def test_uses_hw_agnostic_when_enabled(monkeypatch, fake_hw_layernorm, caplog_vllm):
"""Enabled and available: the hw-agnostic class is used and logged."""
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "1")
with caplog.at_level(logging.INFO):
with caplog_vllm.at_level(logging.INFO):
resolved = layers._resolve("layernorm", "RMSNorm")
assert resolved is fake_hw_layernorm.RMSNorm
assert "Using hw-agnostic layer: RMSNorm" in caplog.text
assert "Using hw-agnostic layer: RMSNorm" in caplog_vllm.text
def test_falls_back_when_symbol_missing(monkeypatch, caplog):
def test_falls_back_when_symbol_missing(monkeypatch, caplog_vllm):
"""Enabled but the symbol is not ported: fall back to vLLM and warn."""
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "1")
# A hw-agnostic module without the requested attribute triggers fallback.
@@ -59,10 +61,10 @@ def test_falls_back_when_symbol_missing(monkeypatch, caplog):
monkeypatch.setitem(sys.modules, HW_MODULE, empty)
from vllm.model_executor.layers.layernorm import RMSNorm as VllmRMSNorm
with caplog.at_level(logging.WARNING):
with caplog_vllm.at_level(logging.WARNING):
resolved = layers._resolve("layernorm", "RMSNorm")
assert resolved is VllmRMSNorm
assert "falling back to default" in caplog.text
assert "falling back to default" in caplog_vllm.text
def test_act_and_mul_falls_back_for_unknown_activation(
@@ -76,102 +78,3 @@ def test_act_and_mul_falls_back_for_unknown_activation(
from vllm.model_executor.layers.activation import GeluAndMul
assert isinstance(layers.get_act_and_mul_fn("gelu"), GeluAndMul)
@pytest.fixture(scope="module")
def tiny_llama_path(tmp_path_factory):
"""A randomly-initialized microscopic Llama saved to disk (with an ungated
tokenizer) so vLLM can load it like any local checkpoint."""
from transformers import AutoTokenizer, LlamaConfig, LlamaForCausalLM
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
config = LlamaConfig(
vocab_size=tokenizer.vocab_size,
hidden_size=128,
intermediate_size=256,
num_hidden_layers=2,
num_attention_heads=4,
rms_norm_eps=1e-6,
hidden_act="silu",
)
torch.manual_seed(0)
model = LlamaForCausalLM(config)
path = tmp_path_factory.mktemp("tiny_llama")
model.save_pretrained(path)
tokenizer.save_pretrained(path)
return str(path)
# Registered names of the layers the backend can
# currently route to hw-agnostic implementations.
_COVERED_LAYERS = ("rms_norm", "silu_and_mul")
def _layer_providers(model) -> dict[str, str]:
"""Map each covered layer type present in the model to the provider its
implementation came from (``hw_agnostic`` or ``vllm``).
"""
def provider_of(module) -> str | None:
for cls in type(module).__mro__:
if "hw_agnostic.layers" in cls.__module__:
return "hw_agnostic"
if ".model_executor.layers." in cls.__module__:
return "vllm"
return None
providers: dict[str, str] = {}
for module in model.modules():
name = getattr(module, "name", None)
if (
name in _COVERED_LAYERS
and name not in providers
and (prov := provider_of(module)) is not None
):
providers[name] = prov
return providers
def _serve(vllm_runner, model_path, prompts):
"""Serve the model through the backend; return (layer_providers, logprobs)."""
with vllm_runner(
model_path,
model_impl="transformers",
max_model_len=64,
enforce_eager=True,
gpu_memory_utilization=0.3,
) as runner:
assert runner.llm.llm_engine.model_config.using_transformers_backend()
providers = runner.apply_model(_layer_providers)[0]
outputs = runner.generate_greedy_logprobs(
prompts, max_tokens=32, num_logprobs=5
)
return providers, outputs
def test_hw_agnostic_matches_vllm_end_to_end(monkeypatch, vllm_runner, tiny_llama_path):
"""Serving the tiny model with hw-agnostic layers matches the vLLM baseline."""
# spawn: worker re-imports layers with the env set (see docstring).
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# apply_model pickles the introspection function.
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
from ..utils import check_logprobs_close
prompts = ["The capital of France is", "vLLM is"]
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "0")
vllm_providers, vllm_outputs = _serve(vllm_runner, tiny_llama_path, prompts)
# Both replaceable layers present in a Llama block must be vLLM's here.
assert vllm_providers == {"rms_norm": "vllm", "silu_and_mul": "vllm"}
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "1")
hw_providers, hw_outputs = _serve(vllm_runner, tiny_llama_path, prompts)
assert hw_providers == {"rms_norm": "hw_agnostic", "silu_and_mul": "hw_agnostic"}
check_logprobs_close(
outputs_0_lst=vllm_outputs,
outputs_1_lst=hw_outputs,
name_0="vllm",
name_1="hw_agnostic",
)
@@ -0,0 +1,113 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""End-to-end check of the Transformers backend's hw-agnostic layers.
Serves a tiny Llama through `vllm_runner` with and without
`VLLM_USE_HW_AGNOSTIC` and checks the layer providers and logprobs. Needs a
real engine, so it runs in the GPU job. The CPU-only unit tests for the
resolution logic (`layers._resolve`) are in `test_layer_registry.py`.
"""
import pytest
import torch
@pytest.fixture(scope="module")
def tiny_llama_path(tmp_path_factory):
"""A randomly-initialized microscopic Llama saved to disk (with an ungated
tokenizer) so vLLM can load it like any local checkpoint."""
from transformers import AutoTokenizer, LlamaConfig, LlamaForCausalLM
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
config = LlamaConfig(
vocab_size=tokenizer.vocab_size,
hidden_size=128,
intermediate_size=256,
num_hidden_layers=2,
num_attention_heads=4,
rms_norm_eps=1e-6,
hidden_act="silu",
)
torch.manual_seed(0)
model = LlamaForCausalLM(config)
path = tmp_path_factory.mktemp("tiny_llama")
model.save_pretrained(path)
tokenizer.save_pretrained(path)
return str(path)
# Registered names of the layers the backend can
# currently route to hw-agnostic implementations.
_COVERED_LAYERS = ("rms_norm", "silu_and_mul")
def _layer_providers(model) -> dict[str, str]:
"""Map each covered layer type present in the model to the provider its
implementation came from (``hw_agnostic`` or ``vllm``).
"""
def provider_of(module) -> str | None:
for cls in type(module).__mro__:
if "hw_agnostic.layers" in cls.__module__:
return "hw_agnostic"
if ".model_executor.layers." in cls.__module__:
return "vllm"
return None
providers: dict[str, str] = {}
for module in model.modules():
name = getattr(module, "name", None)
if (
name in _COVERED_LAYERS
and name not in providers
and (prov := provider_of(module)) is not None
):
providers[name] = prov
return providers
def _serve(vllm_runner, model_path, prompts):
"""Serve the model through the backend; return (layer_providers, logprobs)."""
with vllm_runner(
model_path,
model_impl="transformers",
max_model_len=64,
enforce_eager=True,
gpu_memory_utilization=0.3,
) as runner:
assert runner.llm.llm_engine.model_config.using_transformers_backend()
providers = runner.apply_model(_layer_providers)[0]
outputs = runner.generate_greedy_logprobs(
prompts, max_tokens=32, num_logprobs=5
)
return providers, outputs
def test_hw_agnostic_matches_vllm_end_to_end(monkeypatch, vllm_runner, tiny_llama_path):
"""Serving the tiny model with hw-agnostic layers matches the vLLM baseline."""
# spawn: `layers` resolves its symbols at import time, so the worker must
# re-import it with VLLM_USE_HW_AGNOSTIC already set (fork would inherit
# the parent's already-resolved module).
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# apply_model pickles the introspection function.
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
from ..utils import check_logprobs_close
prompts = ["The capital of France is", "vLLM is"]
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "0")
vllm_providers, vllm_outputs = _serve(vllm_runner, tiny_llama_path, prompts)
# Both replaceable layers present in a Llama block must be vLLM's here.
assert vllm_providers == {"rms_norm": "vllm", "silu_and_mul": "vllm"}
monkeypatch.setenv("VLLM_USE_HW_AGNOSTIC", "1")
hw_providers, hw_outputs = _serve(vllm_runner, tiny_llama_path, prompts)
assert hw_providers == {"rms_norm": "hw_agnostic", "silu_and_mul": "hw_agnostic"}
check_logprobs_close(
outputs_0_lst=vllm_outputs,
outputs_1_lst=hw_outputs,
name_0="vllm",
name_1="hw_agnostic",
)