Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-20 09:27:57 +09:00
682 changed files with 26127 additions and 5580 deletions
@@ -11,8 +11,6 @@ from unittest.mock import Mock
import pytest
import torch
from packaging.version import Version
from transformers import __version__ as TRANSFORMERS_VERSION
import vllm.envs as envs
from vllm import LLM
@@ -149,15 +147,6 @@ def test_models(
if enable_prompt_embeds:
with torch.no_grad():
prompt_embeds = hf_model.get_prompt_embeddings(example_prompts)
if model == "hmellor/tiny-random-Gemma2ForCausalLM" and (
Version(TRANSFORMERS_VERSION) < Version("5.3.0.dev0")
):
# For Gemma 1/2 models with Transformers 5.4.0+, the prompt embeddings
# are normalised in `get_prompt_embeddings`, like Gemma 3.
# For older versions, we need to manually normalise.
embed_scale = hf_model.config.hidden_size**0.5
normalizer = torch.tensor(embed_scale, dtype=prompt_embeds[0].dtype)
prompt_embeds = [p_e * normalizer for p_e in prompt_embeds]
with VllmRunner(
model,
+94
View File
@@ -109,6 +109,100 @@ def test_basic_cumem():
assert torch.allclose(output, torch.ones_like(output) * 3)
@pytest.mark.parametrize("full_sleep", [0, 1, 2], ids=["kv-only", "sleep-1", "sleep-2"])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_release_kv_cache_memory_preserves_generation(full_sleep, monkeypatch):
"""Rejected release and KV-only/full sleep cycles preserve greedy tokens."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
kv_cache_memory_bytes = 256 * 1024 * 1024
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=kv_cache_memory_bytes,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes_by_tag(worker):
allocator = get_mem_allocator_instance()
mapped_bytes = mapped_usage(allocator)
kv_cache_bytes = sum(
data.handle[1]
for data in allocator.pointer_to_data.values()
if data.tag == "kv_cache" and not data.is_asleep
)
return mapped_bytes, kv_cache_bytes
mapped_before, kv_cache_before = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
# Utility RPC transports the engine error as a plain Exception.
with pytest.raises(Exception, match="requires a completed pause"):
llm.release_kv_cache_memory()
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
assert llm.generate(prompt, sampling_params)[0].outputs[0].token_ids == expected
llm.sleep(level=0)
llm.release_kv_cache_memory()
mapped_after, kv_cache_after = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
assert kv_cache_before > 0
assert kv_cache_after == 0
assert mapped_before - mapped_after >= kv_cache_before
assert mapped_after > 0
assert llm.llm_engine.is_sleeping()
if full_sleep:
llm.sleep(level=full_sleep)
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == 0
llm.wake_up(tags=None if full_sleep else ["kv_cache"])
if full_sleep == 2:
llm.collective_rpc("reload_weights")
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@pytest.mark.parametrize("first_level", [1, 2])
@pytest.mark.parametrize("second_level", [1, 2])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_sleep_with_only_weights_asleep(first_level, second_level, monkeypatch):
"""Repeated sleep after KV-only wake preserves mappings and recoverability."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=256 * 1024 * 1024,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes(worker):
return mapped_usage(get_mem_allocator_instance())
llm.sleep(level=first_level)
llm.wake_up(tags=["kv_cache"])
mapped_before = llm.collective_rpc(get_mapped_bytes)[0]
assert mapped_before > 0
llm.sleep(level=second_level)
assert llm.collective_rpc(get_mapped_bytes)[0] == mapped_before
llm.wake_up(tags=["weights"])
if first_level == 2:
llm.collective_rpc("reload_weights")
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_discard_tags():
"""Test that discard(tags) selectively frees GPU memory for specific
+19
View File
@@ -541,6 +541,25 @@ def _mock_config_for_cudagraph_sizes(
return config
@pytest.mark.parametrize("max_num_seqs", [100, 101])
def test_default_cudagraph_capture_sizes_cover_off_stride_max_num_seqs(
max_num_seqs: int,
) -> None:
compilation_config = CompilationConfig(
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE
)
config = _mock_config_for_cudagraph_sizes(
max_num_seqs=max_num_seqs,
num_speculative_tokens=0,
max_num_batched_tokens=32768,
compilation_config=compilation_config,
)
VllmConfig._set_cudagraph_sizes(config)
assert max_num_seqs in compilation_config.cudagraph_capture_sizes
@pytest.mark.parametrize(
("max_num_seqs", "num_speculative_tokens", "widest_is_captured"),
[
+1 -1
View File
@@ -241,7 +241,7 @@ def dist_init():
rank=0,
distributed_init_method=f"file://{temp_file}",
local_rank=0,
backend="nccl",
backend="gloo" if current_platform.is_cpu() else "nccl",
)
initialize_model_parallel(1, 1)
yield
+4
View File
@@ -91,8 +91,11 @@ class MockSubscriber:
if isinstance(replay_endpoints, str):
replay_endpoints = [replay_endpoints]
ipv6 = any("[" in ep for ep in pub_endpoints + (replay_endpoints or []))
# Set up subscriber socket - connect to all endpoints
self.sub = self.ctx.socket(zmq.SUB)
self.sub.setsockopt(zmq.IPV6, ipv6)
self.sub.setsockopt(zmq.SUBSCRIBE, topic.encode("utf-8"))
for endpoint in pub_endpoints:
self.sub.connect(endpoint)
@@ -103,6 +106,7 @@ class MockSubscriber:
if replay_endpoints:
for replay_endpoint in replay_endpoints:
replay = self.ctx.socket(zmq.DEALER)
replay.setsockopt(zmq.IPV6, ipv6)
replay.connect(replay_endpoint)
self.replay_sockets.append(replay)
+74
View File
@@ -332,3 +332,77 @@ def test_event_publisher_factory(random_port):
publisher = EventPublisherFactory.create(config, DP_RANK)
assert isinstance(publisher, ZmqEventPublisher)
publisher.shutdown()
@pytest.mark.parametrize(
("endpoint", "expected"),
[("tcp://*:5557", "tcp://*:5558"), ("tcp://*:0", "tcp://*:0")],
)
def test_offset_endpoint_port_keeps_port_zero(endpoint, expected):
"""Port 0 is not offset: every rank asks the OS for its own port."""
from vllm.distributed.kv_events import ZmqEventPublisher
assert ZmqEventPublisher.offset_endpoint_port(endpoint, 1) == expected
@pytest.mark.parametrize("node_ip", ["127.0.0.1", "::1"])
def test_ephemeral_publishers_report_bound_endpoints(monkeypatch, node_ip):
"""Two ranks binding tcp://*:0 get distinct OS-assigned ports on this
node's IP and report endpoints a subscriber can use for events and replay."""
from vllm.config.kv_events import KVEventsConfig
from vllm.distributed import kv_events
from vllm.utils.network_utils import split_zmq_path
from .conftest import MockSubscriber
monkeypatch.setattr(kv_events, "get_ip", lambda: node_ip)
config = KVEventsConfig(
enable_kv_cache_events=True,
publisher="zmq",
endpoint="tcp://*:0",
replay_endpoint="tcp://*:0",
topic="kv",
)
pubs = [EventPublisherFactory.create(config, rank) for rank in range(2)]
try:
resolved = [pub.get_publisher_config() for pub in pubs]
endpoints = [e for c in resolved for e in (c.endpoint, c.replay_endpoint)]
hosts_ports = {split_zmq_path(e)[1:] for e in endpoints}
assert {h for h, _ in hosts_ports} == {node_ip}
assert len(hosts_ports) == 4 and "0" not in {p for _, p in hosts_ports}
assert config.endpoint == "tcp://*:0"
sub = MockSubscriber(endpoints[::2], endpoints[1::2], topic="kv")
try:
# PUB/SUB drops messages sent before the subscription lands, so
# keep publishing until both ranks are heard.
ranks: set[int] = set()
deadline = time.time() + 10
while ranks != {0, 1} and time.time() < deadline:
for pub in pubs:
pub.publish(create_test_events(1))
while (result := sub.receive_one(timeout=100)) is not None:
ranks.add(result[1].data_parallel_rank)
assert ranks == {0, 1}
sub.request_replay(0, socket_idx=1)
assert sub.receive_replay(socket_idx=1)
finally:
sub.close()
finally:
for pub in pubs:
pub.shutdown()
@pytest.mark.parametrize("node_ip", ["0.0.0.0", "::"])
def test_ephemeral_bind_needs_a_node_ip(monkeypatch, node_ip):
"""tcp://*:0 is advertised as this node's IP; with no usable IP the
publisher refuses instead of reporting a wildcard."""
from vllm.config.kv_events import KVEventsConfig
from vllm.distributed import kv_events
monkeypatch.setattr(kv_events, "get_ip", lambda: node_ip)
config = KVEventsConfig(
enable_kv_cache_events=True, publisher="zmq", endpoint="tcp://*:0"
)
with pytest.raises(ValueError, match="VLLM_HOST_IP"):
EventPublisherFactory.create(config, DP_RANK)
+172
View File
@@ -3,12 +3,17 @@
import multiprocessing
import random
import sys
import types
from types import SimpleNamespace
import pytest
import ray
import torch
import torch.distributed as dist
import vllm._aiter_ops as aiter_ops
import vllm.distributed as vllm_distributed
import vllm.envs as envs
from vllm import _custom_ops as ops
from vllm.distributed.communication_op import tensor_model_parallel_all_reduce # noqa
@@ -233,6 +238,173 @@ def test_quick_allreduce_passes_dynamic_quant_level(
assert called_quant_level == QuickReduceRegime.FP.value
def test_rocm_aiter_fused_rmsnorm_uses_aiter_qr_rmsnorm_for_prefill(
monkeypatch: pytest.MonkeyPatch,
):
class FakeAiterAllReduce:
aiter_ca = SimpleNamespace(world_size=2, fully_connected=True)
def use_1stage_fused_ar_rms(self, inp):
return False
def custom_fused_ar_rms(self, *args, **kwargs):
raise AssertionError("expected fused QR+RMSNorm dispatch")
class FakeQuickReduce:
disabled = False
def __init__(self):
self.checked_input = None
def should_quick_allreduce(self, inp):
self.checked_input = inp
return True
def _get_qr_quant_level(self, inp):
return QuickReduceRegime.INT4.value
qr_comm = FakeQuickReduce()
device_comm = SimpleNamespace(cpu_group=object(), qr_comm=qr_comm)
monkeypatch.setattr(
vllm_distributed,
"get_tp_group",
lambda: SimpleNamespace(device_communicator=device_comm),
)
monkeypatch.setattr(
aiter_ops.rocm_aiter_ops,
"get_aiter_allreduce",
lambda: FakeAiterAllReduce(),
)
monkeypatch.setattr(aiter_ops.dist, "get_world_size", lambda group: 2)
monkeypatch.setattr(aiter_ops.dist, "get_rank", lambda group: 0)
monkeypatch.setattr(
aiter_ops.dist,
"all_gather_object",
lambda handles, handle, group: handles.__setitem__(0, handle),
)
calls = []
fake_aiter = types.SimpleNamespace(
init_custom_qr=lambda rank, world_size, qr_max_size: 123,
qr_get_handle=lambda ptr: b"handle",
qr_open_handles=lambda ptr, handles: None,
)
def fake_qr_all_reduce_rmsnorm(
ptr,
inp,
residual,
residual_out,
out,
weight,
eps,
hidden_dim,
quant_level,
cast_bf2half,
):
calls.append(
{
"ptr": ptr,
"inp": inp,
"residual": residual,
"residual_out": residual_out,
"out": out,
"weight": weight,
"eps": eps,
"hidden_dim": hidden_dim,
"quant_level": quant_level,
"cast_bf2half": cast_bf2half,
}
)
out.copy_(inp)
residual_out.copy_(residual)
fake_aiter.qr_all_reduce_rmsnorm = fake_qr_all_reduce_rmsnorm
monkeypatch.setitem(sys.modules, "aiter", fake_aiter)
monkeypatch.setattr(envs, "VLLM_ROCM_QUICK_REDUCE_MAX_SIZE_BYTES_MB", None)
monkeypatch.setattr(envs, "VLLM_ROCM_QUICK_REDUCE_CAST_BF16_TO_FP16", True)
# token_num > 80 forces vLLM's AITER fused AR+RMS wrapper onto its
# non-1stage prefill path. hidden_dim=4096 bf16 gives an 8 KiB row, so four
# independent RMSNorm rows fit in one 32 KiB QR tile.
inp = torch.randn(81, 4096, dtype=torch.bfloat16)
residual = torch.randn_like(inp)
weight = torch.randn(4096, dtype=torch.bfloat16)
out, residual_out = aiter_ops._rocm_aiter_fused_allreduce_rmsnorm_impl(
inp, residual, weight, 1e-6
)
assert qr_comm.checked_input is inp
assert len(calls) == 1
assert calls[0]["ptr"] == 123
assert calls[0]["inp"] is inp
assert calls[0]["residual"] is residual
assert calls[0]["out"] is out
assert calls[0]["residual_out"] is residual_out
assert calls[0]["weight"] is weight
assert calls[0]["hidden_dim"] == 4096
assert calls[0]["quant_level"] == QuickReduceRegime.INT4.value
assert calls[0]["cast_bf2half"] is True
torch.testing.assert_close(out, inp)
torch.testing.assert_close(residual_out, residual)
def test_rocm_aiter_fused_rmsnorm_keeps_1stage_decode_path(
monkeypatch: pytest.MonkeyPatch,
):
calls = []
class FakeAiterCA:
world_size = 2
fully_connected = True
def custom_fused_ar_rms(
self, inp, residual, weight, epsilon, *, use_1stage, gemma_norm
):
calls.append(
{
"inp": inp,
"residual": residual,
"weight": weight,
"eps": epsilon,
"use_1stage": use_1stage,
"gemma_norm": gemma_norm,
}
)
return inp + 1, residual + 1
class FakeAiterAllReduce:
aiter_ca = FakeAiterCA()
def use_1stage_fused_ar_rms(self, inp):
return True
monkeypatch.setattr(
aiter_ops.rocm_aiter_ops,
"get_aiter_allreduce",
lambda: FakeAiterAllReduce(),
)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
inp = torch.randn(4, 4096, dtype=torch.bfloat16)
residual = torch.randn_like(inp)
weight = torch.randn(4096, dtype=torch.bfloat16)
out, residual_out = aiter_ops._rocm_aiter_fused_allreduce_rmsnorm_impl(
inp, residual, weight, 1e-6
)
assert len(calls) == 1
assert calls[0]["inp"] is inp
assert calls[0]["residual"] is residual
assert calls[0]["weight"] is weight
assert calls[0]["use_1stage"] is True
assert calls[0]["gemma_norm"] is False
torch.testing.assert_close(out, inp + 1)
torch.testing.assert_close(residual_out, residual + 1)
@ray.remote(num_gpus=1, max_calls=1)
def graph_quickreduce(
monkeypatch: pytest.MonkeyPatch,
@@ -27,31 +27,10 @@ ROCM_ATTN_BACKENDS = [
ATTN_BACKENDS = ROCM_ATTN_BACKENDS if current_platform.is_rocm() else ["auto"]
# Per-backend tolerance with explicit entries; "default" is the fallback
BACKEND_TOL: dict[str, float] = {
"default": 0.05, # 5% tolerance for other backends (e.g. FLASH_ATTN)
# Relaxed tolerances for ROCm attn
# See: https://github.com/vllm-project/vllm/issues/35569
"ROCM_ATTN": 0.09, # gfx950:~8.45%, gfx942:~3.70%
"ROCM_AITER_FA": 0.045, # gfx950:~2.00%, gfx942:~0.80%
"TRITON_ATTN": 0.045, # gfx950:~3.00%, gfx942:~2.20%
"FLEX_ATTENTION": 0.045, # gfx950:~3.25%, gfx942:~1.10%
}
# Some ROCm attention backends show small absolute drift on the low
# text-vs-text probability even though larger scores remain well inside the
# relative tolerance. The absolute drift is uniform across score magnitudes
# (~0.005-0.010), so it only exceeds the relative tolerance for the small
# ~0.10 text-vs-text value. Keep the relative tolerances tight and add only a
# small absolute floor for the affected backends.
# TRITON_ATTN: gfx942/ROCm 7.2 drifts ~0.008 abs on text-vs-text (~7.9% rel).
BACKEND_ABS_TOL: dict[str, float] = {
"default": 0.0,
"auto": 0.007,
"ROCM_AITER_FA": 0.005,
"TRITON_ATTN": 0.009,
"FLEX_ATTENTION": 0.00875,
}
# The absolute floor matters only for the low ~0.10 text-vs-text score, where a
# few thousandths of drift would otherwise exceed the relative bound.
REL_TOL = 0.05
ABS_TOL = 0.007
# ROCm: disable prefix caching and eliminate batch variance to reduce
# test flakiness.
@@ -62,17 +41,9 @@ ROCM_EXTRA_ARGS = (
)
def get_tol(backend: str) -> float:
return BACKEND_TOL.get(backend, BACKEND_TOL["default"])
def get_abs_tol(backend: str) -> float:
return BACKEND_ABS_TOL.get(backend, BACKEND_ABS_TOL["default"])
def assert_score(actual: float, expected: float, backend: str, label: str):
tol = get_tol(backend)
abs_tol = get_abs_tol(backend)
tol = REL_TOL
abs_tol = ABS_TOL
diff = abs(actual - expected)
rel_diff = diff / abs(expected) if expected != 0 else diff
print(
@@ -104,9 +75,16 @@ documents = [
},
]
TEXT_VS_TEXT = 0.10040374100208282
TEXT_VS_IMAGE = 0.7423753142356873
TEXT_VS_TEXT_PLUS_IMAGE = 0.5298863053321838
# One bf16 ULP in attention compounds to ~0.1% here, so ROCm backends each
# settle differently; these are their midpoint across backends and archs.
if current_platform.is_rocm():
TEXT_VS_TEXT = 0.105243
TEXT_VS_IMAGE = 0.742472
TEXT_VS_TEXT_PLUS_IMAGE = 0.544568
else:
TEXT_VS_TEXT = 0.10040374100208282
TEXT_VS_IMAGE = 0.7423753142356873
TEXT_VS_TEXT_PLUS_IMAGE = 0.5298863053321838
@pytest.fixture(scope="module", params=ATTN_BACKENDS)
@@ -507,6 +485,4 @@ async def test_rerank_api_instruction_field_matches_chat_template_kwargs(
kwargs_scores = [
r.relevance_score for r in sorted(kwargs_rerank.results, key=lambda x: x.index)
]
assert field_scores == pytest.approx(
kwargs_scores, rel=get_tol(backend), abs=get_abs_tol(backend)
)
assert field_scores == pytest.approx(kwargs_scores, rel=REL_TOL, abs=ABS_TOL)
@@ -800,7 +800,12 @@ def _e2e_generate_response(
@pytest.mark.asyncio
async def test_e2e_plain_roundtrip(parser_client, parser_tokenizer):
"""Plain text without reasoning markers roundtrips correctly."""
"""Plain text without reasoning markers roundtrips correctly.
Markerless output has no ``</think>``, which deepseek_r1 classifies
wholly as reasoning, so the text lands there rather than in content.
What this pins is detokenization fidelity through the parser path.
"""
messages = [{"role": "user", "content": "What is 2+2?"}]
gen_req = await _e2e_render_chat(parser_client, PARSER_MODEL, messages)
@@ -814,16 +819,22 @@ async def test_e2e_plain_roundtrip(parser_client, parser_tokenizer):
"model": PARSER_MODEL,
"generate_response": _e2e_generate_response(output_ids),
"prompt_tokens": len(gen_req["token_ids"]),
"chat_request": {"model": PARSER_MODEL, "messages": messages},
},
)
assert resp.status_code == 200, resp.text
content = resp.json()["choices"][0]["message"]["content"]
assert content == expected
message = resp.json()["choices"][0]["message"]
assert message["reasoning"] == expected
assert message["content"] is None
@pytest.mark.asyncio
async def test_e2e_token_identity(parser_client, parser_tokenizer):
"""encode(derender(token_ids)) == token_ids (RL invariant)."""
"""encode(derender(token_ids)) == token_ids (RL invariant).
Markerless output comes back as reasoning (see
``test_e2e_plain_roundtrip``), so re-encode that.
"""
messages = [{"role": "user", "content": "Hi"}]
gen_req = await _e2e_render_chat(parser_client, PARSER_MODEL, messages)
@@ -836,17 +847,22 @@ async def test_e2e_token_identity(parser_client, parser_tokenizer):
"model": PARSER_MODEL,
"generate_response": _e2e_generate_response(output_ids),
"prompt_tokens": len(gen_req["token_ids"]),
"chat_request": {"model": PARSER_MODEL, "messages": messages},
},
)
assert resp.status_code == 200
content = resp.json()["choices"][0]["message"]["content"]
re_encoded = _encode(parser_tokenizer, content)
reasoning = resp.json()["choices"][0]["message"]["reasoning"]
re_encoded = _encode(parser_tokenizer, reasoning)
assert output_ids == re_encoded
@pytest.mark.asyncio
async def test_e2e_non_ascii_roundtrip(parser_client, parser_tokenizer):
"""CJK + emoji roundtrip without U+FFFD."""
"""CJK + emoji roundtrip without U+FFFD.
Markerless output comes back as reasoning (see
``test_e2e_plain_roundtrip``).
"""
messages = [{"role": "user", "content": "Reply in Chinese"}]
gen_req = await _e2e_render_chat(parser_client, PARSER_MODEL, messages)
@@ -859,11 +875,12 @@ async def test_e2e_non_ascii_roundtrip(parser_client, parser_tokenizer):
"model": PARSER_MODEL,
"generate_response": _e2e_generate_response(output_ids),
"prompt_tokens": len(gen_req["token_ids"]),
"chat_request": {"model": PARSER_MODEL, "messages": messages},
},
)
assert resp.status_code == 200
content = resp.json()["choices"][0]["message"]["content"]
assert "�" not in content
reasoning = resp.json()["choices"][0]["message"]["reasoning"]
assert "�" not in reasoning
@pytest.mark.asyncio
@@ -976,8 +993,10 @@ async def test_e2e_parsed_reasoning_and_tool_call(parser_client, parser_tokenize
@pytest.mark.asyncio
async def test_e2e_no_chat_request_fallback(parser_client, parser_tokenizer):
"""Without chat_request, derender falls back to plain detokenization."""
async def test_e2e_no_chat_request_rejected(parser_client, parser_tokenizer):
"""Without chat_request a parser configured model rejects with 400
rather than silently falling back to plain detokenization. This is to
prevent the leak of raw reasoning/tool markup into content."""
messages = [{"role": "user", "content": "Hello"}]
gen_req = await _e2e_render_chat(parser_client, PARSER_MODEL, messages)
@@ -992,9 +1011,8 @@ async def test_e2e_no_chat_request_fallback(parser_client, parser_tokenizer):
"prompt_tokens": len(gen_req["token_ids"]),
},
)
assert resp.status_code == 200
content = resp.json()["choices"][0]["message"]["content"]
assert "Hi" in content
assert resp.status_code == 400
assert "chat_request" in resp.json()["error"]["message"]
# ---------------------------------------------------------------------------
File diff suppressed because it is too large Load Diff
@@ -594,176 +594,6 @@ async def test_completion_render_multiple_prompts_token_offsets(client):
assert 0 <= start <= end <= len(prompt)
@pytest.mark.asyncio
async def test_chat_completion_render_assistant_tokens_mask_default(client):
"""Without return_assistant_tokens_mask, assistant_tokens_mask should be null."""
response = await client.post(
"/v1/chat/completions/render",
json={
"model": MODEL_NAME,
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi!"},
{"role": "user", "content": "How are you?"},
],
},
)
assert response.status_code == 200
data = response.json()
assert data.get("assistant_tokens_mask") is None
@pytest.mark.asyncio
async def test_chat_completion_render_assistant_tokens_mask_false(client):
"""Explicitly setting return_assistant_tokens_mask=false gives null."""
response = await client.post(
"/v1/chat/completions/render",
json={
"model": MODEL_NAME,
"messages": [
{"role": "user", "content": "Hello"},
],
"return_assistant_tokens_mask": False,
},
)
assert response.status_code == 200
data = response.json()
assert data.get("assistant_tokens_mask") is None
@pytest.mark.asyncio
async def test_chat_render_assistant_tokens_mask_null_without_gen_tags(
client,
):
"""The tiny test model lacks ``{% generation %}`` tags, so the mask is null."""
response = await client.post(
"/v1/chat/completions/render",
json={
"model": MODEL_NAME,
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi!"},
],
"return_assistant_tokens_mask": True,
},
)
assert response.status_code == 200
assert response.json().get("assistant_tokens_mask") is None
# A minimal chat template with {% generation %} tags so we can test that
# the mask correctly marks assistant tokens.
_TEMPLATE_WITH_GENERATION = (
"{% for m in messages %}"
"{% if m['role'] == 'user' %}User: {{ m['content'] }}\n"
"{% elif m['role'] == 'assistant' %}"
"{% generation %}Assistant: {{ m['content'] }}\n{% endgeneration %}"
"{% endif %}"
"{% endfor %}"
)
@pytest.mark.asyncio
async def test_chat_completion_render_assistant_tokens_mask_with_generation_tags(
client,
):
"""With a ``{% generation %}``-enabled template, the mask marks assistant
tokens and the masked tokens decode to the assistant content."""
response = await client.post(
"/v1/chat/completions/render",
json={
"model": MODEL_NAME,
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi!"},
{"role": "user", "content": "Bye"},
],
"chat_template": _TEMPLATE_WITH_GENERATION,
"return_assistant_tokens_mask": True,
},
)
assert response.status_code == 200
data = response.json()
mask = data["assistant_tokens_mask"]
token_ids = data["token_ids"]
assert mask is not None
assert isinstance(mask, list)
assert len(mask) == len(token_ids)
assert all(v in (0, 1) for v in mask)
assert sum(mask) > 0, "mask should mark at least one assistant token"
# Detokenize masked (assistant) and unmasked (non-assistant) tokens
# separately to verify the mask is correct, not just non-empty.
masked_ids = [t for t, m in zip(token_ids, mask, strict=True) if m]
unmasked_ids = [t for t, m in zip(token_ids, mask, strict=True) if not m]
detok = await client.post(
"/detokenize",
json={"model": MODEL_NAME, "tokens": masked_ids},
)
assert detok.status_code == 200
assert "Hi!" in detok.json()["prompt"]
detok_rest = await client.post(
"/detokenize",
json={"model": MODEL_NAME, "tokens": unmasked_ids},
)
assert detok_rest.status_code == 200
assert "Hi!" not in detok_rest.json()["prompt"]
assert "Bye" in detok_rest.json()["prompt"]
@pytest.mark.asyncio
async def test_chat_render_assistant_tokens_mask_follows_truncation(client):
"""The assistant mask must be truncated with the prompt it describes.
`assistant_tokens_mask` is positional: entry i labels token i. Truncating
`token_ids` from the left without truncating the mask leaves the two
describing different positions, and the mask ends up marking whichever
tokens happen to sit at the old offsets.
"""
messages = [
# Deliberately lopsided: a long leading user turn and a short trailing
# one, so keeping the head of the mask is distinguishable from keeping
# its tail.
{"role": "user", "content": "Hello hello hello hello hello hello"},
{"role": "assistant", "content": "Hi!"},
{"role": "user", "content": "Bye"},
]
body = {
"model": MODEL_NAME,
"messages": messages,
"chat_template": _TEMPLATE_WITH_GENERATION,
"return_assistant_tokens_mask": True,
}
full = await client.post("/v1/chat/completions/render", json=body)
assert full.status_code == 200
full_token_ids = full.json()["token_ids"]
full_mask = full.json()["assistant_tokens_mask"]
assert sum(full_mask) > 0
keep = len(full_token_ids) - 4
# Precondition: with this prompt the head and tail slices of the mask
# really do differ, so the assertion below can tell them apart.
assert full_mask[-keep:] != full_mask[:keep]
truncated = await client.post(
"/v1/chat/completions/render",
json={**body, "truncate_prompt_tokens": keep, "truncation_side": "left"},
)
assert truncated.status_code == 200
data = truncated.json()
assert data["token_ids"] == full_token_ids[-keep:]
assert data["assistant_tokens_mask"] == full_mask[-keep:]
@pytest.mark.asyncio
async def test_messages_render_basic(client):
"""Test basic Anthropic Messages render endpoint."""
@@ -569,40 +569,6 @@ async def test_stream_omits_prompt_metadata_by_default():
assert "mm_placeholders" not in chunk
@pytest.mark.asyncio
async def test_stream_chunks_omit_absent_fields():
"""Absent optional fields are omitted from stream chunks, like Rust."""
engine = _mock_engine()
async def mock_generate(*args, **kwargs):
yield _make_request_output("req-1", token_ids=[10])
yield _make_request_output(
"req-1", token_ids=[20], finish_reason="stop", finished=True
)
engine.generate = MagicMock(side_effect=mock_generate)
serving = _build_serving_tokens(engine)
request = GenerateRequest(
token_ids=[1, 2, 3],
sampling_params=SamplingParams(max_tokens=2),
model=MODEL_NAME,
stream=True,
)
response = await serving.serve_tokens(request)
parsed = _parse_sse_chunks([chunk async for chunk in response])
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
assert len(data_chunks) == 2
for chunk in data_chunks:
assert "usage" not in chunk
assert "prompt_token_ids" not in chunk
assert "mm_placeholders" not in chunk
assert "logprobs" not in chunk["choices"][0]
assert "finish_reason" not in data_chunks[0]["choices"][0]
assert data_chunks[1]["choices"][0]["finish_reason"] == "stop"
@pytest.mark.asyncio
async def test_stream_text_only_prompt_omits_mm_placeholders_key():
engine = _mock_engine()
@@ -422,6 +422,31 @@ async def test_stop_string_workflow(client, tokenizer, messages):
assert generate_res == completions_res
@pytest.mark.asyncio
@pytest.mark.skipif(
envs.VLLM_USE_RUST_FRONTEND,
reason="--tokens-only is not supported by the Rust frontend",
)
@pytest.mark.parametrize("server", [["--tokens-only"]], indirect=True)
async def test_stop_strings_rejected_when_tokens_only(client):
"""--tokens-only forces detokenize=False after request validation, so
stop strings must be rejected explicitly rather than silently ignored."""
sampling_params = {"max_tokens": 5, "stop": ["never"]}
payload = {
"model": MODEL_NAME,
"token_ids": [1, 2, 3],
"sampling_params": sampling_params,
"stream": False,
}
resp = await client.post(GEN_ENDPOINT, json=payload)
assert resp.status_code == 400
assert "stop strings" in resp.json()["error"]["message"]
sampling_params["stop"] = None
resp = await client.post(GEN_ENDPOINT, json=payload)
resp.raise_for_status()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"server",
+24 -1
View File
@@ -1,14 +1,37 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from unittest.mock import AsyncMock
import pytest
import requests
from fastapi import FastAPI
from fastapi.testclient import TestClient
from prometheus_client.parser import text_string_to_metric_families
from tests.utils import RemoteOpenAIServer
from vllm.entrypoints.serve.dev.sleep.api_router import attach_router
MODEL_NAME = "meta-llama/Llama-3.2-1B"
@pytest.mark.cpu_test
@pytest.mark.parametrize("fails", [False, True])
def test_release_kv_cache_memory_route(fails):
app = FastAPI()
app.state.engine_client = AsyncMock()
release = app.state.engine_client.release_kv_cache_memory
if fails:
release.side_effect = RuntimeError("requires a completed pause first")
attach_router(app)
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post("/release_kv_cache_memory")
assert response.status_code == (500 if fails else 200)
release.assert_awaited_once_with()
def test_sleep_mode():
# dtype, max-len etc set so that this can run in CI
args = [
@@ -63,7 +86,7 @@ def test_sleep_mode():
)
assert response.status_code == 200
# is sleeping should be false after waking up any part of the engine
# Partial wake keeps the engine sleeping.
response = requests.get(remote_server.url_for("is_sleeping"))
assert response.status_code == 200
assert response.json().get("is_sleeping") is True
@@ -3,6 +3,8 @@ accuracy_threshold: 0.90
num_questions: 1319
num_fewshot: 5
max_concurrency: 100
# 30B+ MoE with EP/PCP: download + kernel autotuning can exceed the 1200s default.
startup_max_wait_seconds: 2400
# Leave headroom for FlashInfer CUTLASS autotuning after KV-cache allocation.
server_args: >-
--compilation-config '{"cudagraph_mode":"NONE"}'
@@ -0,0 +1,5 @@
model_name: "Qwen/Qwen3-30B-A3B"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
server_args: "--enforce-eager --max-model-len 8192 --data-parallel-size 2 --enable-expert-parallel --all2all-backend=moonep"
@@ -2,6 +2,8 @@ model_name: "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
# 30B MoE + DeepGEMM/DeepEP JIT compile can exceed the 1200s default startup wait.
startup_max_wait_seconds: 2400
server_args: "--enforce-eager --max-model-len 8192 --data-parallel-size 2 --enable-expert-parallel --all2all-backend deepep_low_latency --disable-uvicorn-access-log"
env:
VLLM_USE_DEEP_GEMM: "1"
@@ -2,6 +2,8 @@ model_name: "RedHatAI/Qwen3-30B-A3B-FP8-block"
accuracy_threshold: 0.85
num_questions: 1319
num_fewshot: 5
# 30B MoE + DeepGEMM/DeepEP JIT compile can exceed the 1200s default startup wait.
startup_max_wait_seconds: 2400
server_args: "--enforce-eager --max-model-len 8192 --data-parallel-size 2 --enable-expert-parallel --all2all-backend deepep_low_latency --disable-uvicorn-access-log"
env:
VLLM_USE_DEEP_GEMM: "1"
@@ -2,4 +2,6 @@ model_name: "RedHatAI/Qwen3-30B-A3B-NVFP4"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
# 30B MoE + CuTeDSL/DeepEP JIT compile can exceed the 1200s default startup wait.
startup_max_wait_seconds: 2400
server_args: "--enforce-eager --max-model-len 8192 --data-parallel-size 2 --enable-expert-parallel --all2all-backend deepep_low_latency --moe-backend=flashinfer_cutedsl"
@@ -2,4 +2,6 @@ model_name: "nvidia/Qwen3-30B-A3B-NVFP4"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
# 30B MoE + CuTeDSL/DeepEP JIT compile can exceed the 1200s default startup wait.
startup_max_wait_seconds: 2400
server_args: "--enforce-eager --max-model-len 8192 --data-parallel-size 2 --enable-expert-parallel --all2all-backend deepep_low_latency --moe-backend=flashinfer_cutedsl"
@@ -10,3 +10,4 @@ Qwen3-30B-A3B-Fp8-CT-Block-deepgemm-deepep-ht.yaml
Qwen3-30B-A3B-Fp8-CT-Block-deepgemm-deepep-ll.yaml
Qwen3-30B-A3B-Fp8-CT-Block-deepgemm.yaml
Qwen3-30B-A3B-BF16-triton.yaml
Qwen3-30B-A3B-BF16-moonep.yaml
@@ -128,6 +128,12 @@ def test_gsm8k_correctness(config_filename):
"Skipping Qwen3.5-35B-A3B-MXFP4-AITER-TP2 on non-GFX950 platforms. "
"The quantization scheme is not supported on non-GFX950 platforms."
)
if "--all2all-backend=moonep" in eval_config.get("server_args", ""):
from vllm.utils.import_utils import has_moonep
if not has_moonep():
pytest.skip("Skipping MoonEP config: the moonep package is not installed.")
# Parse server arguments from config (use shlex to handle quoted strings)
server_args_str = eval_config.get("server_args", "")
server_args = shlex.split(server_args_str) if server_args_str else []
+5 -5
View File
@@ -960,14 +960,14 @@ def test_concat_and_cache_ds_mla(
tile_end = (tile_idx + 1) * 128
tile_data[:] = kv_c_data[tile_start:tile_end]
# tile_scale = tile_data.amax().to(torch.float32) / 448.
# NOTE: Using torch's amax() gives different results,
# so this must be manually computed.
# Using torch's amax() gives different results, so this must be
# manually computed.
tile_data_float = tile_data.to(torch.float32)
manual_max = abs(tile_data_float[0])
for j in range(1, 128):
manual_max = max(manual_max, abs(tile_data_float[j]))
tile_scale = manual_max / 448.0
raw_scale = torch.clamp(manual_max / 448.0, min=1e-4)
tile_scale = torch.exp2(torch.ceil(torch.log2(raw_scale)))
ref_cache_32bit[kv_lora_rank // 4 + tile_idx] = tile_scale
@@ -1008,7 +1008,7 @@ def test_concat_and_cache_ds_mla(
ref_rope = ref_cache_slice.view(dtype)[kv_lora_rank // 2 + 8 :]
torch.testing.assert_close(kv_nope, ref_nope, atol=0.001, rtol=0.1)
torch.testing.assert_close(kv_scales, ref_scales, atol=0.001, rtol=0.1)
torch.testing.assert_close(kv_scales, ref_scales, atol=0, rtol=0)
torch.testing.assert_close(kv_rope, ref_rope, atol=0.001, rtol=0.1)
@@ -109,8 +109,9 @@ def test_sparse_flashmla_metadata_smoke():
assert num_splits is None
def test_sparse_flashmla_decode_smoke():
def test_sparse_flashmla_decode_matches_cache_writer_scales():
import vllm.v1.attention.ops.flashmla as fm
from vllm import _custom_ops as ops
ok, reason = fm.is_flashmla_sparse_supported()
if not ok:
@@ -130,7 +131,7 @@ def test_sparse_flashmla_decode_smoke():
# Metadata
q_seq_per_hk = seqlen_q * num_heads_q // num_heads_k
# q_heads_per_hk = num_heads_q // num_heads_k
cache_seqlens = torch.zeros(batch_size, dtype=torch.int32, device=device)
cache_seqlens = torch.ones(batch_size, dtype=torch.int32, device=device)
tile_md, num_splits = fm.get_mla_metadata(
cache_seqlens,
q_seq_per_hk,
@@ -146,14 +147,33 @@ def test_sparse_flashmla_decode_smoke():
dtype=torch.bfloat16,
device=device,
)
k_cache = torch.zeros(
(1, page_block_size, num_heads_k, bytes_per_token),
dtype=torch.uint8,
device=device,
cache_rows = torch.zeros(
(1, page_block_size, bytes_per_token), dtype=torch.uint8, device=device
)
indices = torch.zeros(
(batch_size, seqlen_q, topk), dtype=torch.int32, device=device
# 336 / 448 = 0.75 distinguishes arbitrary FP32 from power-of-two scales.
kv_c = torch.full((1, 512), 336.0, dtype=torch.bfloat16, device=device)
kv_c[:, -128:] = 0
ops.concat_and_cache_mla(
kv_c,
torch.zeros((1, 64), dtype=torch.bfloat16, device=device),
cache_rows,
torch.zeros(1, dtype=torch.int64, device=device),
"fp8_ds_mla",
torch.ones(1, dtype=torch.float32, device=device),
)
scales = cache_rows[0, 0].view(torch.float32)[128:132]
expected_scales = torch.tensor([1.0, 1.0, 1.0, 2**-13], device=device)
torch.testing.assert_close(scales, expected_scales, rtol=0, atol=0)
cached_nope = cache_rows[0, 0, :512].view(torch.float8_e4m3fn).float()
expected = (cached_nope * scales.repeat_interleave(128)).to(torch.bfloat16)
k_cache = cache_rows.unsqueeze(2)
indices = torch.full(
(batch_size, seqlen_q, topk), -1, dtype=torch.int32, device=device
)
indices[..., 0] = 0
# SM90 sparse decode only supports a fixed top-k width. Padding with -1
# exercises the same cache data on SM90 and SM100 without topk_length.
block_table = torch.zeros((batch_size, 128), dtype=torch.int32, device=device)
out, lse = fm.flash_mla_with_kvcache(
@@ -170,6 +190,9 @@ def test_sparse_flashmla_decode_smoke():
assert out.shape[0] == batch_size
assert out.shape[-1] == head_dim_v
assert lse.shape[0] == batch_size
torch.testing.assert_close(
out, expected.view(1, 1, 1, 512).expand_as(out), rtol=0, atol=0
)
@pytest.mark.parametrize("h_q", [64, 128])
@@ -222,7 +222,8 @@ def test_decode_concat_ignores_negative_slots_for_cache(cache_format: str) -> No
_assert_cache_matches_reference(mixed_cache, reference_cache, initial_cache)
def test_ds_mla_cache_insert_bit_compatible_with_reference() -> None:
@pytest.mark.parametrize("decode", [False, True])
def test_ds_mla_cache_insert_bit_compatible_with_reference(decode: bool) -> None:
"""Fused ds_mla insertion must match the reference bit-for-bit."""
torch.manual_seed(0)
num_tokens, num_blocks = 33, 16
@@ -242,5 +243,18 @@ def test_ds_mla_cache_insert_bit_compatible_with_reference() -> None:
got = ref.clone()
scale = torch.ones(1, device="cuda", dtype=torch.float32)
ops.concat_and_cache_mla(kv_c, k_pe.squeeze(1), ref, slots, "fp8_ds_mla", scale)
fused_mla_key_concat_ds_mla_insert(q, k_nope, k_pe, kv_c, got, slots)
if decode:
ql_nope = torch.randn(
num_tokens, NUM_HEADS, KV_LORA_RANK, device="cuda", dtype=dt
)
fused_mla_decode_q_concat_kv_cache_insert(
ql_nope, q[..., -ROPE_HEAD_DIM:], kv_c, k_pe, got, slots, ds_mla=True
)
else:
fused_mla_key_concat_ds_mla_insert(q, k_nope, k_pe, kv_c, got, slots)
assert torch.equal(ref, got)
rows = got.view(-1, DS_MLA_CACHE_ENTRY)[slots[slots >= 0]]
scales = rows[:, KV_LORA_RANK : KV_LORA_RANK + 16].view(torch.float32)
torch.testing.assert_close(
torch.log2(scales), torch.log2(scales).round(), rtol=0, atol=0
)
@@ -1430,3 +1430,189 @@ def test_get_cached_wo_a_bf16_fp8_blockscale_caches() -> None:
# Second call returns the same cached object.
assert _get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim) is out
@requires_split_decode_arch
@torch.inference_mode()
def test_fp8_paged_mqa_logits_triton_matches_torch_ref() -> None:
"""Block-flat Triton decode logits vs the eager torch reference.
Compare only valid key positions: the kernel skips the -inf pad that
the torch ref writes past seq_len.
"""
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod
from vllm.v1.worker.workspace import init_workspace_manager
device = torch.device("cuda")
init_workspace_manager(device)
torch.manual_seed(0)
fp8_dtype = current_platform.fp8_dtype()
batch_size = 2
next_n = 1
num_heads = 4
head_size = 128
block_size = 64
max_model_len = 256
seq_lens = [180, 64]
num_pages = [(seq_len + block_size - 1) // block_size for seq_len in seq_lens]
num_blocks = sum(num_pages)
q = torch.randn(
batch_size, next_n, num_heads, head_size, device=device, dtype=torch.bfloat16
).to(fp8_dtype)
weights = torch.rand(
batch_size * next_n, num_heads, device=device, dtype=torch.float32
)
context_lens = torch.tensor(seq_lens, device=device, dtype=torch.int32)
block_tables = torch.full(
(batch_size, max(num_pages)), 0, device=device, dtype=torch.int32
)
page = 0
for i, n_pages in enumerate(num_pages):
block_tables[i, :n_pages] = torch.arange(
page, page + n_pages, device=device, dtype=torch.int32
)
page += n_pages
kv_cache = torch.empty(
num_blocks, block_size, 1, head_size + 4, device=device, dtype=torch.uint8
)
values = torch.randn(
num_blocks, block_size, head_size, device=device, dtype=torch.bfloat16
).to(fp8_dtype)
scales = torch.rand(
num_blocks, block_size, device=device, dtype=torch.float32
).clamp(min=1e-3)
kv_flat = kv_cache.view(num_blocks, -1)
scale_off = block_size * head_size
kv_flat[:, :scale_off] = values.reshape(num_blocks, -1).view(torch.uint8)
kv_flat[:, scale_off:] = scales.contiguous().view(torch.uint8).view(num_blocks, -1)
got = mod.rocm_fp8_paged_mqa_logits_triton(
q, kv_cache, weights, context_lens, block_tables, max_model_len
)
ref = mod.fp8_paged_mqa_logits_torch(
q, kv_cache, weights, context_lens, block_tables, max_model_len
)
for i, seq_len in enumerate(seq_lens):
torch.testing.assert_close(
got[i, :seq_len], ref[i, :seq_len], atol=2e-3, rtol=2e-3
)
def test_indexer_k_is_c4a_block_flat_gate() -> None:
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_indexer_k_is_c4a_block_flat,
)
assert not _indexer_k_is_c4a_block_flat(1)
assert not _indexer_k_is_c4a_block_flat(2)
assert _indexer_k_is_c4a_block_flat(4)
assert not _indexer_k_is_c4a_block_flat(128)
@requires_split_decode_arch
@torch.inference_mode()
def test_paged_mqa_logits_gate_v41_shuffle_vs_c4a_flat() -> None:
"""Ratio 1/2 stay on AITER; ratio 4 takes Triton."""
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
fp8_paged_mqa_logits_torch,
indexer_k_quant_and_cache_triton,
rocm_fp8_paged_mqa_logits,
rocm_fp8_paged_mqa_logits_triton,
)
from vllm.v1.worker.workspace import init_workspace_manager
device = torch.device("cuda")
init_workspace_manager(device)
torch.manual_seed(1)
fp8_dtype = current_platform.fp8_dtype()
batch_size = 1
next_n = 1
num_heads = 32
head_size = 128
block_size = 64
seq_len = 180
max_model_len = 256
num_pages = (seq_len + block_size - 1) // block_size
num_tokens = num_pages * block_size
q = torch.randn(
batch_size, next_n, num_heads, head_size, device=device, dtype=torch.bfloat16
).to(fp8_dtype)
weights = torch.rand(
batch_size * next_n, num_heads, device=device, dtype=torch.float32
)
context_lens = torch.tensor([seq_len], device=device, dtype=torch.int32)
block_tables = torch.arange(num_pages, device=device, dtype=torch.int32).view(1, -1)
dummy_sched = torch.zeros(8, 2, device=device, dtype=torch.int32)
k_bf16 = torch.randn(num_tokens, head_size, device=device, dtype=torch.bfloat16)
slot = torch.arange(num_tokens, device=device, dtype=torch.int32)
cache_shuffle = torch.zeros(
num_pages, block_size, head_size + 4, device=device, dtype=torch.uint8
)
indexer_k_quant_and_cache_triton(k_bf16, cache_shuffle, slot, 128, "ue8m0")
cache_shuffle = cache_shuffle.unsqueeze(2)
aiter = rocm_fp8_paged_mqa_logits(
q,
cache_shuffle,
weights,
context_lens,
block_tables,
dummy_sched,
max_model_len,
compress_ratio=1,
)
for ratio in (1, 2):
got = rocm_fp8_paged_mqa_logits(
q,
cache_shuffle,
weights,
context_lens,
block_tables,
dummy_sched,
max_model_len,
compress_ratio=ratio,
)
torch.testing.assert_close(got[:, :seq_len], aiter[:, :seq_len], atol=0, rtol=0)
cache_flat = torch.empty(
num_pages, block_size, 1, head_size + 4, device=device, dtype=torch.uint8
)
values = torch.randn(
num_pages, block_size, head_size, device=device, dtype=torch.bfloat16
).to(fp8_dtype)
scales = torch.rand(
num_pages, block_size, device=device, dtype=torch.float32
).clamp(min=1e-3)
kv_flat = cache_flat.view(num_pages, -1)
scale_off = block_size * head_size
kv_flat[:, :scale_off] = values.reshape(num_pages, -1).view(torch.uint8)
kv_flat[:, scale_off:] = scales.contiguous().view(torch.uint8).view(num_pages, -1)
gated_c4a = rocm_fp8_paged_mqa_logits(
q,
cache_flat,
weights,
context_lens,
block_tables,
dummy_sched,
max_model_len,
compress_ratio=4,
)
triton = rocm_fp8_paged_mqa_logits_triton(
q, cache_flat, weights, context_lens, block_tables, max_model_len
)
ref = fp8_paged_mqa_logits_torch(
q, cache_flat, weights, context_lens, block_tables, max_model_len
)
torch.testing.assert_close(
gated_c4a[:, :seq_len], triton[:, :seq_len], atol=0, rtol=0
)
torch.testing.assert_close(
gated_c4a[:, :seq_len], ref[:, :seq_len], atol=2e-3, rtol=2e-3
)
@@ -0,0 +1,215 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for the multi-token decode flatten in ``TritonMLAImpl.forward_mqa``.
``decode_attention_fwd`` has no causal flag: it launches one program per row of
``q`` and reads that row's KV extent from ``B_Seqlen``. So a ``query_len``-token
decode block is flattened to one row per query token, and intra-block causality
has to be expressed through the per-row sequence lengths -- row ``t`` gets
``seq_len - (query_len - 1) + t``, i.e. the committed prefix plus block tokens
``0..t``. A non-causal draft block instead gives every row the same full extent.
The kernel is replaced by a spy, so these tests assert on the ``block_table``
and ``seq_lens`` the backend actually submits and need no GPU or Triton runtime.
"""
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from vllm.model_executor.layers.attention.mla_attention import QueryLenSupport
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.attention.backends.mla.triton_mla import (
TritonMLAImpl,
TritonMLAMetadataBuilder,
)
NUM_HEADS = 16
KV_LORA_RANK = 512
QK_ROPE_HEAD_DIM = 64
HEAD_SIZE = KV_LORA_RANK + QK_ROPE_HEAD_DIM
PAGE_SIZE = 16
# Committed context per request, including a fresh request at zero context
# where the whole KV extent is the block itself. A decode block's seq_len
# already counts the block, so seq_len = context + query_len.
CONTEXT_LENS = [0, 1, 37, 512]
def _seq_lens(query_len: int) -> list[int]:
return [c + query_len for c in CONTEXT_LENS]
def _make_impl(dcp_world_size: int = 1) -> TritonMLAImpl:
"""Only the attributes ``forward_mqa`` reads; __init__ wants a full config."""
impl = object.__new__(TritonMLAImpl)
impl.kv_lora_rank = KV_LORA_RANK
impl.scale = HEAD_SIZE**-0.5
impl._sm_count = 304
impl.dcp_world_size = dcp_world_size
return impl
def _make_metadata(seq_lens: list[int], query_len: int, causal: bool):
num_decodes = len(seq_lens)
return SimpleNamespace(
num_decodes=num_decodes,
num_decode_tokens=num_decodes * query_len,
max_seq_len=max(seq_lens),
causal=causal,
decode=SimpleNamespace(
# arange page ids so each request's window is an identifiable slice.
block_table=torch.arange(num_decodes * 64, dtype=torch.int32).reshape(
num_decodes, 64
),
seq_lens=torch.tensor(seq_lens, dtype=torch.int32),
),
)
def _run_forward_mqa(
seq_lens: list[int],
query_len: int,
causal: bool,
q_rows=None,
dcp_world_size: int = 1,
):
"""Drive forward_mqa with the decode kernel spied out.
Returns the ``(block_table, seq_lens)`` handed to ``decode_attention_fwd``.
"""
captured: dict = {}
def spy(q, kv_cache, kv_c_cache, o, lse, block_table, b_seq_len, *args, **kwargs):
captured["block_table"] = block_table.detach().clone()
captured["seq_lens"] = b_seq_len.detach().clone()
metadata = _make_metadata(seq_lens, query_len, causal)
rows = metadata.num_decode_tokens if q_rows is None else q_rows
q = torch.zeros(rows, NUM_HEADS, HEAD_SIZE, dtype=torch.bfloat16)
kv_cache = torch.zeros(
len(seq_lens) * 64, PAGE_SIZE, HEAD_SIZE, dtype=torch.bfloat16
)
layer = SimpleNamespace(_k_scale=torch.ones(1), layer_name="test")
with patch("vllm.v1.attention.backends.mla.triton_mla.decode_attention_fwd", spy):
_make_impl(dcp_world_size).forward_mqa(q, kv_cache, metadata, layer)
assert captured, "forward_mqa did not reach the decode kernel"
return captured
def test_multi_token_decode_flags_are_declared_together():
"""Capture probes max_query_len > 1, which only clears the assert in
build_for_cudagraph_capture once query_len_support raised the threshold."""
assert (
TritonMLAMetadataBuilder._cudagraph_support == AttentionCGSupport.UNIFORM_BATCH
)
assert TritonMLAMetadataBuilder.query_len_support == QueryLenSupport.UNIFORM
@pytest.mark.parametrize("query_len", [2, 3, 4, 5, 8])
def test_causal_block_rows_see_prefix_plus_own_position(query_len):
"""Causal verify: row t sees seq_len - (query_len - 1) + t KV entries.
Regression guard: the causal branch used to be skipped entirely, so a verify
token could attend the draft siblings it is supposed to be checking. Fails
on unmodified upstream, where no flatten happens at all for causal blocks.
"""
seq_lens = _seq_lens(query_len)
captured = _run_forward_mqa(seq_lens, query_len, causal=True)
got = captured["seq_lens"].tolist()
want = [s - (query_len - 1) + t for s in seq_lens for t in range(query_len)]
assert got == want, (
"causal flatten is not causal: verify row r*query_len+t must get "
f"seq_len_r - {query_len - 1} + t entries.\n"
f" seq_lens {seq_lens}\n got {got}\n expected {want}"
)
# Per-request invariants the arithmetic must hold regardless of query_len.
for r, seq_len in enumerate(seq_lens):
rows = got[r * query_len : (r + 1) * query_len]
assert rows == sorted(rows) and len(set(rows)) == query_len, (
f"request {r} rows must strictly increase, got {rows}"
)
assert rows[-1] == seq_len, "last row must see the full sequence"
assert rows[0] == seq_len - (query_len - 1)
assert all(n > 0 for n in rows), f"non-positive KV extent in {rows}"
def test_cudagraph_padding_rows_present_no_kv_extent():
"""Causal flattening pins cudagraph padding rows (seq_len 0) to exactly
zero KV extent, keeping them in the kernel's skipped branch."""
query_len = 4
seq_lens = _seq_lens(query_len) + [0]
captured = _run_forward_mqa(seq_lens, query_len, causal=True)
padding = captured["seq_lens"].tolist()[-query_len:]
assert padding == [0] * query_len, (
f"padding rows must present exactly zero KV extent, got {padding}"
)
@pytest.mark.parametrize("query_len", [2, 4])
def test_non_causal_block_rows_all_see_the_full_prefix(query_len):
"""The DSpark draft block is generated in one pass, so no row is masked."""
seq_lens = _seq_lens(query_len)
captured = _run_forward_mqa(seq_lens, query_len, causal=False)
want = [s for s in seq_lens for _ in range(query_len)]
assert captured["seq_lens"].tolist() == want
@pytest.mark.parametrize("causal", [True, False])
def test_block_table_is_expanded_to_match_q_rows(causal):
"""The kernel indexes block_table by program_id, so it needs one row per
query token -- a short block_table is read out of bounds."""
query_len = 4
captured = _run_forward_mqa(_seq_lens(query_len), query_len, causal=causal)
num_rows = len(CONTEXT_LENS) * query_len
assert captured["block_table"].shape[0] == num_rows
assert captured["seq_lens"].shape[0] == num_rows
# repeat_interleave, not repeat: a request's rows must stay adjacent.
for r in range(len(CONTEXT_LENS)):
block = captured["block_table"][r * query_len : (r + 1) * query_len]
assert torch.equal(block, block[:1].expand_as(block))
@pytest.mark.parametrize("causal", [True, False])
def test_single_token_decode_is_untouched(causal):
"""query_len == 1 must short-circuit: ordinary decode sees no expansion."""
seq_lens = _seq_lens(1)
captured = _run_forward_mqa(seq_lens, query_len=1, causal=causal)
assert captured["seq_lens"].tolist() == seq_lens
assert captured["block_table"].shape[0] == len(seq_lens)
def test_expansion_factor_follows_the_q_row_count():
"""The kernel indexes block_table and seq_lens by program_id, so the
expansion must follow q rows, not the token/request counts."""
num_rows = len(CONTEXT_LENS) * 4
captured = _run_forward_mqa(_seq_lens(1), query_len=1, causal=True, q_rows=num_rows)
assert captured["block_table"].shape[0] == num_rows
assert captured["seq_lens"].shape[0] == num_rows
def test_non_uniform_block_is_rejected():
"""Q rows must divide evenly across the decode requests."""
with pytest.raises(AssertionError, match="non-uniform decode block"):
_run_forward_mqa(_seq_lens(1), query_len=1, causal=True, q_rows=6)
def test_causal_multi_token_decode_is_rejected_under_dcp():
"""Per-row extents offset the global seq_len, but DCP passes the rank-local
slice, so the causal arithmetic would silently address the wrong KV."""
with pytest.raises(AssertionError, match="not supported with DCP"):
_run_forward_mqa(_seq_lens(4), query_len=4, causal=True, dcp_world_size=2)
# Non-causal rows all take the same extent, which stays correct when local.
_run_forward_mqa(_seq_lens(4), query_len=4, causal=False, dcp_world_size=2)
@@ -192,3 +192,86 @@ def test_gdn_chunk_cutedsl_correctness(num_seqs: int, state_dtype: torch.dtype):
assert no_buffer_state_error.mean().item() < 6e-4
assert buffer_o_error.max().item() == 0
assert buffer_state_error.max().item() == 0
def test_gdn_chunk_cutedsl_correlated_keys_stability():
"""Cover a KKT block where three BF16 Newton rounds diverge."""
total_tokens = 64
num_k_heads = 4
num_v_heads = 8
head_dim = 128
rng = torch.Generator("cuda").manual_seed(3456)
q = torch.zeros(
1,
total_tokens,
num_k_heads,
head_dim,
device="cuda",
dtype=torch.bfloat16,
)
k = torch.zeros_like(q)
q[..., 0] = 1
k[..., 0] = 1
v = torch.randn(
1,
total_tokens,
num_v_heads,
head_dim,
device="cuda",
dtype=torch.bfloat16,
generator=rng,
)
g = torch.zeros(
1,
total_tokens,
num_v_heads,
device="cuda",
dtype=torch.float32,
)
beta = torch.full_like(g, 0.9)
initial_state = torch.zeros(
1,
num_v_heads,
head_dim,
head_dim,
device="cuda",
dtype=torch.float32,
)
cu_seqlens = torch.tensor([0, total_tokens], device="cuda", dtype=torch.int32)
chunk_indices, chunk_offsets = prepare_metadata_cutedsl(cu_seqlens, total_tokens)
ref_o, ref_state = chunk_gated_delta_rule(
q=q,
k=k,
v=v,
g=g,
beta=beta,
initial_state=initial_state,
output_final_state=True,
cu_seqlens=cu_seqlens,
use_qk_l2norm_in_kernel=False,
)
actual_o, actual_state = chunk_gated_delta_rule_cutedsl(
q=q,
k=k,
v=v,
g=g,
beta=beta,
initial_state=initial_state,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
chunk_offsets=chunk_offsets,
)
torch.accelerator.synchronize()
assert torch.isfinite(actual_o).all()
assert torch.isfinite(actual_state).all()
output_error = (actual_o.float() - ref_o.float()).abs()
state_error = (
actual_state.float() - ref_state.to(actual_state.dtype).float()
).abs()
assert output_error.max().item() < 1e-1
assert output_error.mean().item() < 2e-3
assert state_error.max().item() < 2e-1
assert state_error.mean().item() < 6e-4
@@ -0,0 +1,124 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Layout dispatch tests for ``QwenGatedDeltaNetAttention._forward_core_rocm``.
The AITER fused reshape+conv kernel learned Qwen3.5's flat ``[q|k|v|z]``
packing in https://github.com/ROCm/aiter/pull/3251, so flat-layout models take
the decode fast path too instead of falling back to the generic path.
These tests run host-side on CPU: ``_forward_core_rocm`` is bound to a stub
layer whose ``_forward_core_decode_aiter``/``_forward_core`` record which
branch ran, so no GPU or AITER install is needed.
"""
from __future__ import annotations
import types
from unittest.mock import patch
import pytest
import torch
from vllm.model_executor.layers.mamba.gdn import qwen_gdn_linear_attn
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
QwenGatedDeltaNetAttention,
)
from vllm.platforms import current_platform
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
pytestmark = pytest.mark.skipif(
not current_platform.is_rocm(), reason="ROCm-specific tests"
)
PREFIX = "model.layers.0.linear_attn"
H = 2 # num key heads
HV = 4 # num value heads
K = 8 # head_k_dim
V = 8 # head_v_dim
def _make_metadata(
*,
num_prefills: int = 0,
num_decodes: int = 2,
spec_sequence_masks: torch.Tensor | None = None,
):
"""Only the fields the dispatch condition reads carry meaningful values."""
return GDNAttentionMetadata(
num_prefills=num_prefills,
num_prefill_tokens=num_prefills,
num_decodes=num_decodes,
num_decode_tokens=num_decodes,
num_spec_decodes=0,
num_spec_decode_tokens=0,
num_actual_tokens=num_prefills + num_decodes,
spec_sequence_masks=spec_sequence_masks,
)
def _make_layer(gqa_interleaved_layout: bool):
"""Stub layer running the real ``_forward_core_rocm``, recording dispatch."""
layer = types.SimpleNamespace()
layer.prefix = PREFIX
layer.gqa_interleaved_layout = gqa_interleaved_layout
layer.qkvz_layout = "interleaved" if gqa_interleaved_layout else "flat"
layer.calls = []
layer._forward_core_decode_aiter = lambda **kw: layer.calls.append("aiter")
layer._forward_core = lambda **kw: layer.calls.append("generic")
layer.prepare_gdn_attention_core_inputs = lambda qkvz, ba, n: (
torch.zeros(n, H * K * 2 + HV * V),
torch.zeros(n, HV, V),
torch.zeros(n, HV),
torch.zeros(n, HV),
)
layer._forward_core_rocm = types.MethodType(
QwenGatedDeltaNetAttention._forward_core_rocm, layer
)
return layer
def _run(layer, meta) -> str:
num_tokens = max(meta.num_actual_tokens, 1)
ctx = types.SimpleNamespace(attn_metadata={PREFIX: meta})
with patch.object(qwen_gdn_linear_attn, "get_forward_context", return_value=ctx):
layer._forward_core_rocm(
qkvz=torch.zeros(num_tokens, 2 * H * K + 2 * HV * V),
ba=torch.zeros(num_tokens, 2 * HV),
z_out=torch.zeros(num_tokens, HV, V),
core_attn_out=torch.zeros(num_tokens, HV, V),
)
assert len(layer.calls) == 1
return layer.calls[0]
@pytest.mark.parametrize("gqa_interleaved_layout", [True, False])
def test_pure_decode_takes_the_fast_path(gqa_interleaved_layout: bool) -> None:
"""Both packings reach the fast path; flat used to be guarded out."""
layer = _make_layer(gqa_interleaved_layout)
assert _run(layer, _make_metadata()) == "aiter"
@pytest.mark.parametrize("gqa_interleaved_layout", [True, False])
def test_layout_string_matches_the_packing(gqa_interleaved_layout: bool) -> None:
"""The value handed to the kernel's ``qkvz_layout`` parameter."""
layer = _make_layer(gqa_interleaved_layout)
expected = "interleaved" if gqa_interleaved_layout else "flat"
assert layer.qkvz_layout == expected
@pytest.mark.parametrize("gqa_interleaved_layout", [True, False])
@pytest.mark.parametrize(
"meta_kwargs",
[
{"num_prefills": 1},
{"num_decodes": 0},
{"spec_sequence_masks": torch.zeros(1, dtype=torch.bool)},
],
ids=["has_prefill", "no_decode", "spec_decode"],
)
def test_non_pure_decode_batches_use_the_generic_path(
gqa_interleaved_layout: bool, meta_kwargs: dict
) -> None:
layer = _make_layer(gqa_interleaved_layout)
assert _run(layer, _make_metadata(**meta_kwargs)) == "generic"
+17 -5
View File
@@ -306,17 +306,28 @@ def test_cpu_fused_moe(
@pytest.mark.skipif(
current_platform.get_cpu_architecture() != CpuArchEnum.ARM,
reason="Requires Arm CPU",
current_platform.get_cpu_architecture()
not in (CpuArchEnum.ARM, CpuArchEnum.POWERPC),
reason="Requires Arm or POWER CPU",
)
@pytest.mark.parametrize("batch_size", BATCH_SIZE)
@pytest.mark.parametrize("expert_num", EXPERT_NUM)
@pytest.mark.parametrize("hidden_size", HIDDEN_DIM)
@pytest.mark.parametrize("intermediate_size", INTERMEDIATE_DIM)
@pytest.mark.parametrize("use_bias", USE_BIAS)
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
@pytest.mark.parametrize(
"dtype",
(
[torch.float32, torch.float16, torch.bfloat16]
if current_platform.get_cpu_architecture() == CpuArchEnum.ARM
else [torch.float32, torch.bfloat16]
),
)
@pytest.mark.parametrize("act", ACT)
@pytest.mark.parametrize("isa", ["neon"])
@pytest.mark.parametrize(
"isa",
["neon"] if current_platform.get_cpu_architecture() == CpuArchEnum.ARM else ["vsx"],
)
def test_cpu_fused_moe_int8(
batch_size: int,
expert_num: int,
@@ -386,7 +397,8 @@ def test_cpu_fused_moe_int8(
isa,
)
torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=2e-2)
atol = rtol = 1e-1 if isa == "vsx" else 2e-2
torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol)
# moe_intermediate_size not a multiple of 32, e.g. what tensor-parallel
@@ -1114,5 +1114,203 @@ def test_int8_w8a8_cpu_fused_moe(M, N, K, E, topk, seed, is_vnni, inplace):
)
# ===========================================================================
# FP8 W8A8 MoE
# ===========================================================================
requires_cpu_fp8_w8a8 = pytest.mark.skipif(
not ops.cpu_has_amx_fp8(),
reason="requires native AMX-FP8 hardware",
)
FP8_W8A8_MAX = torch.finfo(torch.float8_e4m3fn).max
FP8_W8A8_QUANT_GROUP = 128 # quantization group size for both K and N dimensions
def _make_fp8_w8a8_weight_w13(
E: int, two_n: int, K: int, group_K: int = FP8_W8A8_QUANT_GROUP
) -> tuple[torch.Tensor, torch.Tensor]:
"""Create w13 [E, 2N, K] FP8 with group scales [E, 2N, G] where G = K//group_K."""
G = K // group_K
w_list, s_list = [], []
for _ in range(E):
w_f32 = torch.randn(two_n, K)
# Per-row, per-K-group quantization: scale [2N, G]
w_re = w_f32.view(two_n, G, group_K)
abs_max = w_re.abs().amax(dim=2, keepdim=True).clamp(min=1e-7) # [2N, G, 1]
scale = (abs_max / FP8_W8A8_MAX).squeeze(2) # [2N, G]
w_q = (
(w_re / abs_max).clamp(-FP8_W8A8_MAX, FP8_W8A8_MAX).to(torch.float8_e4m3fn)
)
w_list.append(w_q.view(two_n, K).contiguous())
s_list.append(scale.float())
return torch.stack(w_list), torch.stack(s_list) # [E, 2N, K], [E, 2N, G]
def _make_fp8_w8a8_weight_w2(
E: int,
K: int,
N: int,
group_K: int = FP8_W8A8_QUANT_GROUP,
group_N: int = FP8_W8A8_QUANT_GROUP,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Create w2 [E, K, N] FP8 with block scales [E, K//gK, N//gN]."""
nK = K // group_K
nN = N // group_N
w_list, s_list = [], []
for _ in range(E):
w_f32 = torch.randn(K, N)
w_re = w_f32.view(nK, group_K, nN, group_N)
abs_max = w_re.abs().amax(dim=(1, 3), keepdim=True).clamp(min=1e-7)
scale = (abs_max / FP8_W8A8_MAX).squeeze(1).squeeze(2) # [nK, nN]
w_q = (
(w_re / abs_max).clamp(-FP8_W8A8_MAX, FP8_W8A8_MAX).to(torch.float8_e4m3fn)
)
w_list.append(w_q.view(K, N).contiguous())
s_list.append(scale.float())
return torch.stack(w_list), torch.stack(s_list) # [E, K, N], [E, K//gK, N//gN]
def _pack_fp8_w8a8_w13(
w13: torch.Tensor, # [E, 2N, K] FP8
w13_scale: torch.Tensor, # [E, 2N, G] float32
) -> tuple[torch.Tensor, torch.Tensor]:
"""Pack w13 for CPU FP8 W8A8 MoE kernel using float8_linear_prepack_cpu."""
E = w13.size(0)
packed_list, scale_list = [], []
for i in range(E):
pw, ps = torch.ops._C.float8_linear_prepack_cpu(
w13[i].contiguous(), w13_scale[i].contiguous()
)
packed_list.append(pw)
scale_list.append(ps)
return torch.stack(packed_list), torch.stack(scale_list)
def _ref_fp8_w8a8_moe(
hidden_states: torch.Tensor, # BF16 [M, K_hidden] (after FP8 round-trip dequant)
w13: torch.Tensor, # FP8 [E, 2N, K_hidden]
w13_scale: torch.Tensor, # float32 [E, 2N, G] (G = K_hidden//group_K)
w2: torch.Tensor, # FP8 [E, K_hidden, N]
w2_scale: torch.Tensor, # float32 [E, K_hidden//gK, N//gN]
topk_weights: torch.Tensor, # float32 [M, top_k]
topk_ids: torch.Tensor, # int64 [M, top_k]
N: int,
group_K: int = FP8_W8A8_QUANT_GROUP,
group_N: int = FP8_W8A8_QUANT_GROUP,
) -> torch.Tensor:
"""Reference implementation: dequantize weights then compute MoE."""
M, K_hidden = hidden_states.shape
top_k = topk_ids.shape[1]
output = torch.zeros(M, K_hidden, dtype=torch.bfloat16)
for tok in range(M):
x = hidden_states[tok].float() # [K_hidden]
for k_idx in range(top_k):
expert_id = topk_ids[tok, k_idx].item()
w = topk_weights[tok, k_idx].item()
# Stage 1: x @ w13.T — gate and up projections
w13_e = w13[expert_id].float() # [2N, K_hidden]
ws_e = w13_scale[expert_id].float() # [2N, G]
G = ws_e.shape[1]
w13_dq = torch.zeros_like(w13_e)
for g in range(G):
c0, c1 = g * group_K, (g + 1) * group_K
w13_dq[:, c0:c1] = w13_e[:, c0:c1] * ws_e[:, g : g + 1]
gate_up = (x.unsqueeze(0) @ w13_dq.T).squeeze(0) # [2N]
gate = gate_up[:N]
up = gate_up[N:]
act = F.silu(gate) * up # [N]
# Stage 2: act @ w2.T — down projection
w2_e = w2[expert_id].float() # [K_hidden, N]
ws2_e = w2_scale[expert_id].float() # [K_hidden//gK, N//gN]
nK2 = K_hidden // group_K
nN2 = N // group_N
w2_dq = torch.zeros_like(w2_e)
for gi in range(nK2):
for gj in range(nN2):
r0, r1 = gi * group_K, (gi + 1) * group_K
c0, c1 = gj * group_N, (gj + 1) * group_N
w2_dq[r0:r1, c0:c1] = w2_e[r0:r1, c0:c1] * ws2_e[gi, gj]
out_e = (act.unsqueeze(0) @ w2_dq.T).squeeze(0) # [K_hidden]
output[tok] += (w * out_e).to(torch.bfloat16)
return output
@requires_cpu_fp8_w8a8
@pytest.mark.parametrize(
"E,N,K,M,top_k",
[
# N and K must be multiples of FP8_W8A8_QUANT_GROUP=128
(4, 128, 256, 1, 2), # single token (decode phase)
(4, 128, 256, 8, 2),
(8, 256, 512, 16, 2),
(4, 256, 512, 4, 1),
],
)
def test_fp8_w8a8_cpu_fused_moe(E: int, N: int, K: int, M: int, top_k: int):
"""Test fused_experts_cpu FP8_W8A8 shape/dtype and accuracy vs a
dequantized BF16 reference."""
set_random_seed(42)
w13, w13_scale = _make_fp8_w8a8_weight_w13(E, 2 * N, K)
w2, w2_scale = _make_fp8_w8a8_weight_w2(E, K, N)
packed_w13, packed_w13_scale = _pack_fp8_w8a8_w13(w13, w13_scale)
packed_w2 = _prepack_experts(w2)
hidden_states = torch.randn(M, K, dtype=torch.bfloat16) * 0.1
x_fp8, x_scales = torch.ops._C.quantize_fp8e4m3_vec(hidden_states, True, None)
assert x_fp8.dtype == torch.float8_e4m3fn
assert x_scales.shape == (M,)
gen = torch.Generator().manual_seed(0)
topk_weights = torch.softmax(torch.randn(M, top_k, generator=gen), dim=-1).float()
topk_ids = torch.zeros(M, top_k, dtype=torch.int32)
for i in range(M):
topk_ids[i] = torch.randperm(E, generator=torch.Generator().manual_seed(i))[
:top_k
].int()
output = torch.empty(M, K, dtype=torch.bfloat16)
ops.fused_experts_cpu(
output,
x_fp8,
packed_w13,
packed_w2,
topk_weights,
topk_ids,
ops.CPUQuantMethod.FP8_W8A8,
packed_w13_scale, # w1_scale: [E, Nc, G, BLOCK_N]
w2_scale, # w2_scale: [E, K//128, N//128]
None, # w1_zero
None, # w2_zero
[FP8_W8A8_QUANT_GROUP, FP8_W8A8_QUANT_GROUP], # block_size
None, # w1_bias
None, # w2_bias
None, # alpha
None, # limit
True, # is_vnni (weights already packed)
x_scales, # a1_scale: per-token FP8 activation scales
)
assert output.shape == (M, K)
assert output.dtype == torch.bfloat16
assert not torch.isnan(output).any()
assert not torch.isinf(output).any()
x_dequant = (x_fp8.float() * x_scales.unsqueeze(1)).bfloat16()
ref = _ref_fp8_w8a8_moe(
x_dequant, w13, w13_scale, w2, w2_scale, topk_weights, topk_ids.long(), N
)
torch.testing.assert_close(output.float(), ref.float(), atol=1e-2, rtol=1e-2)
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-v"]))
+40
View File
@@ -26,6 +26,10 @@ from vllm.model_executor.layers.fused_moe.config import (
)
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import (
deepgemm_moe_permute,
ep_gather,
)
from vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe import (
_fp8_workspace_shape,
)
from vllm.model_executor.layers.fused_moe.experts.triton_deep_gemm_moe import (
TritonOrDeepGemmExperts,
@@ -43,6 +47,42 @@ from vllm.utils.deep_gemm import (
BLOCK_SIZE = [128, 128]
def test_ep_gather_uses_64_bit_row_offsets():
hidden_size = 4096
source_row = 1 << 18
input_tensor = torch.empty(
(source_row + 1, hidden_size),
device="cuda",
dtype=torch.bfloat16,
)
input_tensor[source_row].fill_(1)
output = torch.empty((1, hidden_size), device="cuda", dtype=torch.bfloat16)
ep_gather(
input_tensor=input_tensor,
recv_topk_ids=torch.zeros((1, 1), device="cuda", dtype=torch.int64),
recv_topk_weight=torch.ones((1, 1), device="cuda", dtype=torch.float32),
input_index=torch.full((1, 1), source_row, device="cuda", dtype=torch.int32),
expert_map=None,
output_tensor=output,
)
torch.testing.assert_close(output, torch.ones_like(output), rtol=0, atol=0)
@pytest.mark.parametrize("workspace_dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("num_columns", [2048, 6144, 6145])
def test_fp8_workspace_shape(workspace_dtype, num_columns):
num_rows = 17
shape = _fp8_workspace_shape(num_rows, num_columns, workspace_dtype)
allocated_bytes = math.prod(shape) * workspace_dtype.itemsize
required_bytes = num_rows * num_columns * torch.float8_e4m3fn.itemsize
assert allocated_bytes >= required_bytes
assert allocated_bytes - required_bytes < num_rows * workspace_dtype.itemsize
@pytest.mark.skipif(not is_deep_gemm_supported(), reason="Requires deep_gemm kernels")
def test_deepgemm_moe_permute_initializes_padding_scales(workspace_init):
hidden_states = torch.randn(2, 128, device="cuda", dtype=torch.bfloat16)
+272
View File
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import multiprocessing
from dataclasses import dataclass
from unittest.mock import MagicMock
import pytest
import torch
@@ -22,6 +24,9 @@ from vllm.model_executor.layers.fused_moe.config import (
from vllm.model_executor.layers.fused_moe.experts.flashinfer_cutlass_moe import (
FlashInferExperts,
)
from vllm.model_executor.layers.fused_moe.experts.trtllm_bf16_moe import (
view_as_block_major_k,
)
from vllm.model_executor.layers.fused_moe.experts.trtllm_fp8_moe import (
TrtLlmFp8ExpertsModular,
TrtLlmFp8ExpertsMonolithic,
@@ -433,6 +438,273 @@ def test_convert_moe_weights_to_flashinfer_trtllm_block_layout(
assert w13_converted.shape[0] == num_experts
assert w2_converted.shape[0] == num_experts
assert w13_converted.data_ptr() == w13.data_ptr()
assert w2_converted.data_ptr() == w2.data_ptr()
@pytest.mark.parametrize("is_gated_act_gemm", [True, False])
def test_convert_moe_weights_to_flashinfer_trtllm_block_layout_values(
is_gated_act_gemm,
):
from flashinfer.fused_moe.core import (
_maybe_get_cached_w3_w1_permute_indices,
get_w2_permute_indices_with_cache,
)
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
convert_moe_weights_to_flashinfer_trtllm_block_layout,
)
num_experts, intermediate, hidden = 2, 256, 256
w13_multiplier = 2 if is_gated_act_gemm else 1
w13 = torch.randn(
(num_experts, w13_multiplier * intermediate, hidden),
dtype=torch.bfloat16,
device="cuda",
)
w2 = torch.randn(
(num_experts, hidden, intermediate),
dtype=torch.bfloat16,
device="cuda",
)
def _reference_block_layout(
weight: torch.Tensor,
is_w13: bool,
cache: dict[torch.Size, torch.Tensor],
) -> torch.Tensor:
outputs = []
for expert in weight:
expert_uint8 = expert.view(torch.uint8)
if is_w13:
indices = _maybe_get_cached_w3_w1_permute_indices(
cache,
expert_uint8,
128,
is_gated_act_gemm=is_gated_act_gemm,
)
if is_gated_act_gemm:
indices = (indices + expert_uint8.shape[0] // 2) % (
expert_uint8.shape[0]
)
else:
indices = get_w2_permute_indices_with_cache(
cache,
expert_uint8,
128,
)
rows, cols = expert_uint8.shape
blocks = expert_uint8.view(rows, cols // 128, 128).permute(1, 0, 2)
outputs.append(torch.index_select(blocks, 1, indices.to(weight.device)))
return torch.stack(outputs).view(torch.bfloat16)
reference_cache: dict[torch.Size, torch.Tensor] = {}
expected_w13 = _reference_block_layout(w13, is_w13=True, cache=reference_cache)
expected_w2 = _reference_block_layout(w2, is_w13=False, cache=reference_cache)
w13_ptr = w13.data_ptr()
w2_ptr = w2.data_ptr()
actual_w13, actual_w2 = convert_moe_weights_to_flashinfer_trtllm_block_layout(
{},
w13,
w2,
is_gated_act_gemm=is_gated_act_gemm,
)
assert actual_w13.data_ptr() == w13_ptr
assert actual_w2.data_ptr() == w2_ptr
assert torch.equal(actual_w13, expected_w13)
assert torch.equal(actual_w2, expected_w2)
def _make_unquantized_flashinfer_test_layer(
monkeypatch, intermediate, is_gated, *, device="cuda"
):
from vllm.model_executor.layers.fused_moe.oracle.unquantized import (
UnquantizedMoeBackend,
)
from vllm.model_executor.layers.fused_moe.unquantized_fused_moe_method import (
UnquantizedFusedMoEMethod,
)
moe_config = make_dummy_moe_config(
num_experts=2,
hidden_dim=256,
intermediate_size=intermediate,
activation=MoEActivation.SILU if is_gated else MoEActivation.RELU2_NO_MUL,
)
moe_config.intermediate_size_per_partition = (intermediate + 127) // 128 * 128
method = object.__new__(UnquantizedFusedMoEMethod)
method.moe = moe_config
method.unquantized_backend = UnquantizedMoeBackend.FLASHINFER_TRTLLM
method.moe_kernel = None
mock_kernel = MagicMock()
monkeypatch.setattr(
method,
"_init_moe_kernel",
lambda _: setattr(method, "moe_kernel", mock_kernel),
)
layer = torch.nn.Module()
layer.moe_config = moe_config
with torch.device(device):
method.create_weights(
layer,
num_experts=2,
hidden_size=256,
intermediate_size_per_partition=moe_config.intermediate_size_per_partition,
params_dtype=torch.bfloat16,
)
return method, layer
@pytest.mark.parametrize("intermediate", [192, 256])
@pytest.mark.parametrize("is_gated", [True, False])
def test_unquantized_flashinfer_trtllm_weights_can_be_reprocessed(
monkeypatch, intermediate, is_gated
):
"""Each raw reload clears padding left dirty by prior in-place conversion."""
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
convert_moe_weights_to_flashinfer_trtllm_block_layout,
)
method, layer = _make_unquantized_flashinfer_test_layer(
monkeypatch, intermediate, is_gated
)
w13_shape, w2_shape = layer.w13_weight.shape, layer.w2_weight.shape
padded = w2_shape[-1]
w13_ptr = layer.w13_weight.data_ptr()
w2_ptr = layer.w2_weight.data_ptr()
load_numel = (
layer.w13_weight.weight_loader_numel,
layer.w2_weight.weight_loader_numel,
)
for _ in range(2):
reloaded_w13 = torch.randn_like(layer.w13_weight)
reloaded_w2 = torch.randn_like(layer.w2_weight)
reloaded_w13[:, intermediate:padded].zero_()
if is_gated:
reloaded_w13[:, padded + intermediate :].zero_()
reloaded_w2[:, :, intermediate:].zero_()
expected_w13, expected_w2 = (
convert_moe_weights_to_flashinfer_trtllm_block_layout(
{},
reloaded_w13.clone(),
reloaded_w2.clone(),
is_gated_act_gemm=is_gated,
)
)
# The loader writes only logical checkpoint slices, not padding.
layer.w13_weight.fill_(float("nan"))
layer.w2_weight.fill_(float("nan"))
layer.w13_weight[:, :intermediate].copy_(reloaded_w13[:, :intermediate])
if is_gated:
layer.w13_weight[:, padded : padded + intermediate].copy_(
reloaded_w13[:, padded : padded + intermediate]
)
layer.w2_weight[:, :, :intermediate].copy_(reloaded_w2[:, :, :intermediate])
method.process_weights_after_loading(layer)
assert layer.w13_weight.shape == w13_shape
assert layer.w2_weight.shape == w2_shape
assert layer.w13_weight.data_ptr() == w13_ptr
assert layer.w2_weight.data_ptr() == w2_ptr
assert (
layer.w13_weight.weight_loader_numel,
layer.w2_weight.weight_loader_numel,
) == load_numel
kernel_w13 = view_as_block_major_k(layer.w13_weight)
kernel_w2 = view_as_block_major_k(layer.w2_weight)
assert torch.equal(kernel_w13, expected_w13)
assert torch.equal(kernel_w2, expected_w2)
def _check_flashinfer_ipc_weights(entries, expected, mode, device_index):
from vllm.model_executor.model_loader.weight_cache.ipc_loader import IpcModelLoader
from vllm.model_executor.utils import weights_already_processed
torch.accelerator.set_device_index(device_index)
with pytest.MonkeyPatch.context() as monkeypatch:
method, layer = _make_unquantized_flashinfer_test_layer(
monkeypatch, 192, is_gated=True, device="meta"
)
loader = object.__new__(IpcModelLoader)
loader.mode = mode
loader._apply_entries(layer, entries, {}, device_index)
pointers = (layer.w13_weight.data_ptr(), layer.w2_weight.data_ptr())
# Like ipc_cache: a fresh method, only tensor metadata, no _setup_kernel.
with weights_already_processed():
method.process_weights_after_loading(layer)
assert method.moe_kernel is not None
actual = (
view_as_block_major_k(layer.w13_weight),
view_as_block_major_k(layer.w2_weight),
)
for weight, reference, pointer in zip(actual, expected, pointers):
assert weight.data_ptr() == pointer
assert torch.equal(weight.cpu(), reference)
# Cross-process addresses need not match; writes prove sharing/isolation.
with torch.no_grad():
for weight in actual:
weight.fill_(1.0)
torch.accelerator.synchronize()
@pytest.mark.parametrize("cache_ndim", [3, 4])
@pytest.mark.parametrize("mode", ["copy", "zero_copy"])
def test_unquantized_flashinfer_trtllm_cached_weights_need_no_method_state(
monkeypatch, cache_ndim, mode
):
"""A spawned IPC consumer restores views without transient method state."""
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
convert_moe_weights_to_flashinfer_trtllm_block_layout,
)
from vllm.model_executor.model_loader.weight_cache.protocol import TensorEntry
method, layer = _make_unquantized_flashinfer_test_layer(
monkeypatch, 192, is_gated=True, device="meta"
)
packed = convert_moe_weights_to_flashinfer_trtllm_block_layout(
{},
torch.randn_like(layer.w13_weight, device="cuda"),
torch.randn_like(layer.w2_weight, device="cuda"),
)
expected = [weight.cpu() for weight in packed]
entries = {}
for name, weight in zip(("w13_weight", "w2_weight"), packed):
cached = weight.view_as(getattr(layer, name)) if cache_ndim == 3 else weight
entries[name] = TensorEntry.from_tensor(cached, kind="param")
consumer = multiprocessing.get_context("spawn").Process(
target=_check_flashinfer_ipc_weights,
args=(
entries,
expected,
mode,
torch.accelerator.current_device_index(),
),
)
consumer.start()
try:
# Keep producer allocations alive until the consumer releases its views.
consumer.join(timeout=180)
assert not consumer.is_alive(), "IPC consumer timed out"
assert consumer.exitcode == 0, "IPC consumer failed; see child traceback"
for source, reference in zip(packed, expected):
expected_source = (
torch.ones_like(reference) if mode == "zero_copy" else reference
)
assert torch.equal(source.cpu(), expected_source)
finally:
if consumer.is_alive():
consumer.terminate()
consumer.join(timeout=10)
if consumer.is_alive():
consumer.kill()
consumer.join(timeout=10)
consumer.close()
@pytest.mark.parametrize(
+311
View File
@@ -0,0 +1,311 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
import vllm.distributed as distributed
from tests.kernels.moe.utils import make_dummy_moe_config
from vllm.model_executor.layers.fused_moe import (
unquantized_fused_moe_method as unquantized_module,
)
from vllm.model_executor.layers.fused_moe.config import RoutingMethodType
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
from vllm.model_executor.layers.quantization import fp8 as fp8_module
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
def _make_fp8_tp_experts(
monkeypatch,
tp_size,
tp_rank,
backend="flashinfer_trtllm",
*,
mock_backend=True,
num_experts=2,
hidden_dim=256,
intermediate_size=640,
quant_config=None,
config_overrides=None,
):
# Exercise allocation and the public weight loader without selecting a GPU kernel.
if mock_backend:
monkeypatch.setattr(
fp8_module, "select_fp8_moe_backend", lambda **kwargs: (None, None)
)
monkeypatch.setattr(
unquantized_module,
"select_unquantized_moe_backend",
lambda **kwargs: (None, None),
)
monkeypatch.setattr(
fp8_module, "get_tensor_model_parallel_world_size", lambda: tp_size
)
# The block-shape validator imports this function from vllm.distributed.
monkeypatch.setattr(
distributed, "get_tensor_model_parallel_world_size", lambda: tp_size
)
config = make_dummy_moe_config(
num_experts=num_experts,
hidden_dim=hidden_dim,
intermediate_size=intermediate_size,
experts_per_token=min(num_experts, 10),
)
config.routing_method = RoutingMethodType.RenormalizeNaive
config.moe_parallel_config.tp_size = tp_size
config.moe_parallel_config.tp_rank = tp_rank
config.intermediate_size_per_partition = intermediate_size // tp_size
config.intermediate_size_per_partition_unpadded = intermediate_size // tp_size
config.moe_backend = backend
for field, value in (config_overrides or {}).items():
setattr(config, field, value)
return RoutedExperts(
"model.layers.0.mlp.experts",
torch.bfloat16,
config,
quant_config
or Fp8Config(is_checkpoint_fp8_serialized=True, weight_block_size=[128, 128]),
expert_map_manager=SimpleNamespace(
local_num_experts=num_experts,
placement_strategy="linear",
expert_map=None,
expert_mask=None,
routing_tables=None,
map_global_to_local=lambda index: index,
),
)
@pytest.mark.parametrize("tp_size", [2, 4, 8])
@pytest.mark.parametrize("batched", [False, True])
@pytest.mark.parametrize("intermediate_size", [640, 896])
def test_fp8_block_aligned_tp_preserves_checkpoint(
monkeypatch, tp_size, batched, intermediate_size
):
"""All ranks reconstruct the original dequantized projections, including
padding-only ranks. Reloading must clear stale weights and scales.
"""
generator = torch.Generator().manual_seed(42)
weights = {
"w1": torch.randn(2, intermediate_size, 256, generator=generator).to(
torch.float8_e4m3fn
),
"w3": torch.randn(2, intermediate_size, 256, generator=generator).to(
torch.float8_e4m3fn
),
"w2": torch.randn(2, 256, intermediate_size, generator=generator).to(
torch.float8_e4m3fn
),
}
scales = {
name: torch.rand(2, w.shape[1] // 128, w.shape[2] // 128, generator=generator)
+ 0.1
for name, w in weights.items()
}
reconstructed: dict[str, list[torch.Tensor]] = {name: [] for name in weights}
num_blocks = intermediate_size // 128
for rank in range(tp_size):
layer = _make_fp8_tp_experts(
monkeypatch, tp_size, rank, intermediate_size=intermediate_size
)
assert layer.quant_method.weight_scale_refine is None
assert layer.quant_method.moe_block_shape == [128, 128]
width = layer.moe_config.intermediate_size_per_partition
assert width == ((num_blocks + tp_size - 1) // tp_size) * 128
for name in weights:
prefix = "w2" if name == "w2" else "w13"
for suffix, checkpoint in (
("weight", weights[name]),
("weight_scale_inv", scales[name]),
):
param_name = f"{prefix}_{suffix}"
param = getattr(layer, param_name)
# Also reload after dirtying the destination, to catch padding leaks.
for _ in range(2):
if name != "w3":
param.data.fill_(7)
if batched:
assert param.weight_loader(
param, checkpoint, param_name, name, 0, return_success=True
)
else:
for expert in range(2):
assert param.weight_loader(
param,
checkpoint[expert],
param_name,
name,
expert,
return_success=True,
)
w = getattr(layer, f"{prefix}_weight").float()
s = getattr(layer, f"{prefix}_weight_scale_inv")
if name in ("w1", "w3"):
half = 0 if name == "w1" else 1
w = w.chunk(2, dim=1)[half]
s = s.chunk(2, dim=1)[half]
dim = 2 if name == "w2" else 1
valid = max(0, min(width, intermediate_size - rank * width))
assert torch.count_nonzero(w.narrow(dim, valid, width - valid)) == 0
assert torch.all(s.narrow(dim, valid // 128, (width - valid) // 128) == 1)
dequant = w * s.repeat_interleave(128, dim=1).repeat_interleave(128, dim=2)
reconstructed[name].append(dequant.narrow(dim, 0, valid))
for name, parts in reconstructed.items():
expected = weights[name].float() * scales[name].repeat_interleave(
128, dim=1
).repeat_interleave(128, dim=2)
assert torch.equal(torch.cat(parts, dim=2 if name == "w2" else 1), expected)
@pytest.mark.parametrize("backend", ["auto", "triton"])
@pytest.mark.parametrize("tp_size,block", [(2, 64), (4, 32)])
def test_fp8_tp_default_keeps_refined_layout(monkeypatch, backend, tp_size, block):
layer = _make_fp8_tp_experts(monkeypatch, tp_size, 0, backend)
assert layer.moe_config.intermediate_size_per_partition == 640 // tp_size
assert layer.quant_method.moe_block_shape == [block, block]
@pytest.mark.parametrize(
"field,value",
[
("hidden_dim", 192),
("intermediate_size", 672),
("is_lora_enabled", True),
("has_bias", True),
],
)
def test_fp8_block_aligned_tp_rejects_unsupported_layout(monkeypatch, field, value):
with pytest.raises(ValueError, match="Block-aligned FP8 TP sharding requires"):
_make_fp8_tp_experts(monkeypatch, 4, 0, config_overrides={field: value})
@pytest.mark.parametrize("tp_size", [1, 5])
def test_fp8_aligned_tp_keeps_original_layout(monkeypatch, tp_size):
layer = _make_fp8_tp_experts(monkeypatch, tp_size, 0)
assert layer.moe_config.intermediate_size_per_partition == 640 // tp_size
assert not layer.moe_config.tp_shard_with_padding
assert layer.quant_method.weight_scale_refine is None
def test_fp8_skipped_layer_keeps_original_tp_layout(monkeypatch, default_vllm_config):
layer = _make_fp8_tp_experts(
monkeypatch,
4,
0,
quant_config=Fp8Config(
is_checkpoint_fp8_serialized=True,
weight_block_size=[128, 128],
ignored_layers=["model.layers.0.mlp.experts"],
),
)
assert isinstance(layer.quant_method, unquantized_module.UnquantizedFusedMoEMethod)
assert not layer.moe_config.tp_shard_with_padding
assert layer.moe_config.intermediate_size_per_partition == 160
assert layer.w13_weight.shape == (2, 320, 256)
assert layer.w2_weight.shape == (2, 256, 160)
def test_fp8_block_aligned_tp_rejects_presharded_weights(monkeypatch):
layer = _make_fp8_tp_experts(monkeypatch, 4, 0)
with pytest.raises(ValueError, match="unsharded checkpoint"):
layer.w13_weight.weight_loader(
layer.w13_weight,
torch.zeros(160, 256, dtype=torch.float8_e4m3fn),
"w13_weight",
"w1",
0,
)
@pytest.mark.parametrize("tp_size", [2, 4, 8])
@pytest.mark.parametrize("num_tokens", [1, 17])
@torch.inference_mode()
def test_fp8_block_aligned_tp_flashinfer_matches_unsharded(
monkeypatch,
tp_size,
num_tokens,
dist_init,
workspace_init,
):
"""Compare sharded FI with unsharded FI, reporting the cross-backend
difference separately because activation quantization can differ.
"""
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.model_executor.layers.fused_moe.config import fp8_w8a8_moe_quant_config
from vllm.model_executor.layers.fused_moe.fused_moe import fused_experts
from vllm.platforms import current_platform
if not current_platform.is_device_capability_family(100):
pytest.skip("Requires datacenter Blackwell and FlashInfer TRTLLM")
torch.manual_seed(42)
e, h, n, topk = 16, 2560, 640, 10
with torch.device("cuda"), set_current_vllm_config(VllmConfig()):
x = torch.randn(num_tokens, h, dtype=torch.bfloat16) / 10
logits = torch.randn(num_tokens, e, dtype=torch.float32)
probabilities = logits.softmax(dim=-1)
topk_weights, topk_ids = probabilities.topk(topk, dim=-1)
topk_weights /= topk_weights.sum(dim=-1, keepdim=True)
weights = {
"w1": torch.randn(e, n, h).to(torch.float8_e4m3fn),
"w3": torch.randn(e, n, h).to(torch.float8_e4m3fn),
"w2": torch.randn(e, h, n).to(torch.float8_e4m3fn),
}
scales = {
name: (torch.rand(e, w.shape[1] // 128, w.shape[2] // 128) + 0.5) / 32
for name, w in weights.items()
}
ref = fused_experts(
x,
torch.cat([weights["w1"], weights["w3"]], dim=1),
weights["w2"],
topk_weights,
topk_ids,
quant_config=fp8_w8a8_moe_quant_config(
w1_scale=torch.cat([scales["w1"], scales["w3"]], dim=1),
w2_scale=scales["w2"],
block_shape=[128, 128],
),
)
total = torch.zeros_like(ref, dtype=torch.float32)
fi_reference = None
for rank in range(-1, tp_size):
layer = _make_fp8_tp_experts(
monkeypatch,
1 if rank == -1 else tp_size,
max(rank, 0),
mock_backend=False,
num_experts=e,
hidden_dim=h,
)
for name in weights:
prefix = "w2" if name == "w2" else "w13"
for suffix, checkpoint in (
("weight", weights[name]),
("weight_scale_inv", scales[name]),
):
param_name = f"{prefix}_{suffix}"
param = getattr(layer, param_name)
param.weight_loader(param, checkpoint, param_name, name, 0)
method = layer.quant_method
method.process_weights_after_loading(layer)
assert method.is_monolithic
out = method.apply_monolithic(layer, x, logits)
assert torch.isfinite(out).all()
if rank == -1:
fi_reference = out.float().clone()
else:
total += out.float()
# Different FP8 GEMM reduction orders need not be bitwise identical.
assert fi_reference is not None
relative_l2 = (total - fi_reference).norm() / fi_reference.norm().clamp_min(
1e-8
)
cross_backend_l2 = (
fi_reference - ref.float()
).norm() / ref.float().norm().clamp_min(1e-8)
print(
f"TP{tp_size} M={num_tokens}: shard_l2={relative_l2.item():.6f}, "
f"unsharded_fi_vs_triton_l2={cross_backend_l2.item():.6f}"
)
assert relative_l2 < 0.01, relative_l2.item()
@@ -7,7 +7,7 @@ import torch
import torch.nn.functional as F
from vllm.platforms import current_platform
from vllm.utils.import_utils import has_triton_kernels
from vllm.utils.import_utils import get_triton_kernels_version, has_triton_kernels
if not has_triton_kernels():
pytest.skip(
@@ -15,9 +15,15 @@ if not has_triton_kernels():
allow_module_level=True,
)
import triton_kernels.matmul_ogs_details.opt_flags as opt_flags
import triton_kernels.swiglu
from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig
if get_triton_kernels_version() == "3.8":
# 3.8: matmul_ogs -> matmul, matmul_ogs_details -> matmul_details
import triton_kernels.matmul_details.opt_flags as opt_flags
from triton_kernels.matmul import FlexCtx, PrecisionConfig
else:
import triton_kernels.matmul_ogs_details.opt_flags as opt_flags
from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig
from triton_kernels.numerics import InFlexData
from triton_kernels.numerics_details.mxfp import downcast_to_mxfp, upcast_from_mxfp
from triton_kernels.tensor import FP4, convert_layout, wrap_torch_tensor
@@ -28,9 +34,10 @@ from vllm.model_executor.layers.fused_moe.config import mxfp4_w4a16_moe_quant_co
from vllm.model_executor.layers.fused_moe.experts.gpt_oss_triton_kernels_moe import (
triton_kernel_moe_forward,
)
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import mx_scale_kwargs
from vllm.utils.math_utils import round_up
from .utils import shuffle_weight
from .utils import mxfp4_w_layouts, shuffle_weight
def deshuffle(w: torch.Tensor):
@@ -133,12 +140,12 @@ def init_compute_data(M, K, N, E, a_dtype: str, w_dtype: str, num_warps: int):
x_tri = F.pad(x_tri, (0, x_pad, 0, 0), mode="constant", value=0)
w_layout, w_layout_opts = layout.make_default_matmul_mxfp4_w_layout(mx_axis=1)
w_scale_layout, w_scale_layout_opts = (
layout.make_default_matmul_mxfp4_w_scale_layout(
mx_axis=1, num_warps=num_warps
)
)
(
w_layout,
w_layout_opts,
w_scale_layout,
w_scale_layout_opts,
) = mxfp4_w_layouts(mx_axis=1, num_warps=num_warps)
w1_tri, w1_scale_tri = downcast_to_mxfp(w1_tri, torch.uint8, axis=1)
w1 = upcast_from_mxfp(w1_tri, w1_scale_tri, torch.bfloat16, axis=1)
@@ -165,10 +172,10 @@ def init_compute_data(M, K, N, E, a_dtype: str, w_dtype: str, num_warps: int):
)
pc1 = PrecisionConfig(
weight_scale=w1_scale_tri, flex_ctx=FlexCtx(rhs_data=InFlexData())
**mx_scale_kwargs(w1_scale_tri), flex_ctx=FlexCtx(rhs_data=InFlexData())
)
pc2 = PrecisionConfig(
weight_scale=w2_scale_tri, flex_ctx=FlexCtx(rhs_data=InFlexData())
**mx_scale_kwargs(w2_scale_tri), flex_ctx=FlexCtx(rhs_data=InFlexData())
)
# tucuate so the rest can run properly
@@ -281,8 +288,6 @@ class Case:
@pytest.mark.parametrize("num_token", [2])
@pytest.mark.parametrize("tp", [1, 2, 4, 8])
def test_equiv(num_token, a_dtype, w_dtype, tp, workspace_init):
from triton_kernels.tensor_details import layout
if not hasattr(layout, "make_default_matmul_mxfp4_w_layout"):
pytest.skip("make_default_matmul_mxfp4_w_layout not available")
@@ -387,6 +392,11 @@ def test_routing_data_from_sparse_topk_parity(n_tokens, n_experts, topk):
if gptoss_moe.triton_kernels_version == "3.5.1":
pytest.skip("SparseMatrix path requires triton_kernels v3.6.0+")
if gptoss_moe.triton_kernels_version == "3.8":
pytest.skip(
"3.8 rebuilds routing from raw ids, so routing_data_from_sparse_topk "
"just forwards to make_routing_data and the comparison is vacuous"
)
from triton_kernels.topk import topk as topk_fn
+32
View File
@@ -15,8 +15,10 @@ from vllm.config import (
get_cached_compilation_config,
set_current_vllm_config,
)
from vllm.forward_context import set_forward_context
from vllm.model_executor.layers.fused_moe.router.grouped_topk_router import (
GroupedTopk,
GroupedTopKRouter,
fused_grouped_topk,
)
from vllm.platforms import current_platform
@@ -70,6 +72,36 @@ def _single_group_reference(
return values, indices.to(torch.int32)
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="This test is skipped on non-CUDA platform."
)
@pytest.mark.parametrize("skip_padding", [False, True])
def test_kimi_grouped_topk_masks_padding_when_enabled(skip_padding: bool):
hidden_states = torch.randn((2, 16), device="cuda")
gating_output = torch.randn((2, 896), device="cuda")
is_padding = torch.tensor([False, True], device="cuda")
router = GroupedTopKRouter(
top_k=16,
global_num_experts=896,
num_expert_group=1,
topk_group=1,
skip_padding=skip_padding,
)
with set_forward_context(None, VllmConfig(), is_padding=is_padding):
topk_weights, topk_ids = router._compute_routing(
hidden_states, gating_output, torch.int32
)
assert torch.all(topk_ids[0] >= 0)
if skip_padding:
assert torch.all(topk_ids[1] == -1)
assert torch.all(topk_weights[1] == 0)
else:
assert torch.all(topk_ids[1] >= 0)
assert torch.all(topk_weights[1] > 0)
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="This test is skipped on non-CUDA platform."
)
@@ -10,7 +10,7 @@ import torch.nn.functional as F
from tests.utils import wait_for_gpu_memory_to_clear
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.utils.import_utils import has_triton_kernels
from vllm.utils.import_utils import get_triton_kernels_version, has_triton_kernels
if not has_triton_kernels():
pytest.skip(
@@ -18,11 +18,14 @@ if not has_triton_kernels():
allow_module_level=True,
)
from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig
if get_triton_kernels_version() == "3.8":
# 3.8: matmul_ogs -> matmul
from triton_kernels.matmul import FlexCtx, PrecisionConfig
else:
from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig
from triton_kernels.numerics import InFlexData
from triton_kernels.numerics_details.mxfp import downcast_to_mxfp, upcast_from_mxfp
from triton_kernels.tensor import FP4, convert_layout, wrap_torch_tensor
from triton_kernels.tensor_details import layout
from triton_kernels.testing import assert_close
from vllm.config import VllmConfig, set_current_vllm_config
@@ -35,11 +38,12 @@ from vllm.model_executor.layers.fused_moe.experts.gpt_oss_triton_kernels_moe imp
UnfusedOAITritonExperts,
)
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import mx_scale_kwargs
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up
from vllm.utils.torch_utils import set_random_seed
from .utils import make_dummy_moe_config, shuffle_weight
from .utils import make_dummy_moe_config, mxfp4_w_layouts, shuffle_weight
MNK = [
(1, 512, 384),
@@ -130,10 +134,12 @@ def make_weights(dtype, k, n, e):
w2 = w2[..., :n, :k]
num_warps = 8
w_layout, w_layout_opts = layout.make_default_matmul_mxfp4_w_layout(mx_axis=1)
w_scale_layout, w_scale_layout_opts = (
layout.make_default_matmul_mxfp4_w_scale_layout(mx_axis=1, num_warps=num_warps)
)
(
w_layout,
w_layout_opts,
w_scale_layout,
w_scale_layout_opts,
) = mxfp4_w_layouts(mx_axis=1, num_warps=num_warps)
w1_tri = convert_layout(wrap_torch_tensor(w1_tri, FP4), w_layout, **w_layout_opts)
w1_scale_tri = convert_layout(
@@ -150,10 +156,10 @@ def make_weights(dtype, k, n, e):
)
w1_precision_config = PrecisionConfig(
weight_scale=w1_scale_tri, flex_ctx=FlexCtx(rhs_data=InFlexData())
**mx_scale_kwargs(w1_scale_tri), flex_ctx=FlexCtx(rhs_data=InFlexData())
)
w2_precision_config = PrecisionConfig(
weight_scale=w2_scale_tri, flex_ctx=FlexCtx(rhs_data=InFlexData())
**mx_scale_kwargs(w2_scale_tri), flex_ctx=FlexCtx(rhs_data=InFlexData())
)
return (
@@ -12,7 +12,13 @@ correctly handles this mismatch.
import pytest
import torch
from vllm.model_executor.layers.fused_moe.oracle.unquantized import (
UnquantizedMoeBackend,
)
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
from vllm.model_executor.layers.fused_moe.unquantized_fused_moe_method import (
UnquantizedFusedMoEMethod,
)
from .utils import make_dummy_moe_config
@@ -249,6 +255,57 @@ class TestNarrowExpertDataForPadding:
class TestWeightLoadingWithPaddedHiddenSize:
"""Integration-style tests that simulate padded weight loading."""
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])
@pytest.mark.parametrize("tp_rank", [0, 1])
def test_load_w2_chunks_noncontiguous_cpu_source_to_padded_cuda(
self, dtype, tp_rank
):
hidden = 4096
intermediate = 1024
loaded_weight = (
torch.arange(hidden * intermediate * 2)
.remainder(251)
.to(dtype)
.reshape(hidden, intermediate * 2)
)
tp_source = loaded_weight[
:, intermediate * tp_rank : intermediate * (tp_rank + 1)
]
expert_data_full = torch.zeros(
hidden + 8, intermediate + 8, device="cuda", dtype=dtype
)
destination = expert_data_full[:hidden, :intermediate]
assert not tp_source.is_contiguous()
assert tp_source.nbytes > 1 << 20
assert not destination.is_contiguous()
experts = object.__new__(RoutedExperts)
torch.nn.Module.__init__(experts)
experts.moe_config = make_dummy_moe_config()
experts.moe_config.moe_parallel_config.tp_size = 2
torch.accelerator.synchronize()
allocated_before = torch.accelerator.memory_allocated()
torch.accelerator.reset_peak_memory_stats()
experts._load_w2(
expert_data=expert_data_full,
shard_dim=1,
loaded_weight=loaded_weight,
tp_rank=tp_rank,
)
torch.accelerator.synchronize()
peak_extra = torch.accelerator.max_memory_allocated() - allocated_before
# A single copy into the strided CUDA view allocates a full-shard
# temporary. Correct values alone would not catch that regression.
assert peak_extra < tp_source.nbytes
torch.testing.assert_close(destination.cpu(), tp_source)
assert torch.count_nonzero(expert_data_full[hidden:, :]) == 0
assert torch.count_nonzero(expert_data_full[:hidden, intermediate:]) == 0
def test_load_w2_with_padding(self):
"""Simulate loading w2 weights when hidden_size is padded."""
padded_hidden = 3072
@@ -364,6 +421,50 @@ class TestWeightLoadingWithPaddedHiddenSize:
)
class TestUnquantizedTrtLlmPrePadding:
@staticmethod
def _make_method(
intermediate: int,
backend: UnquantizedMoeBackend = UnquantizedMoeBackend.FLASHINFER_TRTLLM,
) -> UnquantizedFusedMoEMethod:
moe_config = make_dummy_moe_config(
num_experts=2,
hidden_dim=64,
intermediate_size=intermediate,
)
method = object.__new__(UnquantizedFusedMoEMethod)
method.moe = moe_config
method.unquantized_backend = backend
method.moe_kernel = None
return method
@pytest.mark.parametrize(
"backend,original,expected",
[
(UnquantizedMoeBackend.FLASHINFER_TRTLLM, 1344, 1408),
(UnquantizedMoeBackend.FLASHINFER_TRTLLM, 1408, 1408),
(UnquantizedMoeBackend.TRITON, 1344, 1344),
],
)
def test_rounds_intermediate_before_weight_allocation(
self,
backend: UnquantizedMoeBackend,
original: int,
expected: int,
):
method = self._make_method(original, backend)
hidden, intermediate = method.maybe_roundup_sizes(
hidden_size=64,
intermediate_size_per_partition=original,
act_dtype=torch.bfloat16,
moe_parallel_config=method.moe.moe_parallel_config,
)
assert hidden == 64
assert intermediate == expected
class TestLoadWeightsExpertBias:
"""Some quantized exports (e.g. GPTQ, llm-compressor NVFP4) materialize
all-zero per-expert `.bias` tensors for models whose experts have no bias
+412
View File
@@ -0,0 +1,412 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test MoonEP dispatch / prefetch / combine logic (BF16 PoC).
Two paths, both compared against the pure-PyTorch reference MoE:
- MoonEPPrepareAndFinalize + a reference segment-loop expert runner over
MoonEP's expert-grouped ``[NvS, H]`` layout;
- the full modular kernel, MoonEPPrepareAndFinalize + MoonEPExperts through
FusedMoEKernel.
Requires NVSwitch multicast capable GPUs.
"""
import dataclasses
import types
import pytest
import torch
import torch.nn.functional as F
from torch.distributed import ProcessGroup
from tests.kernels.moe.utils import make_test_weights
from tests.kernels.utils import torch_experts
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
from vllm.utils.import_utils import has_moonep
from vllm.utils.torch_utils import set_random_seed
from ...utils import multi_gpu_test
from .parallel_utils import ProcessGroupInfo, parallel_launch
if has_moonep():
from vllm.model_executor.layers.fused_moe.prepare_finalize.moonep import (
MoonEPExpertWeightLayout,
MoonEPPrepareAndFinalize,
make_moonep_weight_layout,
)
requires_moonep = pytest.mark.skipif(
not has_moonep(),
reason="Requires MoonEP",
)
class MulticastNotAvailableError(RuntimeError):
pass
@dataclasses.dataclass
class TestConfig:
topk: int
m: int
k: int
n: int
num_experts: int
router_skew: float
apply_router_weight_on_input: bool = False
@dataclasses.dataclass
class TestTensors:
rank_tokens: torch.Tensor
topk: torch.Tensor
topk_weights: torch.Tensor
config: TestConfig
@staticmethod
def make(config: TestConfig) -> "TestTensors":
rank_tokens = (
torch.randn((config.m, config.k), device="cuda", dtype=torch.bfloat16) / 10
)
# Skewed routing via a per-expert bias: scaling logits by a scalar
# preserves their ordering and would not change the selected topk
# ids, but a shared bias makes a few experts hot on every token so
# the planner has to fill redundant-expert prefetch slots.
expert_bias = config.router_skew * torch.randn(
1, config.num_experts, device="cuda", dtype=torch.float32
)
logits = (
torch.randn(
config.m, config.num_experts, device="cuda", dtype=torch.float32
)
+ expert_bias
)
topk_weights, topk = torch.topk(logits, config.topk, dim=-1)
topk_weights = torch.softmax(topk_weights, dim=-1)
return TestTensors(
rank_tokens=rank_tokens,
topk=topk.to(dtype=torch.int64),
topk_weights=topk_weights,
config=config,
)
def reference_moonep_experts(
hidden_nvsh: torch.Tensor,
route_weights_nvs: torch.Tensor,
cu_seqlens: torch.Tensor,
weight_layout: "MoonEPExpertWeightLayout",
) -> torch.Tensor:
"""Segment loop over MoonEP's expert-grouped layout.
``prefetch_weight`` has already materialized redundant experts' weights
in rows ``[E, E+B)``, so every segment reads its own row. Route weights
are applied here; MoonEP's combine does the K-sum.
"""
output = torch.empty_like(hidden_nvsh)
prev = 0
for row, cur in enumerate(cu_seqlens.tolist()):
if cur == prev:
continue
x = hidden_nvsh[prev:cur]
gate = F.linear(x, weight_layout.full_gate_weight[row])
up = F.linear(x, weight_layout.full_up_weight[row])
y = F.linear(F.silu(gate) * up, weight_layout.full_down_weight[row])
y = y * route_weights_nvs[prev:cur].to(dtype=y.dtype).unsqueeze(-1)
output[prev:cur].copy_(y)
prev = cur
if prev < hidden_nvsh.shape[0]:
output[prev:].zero_()
return output
def make_moonep_prepare_finalize(
pg: ProcessGroup,
pgi: ProcessGroupInfo,
hidden_size: int,
num_experts: int,
topk: int,
max_tokens_per_rank: int,
weight_layout: "MoonEPExpertWeightLayout",
pass_layout_to_pf: bool = True,
):
from moonep._C import nvl_multicast_supported
from vllm.model_executor.layers.fused_moe.prepare_finalize.moonep import (
MoonEPBufferPool,
)
if not nvl_multicast_supported():
raise MulticastNotAvailableError("NVSwitch multicast not available")
pool = MoonEPBufferPool(
dict(
H=hidden_size,
K=topk,
E=num_experts,
num_ep_ranks=pgi.world_size,
B=weight_layout.num_prefetch_slots,
group=pg,
explicitly_destroy=True,
),
max_tokens_per_rank=max_tokens_per_rank,
)
return pool, MoonEPPrepareAndFinalize(
buffer_pool=pool,
max_tokens_per_rank=max_tokens_per_rank,
num_dispatchers=pgi.world_size,
num_global_experts=num_experts,
weight_layout=weight_layout if pass_layout_to_pf else None,
)
def moonep_moe_impl(
pg: ProcessGroup,
pgi: ProcessGroupInfo,
test_tensors: TestTensors,
w1: torch.Tensor,
w2: torch.Tensor,
num_prefetch_slots: int,
) -> torch.Tensor:
config = test_tensors.config
hidden_size = test_tensors.rank_tokens.shape[1]
max_tokens_per_rank = 128 * ((config.m + 127) // 128)
weight_layout = make_moonep_weight_layout(w1, w2, num_prefetch_slots)
pool, pf = make_moonep_prepare_finalize(
pg,
pgi,
hidden_size,
config.num_experts,
config.topk,
max_tokens_per_rank,
weight_layout,
)
try:
hidden_nvsh, _, _, _, route_weights_nvs = pf.prepare(
test_tensors.rank_tokens,
test_tensors.topk_weights,
test_tensors.topk,
num_experts=config.num_experts,
expert_map=None,
apply_router_weight_on_input=config.apply_router_weight_on_input,
quant_config=_no_quant_config(),
)
assert route_weights_nvs is not None
if config.apply_router_weight_on_input:
# prepare() already applied the weights to the inputs; the
# runner must not apply them again.
route_weights_nvs = torch.ones_like(route_weights_nvs)
if config.router_skew >= 8 and config.m >= 100:
# Heavy skew must actually engage the redundant-expert planner.
assert (pf.plan.experts_to_copy >= 0).any(), (
"no prefetch slot used despite heavy router skew"
)
expert_out = reference_moonep_experts(
hidden_nvsh, route_weights_nvs, pf.cu_seqlens, weight_layout
)
output = torch.empty_like(test_tensors.rank_tokens)
pf.finalize(
output,
expert_out,
test_tensors.topk_weights,
test_tensors.topk,
apply_router_weight_on_input=False,
weight_and_reduce_impl=TopKWeightAndReduceNoOP(),
)
torch.accelerator.synchronize()
return output
finally:
pool.destroy()
def _no_quant_config():
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
return FusedMoEQuantConfig.make(quant_dtype=None)
def moonep_modular_kernel_impl(
pg: ProcessGroup,
pgi: ProcessGroupInfo,
test_tensors: TestTensors,
w1: torch.Tensor,
w2: torch.Tensor,
num_prefetch_slots: int,
) -> torch.Tensor:
"""Full modular-kernel path: MoonEPPrepareAndFinalize + MoonEPExperts."""
from tests.kernels.moe.utils import make_dummy_moe_config
from vllm.model_executor.layers.fused_moe.experts.moonep_experts import (
MoonEPExperts,
)
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
config = test_tensors.config
hidden_size = test_tensors.rank_tokens.shape[1]
max_tokens_per_rank = 128 * ((config.m + 127) // 128)
weight_layout = make_moonep_weight_layout(w1, w2, num_prefetch_slots)
# weight_layout deliberately not passed to the P/F: the engine path
# resolves it through post_init_setup + the experts' weight hook.
pool, pf = make_moonep_prepare_finalize(
pg,
pgi,
hidden_size,
config.num_experts,
config.topk,
max_tokens_per_rank,
weight_layout,
pass_layout_to_pf=False,
)
try:
moe_config = make_dummy_moe_config(
num_experts=config.num_experts,
experts_per_token=config.topk,
hidden_dim=hidden_size,
intermediate_size=config.n,
max_num_tokens=max_tokens_per_rank,
)
experts = MoonEPExperts(moe_config=moe_config, quant_config=_no_quant_config())
# Stand-in for the layer carrying the layout, as
# convert_to_unquantized_kernel_format leaves it in the engine path.
fake_layer = types.SimpleNamespace(_moonep_weight_layout=weight_layout)
experts.process_weights_after_loading(fake_layer)
kernel = FusedMoEKernel(prepare_finalize=pf, fused_experts=experts)
out = kernel.apply(
hidden_states=test_tensors.rank_tokens,
w1=weight_layout.full_gate_weight,
w2=weight_layout.full_down_weight,
topk_weights=test_tensors.topk_weights,
topk_ids=test_tensors.topk,
activation=MoEActivation.SILU,
global_num_experts=config.num_experts,
expert_map=None,
apply_router_weight_on_input=config.apply_router_weight_on_input,
)
torch.accelerator.synchronize()
return out
finally:
pool.destroy()
def _moonep_moe(
pgi: ProcessGroupInfo,
config: TestConfig,
w1: torch.Tensor,
w2: torch.Tensor,
num_prefetch_slots: int,
use_modular_kernel: bool,
):
from vllm.v1.worker.workspace import init_workspace_manager
device_idx = torch.accelerator.current_device_index()
init_workspace_manager(torch.device("cuda", device_idx))
w1 = w1.to(device=device_idx)
w2 = w2.to(device=device_idx)
pg = torch.distributed.new_group(list(range(pgi.world_size)))
set_random_seed(7 + pgi.rank)
test_tensors = TestTensors.make(config)
with set_current_vllm_config(VllmConfig()):
torch_combined = torch_experts(
test_tensors.rank_tokens,
w1,
w2,
test_tensors.topk_weights,
test_tensors.topk,
apply_router_weights_on_input=config.apply_router_weight_on_input,
)
impl = moonep_modular_kernel_impl if use_modular_kernel else moonep_moe_impl
moonep_combined = impl(pg, pgi, test_tensors, w1, w2, num_prefetch_slots)
torch.testing.assert_close(
torch_combined,
moonep_combined,
atol=6e-2,
rtol=6e-2,
)
MNKs = [
(1, 256, 512),
(37, 256, 512),
(100, 512, 1024),
(512, 768, 2048),
]
@pytest.mark.parametrize("m,n,k", MNKs)
@pytest.mark.parametrize("num_experts", [32])
@pytest.mark.parametrize("topk", [4])
@pytest.mark.parametrize("router_skew", [1.0, 8.0])
@pytest.mark.parametrize("num_prefetch_slots", [4])
@pytest.mark.parametrize("world_size", [2])
@pytest.mark.parametrize("use_modular_kernel", [False, True])
@multi_gpu_test(num_gpus=2)
@requires_moonep
def test_moonep_bf16_moe(
m: int,
n: int,
k: int,
num_experts: int,
topk: int,
router_skew: float,
num_prefetch_slots: int,
world_size: int,
use_modular_kernel: bool,
):
set_random_seed(7)
config = TestConfig(
topk=topk,
m=m,
k=k,
n=n,
num_experts=num_experts,
router_skew=router_skew,
)
(_, w1, _, _), (_, w2, _, _) = make_test_weights(num_experts, n, k)
try:
parallel_launch(
world_size,
_moonep_moe,
config,
w1,
w2,
num_prefetch_slots,
use_modular_kernel,
)
except Exception as exc:
if "MulticastNotAvailableError" in str(exc):
pytest.skip("NVSwitch multicast not available")
raise
@pytest.mark.parametrize("use_modular_kernel", [False, True])
@multi_gpu_test(num_gpus=2)
@requires_moonep
def test_moonep_input_weighted_moe(use_modular_kernel: bool):
"""Llama-4-style routing applies route weights to the expert inputs."""
set_random_seed(7)
config = TestConfig(
topk=1,
m=100,
k=1024,
n=512,
num_experts=32,
router_skew=1.0,
apply_router_weight_on_input=True,
)
(_, w1, _, _), (_, w2, _, _) = make_test_weights(
config.num_experts, config.n, config.k
)
try:
parallel_launch(2, _moonep_moe, config, w1, w2, 4, use_modular_kernel)
except Exception as exc:
if "MulticastNotAvailableError" in str(exc):
pytest.skip("NVSwitch multicast not available")
raise
@@ -2,10 +2,11 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""MXFP8 MoE backend selection for the AITER FlyDSL kernel (gfx950).
GPU-free: mocks the platform (gfx950) and the ``flydsl`` package check, then
GPU-free: mocks the platform (gfx950) and the aiter fused-MoE enable flag, then
exercises the oracle so the FlyDSL backend is auto-picked when usable (including
under expert parallelism, since apply() forwards the expert_map as aiter's
expert_mask) and skipped (native fallback) when the device/package is missing.
expert_mask) and skipped (native fallback) when the device is unsupported or the
aiter runtime is disabled.
"""
import dataclasses
@@ -48,6 +49,8 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import ( # noqa:
kMxfp8Static,
)
from vllm._aiter_ops import rocm_aiter_ops # noqa: E402 # isort: skip
_AITER_MOD = "vllm.model_executor.layers.fused_moe.experts.aiter_mxfp8_moe"
@@ -82,8 +85,8 @@ def _gfx950():
)
def _flydsl_installed(present: bool):
return patch(f"{_AITER_MOD}.is_aiter_mxfp8_moe_available", return_value=present)
def _aiter_moe_enabled(present: bool):
return patch.object(rocm_aiter_ops, "is_fused_moe_enabled", return_value=present)
def test_aiter_mxfp8_registered():
@@ -109,13 +112,18 @@ def test_ep_supported(ep_size):
@pytest.mark.parametrize(
"present,ep_size,supported,reason_substr",
[
(True, 1, True, None), # gfx950 + flydsl + TP -> selectable
(True, 2, True, None), # gfx950 + flydsl + EP -> selectable (expert_mask)
(False, 1, False, "flydsl package"), # package missing -> clear reason
(True, 1, True, None), # gfx950 + aiter MoE + TP -> selectable
(True, 2, True, None), # gfx950 + aiter MoE + EP -> selectable (expert_mask)
(
False,
1,
False,
"does not support current device",
), # disabled -> not selected
],
)
def test_is_supported_config(present, ep_size, supported, reason_substr):
with _gfx950(), _flydsl_installed(present):
with _gfx950(), _aiter_moe_enabled(present):
ok, reason = AiterMxfp8Experts.is_supported_config(
AiterMxfp8Experts,
_config(ep_size),
@@ -130,8 +138,8 @@ def test_is_supported_config(present, ep_size, supported, reason_substr):
def test_explicit_moe_backend_aiter():
"""--moe-backend aiter: returns FlyDSL when usable (TP or EP), else a clear
ValueError when the flydsl package is missing."""
with _gfx950(), _flydsl_installed(True):
ValueError when the aiter MoE runtime is disabled."""
with _gfx950(), _aiter_moe_enabled(True):
assert (
_select_kernel_cls(Fp8MoeBackend.AITER_MXFP8, _config(1))
is AiterMxfp8Experts
@@ -142,18 +150,17 @@ def test_explicit_moe_backend_aiter():
)
with (
_gfx950(),
_flydsl_installed(False),
pytest.raises(ValueError, match="flydsl package"),
_aiter_moe_enabled(False),
pytest.raises(ValueError, match="does not support current device"),
):
_select_kernel_cls(Fp8MoeBackend.AITER_MXFP8, _config(1))
def test_gfx950_picks_aiter():
"""Auto-select on real ROCm hardware with flydsl usable -> FlyDSL wins."""
# NOTE: Fp8MoeBackend.AITER_MXFP8 does not require VLLM_ROCM_USE_AITER=1
"""Auto-select on real ROCm hardware with aiter MoE enabled -> FlyDSL wins."""
with (
patch(f"{_AITER_MOD}.current_platform.supports_mx", return_value=True),
_flydsl_installed(True),
_aiter_moe_enabled(True),
):
backend, experts_cls = select_mxfp8_moe_backend(_config())
assert backend is Fp8MoeBackend.AITER_MXFP8
+15
View File
@@ -87,6 +87,21 @@ def test_multiple_expert_groups_use_grouped_topk() -> None:
)
assert isinstance(router, GroupedTopKRouter)
assert not router.skip_padding
def test_grouped_topk_padding_skip_must_be_enabled() -> None:
router = create_fused_moe_router(
top_k=4,
global_num_experts=128,
use_grouped_topk=True,
num_expert_group=8,
topk_group=4,
skip_padding=True,
)
assert isinstance(router, GroupedTopKRouter)
assert router.skip_padding
def test_degenerate_grouped_config_with_bias_uses_topk_bias() -> None:
+55 -2
View File
@@ -12,6 +12,7 @@ import pytest
import torch
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from tests.kernels.moe.utils import make_dummy_moe_config
from tests.kernels.utils import torch_moe
from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
@@ -27,6 +28,9 @@ from vllm.model_executor.layers.fused_moe.config import (
from vllm.model_executor.layers.fused_moe.experts.trtllm_bf16_moe import (
TrtLlmBf16ExpertsModular,
)
from vllm.model_executor.layers.fused_moe.experts.trtllm_lora_moe import (
TrtLlmBf16LoRAExperts,
)
from vllm.model_executor.layers.fused_moe.oracle.unquantized import (
UnquantizedMoeBackend,
convert_to_unquantized_kernel_format,
@@ -75,6 +79,10 @@ def test_trtllm_bf16_moe_modular_no_graph(
a = torch.randn((m, k), device="cuda", dtype=dtype) / 10
w1 = torch.randn((e, 2 * n, k), device="cuda", dtype=dtype) / 10
w2 = torch.randn((e, k, n), device="cuda", dtype=dtype) / 10
# The FlashInfer conversion may rewrite unpadded input storage in place.
# Preserve the original layout for the independent torch reference.
reference_w1 = w1.clone()
reference_w2 = w2.clone()
score = torch.randn((m, e), device="cuda", dtype=dtype)
scores = torch.softmax(score, dim=-1, dtype=torch.float32)
topk_weights, topk_ids = torch.topk(scores, topk)
@@ -133,8 +141,8 @@ def test_trtllm_bf16_moe_modular_no_graph(
torch_output = torch_moe(
a,
w1,
w2,
reference_w1,
reference_w2,
score,
topk,
activation=MoEActivation.SILU,
@@ -146,3 +154,48 @@ def test_trtllm_bf16_moe_modular_no_graph(
atol=1e-1,
rtol=2e-1,
)
@pytest.mark.parametrize("has_lora_delta", [False, True])
@torch.inference_mode()
def test_trtllm_bf16_lora_accepts_checkpoint_shaped_weights(has_lora_delta):
"""LoRA dispatch accepts both 3D parameters and legacy 4D packed views."""
config = make_dummy_moe_config(
num_experts=128, hidden_dim=256, intermediate_size=128
)
experts = TrtLlmBf16LoRAExperts(config, FUSED_MOE_UNQUANTIZED_CONFIG)
x = torch.randn(2, 256, device="cuda", dtype=torch.bfloat16) / 10
w1, w2 = convert_to_unquantized_kernel_format(
UnquantizedMoeBackend.FLASHINFER_TRTLLM,
config,
torch.randn(128, 256, 256, device="cuda", dtype=torch.bfloat16) / 10,
torch.randn(128, 256, 128, device="cuda", dtype=torch.bfloat16) / 10,
)
assert w1.ndim == w2.ndim == 3
topk = (
torch.tensor([[0], [1]], device="cuda", dtype=torch.int32),
torch.ones(2, 1, device="cuda", dtype=torch.float32),
)
delta = torch.randn(2, 1, 256, device="cuda", dtype=torch.bfloat16)
def invoke(w1, w2):
result = experts.invoke_routed_moe(
hidden_states=x,
w1=w1,
w2=w2,
topk_ids_and_weights=topk,
gemm1_lora_delta=delta if has_lora_delta else None,
global_num_experts=128,
a1q_scale=None,
output=torch.empty_like(x),
)
if has_lora_delta:
# Only compare rows belonging to real tokens, excluding padding.
indices = result[2].flatten().long()
return result[0][indices], result[3][indices]
return result
actual = invoke(w1, w2)
expected = invoke(w1.view(128, 4, 256, 64), w2.view(128, 2, 256, 64))
for actual_tensor, expected_tensor in zip(actual, expected):
torch.testing.assert_close(actual_tensor, expected_tensor)
@@ -6,6 +6,7 @@ import pytest
import torch
from tests.kernels.moe.utils import make_dummy_moe_config
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.config import RoutingMethodType
from vllm.model_executor.layers.fused_moe.oracle.unquantized import (
UnquantizedMoeBackend,
@@ -228,6 +229,65 @@ def test_select_rocm_aiter_backend(mock_aiter_enabled, mock_has_flashinfer):
assert expert_cls is not None
@patch(
"vllm.utils.flashinfer.has_flashinfer",
return_value=False,
)
@patch(
"vllm.model_executor.layers.fused_moe.oracle.unquantized.rocm_aiter_ops."
"is_fused_moe_enabled",
return_value=True,
)
@patch(
"vllm.model_executor.layers.fused_moe.oracle.unquantized.rocm_aiter_ops."
"is_rdna_aiter_enabled",
return_value=False,
)
@pytest.mark.skipif(
not current_platform.is_rocm(), reason="ROCm-specific backend selection test"
)
def test_select_rocm_aiter_backend_non_gated_activation_falls_back(
mock_rdna_disabled, mock_aiter_enabled, mock_has_flashinfer, monkeypatch
):
"""Test ROCm backend selection falls back (not raises) for non-gated MoE."""
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "1")
with patch(
"vllm.model_executor.layers.fused_moe.oracle.unquantized.current_platform"
) as mock_platform:
mock_platform.is_cuda.return_value = False
mock_platform.is_rocm.return_value = True
mock_platform.is_cpu.return_value = False
mock_platform.is_xpu.return_value = False
mock_platform.is_tpu.return_value = False
mock_platform.is_out_of_tree.return_value = False
moe_config = make_dummy_moe_config(activation=MoEActivation.SILU_NO_MUL)
assert moe_config.is_act_and_mul is False
selected_backend, expert_cls = select_unquantized_moe_backend(
moe_config=moe_config,
)
assert selected_backend != UnquantizedMoeBackend.AITER
assert expert_cls is not None
@pytest.mark.skipif(
not current_platform.is_rocm(), reason="ROCm-specific backend selection test"
)
def test_explicit_aiter_backend_non_gated_activation_still_raises():
"""Explicit `--moe-backend aiter` still raises for non-gated MoE;
only the env-var opt-in path falls back."""
moe_config = make_dummy_moe_config(activation=MoEActivation.SILU_NO_MUL)
moe_config.moe_backend = "aiter" # explicit pin, not "auto"
assert moe_config.is_act_and_mul is False
with pytest.raises(ValueError):
select_unquantized_moe_backend(moe_config=moe_config)
@patch(
"vllm.model_executor.layers.fused_moe.experts.trtllm_bf16_moe.TrtLlmBf16ExpertsMonolithic.is_supported_config",
return_value=(True, None),
+24
View File
@@ -705,3 +705,27 @@ def check_accuracy(a, b, atol, rtol, percent):
f"Mismatch percentage is {mismatch_percent:.4f} for rtol {rtol} "
f"(threshold: {1 - percent:.4f})"
)
def mxfp4_w_layouts(mx_axis: int, num_warps: int = 8):
"""Weight/scale layouts for mxfp4 MoE, as (layout, opts) pairs.
triton_kernels 3.8 returns layout instances; earlier versions return a
(layout, opts) tuple.
"""
from triton_kernels.tensor_details import layout
from vllm.utils.import_utils import get_triton_kernels_version
if get_triton_kernels_version() == "3.8":
w = layout.make_default_matmul_mxfp4_w_layout(mx_axis=mx_axis)
s = layout.make_default_matmul_mxfp4_w_scale_layout(
mx_axis=mx_axis, num_warps=num_warps
)
return w, {}, s, {}
w, w_opts = layout.make_default_matmul_mxfp4_w_layout(mx_axis=mx_axis)
s, s_opts = layout.make_default_matmul_mxfp4_w_scale_layout(
mx_axis=mx_axis, num_warps=num_warps
)
return w, w_opts, s, s_opts
+7 -2
View File
@@ -162,11 +162,16 @@ def test_w8a8_block_fp8_matmul(M, N, K, block_size, out_dtype, seed):
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUTLASS only supported on CUDA platform."
)
@pytest.mark.parametrize(
# 65/66/67 cover all M%4 residue classes above the SM100 swapAB
# threshold (m <= 64); 1026 crosses multiple 128-row SF atoms.
"M",
[32, 65, 66, 67, 1026],
)
@torch.inference_mode()
def test_w8a8_block_fp8_cutlass_matmul():
def test_w8a8_block_fp8_cutlass_matmul(M):
# Test simple case where weight.shape % 128 != 0,
# like in DSV3 kv_a_proj_with_mqa
M = 32
N = 576
K = 7168
block_size = [128, 128]
@@ -1,6 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for CPU FP8 W8A16 block-scaled GEMM kernel (fp8_scaled_mm_cpu).
"""Tests for CPU FP8 scaled-mm GEMM kernels.
Covers:
* fp8_scaled_mm_cpu (W8A16)
* fp8_scaled_mm_with_quant (W8A8)
Run `pytest tests/kernels/quantization/test_cpu_fp8_scaled_mm.py -v`.
"""
@@ -23,19 +27,31 @@ from vllm.platforms import current_platform
if not current_platform.is_cpu():
pytest.skip("skipping CPU-only tests", allow_module_level=True)
if not ops._supports_cpu_fp8_w8a16:
pytest.skip("fp8_scaled_mm_cpu op not available", allow_module_level=True)
requires_cpu_fp8_w8a16 = pytest.mark.skipif(
not ops._supports_cpu_fp8_w8a16, reason="fp8_scaled_mm_cpu op not available"
)
requires_cpu_fp8_w8a8 = pytest.mark.skipif(
not ops.cpu_has_amx_fp8(),
reason="requires native AMX-FP8 hardware",
)
if not torch.cpu._is_amx_tile_supported():
pytest.skip("requires AMX tile support", allow_module_level=True)
FP8_MAX = torch.finfo(torch.float8_e4m3fn).max
BLOCK_SIZE = [128, 128]
GROUP_SIZE = 128
def cdiv(a: int, b: int) -> int:
return -(a // -b)
# ---------------------------------------------------------------------------
# W8A16 helpers
# ---------------------------------------------------------------------------
def quantize_weight_block_fp8(
weight: torch.Tensor,
block_size: list[int],
@@ -126,7 +142,7 @@ def ref_fp8_block_scaled_mm(
# ---------------------------------------------------------------------------
# Test parameters
# W8A16 test: fp8_scaled_mm_cpu
# ---------------------------------------------------------------------------
M_SIZES = [1, 4, 16, 64, 128]
# (N, K) — weight shape is [N, K], output has N columns.
@@ -141,6 +157,7 @@ NK_SIZES = [
]
@requires_cpu_fp8_w8a16
@pytest.mark.parametrize("M", M_SIZES)
@pytest.mark.parametrize("N,K", NK_SIZES)
@pytest.mark.parametrize("use_bias", [False, True])
@@ -200,6 +217,77 @@ def ref_fp8_per_tensor_scaled_mm(
return out.to(out_dtype)
# ---------------------------------------------------------------------------
# W8A8 helpers
# ---------------------------------------------------------------------------
def quantize_weight_per_tensor(
weight: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Quantize weight [N, K] to FP8 with a single per-tensor scale, broadcast
to [N, 1] (the shape float8_linear_prepack_cpu expects)."""
N = weight.shape[0]
abs_max = weight.abs().max()
scale = (abs_max / FP8_MAX).clamp(min=1e-7)
q = (weight.float() / scale).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn)
return q, scale.expand(N).contiguous().view(N, 1)
def quantize_weight_per_channel(
weight: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Quantize weight [N, K] to FP8 with per-channel (per-row) scales [N, 1]."""
abs_max = weight.abs().amax(dim=1, keepdim=True)
scale = (abs_max / FP8_MAX).clamp(min=1e-7)
q = (weight.float() / scale).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn)
return q, scale.float()
def quantize_weight_per_group(
weight: torch.Tensor,
group_size: int = GROUP_SIZE,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Quantize weight [N, K] to FP8 with per-group (128-block) scales [N, G]."""
N, K = weight.shape
G = K // group_size
w_groups = weight.view(N, G, group_size)
abs_max = w_groups.abs().amax(dim=2, keepdim=True)
scale = (abs_max / FP8_MAX).clamp(min=1e-7)
q = (w_groups.float() / scale).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn)
return q.view(N, K), scale.squeeze(2).float()
def quantize_act_per_token(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Reference per-token (row) dynamic FP8 quantization of activations."""
x_f = x.float()
scale = (x_f.abs().amax(dim=1, keepdim=True) / FP8_MAX).clamp(min=1e-7)
scaled = (x_f / scale).clamp(-FP8_MAX, FP8_MAX)
# Round via fp16 to match the AVX10.2 kernel path.
q = scaled.half().to(torch.float8_e4m3fn)
return q, scale
def reference_static_fp8_linear(
x: torch.Tensor, # BF16 [M, K]
weight_fp8: torch.Tensor, # FP8 [N, K]
weight_scale: torch.Tensor, # float32 [N, 1]
act_scale: torch.Tensor, # float32 scalar
bias: torch.Tensor | None,
out_dtype: torch.dtype,
) -> torch.Tensor:
"""Static per-tensor: quantize/dequant x with act_scale, dequant weight, matmul."""
x_scaled = (x.float() / act_scale.item()).clamp(-FP8_MAX, FP8_MAX)
# Round via fp16 to match the AVX10.2 kernel path.
x_q = x_scaled.half().to(torch.float8_e4m3fn)
x_dq = x_q.float() * act_scale.item()
w_dq = weight_fp8.float() * weight_scale.view(-1, 1)
out = torch.mm(x_dq, w_dq.t())
if bias is not None:
out = out + bias.float()
return out.to(out_dtype)
NK_SIZES_PER_TENSOR = [
(32, 64),
(5120, 5120),
@@ -274,3 +362,136 @@ def test_cpu_fp8_per_tensor_kernel_rejects_non_multiple_of_32_n(n: int):
)
supported, _ = CPUFp8PerTensorScaledMMLinearKernel.can_implement(config)
assert not supported
def reference_dynamic_fp8_linear(
x: torch.Tensor, # BF16 [M, K]
weight_fp8: torch.Tensor, # FP8 [N, K]
weight_scale: torch.Tensor, # float32 [N, G]
bias: torch.Tensor | None,
out_dtype: torch.dtype,
) -> torch.Tensor:
"""Dynamic per-token act x per-group weight: quantize x per-token,
dequant weight per-group, matmul."""
N, K = weight_fp8.shape
G = weight_scale.shape[1]
group_size = K // G
x_q, x_scale = quantize_act_per_token(x)
x_dq = x_q.float() * x_scale
w_dq = (
weight_fp8.float().view(N, G, group_size) * weight_scale.view(N, G, 1)
).view(N, K)
out = torch.mm(x_dq, w_dq.t())
if bias is not None:
out = out + bias.float()
return out.to(out_dtype)
# ---------------------------------------------------------------------------
# W8A8 tests: fp8_scaled_mm_with_quant
# ---------------------------------------------------------------------------
W8A8_M_SIZES = [1, 4, 16, 64]
W8A8_NK_SIZES = [(128, 256), (256, 512), (64, 128)]
@requires_cpu_fp8_w8a8
@pytest.mark.parametrize("static_activation", [True, False])
@pytest.mark.parametrize("M", W8A8_M_SIZES)
@pytest.mark.parametrize("N,K", W8A8_NK_SIZES)
@pytest.mark.parametrize("use_bias", [False, True])
def test_cpu_fp8_w8a8_per_tensor(
M: int, N: int, K: int, use_bias: bool, static_activation: bool
):
"""CPUFP8W8A8ScaledMMLinearKernel with per-tensor weight scale."""
torch.manual_seed(42)
out_dtype = torch.bfloat16
x = torch.randn(M, K, dtype=torch.bfloat16)
weight = torch.randn(N, K, dtype=torch.bfloat16)
bias = torch.randn(N, dtype=torch.float32) if use_bias else None
w_fp8, w_scale = quantize_weight_per_tensor(weight)
packed_weight, packed_scale = torch.ops._C.float8_linear_prepack_cpu(w_fp8, w_scale)
if static_activation:
act_scale = (x.float().abs().max() / FP8_MAX).clamp(min=1e-7).view(1)
kernel_out = ops.fp8_scaled_mm_with_quant(
x, act_scale, False, packed_weight, packed_scale, bias, out_dtype
)
ref_out = reference_static_fp8_linear(
x, w_fp8, w_scale, act_scale, bias, out_dtype
)
atol = 0.05
else:
kernel_out = ops.fp8_scaled_mm_with_quant(
x, None, True, packed_weight, packed_scale, bias, out_dtype
)
ref_out = reference_dynamic_fp8_linear(x, w_fp8, w_scale, bias, out_dtype)
atol = 0.05
assert kernel_out.dtype == out_dtype
torch.testing.assert_close(kernel_out, ref_out, rtol=0.05, atol=atol)
@requires_cpu_fp8_w8a8
@pytest.mark.parametrize("static_activation", [True, False])
@pytest.mark.parametrize("M", W8A8_M_SIZES)
@pytest.mark.parametrize("N,K", W8A8_NK_SIZES)
@pytest.mark.parametrize("use_bias", [False, True])
def test_cpu_fp8_w8a8_per_channel(
M: int, N: int, K: int, use_bias: bool, static_activation: bool
):
"""CPUFP8W8A8ScaledMMLinearKernel with per-channel weight scale."""
torch.manual_seed(42)
out_dtype = torch.bfloat16
x = torch.randn(M, K, dtype=torch.bfloat16)
weight = torch.randn(N, K, dtype=torch.bfloat16)
bias = torch.randn(N, dtype=torch.float32) if use_bias else None
w_fp8, w_scale = quantize_weight_per_channel(weight)
packed_weight, packed_scale = torch.ops._C.float8_linear_prepack_cpu(w_fp8, w_scale)
if static_activation:
act_scale = (x.float().abs().max() / FP8_MAX).clamp(min=1e-7).view(1)
kernel_out = ops.fp8_scaled_mm_with_quant(
x, act_scale, False, packed_weight, packed_scale, bias, out_dtype
)
ref_out = reference_static_fp8_linear(
x, w_fp8, w_scale, act_scale, bias, out_dtype
)
atol = 0.05
else:
kernel_out = ops.fp8_scaled_mm_with_quant(
x, None, True, packed_weight, packed_scale, bias, out_dtype
)
ref_out = reference_dynamic_fp8_linear(x, w_fp8, w_scale, bias, out_dtype)
atol = 0.05
assert kernel_out.dtype == out_dtype
torch.testing.assert_close(kernel_out, ref_out, rtol=0.05, atol=atol)
@requires_cpu_fp8_w8a8
@pytest.mark.parametrize("M", W8A8_M_SIZES)
@pytest.mark.parametrize("N,K", W8A8_NK_SIZES)
@pytest.mark.parametrize("use_bias", [False, True])
def test_cpu_fp8_w8a8_per_group(M: int, N: int, K: int, use_bias: bool):
"""CPUFp8W8A8BlockScaledMMKernel: per-group (128-block) weight scale +
dynamic per-token activation scale."""
torch.manual_seed(42)
out_dtype = torch.bfloat16
x = torch.randn(M, K, dtype=torch.bfloat16)
weight = torch.randn(N, K, dtype=torch.bfloat16)
bias = torch.randn(N, dtype=torch.float32) if use_bias else None
w_fp8, w_scale = quantize_weight_per_group(weight)
packed_weight, packed_scale = torch.ops._C.float8_linear_prepack_cpu(w_fp8, w_scale)
kernel_out = ops.fp8_scaled_mm_with_quant(
x, None, True, packed_weight, packed_scale, bias, out_dtype
)
ref_out = reference_dynamic_fp8_linear(x, w_fp8, w_scale, bias, out_dtype)
assert kernel_out.dtype == out_dtype
torch.testing.assert_close(kernel_out, ref_out, rtol=0.05, atol=0.05)
@@ -17,7 +17,6 @@ from vllm.platforms import current_platform
@pytest.mark.parametrize(
"model_path",
[
# Listed in tests/weight_loading/models.txt
"nm-testing/tinyllama-oneshot-w4a16-group128-v2",
],
)
+12 -4
View File
@@ -156,22 +156,26 @@ def test_fp4_env_defaults():
"""ROCm FP4 env defaults should stay stable for the AITER gates."""
import vllm.envs as envs
assert envs.VLLM_ROCM_USE_AITER_FP4_ASM_GEMM is False
assert envs.VLLM_ROCM_USE_AITER_FP4BMM is True
@pytest.mark.parametrize(
(
"use_aiter",
"use_fp4_asm_gemm",
"use_fp4bmm",
),
[
(True, True),
(True, False),
(False, True),
(True, True, True),
(True, True, False),
(True, False, True),
(False, True, True),
],
)
def test_rocm_aiter_fp4_enablement_follows_env_and_arch(
use_aiter,
use_fp4_asm_gemm,
use_fp4bmm,
monkeypatch,
):
@@ -187,11 +191,15 @@ def test_rocm_aiter_fp4_enablement_follows_env_and_arch(
_assert_aiter_supported()
on_gfx950_value = on_gfx950()
expected_asm_gemm = use_aiter and on_gfx950_value
expected_asm_gemm = use_aiter and use_fp4_asm_gemm and on_gfx950_value
expected_fp4bmm = use_aiter and use_fp4bmm and on_gfx950_value
with monkeypatch.context() as mp:
mp.setenv("VLLM_ROCM_USE_AITER", "1" if use_aiter else "0")
mp.setenv(
"VLLM_ROCM_USE_AITER_FP4_ASM_GEMM",
"1" if use_fp4_asm_gemm else "0",
)
mp.setenv("VLLM_ROCM_USE_AITER_FP4BMM", "1" if use_fp4bmm else "0")
_reload_envs()
rocm_aiter_ops.refresh_env_variables()
+68 -27
View File
@@ -473,15 +473,18 @@ _E2M1_MAGNITUDES = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
def _decode_nvfp4_row(packed: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
"""Unpack one 256-byte e2m1 row and apply its 32 e4m3 tile scales."""
"""Unpack e2m1 rows and apply their e4m3 tile scales."""
mags = torch.tensor(_E2M1_MAGNITUDES, device=packed.device)
codes = torch.empty(512, dtype=torch.uint8, device=packed.device)
codes[0::2] = packed & 0xF # even element in the low nibble
codes[1::2] = packed >> 4
codes = torch.empty(
(*packed.shape[:-1], 512), dtype=torch.uint8, device=packed.device
)
codes[..., 0::2] = packed & 0xF # even element in the low nibble
codes[..., 1::2] = packed >> 4
vals = mags[(codes & 7).long()] * torch.where(codes >= 8, -1.0, 1.0)
return (
vals.view(32, 16) * scales.view(torch.float8_e4m3fn).float().view(32, 1)
).flatten()
vals.reshape(*packed.shape[:-1], 32, 16)
* scales.view(torch.float8_e4m3fn).float().reshape(*packed.shape[:-1], 32, 1)
).flatten(-2)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
@@ -543,7 +546,10 @@ def test_v41_rope_insert_nvfp4_record(compress_ratio: int):
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
def test_v41_nvfp4_gather_matches_insert():
@pytest.mark.parametrize("num_reqs", [1, 8, 32])
@pytest.mark.parametrize("num_tokens", [70, 128, 129, 2051])
@pytest.mark.parametrize("partial", [False, True])
def test_v41_nvfp4_gather_matches_insert(num_reqs, num_tokens, partial):
"""The NVFP4 gather dequantizes exactly what the insert kernel wrote."""
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
@@ -553,38 +559,73 @@ def test_v41_nvfp4_gather_matches_insert():
torch.manual_seed(17)
device = "cuda"
block_size = 64
num_tokens = 70
num_blocks = 4
num_blocks = math.ceil(num_tokens / block_size)
page_bytes = math.ceil(block_size * 288 / 512) * 512
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
angles = torch.randn(128, 32, device=device)
angles = torch.randn(num_tokens, 32, device=device)
cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
backing = torch.zeros(num_blocks, page_bytes, dtype=torch.uint8, device=device)
cache = backing.as_strided((num_blocks, block_size, 288), (page_bytes, 288, 1))
slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
rope_quant_insert(latent, positions, cos_sin, cache, slots, 1)
out = torch.zeros(1, num_tokens, 512, dtype=torch.bfloat16, device=device)
dequantize_and_gather_k_cache(
out,
cache,
seq_lens=torch.tensor([num_tokens], dtype=torch.int32, device=device),
gather_lens=None,
block_table=torch.arange(num_blocks, dtype=torch.int32, device=device).view(
1, -1
),
block_size=block_size,
offset=0,
offset = 7 if partial else 0
seq_lens = num_tokens - torch.arange(num_reqs, dtype=torch.int32, device=device)
gather_lens = seq_lens - 3 if partial else None
storage = torch.full(
(num_reqs, num_tokens + offset + 16, 512),
-123.0,
dtype=torch.bfloat16,
device=device,
)
for t in (0, 1, block_size, num_tokens - 1):
page, row = divmod(t, block_size)
expected = _decode_nvfp4_row(
backing[page, row * 256 : (row + 1) * 256],
backing[page, block_size * 256 + row * 32 :][:32],
out = storage[:, : num_tokens + offset]
block_table = torch.arange(num_blocks, dtype=torch.int32, device=device).repeat(
num_reqs, 1
)
def gather():
dequantize_and_gather_k_cache(
out,
cache,
seq_lens=seq_lens,
gather_lens=gather_lens,
block_table=block_table,
block_size=block_size,
offset=offset,
)
torch.testing.assert_close(out[0, t].float(), expected, rtol=0, atol=0)
expected = _decode_nvfp4_row(
backing[:, : block_size * 256].reshape(-1, 256),
backing[:, block_size * 256 : block_size * 288].reshape(-1, 32),
)
def check(shorter_by):
assert (storage[:, num_tokens + offset :] == -123).all()
for req in range(num_reqs):
start = 3 if partial else 0
length = num_tokens - req - start - shorter_by
assert (out[req, :offset] == -123).all()
assert (out[req, offset + length :] == -123).all()
torch.testing.assert_close(
out[req, offset : offset + length].float(),
expected[start : start + length],
rtol=0,
atol=0,
)
gather()
check(0)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
gather()
storage.fill_(-123)
seq_lens.sub_(1)
if gather_lens is not None:
gather_lens.sub_(1)
graph.replay()
check(1)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
@@ -507,8 +507,8 @@ def test_fused_norm_rope_materializes_pcp_cache_inputs(has_indexer: bool):
def test_fused_norm_rope_ds_mla(num_tokens: int):
"""fp8_ds_mla MLA cache layout (FlashMLA sparse, bf16-query path; SM90/SM100).
Per-token 656-byte entry: 512 fp8 NoPE (4 per-128 tiles, dynamic float32
scale) | 4 float32 scales | 64 bf16 (unquantized) RoPE.
Per-token 656-byte entry: 512 fp8 NoPE (4 per-128 tiles, power-of-two scales
stored as float32) | 4 float32 scales | 64 bf16 (unquantized) RoPE.
"""
torch.manual_seed(5)
dev = "cuda"
@@ -557,7 +557,8 @@ def test_fused_norm_rope_ds_mla(num_tokens: int):
kv_ref = rms_norm(kv_c, kvw) # [N, 512] fp32
kpe_ref = rope(k_pe.float(), pos, mla_cos_sin, interleave=True) # [N, 64]
tiles = kv_ref.view(num_tokens, 4, 128)
ref_scale = torch.clamp(tiles.abs().amax(dim=-1) / FP8_MAX, min=1.1754944e-38)
ref_scale = torch.clamp(tiles.abs().amax(dim=-1) / FP8_MAX, min=1e-4)
ref_scale = torch.exp2(torch.ceil(torch.log2(ref_scale)))
ref_nope = (tiles / ref_scale[..., None]).reshape(num_tokens, KV_LORA).to(FP8)
cache = mla_cache[0, :num_tokens] # [N, 656] uint8
@@ -566,7 +567,7 @@ def test_fused_norm_rope_ds_mla(num_tokens: int):
rope_off = KV_LORA // 2 + 8
rope_vals = cache.view(torch.bfloat16)[:, rope_off : rope_off + ROPE_DIM]
torch.testing.assert_close(scales, ref_scale, rtol=1e-2, atol=1e-6)
torch.testing.assert_close(scales, ref_scale, rtol=0, atol=0)
assert_fp8(nope, ref_nope, "ds_mla NoPE fp8")
assert_bf16(rope_vals, kpe_ref, "ds_mla RoPE bf16")
# No indexer on this call: top-k buffer must be untouched.
+3 -2
View File
@@ -132,6 +132,7 @@ def test_v41_dspark_head_collapses_with_last_ffn_mix(num_tokens, monkeypatch):
monkeypatch.setattr(dspark, "mhc_post_tilelang", lambda *args: streams)
draft = SimpleNamespace(
use_mega_moe=False,
use_sequence_parallel=False,
hc_mult=hc_mult,
layers=[make_layer(mix) for mix in mixes],
@@ -452,7 +453,7 @@ def test_deepseek_v41_decoder_mixes_match_torch(
device=DEVICE, dtype=torch.bfloat16
)
decoder.attn = lambda positions, x, _: x * 0.5
decoder.ffn = lambda x, input_ids: x * 0.25
decoder.ffn = lambda x, input_ids, mega_gate_metadata=None: x * 0.25
with torch.device(DEVICE):
decoder.hc_attn_fn = torch.randn(24, 20480) * 0.02
decoder.hc_ffn_fn = torch.randn(24, 20480) * 0.02
@@ -536,7 +537,7 @@ def test_deepseek_v41_capture_previous_aux(entry, monkeypatch, default_vllm_conf
device=DEVICE, dtype=torch.bfloat16
)
decoder.attn = lambda positions, x, _: x * 0.5
decoder.ffn = lambda x, input_ids: x * 0.25
decoder.ffn = lambda x, input_ids, mega_gate_metadata=None: x * 0.25
with torch.device(DEVICE):
decoder.hc_attn_fn = torch.randn(24, 20480) * 0.02
decoder.hc_ffn_fn = torch.randn(24, 20480) * 0.02
+29 -7
View File
@@ -24,19 +24,26 @@ class _PassConfigKey:
def _install_tilelang_stub(
monkeypatch: pytest.MonkeyPatch,
) -> dict[str, int]:
calls = {"jit_decorate": 0, "compiled_call": 0}
calls = {"jit_decorate": 0, "compiled_call": 0, "compiled_compile": 0}
tilelang: Any = ModuleType("tilelang")
class _JitImpl:
def __init__(self, func: Any) -> None:
self.func = func
def __call__(self, *args: Any, **kw: Any) -> Any:
calls["compiled_call"] += 1
return self.func.__name__
def compile(self, *args: Any, **kw: Any) -> Any:
calls["compiled_compile"] += 1
return self.func.__name__
def jit(**kwargs: Any) -> Any:
def decorate(func: Any) -> Any:
calls["jit_decorate"] += 1
def compiled(*args: Any, **kw: Any) -> Any:
calls["compiled_call"] += 1
return func.__name__
return compiled
return _JitImpl(func)
return decorate
@@ -78,6 +85,21 @@ def test_tilelang_jit_decorator_is_lazy_only_on_rocm(
assert calls["compiled_call"] == 1
@pytest.mark.skipif(not current_platform.is_rocm(), reason="Test requires ROCm")
def test_tilelang_jit_proxies_compile_only_warmup(
monkeypatch: pytest.MonkeyPatch,
) -> None:
calls = _install_tilelang_stub(monkeypatch)
module_name = "vllm.model_executor.kernels.mhc.tilelang_kernels"
monkeypatch.delitem(sys.modules, module_name, raising=False)
module = importlib.import_module(module_name)
assert module.mhc_post_tilelang.compile() == "mhc_post_tilelang"
assert calls["jit_decorate"] == 1
assert calls["compiled_compile"] == 1
assert calls["compiled_call"] == 0
@pytest.mark.skipif(not current_platform.is_rocm(), reason="Test requires ROCm")
def test_deepseek_v4_import_and_jit_monitor_do_not_hijack_hip_symbols() -> None:
if importlib.util.find_spec("tilelang") is None:
+76
View File
@@ -10,6 +10,7 @@ tests assert the two agree within tolerance:
* Fused MXFP8 activation quant (Triton) -> _mxfp8_e4m3_quantize_torch
* Native MXFP8 linear (dot_scaled) -> dequant-to-bf16 @ matmul
* Native MXFP8 MoE (dot_scaled grouped GEMM) -> dequant-to-bf16 MoE math
* Strided K/V sparse-PA cache insert -> contiguous-copy insert
The native MXFP8 GEMMs also guard the ``dot_scaled`` rhs-scale orientation: the
scale is loaded ``[N, K//32]`` and passed WITHOUT transpose; a stray ``.T``
@@ -39,6 +40,7 @@ from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( # noqa:
_mxfp8_e4m3_quantize_triton,
dequant_mxfp8_to_bf16,
)
from vllm.models.minimax_m3.amd.model import _kv_insert_operand # noqa: E402
from vllm.models.minimax_m3.amd.ops import ( # noqa: E402
gemma_fused_add_rmsnorm,
gemma_rmsnorm,
@@ -608,3 +610,77 @@ def test_routed_experts_expert_map_delegates_to_kernel():
assert torch.equal(resolve(True), mask) # AITER kernel -> 0/1 mask
assert torch.equal(resolve(False), canonical) # non-AITER -> canonical map
assert torch.equal(resolve(False, has_moe_kernel=False), canonical) # non-modular
# --------------------------------------------------------------------------- #
# Strided K/V operand for the AITER sparse-PA cache insert
# --------------------------------------------------------------------------- #
def _fused_qkv_kv_slices(num_tokens, num_kv_heads, head_dim, num_q_heads=16):
"""K/V as the sparse-PA insert sees them: column slices of a fused qkv."""
kv = num_kv_heads * head_dim
row = num_q_heads * head_dim + 2 * kv + 2 * head_dim
qkv = torch.randn((num_tokens, row), dtype=torch.bfloat16, device=DEVICE)
k_start = num_q_heads * head_dim
k = qkv[:, k_start : k_start + kv].view(num_tokens, num_kv_heads, head_dim)
v = qkv[:, k_start + kv : k_start + 2 * kv].view(num_tokens, num_kv_heads, head_dim)
return k, v
def _asm_kv_cache(pages, num_kv_heads, head_dim):
"""Page-16 K/V cache views matching ``_ensure_aiter_sparse_pa_kv_cache``."""
x = 16 // torch.tensor([], dtype=torch.bfloat16).element_size()
key = torch.zeros(
(pages, num_kv_heads, head_dim // x, 16, x),
dtype=torch.bfloat16,
device=DEVICE,
)
value = torch.zeros(
(pages, num_kv_heads, 16 // x, head_dim, x),
dtype=torch.bfloat16,
device=DEVICE,
)
return key, value
@pytest.mark.parametrize("num_tokens", [1, 8, 129, 1024])
@pytest.mark.parametrize("num_kv_heads", [1, 2])
def test_kv_insert_operand_matches_contiguous(num_tokens, num_kv_heads):
"""A strided K/V slice must insert bit-identically to a contiguous copy."""
reshape_and_cache = pytest.importorskip("aiter").reshape_and_cache
head_dim = 128
pages = num_tokens // 16 + 4
slots = torch.randperm(pages * 16, device=DEVICE)[:num_tokens].to(torch.int32)
torch.manual_seed(num_tokens)
k, v = _fused_qkv_kv_slices(num_tokens, num_kv_heads, head_dim)
assert num_tokens == 1 or not k.is_contiguous()
caches = []
for operand in (lambda t: t.contiguous(), _kv_insert_operand):
key_cache, value_cache = _asm_kv_cache(pages, num_kv_heads, head_dim)
reshape_and_cache(
operand(k),
operand(v),
key_cache,
value_cache,
slots,
kv_cache_dtype="auto",
asm_layout=True,
)
caches.append((key_cache, value_cache))
(ref_k, ref_v), (got_k, got_v) = caches
assert torch.equal(ref_k, got_k)
assert torch.equal(ref_v, got_v)
def test_kv_insert_operand_copies_unsupported_layouts():
"""Only a row-strided slice passes through; anything else is copied."""
k, _ = _fused_qkv_kv_slices(32, 2, 128)
assert _kv_insert_operand(k) is k
inner_strided = k[:, :, ::2]
assert _kv_insert_operand(inner_strided).is_contiguous()
flat = k.reshape(32, -1)
assert _kv_insert_operand(flat).is_contiguous()
+2 -2
View File
@@ -147,10 +147,10 @@ def test_gemma4_lora_weights_mapping():
def test_gemma4_moe_lora_weights_mapping():
mapper = Gemma4ForCausalLM.hf_to_vllm_mapper
name = (
"base_model.model.model.language_model.layers.9.moe.experts."
"base_model.model.model.language_model.layers.9.experts."
"gate_up_proj.lora_B.weight"
)
assert parse_fine_tuned_lora_name(name, mapper) == (
"model.layers.9.moe.gate_up_proj",
"model.layers.9.experts.gate_up_proj",
False,
)
+5 -15
View File
@@ -3,8 +3,6 @@
from dataclasses import dataclass
import pytest
from packaging.version import Version
from transformers import __version__ as TRANSFORMERS_VERSION
import vllm
from tests.conftest import VllmRunner
@@ -29,20 +27,12 @@ class TestConfig:
def __post_init__(self):
if self.mm_processor_kwargs is None:
# There is a bug in transformers v4 where size is ignored by
# `Qwen2VLProcessor.__call__`
if Version(TRANSFORMERS_VERSION) < Version("5.2.0"):
self.mm_processor_kwargs = {
"min_pixels": 28 * 28,
"max_pixels": 1280 * 28 * 28,
}
else:
self.mm_processor_kwargs = {
"size": {
"shortest_edge": 28 * 28,
"longest_edge": 1280 * 28 * 28,
}
self.mm_processor_kwargs = {
"size": {
"shortest_edge": 28 * 28,
"longest_edge": 1280 * 28 * 28,
}
}
class Qwen2VLTester:
@@ -0,0 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import partial
import pytest
import torch
import torch.nn as nn
from vllm.model_executor.layers.activation import GeluAndMul, SiluAndMul
from vllm.platforms import CpuArchEnum, current_platform
@pytest.mark.skipif(
not current_platform.is_cpu()
or current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC,
reason="Native CPU activations require a non-PowerPC CPU platform",
)
@pytest.mark.parametrize(
"activation_factory,reference",
[
(SiluAndMul, nn.SiLU()),
(GeluAndMul, nn.GELU()),
(partial(GeluAndMul, approximate="tanh"), nn.GELU(approximate="tanh")),
],
ids=["silu", "gelu", "gelu_tanh"],
)
def test_cpu_act_and_mul_without_compiled_ops(
default_vllm_config, monkeypatch, activation_factory, reference
):
"""CPU activations must construct and run without compiled wheel operators."""
default_vllm_config.compilation_config.custom_ops = ["all"]
monkeypatch.setattr(torch.ops, "_C", object())
x = torch.tensor([[-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device="cpu")
layer = activation_factory()
torch.testing.assert_close(layer(x), reference(x[:, :4]) * x[:, 4:])
@@ -365,6 +365,26 @@ def test_select_candidate_blocks_tolerates_empty_rows():
assert (out[0] >= 0).all() and (out[2, :2] >= 0).all()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize("score", [0.0, float("nan")])
@pytest.mark.parametrize("start", [0, 3])
def test_candidate_selection_keeps_valid_blocks_with_nan_scores(score, start):
"""NaN warmup scores must not turn real blocks into repeated sparse padding."""
logits = torch.full((3, 64), score, device="cuda")
starts = torch.full((3,), start, device="cuda", dtype=torch.int32)
lengths = torch.tensor([0, 17, 35], device="cuda", dtype=torch.int32)
out = torch.empty(3, 8, device="cuda", dtype=torch.int32)
sparse_indexer._select_candidate_blocks(logits, starts, starts + lengths, 8, 8, out)
for row, count in enumerate([0, 3, 5]):
valid = out[row][out[row] >= 0].sort().values
torch.testing.assert_close(
valid, torch.arange(count, device="cuda", dtype=torch.int32)
)
assert (out[row] == -1).sum().item() == 8 - count
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize(
"width,block_size,k,decode",
@@ -413,7 +433,7 @@ def test_candidate_kernels_preserve_packed_bounds_and_padding(
top = reduced.topk(min(k, nblocks), dim=-1)
expected = torch.full((rows, k), -1, device="cuda", dtype=torch.int32)
expected[:, : top.indices.shape[1]] = torch.where(
top.values > -torch.inf, top.indices, -1
top.values != -torch.inf, top.indices, -1
).int()
actual = torch.empty(rows, k * 2, device="cuda", dtype=torch.int32)[:, ::2]
select_candidate_blocks(logits, starts, ends, k, block_size, actual, repeat)
@@ -608,7 +628,10 @@ def test_candidate_blocks_to_sparse_indices_math():
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Triton kernel")
@pytest.mark.parametrize("cbk,sbk", [(8, 8), (16, 8), (16, 16)])
def test_candidate_blocks_to_sparse_indices_matches_reference(cbk: int, sbk: int):
@pytest.mark.parametrize("end_offset", [0, 1])
def test_candidate_blocks_to_sparse_indices_matches_reference(
cbk: int, sbk: int, end_offset: int
):
"""The Triton expansion equals the PyTorch reference on production-shaped
random inputs, including strided (column-sliced) candidate rows and
strided output buffers."""
@@ -643,7 +666,7 @@ def test_candidate_blocks_to_sparse_indices_matches_reference(cbk: int, sbk: int
ke,
cbk,
sbk,
out=(si_buf[:, : num_candidates * ratio], end_buf[::2]),
out=(si_buf[:, : num_candidates * ratio], end_buf[end_offset::2]),
)
assert torch.equal(got_indices, ref_indices)
assert torch.equal(got_end, ref_end)
@@ -651,7 +674,7 @@ def test_candidate_blocks_to_sparse_indices_matches_reference(cbk: int, sbk: int
cand_buf[:, num_candidates:], torch.full_like(cand_buf[:, num_candidates:], -7)
)
assert not si_buf[:, num_candidates * ratio :].any()
assert not end_buf[1::2].any()
assert not end_buf[1 - end_offset :: 2].any()
def _skip_unless_sm100_sparse_kernels():
@@ -5,6 +5,7 @@ import importlib.machinery
import inspect
import sys
import types
from types import SimpleNamespace
from unittest.mock import Mock
from weakref import WeakKeyDictionary, ref
@@ -467,6 +468,111 @@ def test_model_cleanup(dist_init, default_vllm_config):
assert len(mock_info_dict) == 0
@pytest.mark.parametrize("is_gated", [False, True])
@pytest.mark.parametrize("has_bias", [False, True])
@pytest.mark.parametrize("tp_rank", [0, 1])
@pytest.mark.parametrize("padded", [False, True])
def test_padded_moe_reload_releases_each_layer(
monkeypatch, is_gated, has_bias, tp_rank, padded
):
"""Checkpoint-sized copies finish each layer without global finalization."""
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
from vllm.model_executor.layers.fused_moe.unquantized_fused_moe_method import (
UnquantizedFusedMoEMethod,
)
hidden, intermediate, experts = 4, 3, 2
stored_hidden, stored_intermediate = (8, 8) if padded else (hidden, intermediate)
config = SimpleNamespace(
hidden_dim_unpadded=hidden,
intermediate_size_per_partition_unpadded=intermediate,
is_act_and_mul=is_gated,
has_bias=has_bias,
tp_rank=tp_rank,
tp_shard_with_padding=False,
moe_parallel_config=SimpleNamespace(tp_size=2),
)
model = torch.nn.ModuleList()
processed: list[torch.nn.Module] = []
for _ in range(2):
method = object.__new__(UnquantizedFusedMoEMethod)
torch.nn.Module.__init__(method)
method.moe = config
# The regression concerns streaming reload, not kernel conversion.
monkeypatch.setattr(method, "process_weights_after_loading", processed.append)
layer = object.__new__(RoutedExperts)
torch.nn.Module.__init__(layer)
layer.moe_config = config
layer.quant_config = None
layer.quant_method = method
layer.expert_map_manager = SimpleNamespace(map_global_to_local=lambda i: i)
layer._loaded_expert_biases = set()
method.create_weights(
layer,
experts,
stored_hidden,
stored_intermediate,
torch.float32,
weight_loader=layer.weight_loader,
)
model.append(layer)
record_metadata_for_reloading(model)
original_params = [dict(layer.named_parameters()) for layer in model]
shards = ["w1", "w3", "w2"] if is_gated else ["w1", "w2"]
for cycle in range(2):
initialize_layerwise_reload(model)
for layer_index, layer in enumerate(model):
info = reload_layerwise.get_layerwise_info(layer)
inputs = []
expected = {
name: torch.full_like(p, float("nan"))
for name, p in original_params[layer_index].items()
}
params = dict(layer.named_parameters())
calls = [
(e, s, b)
for e in range(experts)
for s in shards
for b in ([False, True] if has_bias else [False])
]
for call_index, (expert, shard, bias) in enumerate(calls):
name = ("w2" if shard == "w2" else "w13") + (
"_bias" if bias else "_weight"
)
shape = (
((hidden,) if bias else (hidden, 2 * intermediate))
if shard == "w2"
else ((2 * intermediate,) if bias else (2 * intermediate, hidden))
)
weight = torch.arange(
torch.Size(shape).numel(), dtype=torch.float32
).reshape(shape)
weight = weight + 100 * (1 + call_index + cycle)
inputs.append(ref(weight))
# Direct checkpoint loading is the reference for deferred reload.
layer.weight_loader(expected[name], weight, name, shard, expert)
param = params[name]
param.weight_loader(param, weight, name, shard, expert)
del weight
if call_index != len(calls) - 1:
assert info.can_load(), (
"Layer processed before its final checkpoint shard"
)
assert not info.can_load(), (
"Padding must not defer the layer until finalization"
)
assert not info.loaded_weights
assert len(processed) == cycle * len(model) + layer_index + 1
assert all(source() is None for source in inputs)
for name, original in original_params[layer_index].items():
assert getattr(layer, name) is original
# Kernel-specific tests cover padding, which is not checkpoint data.
mask = torch.isfinite(expected[name])
assert torch.equal(original[mask], expected[name][mask])
def test_get_numel_loaded():
param = torch.empty(10, device="meta")
loaded_weight = torch.empty(10)
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Focused unit tests for the GLM decode top-k dispatch."""
import pytest
import torch
from vllm.models.glm5next.nvidia.sparse_indexer import _use_cooperative_topk
from vllm.platforms import current_platform
pytestmark = pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUDA-only dispatch"
)
@pytest.mark.parametrize("num_rows", [1, 64], ids=["1row", "64rows"])
@torch.inference_mode()
def test_cooperative_topk_is_selected_for_supported_batch(num_rows: int):
logits = torch.empty(num_rows, 8192, dtype=torch.float32, device="cuda")
assert _use_cooperative_topk(logits, 512, num_rows)
@pytest.mark.parametrize(
("num_rows", "select_k", "stride_padding"),
[
(65, 512, 0),
(1, 256, 0),
(1, 512, 1),
],
ids=["too_many_rows", "unsupported_k", "unaligned_stride"],
)
@torch.inference_mode()
def test_cooperative_topk_falls_back_on_unsupported_batch(
num_rows: int, select_k: int, stride_padding: int
):
logits = torch.empty(
num_rows, 8192 + stride_padding, dtype=torch.float32, device="cuda"
)
if stride_padding:
logits = logits[:, :8192]
assert not _use_cooperative_topk(logits, select_k, num_rows)
@@ -3,8 +3,6 @@
import pytest
import torch
from packaging.version import Version
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.platforms import current_platform
@@ -26,7 +24,7 @@ AITER_MODEL_LIST = [
"meta-llama/Llama-3.2-1B-Instruct",
"openbmb/MiniCPM3-4B",
"Qwen/Qwen2.5-0.5B-Instruct",
"TitanML/tiny-mixtral",
"axolotl-ai-co/tiny-mixtral-30m",
"Qwen/Qwen3-8B",
]
@@ -95,7 +93,7 @@ AITER_MODEL_LIST = [
pytest.param("stabilityai/stablelm-3b-4e1t"), # stablelm
pytest.param("bigcode/starcoder2-3b"), # starcoder2
pytest.param(
"TitanML/tiny-mixtral", # mixtral
"axolotl-ai-co/tiny-mixtral-30m", # mixtral
marks=[pytest.mark.core_model],
),
pytest.param("swiss-ai/Apertus-8B-Instruct-2509"), # apertus
@@ -126,12 +124,6 @@ def test_models(
model_info.check_available_online(on_fail="skip")
model_info.check_transformers_version(on_fail="skip")
if current_platform.is_rocm() and model == "TitanML/tiny-mixtral":
# Its single-token router selects LLMM1, whose low-precision
# accumulation can change the top-2 experts. Keep the optimized kernel
# enabled generally, but use the reference GEMM for this accuracy test.
monkeypatch.setenv("VLLM_ROCM_USE_SKINNY_GEMM", "0")
if use_rocm_aiter and (model in AITER_MODEL_LIST):
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
elif use_rocm_aiter and model not in AITER_MODEL_LIST:
@@ -168,16 +160,6 @@ def test_models(
if prompt_embeds is not None:
embed = hf_model.model.get_input_embeddings()(token_ids)
if "gemma" in model.lower() and (
Version(TRANSFORMERS_VERSION) < Version("5.3.0.dev0")
):
# For Gemma 1/2 models with Transformers 5.4.0+, the prompt
# embeddings are normalised in `get_prompt_embeddings`,
# like Gemma 3. For older versions, we need to manually normalise.
embed_scale = hf_model.config.hidden_size**0.5
normalizer = torch.tensor(embed_scale, dtype=embed.dtype)
embed *= normalizer
# MiniCPM models apply scale_emb to embeddings internally.
# vLLM expects pre-scaled embeddings when using inputs_embeds.
if model in EMBED_SCALING_MODELS:
+65 -28
View File
@@ -14,7 +14,10 @@ from vllm.model_executor.models.gemma3n import (
Gemma3nTextModel,
_kv_sharing_weights_mapper,
)
from vllm.model_executor.models.gemma4 import Gemma4Model
from vllm.model_executor.models.gemma4 import (
Gemma4ForCausalLM,
_gemma4_layer_weights_mapper,
)
MODELS = ["google/gemma-2b", "google/gemma-2-2b", "google/gemma-3-4b-it"]
@@ -57,36 +60,70 @@ def test_checkpoint_lm_head_can_override_tied_config(monkeypatch) -> None:
@pytest.mark.cpu_test
def test_gemma4_kv_shared_layer_loads_plain_q_proj() -> None:
"""KV-shared layers have q_proj instead of a packed qkv_proj; their
redundant K/V tensors in original checkpoints have no parameter and are
skipped rather than failing the load."""
model = torch.nn.Module()
model.config = SimpleNamespace(num_experts=0)
model.start_layer, model.end_layer = 0, 2
model.layers = torch.nn.ModuleList([torch.nn.Module(), torch.nn.Module()])
for layer in model.layers:
layer.self_attn = torch.nn.Module()
model.layers[0].self_attn.qkv_proj = torch.nn.Linear(2, 6, bias=False)
model.layers[1].self_attn.q_proj = torch.nn.Linear(2, 2, bias=False)
shards: list[str] = []
model.layers[0].self_attn.qkv_proj.weight.weight_loader = (
lambda param, weight, shard_id: shards.append(shard_id)
def test_gemma4_attention_mapper() -> None:
"""Layers with a qkv_proj pack q/k/v; `attention_k_eq_v` full-attention
layers also load K as the V shard, and leave any v_proj such a checkpoint
ships unmapped so it fails the load rather than silently overwriting V;
KV-shared layers keep q_proj and drop the K/V tensors original checkpoints
still ship for them."""
config = SimpleNamespace(
num_hidden_layers=3,
num_kv_shared_layers=1,
attention_k_eq_v=True,
layer_types=["sliding_attention", "full_attention", "sliding_attention"],
)
q_weight = torch.full((2, 2), 2.0)
weights = [
(f"layers.{i}.self_attn.{tensor}.weight", q_weight)
for i in (0, 1)
for tensor in ("q_proj", "k_proj", "v_proj")
] + [("layers.1.self_attn.k_norm.weight", torch.ones(2))]
loaded = Gemma4Model.load_weights(cast(Gemma4Model, model), weights)
(f"model.layers.{i}.self_attn.{tensor}.weight", torch.full((2, 2), i + 1.0))
for i in range(3)
for tensor in ("q_proj", "k_proj", "k_norm")
] + [
("model.layers.0.mlp.up_proj.weight", torch.empty(0)),
("model.layers.1.self_attn.v_proj.weight", torch.empty(0)),
]
assert shards == ["q", "k", "v"]
assert "layers.1.self_attn.q_proj.weight" in loaded
assert not any(name.startswith("layers.1.self_attn.k") for name in loaded)
assert not any(name.startswith("layers.1.self_attn.v") for name in loaded)
assert torch.equal(model.layers[1].self_attn.q_proj.weight, q_weight)
mapper = _gemma4_layer_weights_mapper(config)
mapped = list(mapper.apply(weights))
assert [(name, getattr(w, "shard_id", None)) for name, w in mapped] == [
("model.layers.0.self_attn.qkv_proj.weight", "q"),
("model.layers.0.self_attn.qkv_proj.weight", "k"),
("model.layers.0.self_attn.k_norm.weight", None),
("model.layers.1.self_attn.qkv_proj.weight", "q"),
("model.layers.1.self_attn.qkv_proj.weight", "k"),
("model.layers.1.self_attn.qkv_proj.weight", "v"),
("model.layers.1.self_attn.k_norm.weight", None),
("model.layers.2.self_attn.q_proj.weight", None),
("model.layers.0.mlp.gate_up_proj.weight", 1),
("model.layers.1.self_attn.v_proj.weight", None),
]
k_weight, v_weight = weights[4][1], mapped[5][1]
assert torch.equal(v_weight, k_weight) and v_weight is not k_weight
@pytest.mark.cpu_test
def test_gemma4_expert_names_strip_language_model_prefix() -> None:
"""The text-only path reuses the conditional wrapper's checkpoint naming,
so fused and per-expert tensors reach the experts under `model.*`."""
prefix = "model.language_model.layers.0."
weights = [
(prefix + name, torch.empty(0))
for name in (
"experts.gate_up_proj",
"experts.3.down_proj.weight_packed",
"router.per_expert_scale",
)
]
mapped = [
(name, getattr(w, "shard_id", None))
for name, w in Gemma4ForCausalLM.hf_to_vllm_mapper.apply(weights)
]
assert mapped == [
("model.layers.0.experts.gate_up_proj", None),
("model.layers.0.experts.3.down_proj.weight_packed", None),
("model.layers.0.router.per_expert_scale", None),
]
@pytest.mark.cpu_test
+28
View File
@@ -2,12 +2,40 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Pytest configuration for vLLM language generation tests."""
import gc
import pytest
import torch
from tests.utils import wait_for_memory_to_settle
from vllm.logger import init_logger
from vllm.platforms import current_platform
logger = init_logger(__name__)
def pytest_sessionstart(session):
"""Configure ROCm-specific settings before test session starts."""
if current_platform.is_rocm():
torch.set_float32_matmul_precision("high")
@pytest.fixture(autouse=True)
def release_gpu_memory_between_tests():
"""Reclaim cached GPU memory between tests in this shard.
These tests start many vLLM/HF engines sequentially in one pytest
process; without explicit reclamation between tests, VRAM fragmentation
accumulates and later tests fail at engine startup ("Engine core
initialization failed").
"""
yield
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
try:
wait_for_memory_to_settle()
except ValueError as e:
# Longer-lived (class/module-scoped) engine fixtures may legitimately
# still hold VRAM; nothing further to reclaim in that case.
logger.info("Failed to clean GPU memory: %s", e)
@@ -128,9 +128,12 @@ def _load_projection_weight(model_name: str, hf_spec: dict, device: torch.device
"""Download and return the ColBERT linear projection weight."""
from safetensors.torch import load_file
from vllm.transformers_utils.repo_utils import hf_api
from vllm.transformers_utils.repo_utils import hf_api, with_retry
path = hf_api().hf_hub_download(model_name, filename=hf_spec["weights_file"])
path = with_retry(
lambda: hf_api().hf_hub_download(model_name, filename=hf_spec["weights_file"]),
f"Error downloading {hf_spec['weights_file']} from {model_name}",
)
weights = load_file(path)
return weights[hf_spec["weights_key"]].to(device)
@@ -2,6 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: SIM117
from functools import partial
import pytest
from ...utils import EmbedModelInfo
@@ -26,6 +28,22 @@ original_max_position_embeddings = 2048
max_model_len = int(original_max_position_embeddings * factor)
@pytest.fixture(scope="module", autouse=True)
def predownload_models():
"""Warm the HF cache so engine startup never hits transient hub errors."""
from vllm.transformers_utils.repo_utils import hf_api, with_retry
for model_info in MODELS:
with_retry(
partial(
hf_api().snapshot_download,
model_info.name,
revision=model_info.revision,
),
f"Error downloading {model_info.name}",
)
@pytest.mark.parametrize("model_info", MODELS)
def test_default(model_info, vllm_runner):
with vllm_runner(
@@ -115,6 +115,7 @@ def test_modernbert_models(
@pytest.mark.parametrize("model", ["Davlan/xlm-roberta-base-ner-hrl"])
@pytest.mark.parametrize("dtype", ["float"])
@pytest.mark.flaky(reruns=3)
@torch.inference_mode
def test_xlm_roberta_models(
hf_runner,
@@ -197,6 +198,7 @@ def test_openai_privacy_filter(
@pytest.mark.parametrize("model", ["bd2lcco/Qwen3-0.6B-finetuned"])
@pytest.mark.parametrize("dtype", ["float"])
@pytest.mark.flaky(reruns=3)
@torch.inference_mode
def test_auto_conversion(
hf_runner,
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Pytest configuration for vLLM pooling MTEB tests."""
import gc
import pytest
import torch
from tests.utils import wait_for_memory_to_settle
from vllm.logger import init_logger
logger = init_logger(__name__)
@pytest.fixture(autouse=True)
def release_gpu_memory_between_tests():
"""Reclaim cached GPU memory between tests in this shard.
These tests start many vLLM/HF engines sequentially in one pytest
process; without explicit reclamation between tests, VRAM fragmentation
accumulates and later tests fail at engine startup ("Engine core
initialization failed").
"""
yield
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
try:
wait_for_memory_to_settle()
except ValueError as e:
# Longer-lived (class/module-scoped) engine fixtures may legitimately
# still hold VRAM; nothing further to reclaim in that case.
logger.info("Failed to clean GPU memory: %s", e)
@@ -161,10 +161,14 @@ def mteb_test_embed_models(
model_info: EmbedModelInfo,
vllm_extra_kwargs=None,
hf_model_callback=None,
atol=MTEB_EMBED_TOL,
atol: float | None = None,
prompt_prefix: str | None = None,
vllm_model_callback=None,
):
if atol is None:
atol = (
model_info.mteb_tol if model_info.mteb_tol is not None else MTEB_EMBED_TOL
)
vllm_extra_kwargs = get_vllm_extra_kwargs(model_info, vllm_extra_kwargs)
# Test embed_dims, isnan and whether to use normalize
@@ -268,4 +272,8 @@ def mteb_test_embed_models(
# We are not concerned that the vllm mteb results are better
# than SentenceTransformers, so we only perform one-sided testing.
assert st_main_score - vllm_main_score < atol
diff = st_main_score - vllm_main_score
assert diff < atol, (
f"diff={diff:.6g} tol={atol} model={model_info.name} "
f"(st={st_main_score}, vllm={vllm_main_score})"
)
@@ -230,8 +230,12 @@ def mteb_test_rerank_models(
hf_runner=HFMtebCrossEncoder,
vllm_extra_kwargs=None,
vllm_mteb_encoder=VllmMtebCrossEncoder,
atol=MTEB_RERANK_TOL,
atol: float | None = None,
):
if atol is None:
atol = (
model_info.mteb_tol if model_info.mteb_tol is not None else MTEB_RERANK_TOL
)
vllm_extra_kwargs = get_vllm_extra_kwargs(model_info, vllm_extra_kwargs)
# Maybe load chat_template.
@@ -308,4 +312,8 @@ def mteb_test_rerank_models(
# We are not concerned that the vllm mteb results are better
# than SentenceTransformers, so we only perform one-sided testing.
assert st_main_score - vllm_main_score < atol
diff = st_main_score - vllm_main_score
assert diff < atol, (
f"diff={diff:.6g} tol={atol} model={model_info.name} "
f"(st={st_main_score}, vllm={vllm_main_score})"
)
@@ -17,6 +17,7 @@ MODELS = [
"BAAI/bge-base-en",
architecture="BertModel",
mteb_score=0.779336792,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -54,6 +55,7 @@ MODELS = [
"BAAI/bge-m3",
architecture="XLMRobertaModel",
mteb_score=0.787343078,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -82,6 +84,7 @@ RERANK_MODELS = [
"BAAI/bge-reranker-base",
architecture="XLMRobertaForSequenceClassification",
mteb_score=0.32398,
mteb_tol=1e-2,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -101,6 +104,7 @@ RERANK_MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -113,6 +117,7 @@ def test_embed_models_correctness(
correctness_test_embed_models(hf_runner, vllm_runner, model_info, example_prompts)
@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)
@@ -26,6 +26,7 @@ RERANK_MODELS = [
"method": "no_post_processing",
},
mteb_score=0.33757,
mteb_tol=1e-2,
seq_pooling_type="LAST",
attn_type="decoder",
is_prefix_caching_supported=True,
@@ -127,6 +128,7 @@ class GemmaRerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
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(
@@ -17,6 +17,7 @@ RERANK_MODELS = [
is_prefix_caching_supported=False,
is_chunked_prefill_supported=False,
mteb_score=0.32898,
mteb_tol=1e-2,
),
RerankModelInfo(
"tomaarsen/Qwen3-Reranker-0.6B-seq-cls",
@@ -27,10 +28,12 @@ RERANK_MODELS = [
is_chunked_prefill_supported=True,
chat_template_name="qwen3_reranker.jinja",
mteb_score=0.33459,
mteb_tol=1e-2,
),
]
@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)
@@ -18,6 +18,7 @@ MODELS = [
EmbedModelInfo(
"thenlper/gte-large",
mteb_score=0.76807651,
mteb_tol=2e-3,
architecture="BertModel",
seq_pooling_type="MEAN",
attn_type="encoder_only",
@@ -44,6 +45,7 @@ MODELS = [
"Alibaba-NLP/gte-multilingual-base",
architecture="GteNewModel",
mteb_score=0.775074696,
mteb_tol=2e-3,
hf_overrides={"architectures": ["GteNewModel"]},
seq_pooling_type="CLS",
attn_type="encoder_only",
@@ -79,6 +81,7 @@ MODELS = [
EmbedModelInfo(
"Alibaba-NLP/gte-modernbert-base",
mteb_score=0.748193353,
mteb_tol=2e-3,
architecture="ModernBertModel",
seq_pooling_type="CLS",
attn_type="encoder_only",
@@ -90,6 +93,7 @@ MODELS = [
EmbedModelInfo(
"Qwen/Qwen3-Embedding-0.6B",
mteb_score=0.771163695,
mteb_tol=2e-3,
architecture="Qwen3ForCausalLM",
seq_pooling_type="LAST",
attn_type="decoder",
@@ -109,6 +113,7 @@ RERANK_MODELS = [
# classifier_pooling: mean
"Alibaba-NLP/gte-reranker-modernbert-base",
mteb_score=0.33386,
mteb_tol=1e-2,
architecture="ModernBertForSequenceClassification",
seq_pooling_type="CLS",
attn_type="encoder_only",
@@ -119,6 +124,7 @@ RERANK_MODELS = [
RerankModelInfo(
"Alibaba-NLP/gte-multilingual-reranker-base",
mteb_score=0.33062,
mteb_tol=1e-2,
architecture="GteNewForSequenceClassification",
hf_overrides={"architectures": ["GteNewForSequenceClassification"]},
seq_pooling_type="CLS",
@@ -130,6 +136,7 @@ RERANK_MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -142,6 +149,7 @@ def test_embed_models_correctness(
correctness_test_embed_models(hf_runner, vllm_runner, model_info, example_prompts)
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", RERANK_MODELS)
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
vllm_extra_kwargs = {}
@@ -13,6 +13,7 @@ MODELS = [
"intfloat/e5-small",
architecture="BertModel",
mteb_score=0.742285423,
mteb_tol=2e-3,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -29,6 +30,7 @@ MODELS = [
"intfloat/multilingual-e5-base",
architecture="XLMRobertaModel",
mteb_score=0.779325955,
mteb_tol=2e-3,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -48,6 +50,7 @@ MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -23,6 +23,7 @@ EMBEDDING_MODELS = [
EmbedModelInfo(
"jinaai/jina-embeddings-v3",
mteb_score=0.824413164,
mteb_tol=2e-3,
architecture="XLMRobertaModel",
is_matryoshka=True,
seq_pooling_type="MEAN",
@@ -33,6 +34,7 @@ EMBEDDING_MODELS = [
EmbedModelInfo(
"jinaai/jina-embeddings-v5-text-small",
mteb_score=0.794535707854956,
mteb_tol=2e-3,
architecture="JinaEmbeddingsV5Model",
seq_pooling_type="LAST",
attn_type="decoder",
@@ -42,6 +44,7 @@ EMBEDDING_MODELS = [
EmbedModelInfo(
"jinaai/jina-embeddings-v5-text-nano",
architecture="JinaEmbeddingsV5Model",
mteb_tol=2e-3,
dtype="bfloat16" if current_platform.is_rocm() else "auto",
seq_pooling_type="LAST",
attn_type="encoder_only",
@@ -54,6 +57,7 @@ RERANK_MODELS = [
RerankModelInfo(
"jinaai/jina-reranker-v2-base-multilingual",
mteb_score=0.33643,
mteb_tol=1e-2,
architecture="XLMRobertaForSequenceClassification",
seq_pooling_type="CLS",
attn_type="encoder_only",
@@ -63,6 +67,7 @@ RERANK_MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", EMBEDDING_MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
task = "retrieval" if "v5" in model_info.name else "text-matching"
@@ -98,6 +103,7 @@ def test_embed_models_correctness(
)
@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)
@@ -56,6 +56,7 @@ def _assert_modernbert_online_fp8(model) -> None:
)
@pytest.mark.flaky(reruns=2)
@pytest.mark.skipif(
_fp8_scaled_mm_unsupported(),
reason="No FP8 ScaledMM kernel is available on this GPU type.",
@@ -30,6 +30,7 @@ RERANK_MODELS = [
is_chunked_prefill_supported=True,
chat_template_name="mxbai_rerank_v2.jinja",
mteb_score=0.33651,
mteb_tol=1e-2,
enable_test=True,
),
RerankModelInfo(
@@ -104,6 +105,7 @@ class MxbaiRerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
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=MxbaiRerankerHfRunner)
@@ -19,6 +19,7 @@ EMBEDDING_MODELS = [
"nvidia/llama-nemotron-embed-1b-v2",
architecture="LlamaBidirectionalModel",
mteb_score=0.689164662128673,
mteb_tol=2e-3,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -32,6 +33,7 @@ RERANK_MODELS = [
architecture="LlamaBidirectionalForSequenceClassification",
chat_template_name="nemotron-rerank.jinja",
mteb_score=0.33994,
mteb_tol=1e-2,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -40,11 +42,13 @@ RERANK_MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", EMBEDDING_MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@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)
@@ -17,6 +17,7 @@ MODELS = [
# HF version and remove revision set.
revision="720244025c1a7e15661a174c63cce63c8218e52b",
mteb_score=0.737568559,
mteb_tol=2e-3,
enable_test=True,
seq_pooling_type="MEAN",
attn_type="encoder_only",
@@ -35,6 +36,7 @@ MODELS = [
"nomic-ai/nomic-embed-text-v2-moe",
architecture="NomicBertModel",
mteb_score=0.715488912,
mteb_tol=2e-3,
enable_test=True,
seq_pooling_type="MEAN",
attn_type="encoder_only",
@@ -44,6 +46,7 @@ MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -32,6 +32,7 @@ RERANK_MODELS = [
is_prefix_caching_supported=True,
is_chunked_prefill_supported=True,
mteb_score=0.33459,
mteb_tol=1e-2,
enable_test=True,
),
RerankModelInfo(
@@ -108,11 +109,13 @@ class Qwen3RerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
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=Qwen3RerankerHfRunner)
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", RERANK_MODELS)
@multi_gpu_test(num_gpus=2)
def test_rerank_models_mteb_tp(vllm_runner, model_info: RerankModelInfo) -> None:
@@ -14,6 +14,7 @@ MODELS = [
is_matryoshka=False,
architecture="BertModel",
mteb_score=0.714927797,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -37,6 +38,7 @@ MODELS = [
is_matryoshka=False,
architecture="NomicBertModel",
mteb_score=0.681146831,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -54,6 +56,7 @@ MODELS = [
is_matryoshka=True,
architecture="BertModel",
mteb_score=0.649088363,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -65,6 +68,7 @@ MODELS = [
is_matryoshka=True,
architecture="XLMRobertaModel",
mteb_score=0.712258299,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -76,6 +80,7 @@ MODELS = [
is_matryoshka=True,
architecture="GteModel",
mteb_score=0.706622444,
mteb_tol=2e-3,
seq_pooling_type="CLS",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -85,6 +90,7 @@ MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -14,6 +14,7 @@ ST_PROJECTOR_MODELS = [
"TencentBAC/Conan-embedding-v1",
architecture="BertModel",
mteb_score=0.688611955,
mteb_tol=2e-3,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -24,6 +25,7 @@ ST_PROJECTOR_MODELS = [
"google/embeddinggemma-300m",
architecture="Gemma3TextModel",
mteb_score=0.7473819294684156,
mteb_tol=2e-3,
seq_pooling_type="MEAN",
attn_type="encoder_only",
is_prefix_caching_supported=False,
@@ -33,6 +35,7 @@ ST_PROJECTOR_MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", ST_PROJECTOR_MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
@@ -22,6 +22,7 @@ MODELS = [
"num_labels": 2048,
},
mteb_score=0.7054,
mteb_tol=2e-3,
# === MTEB Results ===
# STS12: 0.6613
# STS13: 0.6906
@@ -34,6 +35,7 @@ MODELS = [
]
@pytest.mark.flaky(reruns=2)
@pytest.mark.parametrize("model_info", MODELS)
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
# Encoder-only attention models need enforce_eager=True to avoid
@@ -317,8 +317,6 @@ VLM_TEST_SETTINGS = {
img_idx_to_prompt=lambda idx: "",
auto_cls=AutoModelForImageTextToText,
vllm_output_post_proc=model_utils.blip2_vllm_to_hf_output,
# FIXME: https://github.com/huggingface/transformers/pull/38510
marks=[pytest.mark.skip("Model is broken")],
),
"cosmos3": VLMTestInfo(
models=["nvidia/Cosmos3-Nano"],
@@ -819,10 +817,6 @@ 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("4.57.3"),
reason="This model is broken in Transformers v4.57.3",
),
pytest.mark.skipif(
Version(TRANSFORMERS_VERSION) >= Version("5.0.0"),
reason="Model's custom code uses ROPE_INIT_FUNCTIONS"
@@ -499,3 +499,118 @@ def test_vit_cudagraph_video(model_id, vllm_runner, video_assets):
# Ensure the output is a string
assert isinstance(output_text, str)
def _check_eonly_encoder_outputs(worker, batches):
"""Compare real E-only replay with eager, retaining outputs across replay."""
import torch
from vllm.v1.worker.mm_encoder_model_runner import MMEncoderModelRunner
runner = worker.model_runner
assert isinstance(runner, MMEncoderModelRunner)
manager = runner.model_state.encoder_runner.cudagraph_manager
assert manager is not None and manager.is_captured()
retained: list[tuple[torch.Tensor, torch.Tensor]] = []
max_error = 0.0
stats = []
with torch.inference_mode():
for batch in batches:
kwargs = {key: value.to(runner.device) for key, value in batch.items()}
actual = manager.execute(kwargs)
expected = runner.model.embed_multimodal(**kwargs)
assert len(actual) == len(expected)
for output, reference in zip(actual, expected):
assert torch.isfinite(output).all()
# Two BF16 ulps at unit scale, fixed before model validation.
torch.testing.assert_close(output, reference, rtol=0.016, atol=0.016)
max_error = max(max_error, (output - reference).abs().max().item())
for output, snapshot in retained:
torch.testing.assert_close(output, snapshot, rtol=0, atol=0)
retained.extend((output, output.clone()) for output in actual)
stats.append(manager.get_cumulative_stats())
assert stats[0]["graph_hits"] > 0
assert stats[1]["graph_hits"] > stats[0]["graph_hits"]
assert stats[2]["graph_misses"] > stats[1]["graph_misses"]
assert stats[3]["graph_hits"] > stats[2]["graph_hits"]
assert stats[4]["graph_hits"] > stats[3]["graph_hits"]
assert stats[5]["graph_hits"] > stats[4]["graph_hits"]
assert stats[6]["graph_hits"] > stats[5]["graph_hits"]
return {"max_abs_error": max_error, "stats": stats}
@pytest.mark.parametrize(
"model_id",
params_with_marks({key: MODEL_CONFIGS[key] for key in ("qwen3_vl", "qwen3_5")}),
)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA graphs")
def test_eonly_vit_cudagraph_outputs(
model_id, vllm_runner, image_assets, video_assets, monkeypatch
):
"""Exercise startup capture, image/video replay, fallback and output ownership."""
import numpy as np
from PIL import Image
from transformers import AutoProcessor
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
config = MODEL_CONFIGS[model_id]
token_budgets = [64, 256, 2048]
processor = AutoProcessor.from_pretrained(config.model)
first, second = [asset.pil_image for asset in image_assets]
batches = [
[first.resize((224, 224))],
[second.resize((448, 224)), first.resize((224, 224))],
[second.resize((1792, 1792))],
[second.resize((224, 224))],
[first.resize((1280, 720))],
[first.resize((224, 224))],
]
frames = sample_frames_from_video(video_assets[0].np_ndarrays, 2)
video = np.stack(
[np.asarray(Image.fromarray(frame).resize((224, 224))) for frame in frames]
)
with vllm_runner(
config.model,
dtype=config.dtype,
mm_encoder_only=True,
# FA padding NaNs are tracked separately in #57136.
mm_encoder_attn_backend="FLASHINFER",
enable_prefix_caching=False,
max_model_len=4096,
max_num_seqs=2,
limit_mm_per_prompt={"image": 2, "video": 1},
compilation_config={
"cudagraph_mode": "NONE",
"cudagraph_mm_encoder": True,
"encoder_cudagraph_token_budgets": token_budgets,
"encoder_cudagraph_max_vision_items_per_batch": 2,
"encoder_cudagraph_max_frames_per_batch": 2,
},
) as model:
mm_config = model.llm.llm_engine.vllm_config.model_config.multimodal_config
processor_kwargs = mm_config.merge_mm_processor_kwargs({})
inputs = [
dict(
processor.image_processor(
images=images, return_tensors="pt", **processor_kwargs
)
)
for images in batches
]
inputs.append(
dict(
processor.video_processor(
videos=[video],
do_sample_frames=False,
return_tensors="pt",
**processor_kwargs,
)
)
)
results = model.llm.collective_rpc(
partial(_check_eonly_encoder_outputs, batches=inputs)
)
for result in results:
assert result["stats"][0]["token_budgets"] == token_budgets
print(f"E-only {model_id}: {results}")
@@ -308,16 +308,6 @@ def gemma3_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
hf_model.processor = processor
orig_generate = hf_model.model.generate
def _generate(self, *args, **kwargs):
# FIXME: https://github.com/huggingface/transformers/issues/38333
kwargs["disable_compile"] = True
return orig_generate(*args, **kwargs)
hf_model.model.generate = types.MethodType(_generate, hf_model.model)
return hf_model
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Pytest configuration for vLLM multimodal pooling tests."""
import gc
import pytest
import torch
from tests.utils import wait_for_memory_to_settle
from vllm.logger import init_logger
logger = init_logger(__name__)
@pytest.fixture(autouse=True)
def release_gpu_memory_between_tests():
"""Reclaim cached GPU memory between tests in this shard.
These tests start many vLLM/HF engines sequentially in one pytest
process; without explicit reclamation between tests, VRAM fragmentation
accumulates and later tests fail at engine startup ("Engine core
initialization failed").
"""
yield
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
try:
wait_for_memory_to_settle()
except ValueError as e:
# Longer-lived (class/module-scoped) engine fixtures may legitimately
# still hold VRAM; nothing further to reclaim in that case.
logger.info("Failed to clean GPU memory: %s", e)
@@ -2,8 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import transformers
from packaging import version
from transformers import AutoModel
from vllm.assets.base import VLLM_S3_BUCKET_URL
@@ -246,10 +244,6 @@ def _run_test(
@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
@pytest.mark.skipif(
version.parse(transformers.__version__) == version.parse("4.57.5"),
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
def test_model_text_image(
hf_runner,
vllm_runner,
@@ -269,10 +263,6 @@ def test_model_text_image(
@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
@pytest.mark.skipif(
version.parse(transformers.__version__) == version.parse("4.57.5"),
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
def test_model_text_text(
hf_runner,
vllm_runner,
@@ -292,10 +282,6 @@ def test_model_text_text(
@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
@pytest.mark.skipif(
version.parse(transformers.__version__) == version.parse("4.57.5"),
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
def test_model_image_text(
hf_runner,
vllm_runner,
@@ -315,10 +301,6 @@ def test_model_image_text(
@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
@pytest.mark.skipif(
version.parse(transformers.__version__) == version.parse("4.57.5"),
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
def test_model_image_image(
hf_runner,
vllm_runner,
@@ -338,10 +320,6 @@ def test_model_image_image(
@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
@pytest.mark.skipif(
version.parse(transformers.__version__) == version.parse("4.57.5"),
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
def test_model_text_mixed_documents(
hf_runner,
vllm_runner,
@@ -63,36 +63,32 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
mm_processor_cache_gb=1,
)
# Baseline: no cache, always processes from scratch.
baseline_processor = MULTIMODAL_REGISTRY.create_processor(
ctx.model_config, cache=None
)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
# Sender cache: on a cache hit returns (None, prompt_updates) for each
# item, setting mm_kwargs["video"] = [None] – the exact condition that
# triggered the original bug.
sender_cache = MultiModalProcessorSenderCache(ctx.model_config)
cached_processor = MULTIMODAL_REGISTRY.create_processor(
ctx.model_config, cache=sender_cache
)
video_token_id = baseline_processor.info.get_hf_config().video_token_id
video_token_id = processor.info.get_hf_config().video_token_id
mm_data = create_mm_data(num_videos)
hf_processor_mm_kwargs = {"use_audio_in_video": True}
def run(processor):
def run(processor, cache):
return processor(
[video_token_id] * num_videos,
mm_items=baseline_processor.info.parse_mm_data(mm_data),
mm_items=processor.info.parse_mm_data(mm_data),
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
cache=cache,
)["prompt_token_ids"]
baseline_ids = run(baseline_processor)
baseline_ids = run(processor, cache=None)
# First call on the sender-cache processor: cache miss.
# mm_kwargs["video"] items are real tensors; use_audio_in_video is
# detected normally from the item data.
first_ids = run(cached_processor)
first_ids = run(processor, cache=sender_cache)
assert first_ids == baseline_ids, (
"Cache-miss call produced different prompt_token_ids than baseline.\n"
f" baseline : {baseline_ids}\n"
@@ -103,7 +99,7 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
# MultiModalProcessorSenderCache.get_and_update_item returns (None, …),
# so mm_kwargs["video"] = [None]. Before the fix, use_audio_in_video was
# not detected, yielding wrong token ids.
second_ids = run(cached_processor)
second_ids = run(processor, cache=sender_cache)
assert second_ids == baseline_ids, (
"Cache-hit call produced different prompt_token_ids than baseline.\n"
"This is the regression introduced when use_audio_in_video detection\n"
@@ -123,7 +119,7 @@ def test_use_audio_in_video_without_audio_track(model_id: str) -> None:
model_id,
limit_mm_per_prompt={"audio": 1, "image": 0, "video": 1},
)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=None)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
video_token_id = processor.info.get_hf_config().video_token_id
rng = np.random.RandomState(0)
@@ -25,6 +25,7 @@ import torch
from transformers import PretrainedConfig
from tests.models.registry import HF_EXAMPLE_MODELS
from vllm.config.multimodal import MultiModalDummyOptions
class MockAudioFlamingo3Config(PretrainedConfig):
@@ -127,7 +128,7 @@ def test_dummy_data_generation(mock_ctx):
builder = AudioFlamingo3DummyInputsBuilder(info)
mm_counts = {"audio": 2}
dummy_data = builder.get_dummy_mm_data(100, mm_counts, {})
dummy_data = builder.get_dummy_mm_data(100, mm_counts, MultiModalDummyOptions())
assert "audio" in dummy_data
assert len(dummy_data["audio"]) == 2
@@ -13,6 +13,7 @@ from vllm.config.multimodal import (
AudioDummyOptions,
BaseDummyOptions,
ImageDummyOptions,
MultiModalDummyOptions,
VideoDummyOptions,
)
from vllm.inputs import MultiModalDataDict, MultiModalInput
@@ -71,6 +72,8 @@ def glmasr_patch_mm_data(mm_data: MultiModalDataDict) -> MultiModalDataDict:
_IGNORE_MM_KEYS = {
# Dithering causes minor divergence
"cohere_asr": {"input_features"},
# In Ultravox, the audio_features can be different depending on padding
# The slight difference should not be a problem though, since
# attention_mask lets us ignore the difference.
@@ -174,7 +177,7 @@ def get_token_prompt(
inputs = dummy_inputs.get_dummy_processor_inputs(
model_config.max_model_len,
mm_counts,
mm_options={},
mm_options=MultiModalDummyOptions(),
# Assume all Mistral models define this extra argument
mm_data=mm_data, # type: ignore[call-arg]
)
@@ -182,7 +185,7 @@ def get_token_prompt(
inputs = dummy_inputs.get_dummy_processor_inputs(
model_config.max_model_len,
mm_counts,
mm_options={},
mm_options=MultiModalDummyOptions(),
)
if not isinstance(inputs.prompt, list):
@@ -278,13 +281,14 @@ def _test_processing_correctness(
return BaseDummyOptions(count=count)
# Assign normalized DummyOptions to the model config
model_config.get_multimodal_config().limit_per_prompt = {
modality: _to_dummy_options(modality, count)
for modality, count in limit_mm_per_prompt_ints.items()
}
model_config.get_multimodal_config().limit_per_prompt = MultiModalDummyOptions(
{
modality: _to_dummy_options(modality, count)
for modality, count in limit_mm_per_prompt_ints.items()
}
)
baseline_processor = factories.build_processor(ctx, cache=None)
cached_processor = factories.build_processor(ctx, cache=cache)
processor = factories.build_processor(ctx)
rng = np.random.RandomState(0)
@@ -333,41 +337,42 @@ def _test_processing_correctness(
_test_processing_correctness_one(
model_config,
mm_data,
baseline_processor,
cached_processor,
processor,
batch_idx,
hit_rate,
num_batches,
simplify_rate,
cache=cache,
)
def _test_processing_correctness_one(
model_config: ModelConfig,
mm_data: MultiModalDataDict,
baseline_processor: BaseMultiModalProcessor,
cached_processor: BaseMultiModalProcessor,
processor: BaseMultiModalProcessor,
batch_idx: int,
hit_rate: float,
num_batches: int,
simplify_rate: float,
cache: MultiModalProcessorOnlyCache,
):
model_type = model_config.hf_config.model_type
token_prompt = get_token_prompt(baseline_processor, mm_data)
mm_items = baseline_processor.info.parse_mm_data(mm_data)
token_prompt = get_token_prompt(processor, mm_data)
mm_items = processor.info.parse_mm_data(mm_data)
ignore_mm_keys = _IGNORE_MM_KEYS.get(model_type, set[str]())
baseline_tokenized_result = baseline_processor(
baseline_tokenized_result = processor(
token_prompt,
mm_items=mm_items,
hf_processor_mm_kwargs={},
)
cached_tokenized_result = cached_processor(
cached_tokenized_result = processor(
token_prompt,
mm_items=mm_items,
hf_processor_mm_kwargs={},
cache=cache,
)
_assert_inputs_equal(
@@ -221,7 +221,7 @@ def test_video_cache_is_independent_of_image_kwargs(
mm_processor_cache_gb=1,
)
cache = MultiModalProcessorOnlyCache(ctx.model_config)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=cache)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
hf_processor = processor.info.get_hf_processor()
image = PILImage.new("RGB", (48, 48), color=(128, 128, 128))
frames = np.stack([np.asarray(image)] * 2)
@@ -230,15 +230,16 @@ def test_video_cache_is_independent_of_image_kwargs(
{"image": image, "video": [(frames, metadata)]}
)
def process(mm_kwargs):
def process(mm_kwargs, cache):
return processor(
hf_processor.image_token + hf_processor.video_token,
mm_items,
mm_uuid_items={"video": [video_uuid]},
hf_processor_mm_kwargs=mm_kwargs,
cache=cache,
)
baseline = process({})
baseline = process({}, cache=None)
if kwargs_on_init:
ctx = build_model_context(
model_id,
@@ -247,12 +248,12 @@ def test_video_cache_is_independent_of_image_kwargs(
mm_processor_cache_gb=1,
)
cache = MultiModalProcessorOnlyCache(ctx.model_config)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=cache)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
request_kwargs = {} if kwargs_on_init else kwargs
process(request_kwargs)
cached = process(request_kwargs)
process(request_kwargs, cache=cache)
cached = process(request_kwargs, cache=cache)
cache.clear_cache()
fresh = process(request_kwargs)
fresh = process(request_kwargs, cache=cache)
def pixels(result, modality, field):
return result["mm_kwargs"][modality][0][field].data
@@ -3,9 +3,7 @@
"""Tests for Idefics3's multimodal preprocessing kwargs."""
import pytest
from packaging.version import Version
from transformers import Idefics3Config
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -13,10 +11,6 @@ from ....conftest import ImageTestAssets
from ...utils import build_model_context
@pytest.mark.skipif(
Version(TRANSFORMERS_VERSION) < Version("5.2.0"),
reason="See https://github.com/huggingface/transformers/pull/43948",
)
@pytest.mark.parametrize("model_id", ["HuggingFaceM4/Idefics3-8B-Llama3"])
@pytest.mark.parametrize(
("mm_processor_kwargs", "expected_toks_per_img"),
@@ -23,11 +23,9 @@ def test_profiling(model_id: str, max_model_len: int):
model_config_kwargs=model_config_kwargs,
limit_mm_per_prompt=mm_counts,
)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
mm_inputs = MULTIMODAL_REGISTRY.get_dummy_mm_inputs(
ctx.model_config,
mm_counts=mm_counts,
)
mm_inputs = processor.get_dummy_mm_inputs(mm_counts)
hf_config = ctx.get_hf_config(Llama4Config)
image_size = hf_config.vision_config.image_size
@@ -6,7 +6,7 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.config.multimodal import VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions, VideoDummyOptions
from vllm.model_executor.models.molmo2 import (
Molmo2DummyInputsBuilder,
build_flat_image_bool_length,
@@ -83,7 +83,9 @@ def test_dummy_video_num_frames_override_honors_min_of_two(
data = builder.get_dummy_mm_data(
seq_len=128,
mm_counts={"image": 0, "video": 1},
mm_options={"video": VideoDummyOptions(num_frames=num_frames_override)},
mm_options=MultiModalDummyOptions(
video=VideoDummyOptions(num_frames=num_frames_override)
),
)
video, _metadata = data["video"][0]
@@ -168,7 +168,6 @@ def _build_moss_audio_processor(cache=None):
MossAudioMultiModalProcessor(
info,
MossAudioDummyInputsBuilder(info),
cache=cache,
),
ctx,
)
@@ -259,21 +258,24 @@ def test_moss_audio_multimodal_processor_handles_token_and_cache_paths():
)
cache = MultiModalProcessorOnlyCache(ctx.model_config)
cached_processor, _ = _build_moss_audio_processor(cache=cache)
cached_processor, _ = _build_moss_audio_processor()
cached_text_miss = cached_processor(
prompt,
mm_items=mm_items,
hf_processor_mm_kwargs={},
cache=cache,
)
cached_text_hit = cached_processor(
prompt,
mm_items=mm_items,
hf_processor_mm_kwargs={},
cache=cache,
)
cached_token_hit = cached_processor(
token_prompt,
mm_items=mm_items,
hf_processor_mm_kwargs={},
cache=cache,
)
expected_audio_tokens = MossAudioEncoder.compute_num_audio_tokens(raw_mel_len)
@@ -3,9 +3,7 @@
import pytest
import torch
from packaging.version import Version
from PIL import Image
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.model_executor.models.vision import FusedInputNorm
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -28,7 +26,6 @@ def test_jina_vl_processing_order() -> None:
processor = MULTIMODAL_REGISTRY.create_processor(
ctx.model_config,
tokenizer=ctx.tokenizer,
cache=cache,
)
placeholder = "<|vision_start|><|image_pad|><|vision_end|>"
@@ -39,6 +36,7 @@ def test_jina_vl_processing_order() -> None:
return processor(
placeholder * len(images),
mm_items=processor.info.parse_mm_data({"image": images}),
cache=cache,
)
query = process([query_image])
@@ -133,12 +131,6 @@ def test_processor_override(
kwargs_on_init: bool,
):
"""Ensure Qwen2VLMultiModalProcessor handles min/max pixels properly."""
if (
Version(TRANSFORMERS_VERSION) < Version("5.2.0")
and "size" in mm_processor_kwargs
):
pytest.skip("`size` ignored by `Qwen2VLProcessor.__call__`")
ctx = build_model_context(
model_id,
mm_processor_kwargs=mm_processor_kwargs if kwargs_on_init else None,
@@ -184,12 +176,6 @@ def test_get_image_size_with_most_features(
model_id: str,
mm_processor_kwargs: dict[str, object],
):
if (
Version(TRANSFORMERS_VERSION) < Version("5.2.0")
and "size" in mm_processor_kwargs
):
pytest.skip("`size` ignored by `Qwen2VLProcessor.__call__`")
ctx = build_model_context(
model_id,
mm_processor_kwargs=mm_processor_kwargs,
@@ -12,6 +12,7 @@ import numpy as np
import pytest
from vllm.config import ModelConfig
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.multimodal import MULTIMODAL_REGISTRY
from ...registry import HF_EXAMPLE_MODELS
@@ -339,7 +340,9 @@ def test_dummy_video_spreads_budget_when_frame_cap_enabled(model_id: str) -> Non
limit_mm_per_prompt={"image": 0, "video": 1},
)
capped = MULTIMODAL_REGISTRY.create_processor(capped_ctx.model_config)
capped_dummy = capped.dummy_inputs.get_dummy_mm_data(1024, {"video": 1}, {})
capped_dummy = capped.dummy_inputs.get_dummy_mm_data(
1024, {"video": 1}, MultiModalDummyOptions()
)
capped_frames = capped_dummy["video"][0][0].shape[0]
assert capped_frames == 16, (
f"Expected the dummy to spread the budget over 16 frames, got {capped_frames}"
@@ -351,7 +354,9 @@ def test_dummy_video_spreads_budget_when_frame_cap_enabled(model_id: str) -> Non
limit_mm_per_prompt={"image": 0, "video": 1},
)
uncapped = MULTIMODAL_REGISTRY.create_processor(uncapped_ctx.model_config)
uncapped_dummy = uncapped.dummy_inputs.get_dummy_mm_data(1024, {"video": 1}, {})
uncapped_dummy = uncapped.dummy_inputs.get_dummy_mm_data(
1024, {"video": 1}, MultiModalDummyOptions()
)
uncapped_frames = uncapped_dummy["video"][0][0].shape[0]
assert uncapped_frames == 2, (
f"Expected the uncapped dummy to keep 2 frames, got {uncapped_frames}"
@@ -3,9 +3,7 @@
"""Tests for smolvlm's multimodal preprocessing kwargs."""
import pytest
from packaging.version import Version
from transformers import SmolVLMConfig
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -13,10 +11,6 @@ from ....conftest import ImageTestAssets
from ...utils import build_model_context
@pytest.mark.skipif(
Version(TRANSFORMERS_VERSION) < Version("5.2.0"),
reason="See https://github.com/huggingface/transformers/pull/43948",
)
@pytest.mark.parametrize("model_id", ["HuggingFaceTB/SmolVLM2-2.2B-Instruct"])
@pytest.mark.parametrize(
("mm_processor_kwargs", "expected_toks_per_img"),
@@ -18,6 +18,7 @@ from vllm.config.multimodal import (
AudioDummyOptions,
BaseDummyOptions,
ImageDummyOptions,
MultiModalDummyOptions,
VideoDummyOptions,
)
from vllm.distributed import (
@@ -98,7 +99,7 @@ def create_batched_mm_kwargs(
processor_inputs = dummy_inputs.get_dummy_processor_inputs(
seq_len=model_config.max_model_len,
mm_counts=mm_counts,
mm_options={},
mm_options=MultiModalDummyOptions(),
)
mm_items = processor_inputs.mm_data_items
resized_mm_data = {
@@ -248,11 +249,13 @@ def test_model_tensor_schema(model_id: str):
return AudioDummyOptions(count=count)
return BaseDummyOptions(count=count)
model_config.get_multimodal_config().limit_per_prompt = {
modality: _to_dummy_options(modality, count)
for modality, count in limit_mm_per_prompt.items()
}
processor = factories.build_processor(ctx, cache=None)
model_config.get_multimodal_config().limit_per_prompt = MultiModalDummyOptions(
{
modality: _to_dummy_options(modality, count)
for modality, count in limit_mm_per_prompt.items()
}
)
processor = factories.build_processor(ctx)
with initialize_dummy_model(model_cls, model_config) as model:
for modality, _, mm_kwargs in create_batched_mm_kwargs(model_config, processor):
@@ -245,6 +245,7 @@ def test_repeated_image_hits_the_processor_cache():
prompt="<image>\nWhat is this?",
mm_items=mm_processor.info.parse_mm_data({"image": image}),
hf_processor_mm_kwargs={},
cache=cache,
)
first, second = process(), process()

Some files were not shown because too many files have changed in this diff Show More