[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests

- Drop dead model modules, keeping files live imports require
- Remove anthropic, cohere, codegen entrypoints and batch STT modes
- Delete unused attention backends, MoE experts, and NPU/XPU util leaves
- Strip dead third_party trees and ROCm leaves with no CUDA path
- Remove mooncake EC connectors: dependency missing since branch base
- Re-audit verified by full import sweep and Qwen3.5 smoke test

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 00:20:48 +07:00
co-authored by Hinata
parent 6a95f62e2f
commit 81074e94a3
940 changed files with 11 additions and 380533 deletions
-494
View File
@@ -1,494 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Numerical checks against an independent, teacher-forced target model."""
import json
import math
from collections import Counter
from dataclasses import dataclass
from functools import lru_cache
import torch
import xgrammar as xgr
from tokenizers.decoders import DecodeStream
from tests.conftest import HfRunner
from vllm import SamplingParams
from vllm.logprobs import Logprob
from vllm.outputs import RequestOutput
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
from vllm.v1.engine.logprobs import LogprobsProcessor
@dataclass(frozen=True)
class AccuracyTolerance:
logprob_atol: float
greedy_atol: float
logprob_mean_atol: float = 0.1
greedy_total_atol: float = 0.5
def logprob_error(self, reference: torch.Tensor) -> torch.Tensor:
return torch.full_like(reference, self.logprob_atol)
def check_first_divergence(
baseline: RequestOutput,
actual: RequestOutput,
params: SamplingParams,
tolerance: AccuracyTolerance,
context: str,
) -> None:
"""Require the two engines' scores to justify their first different choice."""
assert baseline.finished and actual.finished, context
assert len(baseline.outputs) == len(actual.outputs) == 1, context
assert baseline.prompt_token_ids is not None, context
assert baseline.prompt_token_ids == actual.prompt_token_ids, context
base, other = baseline.outputs[0], actual.outputs[0]
position = next(
(i for i, (a, b) in enumerate(zip(base.token_ids, other.token_ids)) if a != b),
None,
)
if position is None:
assert len(base.token_ids) == len(other.token_ids), (
f"{context}: one completion is a strict prefix of the other"
)
assert (base.finish_reason, base.stop_reason) == (
other.finish_reason,
other.stop_reason,
), f"{context}: identical tokens have different stopping reasons"
return
assert params.logprobs is not None and params.logprobs > 0, context
assert params.temperature == 0.0, context
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
assert not params.logit_bias, context
a, b = base.token_ids[position], other.token_ids[position]
counts = Counter(base.token_ids[:position])
context = (
f"{context}, first divergence position={position}, "
f"baseline token={a}, actual token={b}"
)
for side, completion, selected, alternative in (
("baseline", base, a, b),
("actual", other, b, a),
):
assert completion.logprobs is not None, context
assert len(completion.logprobs) == len(completion.token_ids), context
scores = completion.logprobs[position]
assert selected in scores, f"{context}, {side}: missing selected token score"
chosen = scores[selected].logprob
assert math.isfinite(chosen), f"{context}, {side}: non-finite selected score"
known = alternative in scores
if known:
competing = scores[alternative].logprob
assert math.isfinite(competing), (
f"{context}, {side}: divergent token has a non-finite score"
)
else:
# The sampled token may be returned in addition to the requested
# top-k. An omitted token's raw score is bounded by the kth score.
top_scores = [
score.logprob
for token, score in scores.items()
if len(scores) == params.logprobs or token != selected
]
assert len(top_scores) == params.logprobs, context
assert not any(math.isnan(score) for score in top_scores), context
competing = min(top_scores)
# Both candidates were emitted with the same history and constraints;
# frequency penalties are the only supported transform changing their
# finite score difference. Prompt tokens do not contribute to counts.
chosen -= params.frequency_penalty * counts[selected]
competing -= params.frequency_penalty * counts[alternative]
gap = chosen - competing
detail = (
f"{context}, {side}: selected={selected}, alternative={alternative}, "
f"{'gap' if known else 'gap lower bound'}={gap}"
)
if known:
# Log-softmax and reconstructing penalties may round in FP32, but
# a near tie cannot excuse selecting the engine's own worse token.
assert gap >= -1e-5, f"{detail}: selected token is below its alternative"
# Same FP32 rounding slack as above, applied to the upper bound.
assert gap <= tolerance.greedy_atol + 1e-5, (
f"{detail}: divergence exceeds near-tie bound="
f"{tolerance.greedy_atol} (+1e-5 slack)"
)
def check_logprobs(
scores: dict[int, Logprob],
reference: torch.Tensor,
token: int,
requested: int,
tolerance: AccuracyTolerance,
context: str,
) -> torch.Tensor:
"""Check every score, reported rank, and the complete requested top-k."""
assert all(0 <= token_id < reference.numel() for token_id in scores), context
assert token in scores, f"{context}: missing score for token {token}"
assert max(1, requested) <= len(scores) <= requested + 1, context
assert not torch.isnan(reference).any(), context
assert all(s.rank is not None and s.rank >= 1 for s in scores.values()), context
ids = torch.tensor(list(scores), device=reference.device)
actual = torch.tensor(
[score.logprob for score in scores.values()], device=reference.device
)
expected = reference[ids]
finite = torch.isfinite(expected)
assert torch.equal(torch.isfinite(actual), finite), (
f"{context}: finite/masked logprobs differ: {scores}"
)
assert torch.equal(actual[~finite], expected[~finite]), context
assert (actual[finite] <= 0).all(), f"{context}: positive log probability"
errors = (actual[finite] - expected[finite]).abs()
bounds = tolerance.logprob_error(expected[finite])
assert (errors <= bounds).all(), (
f"{context}: token IDs={ids[finite].tolist()}, "
f"actual={actual[finite].tolist()}, reference={expected[finite].tolist()}, "
f"error={errors.tolist()}, bound={bounds.tolist()}"
)
for token_id, score in scores.items():
value = reference[token_id]
if not torch.isfinite(value):
continue
delta = tolerance.logprob_error(value)
lower = 1 + int((reference > value + 2 * delta).sum())
upper = max(1, int((reference >= value - 2 * delta).sum()))
assert score.rank is not None and lower <= score.rank <= upper, (
f"{context}: token={token_id}, rank={score.rank}, "
f"reference rank interval=[{lower}, {upper}]"
)
if requested:
# The sampled token can be outside top-k even when it ties the kth
# score. Its strict-greater rank can therefore duplicate a top-k rank.
top_ids = (
list(scores)
if len(scores) == requested
else [t for t in scores if t != token]
)
assert len(top_ids) == requested, f"{context}: incomplete top-k"
assert {scores[t].rank for t in top_ids} == set(range(1, requested + 1)), (
context
)
ordered = sorted(top_ids, key=lambda t: scores[t].rank)
assert all(
scores[a].logprob >= scores[b].logprob for a, b in zip(ordered, ordered[1:])
), f"{context}: top-k scores disagree with their reported ranks"
boundary = reference.topk(requested).values[-1]
if torch.isfinite(boundary):
delta = tolerance.logprob_error(boundary)
required = (reference > boundary + 2 * delta).nonzero().flatten()
assert set(required.tolist()) <= scores.keys(), (
f"{context}: missing an unambiguously top-{requested} token"
)
assert (reference[top_ids] >= boundary - 2 * delta).all(), (
f"{context}: returned token below the top-{requested} boundary"
)
return errors
def check_greedy_token(
logits: torch.Tensor,
token: int,
tolerance: AccuracyTolerance,
context: str,
) -> float:
assert not torch.isnan(logits).any(), context
assert torch.isfinite(logits[token]), (
f"{context}: selected token {token} is forbidden by the sampling parameters"
)
best = int(logits.argmax())
gap = float(logits[best] - logits[token])
# FP32 rounding can push a true near-tie fractionally past the bound.
assert gap <= tolerance.greedy_atol + 1e-5, (
f"{context}: selected token={token}, reference best={best}, "
f"logit gap={gap}, bound={tolerance.greedy_atol} (+1e-5 slack)"
)
return gap
def check_accuracy_budget(errors, gaps, tolerance, context):
"""Reject systematic sub-bound errors within each request and score stream."""
if errors:
finite_errors = torch.cat(errors)
if finite_errors.numel():
mean_error = float(finite_errors.mean())
assert mean_error <= tolerance.logprob_mean_atol, (
f"{context}: mean logprob error={mean_error}, "
f"bound={tolerance.logprob_mean_atol}"
)
assert sum(gaps) <= tolerance.greedy_total_atol, (
f"{context}: total greedy logit gap={sum(gaps)}, "
f"bound={tolerance.greedy_total_atol}"
)
def _check_decoded_tokens(processor, scores, history, context):
ids = list(scores)
decoded = convert_ids_list_to_tokens(processor.tokenizer, ids)
decoded = processor._verify_tokens(decoded, ids, context_token_ids=history[-4:])
for token, text in zip(ids, decoded, strict=True):
assert scores[token].decoded_token == text, (
f"{context}: incorrect decoded text for token {token}"
)
@torch.inference_mode()
def check_request_accuracy(
hf: HfRunner,
request: RequestOutput,
params: SamplingParams,
tolerance: AccuracyTolerance,
context: str,
) -> None:
"""Score the actual continuation, including positions after any divergence."""
assert request.finished and len(request.outputs) == 1, context
(completion,) = request.outputs
prompt = request.prompt_token_ids
assert prompt is not None and len(prompt) > 0, context
tokens = list(completion.token_ids)
assert params.max_tokens is not None and 0 < len(tokens) <= params.max_tokens, (
context
)
# Incremental decoding buffers incomplete UTF-8; decoding the final token
# list in one call can incorrectly append a replacement character.
stream = DecodeStream(skip_special_tokens=params.skip_special_tokens)
tokenizer = hf.tokenizer.backend_tokenizer
for token in prompt:
stream.step(tokenizer, token)
visible = tokens
if completion.finish_reason == "stop" and not params.include_stop_str_in_output:
visible = tokens[:-1]
expected_text = "".join(stream.step(tokenizer, token) or "" for token in visible)
assert completion.text == expected_text, (
f"{context}: decoded text does not match generated token IDs"
)
inputs = torch.tensor([prompt + tokens], device=hf.device)
logits = hf.model(input_ids=inputs, use_cache=False).logits[0].float()
# Use the existing byte-fallback handling with an independent request
# history; numerical scores always come from the HF model above.
decoder = LogprobsProcessor(
tokenizer=hf.tokenizer,
logprobs=None,
prompt_logprobs=None,
cumulative_logprob=None,
num_logprobs=None,
num_prompt_logprobs=None,
)
# Prompt token i is predicted by the causal logits at position i - 1.
if params.prompt_logprobs is None:
assert request.prompt_logprobs is None, context
else:
assert request.prompt_logprobs is not None, context
assert len(request.prompt_logprobs) == len(prompt), context
assert request.prompt_logprobs[0] is None, context
errors = []
for i, scores in enumerate(request.prompt_logprobs[1:], 1):
assert scores is not None, context
_check_decoded_tokens(decoder, scores, prompt[1:i], context)
errors.append(
check_logprobs(
scores,
logits[i - 1].log_softmax(-1),
prompt[i],
params.prompt_logprobs,
tolerance,
f"{context}, prompt position={i}",
)
)
check_accuracy_budget(errors, [], tolerance, f"{context}, prompt logprobs")
if params.logprobs is None:
assert completion.logprobs is None, context
else:
assert completion.logprobs is not None, context
assert len(completion.logprobs) == len(tokens), context
reference = SamplingReference(
hf.tokenizer,
logits.shape[-1],
hf.model.generation_config.to_dict(),
params,
)
errors = []
gaps = []
for i, token in enumerate(tokens):
raw, processed = reference.distributions(
logits[len(prompt) + i - 1], tokens[:i]
)
position = f"{context}, generated position={i}"
gaps.append(check_greedy_token(processed, token, tolerance, position))
if completion.logprobs is not None:
_check_decoded_tokens(decoder, completion.logprobs[i], tokens[:i], position)
errors.append(
check_logprobs(
completion.logprobs[i],
raw.log_softmax(-1),
token,
params.logprobs,
tolerance,
position,
)
)
check_accuracy_budget(errors, gaps, tolerance, f"{context}, completion")
# Advance the grammar through the last token too; an incomplete JSON prefix
# is allowed at max_tokens, but every emitted token must remain valid.
reference.accept_history(tokens)
check_stopping(
tokens,
completion.finish_reason,
reference.stop_ids,
params,
context,
eos_token_id=hf.tokenizer.eos_token_id,
stop_reason=completion.stop_reason,
)
def check_stopping(
tokens,
finish_reason,
stop_ids,
params,
context,
*,
eos_token_id: int | None,
stop_reason: int | str | None,
):
assert not params.ignore_eos and not params.stop, context
assert not stop_ids.intersection(tokens[:-1]), (
f"{context}: generation continued after a stop token"
)
if tokens[-1] in stop_ids:
assert finish_reason == "stop", (
f"{context}: stop token did not terminate output"
)
expected_stop_reason = None if tokens[-1] == eos_token_id else tokens[-1]
assert stop_reason == expected_stop_reason, (
f"{context}: stop reason={stop_reason}, expected={expected_stop_reason}"
)
else:
assert finish_reason == "length" and len(tokens) == params.max_tokens, context
assert stop_reason is None, f"{context}: length cap has a stop reason"
@lru_cache(maxsize=4)
def _compiler(tokenizer, vocab_size: int):
info = xgr.TokenizerInfo.from_huggingface(tokenizer, vocab_size=vocab_size)
return xgr.GrammarCompiler(info, max_threads=1, cache_enabled=True)
class SamplingReference:
"""One request's reference; histories must grow without changing their prefix."""
def __init__(
self,
tokenizer,
vocab_size: int,
generation_config: dict,
params: "SamplingParams",
):
assert params.temperature == 0.0, "Only the original greedy matrix is supported"
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
assert params.allowed_token_ids is None and not params.logit_bias
self.vocab_size = vocab_size
self.min_tokens = params.min_tokens
self.frequency_penalty = params.frequency_penalty
self.stop_ids = set(params.stop_token_ids or [])
for eos in (tokenizer.eos_token_id, generation_config.get("eos_token_id")):
if eos is not None:
self.stop_ids.update([eos] if isinstance(eos, int) else eos)
assert all(0 <= token < vocab_size for token in self.stop_ids)
# Match public bad-word tokenization semantics without using sampler code.
self.bad_words: list[list[int]] = []
for word in params.bad_words or []:
plain = tokenizer.encode(word.lstrip(), add_special_tokens=False)
spaced = tokenizer.encode(" " + word.lstrip(), add_special_tokens=False)
assert plain, f"Empty bad-word tokenization: {word!r}"
self.bad_words.append(plain)
if spaced and len(spaced) == len(plain) and spaced[0] != plain[0]:
self.bad_words.append(spaced)
self.history: list[int] = []
self.matcher = None
self.bitmask = None
if params.structured_outputs is not None:
schema = params.structured_outputs.json
assert schema is not None, "Only the original JSON schema is supported"
# Preserve dictionary order: xgrammar's default grammar orders fields.
schema = schema if isinstance(schema, str) else json.dumps(schema)
compiled = _compiler(tokenizer, vocab_size).compile_json_schema(
schema, any_whitespace=True
)
self.matcher = xgr.GrammarMatcher(
compiled, override_stop_tokens=sorted(self.stop_ids) or None
)
self.bitmask = xgr.allocate_token_bitmask(1, vocab_size)
def accept_history(self, generated_ids: list[int]) -> bool:
"""Validate newly generated grammar tokens, including the final EOS.
Return whether the grammar has terminated. Use this after the final
output token; no next-token distribution exists after termination.
"""
assert generated_ids[: len(self.history)] == self.history, (
"Each reference belongs to one monotonically growing request history"
)
if self.matcher is not None:
for token in generated_ids[len(self.history) :]:
assert self.matcher.accept_token(token), (
f"Grammar rejected token {token} at position {len(self.history)}"
)
self.history.append(token)
return self.matcher.is_terminated()
else:
self.history = generated_ids.copy()
return False
def distributions(
self, raw_logits: torch.Tensor, generated_ids: list[int]
) -> tuple[torch.Tensor, torch.Tensor]:
"""Return FP32 logits before and after non-grammar sampling transforms.
``raw_logits`` scores the next token after the prompt and
``generated_ids``. Returned tensors do not alias the model's tensor.
Normalize the first result to check reported completion logprobs;
the second supplies the greedy decision reference.
"""
assert raw_logits.shape == (self.vocab_size,)
assert not self.accept_history(generated_ids), (
"Cannot generate a distribution after grammar EOS"
)
grammar_logits = raw_logits.float().clone()
if self.matcher is not None:
assert self.bitmask is not None
self.matcher.fill_next_token_bitmask(self.bitmask)
words = self.bitmask[0, :, None]
allowed = ((words >> torch.arange(32)) & 1).flatten()
allowed = allowed[: self.vocab_size].bool().to(raw_logits.device)
grammar_logits.masked_fill_(~allowed, -torch.inf)
processed = grammar_logits.clone()
for bad_word in self.bad_words:
prefix = bad_word[:-1]
if not prefix or generated_ids[-len(prefix) :] == prefix:
processed[bad_word[-1]] = -torch.inf
if len(generated_ids) < self.min_tokens and self.stop_ids:
stop_ids = sorted(self.stop_ids)
stop_scores = processed[stop_ids].clone()
processed[stop_ids] = -torch.inf
# A completed grammar may have no continuation except a stop token.
if self.matcher is not None and torch.isneginf(processed).all():
processed[stop_ids] = stop_scores
if self.frequency_penalty:
for token, count in Counter(generated_ids).items():
processed[token] -= self.frequency_penalty * count
return grammar_logits, processed
@@ -1,450 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
from itertools import repeat
from typing import Any
import pytest
import torch._dynamo.config as dynamo_config
from tests.utils import (
large_gpu_mark,
single_gpu_only,
)
from vllm import SamplingParams
from vllm.logprobs import Logprob
from vllm.platforms import current_platform
from vllm.sampling_params import StructuredOutputsParams
from vllm.v1.metrics.reader import Metric
from ....conftest import VllmRunner
from ....models.utils import check_outputs_equal
MODEL = "Qwen/Qwen3-0.6B"
MTP_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
# Need to enforce eager for MRV2 while we sort out cudagraph issues.
ENFORCE_EAGER = os.getenv("ENFORCE_EAGER", "0") == "1"
first_prompt = (
"The following numbers of the sequence "
+ ", ".join(str(i) for i in range(10))
+ " are:"
)
example_prompts = [first_prompt, "In one word, the capital of France is "] + [
f"Tell me about the number {i}: " for i in range(32)
]
default_params = dict(
temperature=0.0, # greedy
max_tokens=30,
min_tokens=28,
)
@single_gpu_only
def test_without_spec_decoding(
sample_json_schema,
monkeypatch: pytest.MonkeyPatch,
):
"""Test consistency of combos of async scheduling, preemption,
uni/multiproc executor, prefill chunking."""
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params: list[dict[str, Any]] = [
dict(),
# dict(min_tokens=20),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
),
dict(
structured_outputs=struct_outputs,
frequency_penalty=-1.0,
),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(True, "mp", False, None, True),
(False, "mp", True, None, False),
(False, "uni", True, None, False),
(True, "mp", True, None, False),
(True, "uni", True, None, False),
(False, "mp", True, None, True),
(True, "mp", True, None, True),
(True, "uni", True, None, True),
]
if current_platform.is_rocm():
# On ROCm, Only test with structured_outputs (deterministic)
# and skip chunk_prefill (more variable).
test_configs = [
cfg
for cfg in test_configs
if not cfg[4] # skip chunk_prefill=True
]
test_sampling_params = [
p for p in test_sampling_params if p.get("structured_outputs") is not None
]
run_tests(monkeypatch, MODEL, test_configs, test_sampling_params)
@single_gpu_only
@large_gpu_mark(min_gb=16)
def test_with_eagle3_spec_decoding(sample_json_schema, monkeypatch: pytest.MonkeyPatch):
"""Test consistency and acceptance rates with some different combos of
preemption, executor, async scheduling, prefill chunking,
spec decoding model length.
"""
spec_config = {
"method": "eagle3",
"num_speculative_tokens": 2,
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
}
# Set small draft model len to force doesn't-fit-in-drafter case.
spec_config_short = spec_config | {"max_model_len": 50}
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params = [
dict(),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, spec_config, False),
(True, "mp", False, spec_config, True),
(True, "uni", False, spec_config_short, True),
(False, "mp", True, spec_config, False),
(True, "mp", True, spec_config, False),
(False, "mp", True, spec_config_short, True),
(True, "uni", True, spec_config, False),
(True, "uni", True, spec_config_short, False),
(True, "mp", True, spec_config, True),
(True, "uni", True, spec_config_short, True),
]
run_tests(monkeypatch, MTP_MODEL, test_configs, test_sampling_params)
@pytest.mark.flaky(reruns=2, only_on=current_platform.is_rocm())
@pytest.mark.skipif(
current_platform.is_xpu(),
reason=("XPU matmul/attention kernels are not batch-invariant"),
)
def test_with_ngram_gpu_spec_decoding(monkeypatch: pytest.MonkeyPatch):
"""Test ngram_gpu speculative decoding with different configurations.
This test specifically validates ngram_gpu behavior with various:
- Number of speculative tokens (2-6)
- Prompt lookup window sizes (min/max)
- Async scheduling enabled (as in production)
- Different executors and chunking settings
"""
# Variant with larger speculation window
ngram_gpu_config = {
"method": "ngram_gpu",
"num_speculative_tokens": 3,
"prompt_lookup_max": 3,
"prompt_lookup_min": 2,
}
# Test configurations covering various scenarios
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, ngram_gpu_config, False),
(True, "mp", False, ngram_gpu_config, True),
(False, "mp", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, False),
(True, "uni", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, True),
]
# Use MODEL (Qwen) for ngram_gpu tests as it's lighter weight
# and ngram_gpu doesn't require a specific draft model
run_tests(monkeypatch, MODEL, test_configs, [{}])
@dynamo_config.patch(cache_size_limit=16)
def run_tests(
monkeypatch: pytest.MonkeyPatch,
model: str,
test_configs: list[tuple],
test_sampling_params: list[dict[str, Any]],
):
"""Test consistency of combos of async scheduling, preemption,
uni/multiproc executor with spec decoding."""
# Flex attention supports float32.
attention_config = {"backend": "FLEX_ATTENTION"}
with monkeypatch.context() as m:
# lock matmul precision to full FP32 (IEEE)
m.setenv("VLLM_FLOAT32_MATMUL_PRECISION", "highest")
outputs: list[tuple[str, list, list]] = []
for n, (
test_preemption,
executor,
async_scheduling,
spec_config,
test_prefill_chunking,
) in enumerate(test_configs, 1):
test_str = f"{n}/{len(test_configs)}"
test_results = run_test(
model,
test_str,
test_sampling_params,
test_preemption,
executor,
async_scheduling,
spec_config,
test_prefill_chunking=test_prefill_chunking,
attention_config=attention_config,
)
outputs.append(test_results)
baseline_config, baseline_tests, _ = outputs[0]
_, _, baseline_acceptances = next(
(o for o in outputs if o[2] is not None), (None, None, None)
)
print(f"BASELINE: config=[{baseline_config}], accept_rates={baseline_acceptances}")
failure = None
for test_config, test_outputs, test_acceptance_rates in outputs[1:]:
for (base_outs, base_logprobs), base_acceptance_rate, (
test_outs,
test_logprobs,
), test_acceptance_rate, params in zip(
baseline_tests,
baseline_acceptances or repeat(None),
test_outputs,
test_acceptance_rates or repeat(None),
test_sampling_params,
):
reason = None
try:
check_outputs_equal(
outputs_0_lst=base_outs,
outputs_1_lst=test_outs,
name_0=f"baseline=[{baseline_config}], params={params}",
name_1=f"config=[{test_config}], params={params}",
)
except AssertionError as e:
reason = "outputs ", e
if reason is None:
try:
assert _all_logprobs_match(base_logprobs, test_logprobs)
except AssertionError as e:
reason = "logprobs", e
if reason is None:
try:
if (
base_acceptance_rate is not None
and test_acceptance_rate is not None
):
if "spec_mml=None" in test_config:
# Preemption causes more variance in acceptance rates
if (
current_platform.is_rocm()
and "preemption=True" in test_config
):
tolerance = 0.10
else:
tolerance = 0.05
assert (
test_acceptance_rate > base_acceptance_rate
or test_acceptance_rate
== pytest.approx(base_acceptance_rate, rel=tolerance)
)
else:
# Currently the reported acceptance rate is expected to be
# lower when we sometimes skip drafting altogether.
assert test_acceptance_rate > 0.1
except AssertionError as e:
reason = "accept ", e
if reason is None:
print(
f"\033[32mPASSED\033[0m: "
f"config=[{test_config}], params={params}"
f" accept_rate={test_acceptance_rate}"
)
else:
reason_str, _ = reason
print(
f"\033[31mFAILED\033[0m({reason_str}): "
f"config=[{test_config}], params={params}"
f" accept_rate={test_acceptance_rate}"
)
if failure is None:
_, failure = reason
if failure is not None:
raise failure
def run_test(
model: str,
test_str: str,
sampling_param_tests: list[dict[str, Any]],
test_preemption: bool,
executor: str,
async_scheduling: bool,
spec_config: dict[str, Any] | None,
test_prefill_chunking: bool,
attention_config: dict[str, Any] | None = None,
):
spec_decoding = spec_config is not None
cache_arg: dict[str, Any] = (
# Force preemptions: with 33 blocks (one is the reserved null block)
# the cache holds at most a single max-length request, so the ~34
# concurrent prompts contend and trigger preemption. (Prompts here are
# << max_model_len, so dropping max_model_len from 4096 to 512 doesn't
# change generation behavior.)
dict(num_gpu_blocks_override=33, max_model_len=512)
if test_preemption
else dict(gpu_memory_utilization=0.9, max_model_len=4096)
)
spec_mml = (spec_config or {}).get("max_model_len")
spec_method = (spec_config or {}).get("method", "none")
test_config = (
f"executor={executor}, preemption={test_preemption}, "
f"async_sched={async_scheduling}, "
f"chunk_prefill={test_prefill_chunking}, "
f"spec_decoding={spec_decoding}, spec_method={spec_method}, spec_mml={spec_mml}"
)
print("-" * 80)
print(f"---- TESTING {test_str}: {test_config}")
print("-" * 80)
with VllmRunner(
model,
enable_chunked_prefill=test_prefill_chunking,
# Force prefill chunking
max_num_batched_tokens=48 if test_prefill_chunking else None,
enforce_eager=ENFORCE_EAGER,
async_scheduling=async_scheduling,
distributed_executor_backend=executor,
dtype="float32",
speculative_config=spec_config,
disable_log_stats=False,
attention_config=attention_config,
enable_prefix_caching=False if current_platform.is_rocm() else None,
**cache_arg,
) as vllm_model:
results = []
acceptance_rates: list[float] | None = [] if spec_decoding else None
for override_params in sampling_param_tests:
metrics_before = vllm_model.llm.get_metrics()
print(f"----------- RUNNING PARAMS: {override_params}")
results.append(
vllm_model.generate(
example_prompts,
sampling_params=SamplingParams(**default_params, **override_params),
return_logprobs=True,
)
)
metrics_after = vllm_model.llm.get_metrics()
if acceptance_rates is not None:
acceptance_rate = _get_acceptance_rate(metrics_before, metrics_after)
acceptance_rates.append(acceptance_rate)
print(f"ACCEPTANCE RATE {acceptance_rate}")
if test_preemption:
preemptions = _get_count(
metrics_before, metrics_after, "vllm:num_preemptions"
)
assert preemptions > 0, "preemption test had no preemptions"
if len(results) > 1:
# First check that the different parameter configs
# actually result in different output.
for (other_test_outs, other_test_logprobs), params in zip(
results[1:], sampling_param_tests[1:]
):
with pytest.raises(AssertionError):
check_outputs_equal(
outputs_0_lst=results[0][0],
outputs_1_lst=other_test_outs,
name_0=f"baseline params={params}",
name_1=f"other params={params}",
)
assert _all_logprobs_match(results[0][1], other_test_logprobs)
return test_config, results, acceptance_rates
def _all_logprobs_match(req_a, req_b) -> bool:
return (
req_a == req_b
or len(req_a) == len(req_b)
and all(
len(seq_a) == len(seq_b)
and all(_logprobs_match(a, b) for a, b in zip(seq_a, seq_b))
for seq_a, seq_b in zip(req_a, req_b)
)
)
def _logprobs_match(
lps_a: dict[int, Logprob] | None,
lps_b: dict[int, Logprob] | None,
) -> bool:
if lps_a is None or lps_b is None:
return lps_a is lps_b
rel_tol, abs_tol = 1e-3, 1e-6
return (
len(lps_a) == len(lps_b)
and lps_a.keys() == lps_b.keys()
and all(
a.decoded_token == b.decoded_token
and a.rank == pytest.approx(b.rank, rel=0.005)
and a.logprob == pytest.approx(b.logprob, rel=rel_tol, abs=abs_tol)
for a, b in ((lps_a[x], lps_b[x]) for x in lps_a)
)
)
def _get_acceptance_rate(before: list[Metric], after: list[Metric]) -> float:
draft = _get_count(before, after, "vllm:spec_decode_num_draft_tokens")
accept = _get_count(before, after, "vllm:spec_decode_num_accepted_tokens")
return accept / draft if draft > 0 else 0.0
def _get_count(before: list[Metric], after: list[Metric], name: str) -> int:
before_val = next(m.value for m in before if m.name == name)
after_val = next(m.value for m in after if m.name == name)
return after_val - before_val
@@ -1,632 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Accuracy with automatic attention selection and the model's normal dtype.
Complements the strict Flex/FP32 invariance checks in test_async_scheduling.py.
"""
import os
from dataclasses import replace
from typing import Any
import pytest
import torch
import vllm.envs as envs
from tests.conftest import HfRunner, VllmRunner
from tests.utils import (
large_gpu_mark,
single_gpu_only,
)
from tests.v1.e2e.general.accuracy_utils import (
AccuracyTolerance,
check_accuracy_budget,
check_first_divergence,
check_greedy_token,
check_logprobs,
check_request_accuracy,
check_stopping,
)
from vllm import SamplingParams
from vllm.logprobs import Logprob
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.platforms import current_platform
from vllm.sampling_params import StructuredOutputsParams
from vllm.utils.torch_utils import set_default_torch_num_threads
from vllm.v1.metrics.reader import Metric
MODEL = "Qwen/Qwen3-0.6B"
EAGLE3_TARGET_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
# Need to enforce eager for MRV2 while we sort out cudagraph issues.
ENFORCE_EAGER = os.getenv("ENFORCE_EAGER", "0") == "1"
first_prompt = (
"The following numbers of the sequence "
+ ", ".join(str(i) for i in range(10))
+ " are:"
)
example_prompts = [first_prompt, "In one word, the capital of France is "] + [
f"Tell me about the number {i}: " for i in range(32)
]
default_params = dict(
temperature=0.0, # greedy
max_tokens=30,
min_tokens=28,
)
@single_gpu_only
def test_without_spec_decoding(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
sample_json_schema,
):
"""Check target-model accuracy across scheduling and executor configurations."""
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params: list[dict[str, Any]] = [
dict(),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(bad_words=["the", " the"], logprobs=2),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
),
dict(
structured_outputs=struct_outputs,
frequency_penalty=-1.0,
),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(True, "mp", False, None, True),
(False, "mp", True, None, False),
(False, "uni", True, None, False),
(True, "mp", True, None, False),
(True, "uni", True, None, False),
(False, "mp", True, None, True),
(True, "mp", True, None, True),
(True, "uni", True, None, True),
]
run_tests(vllm_runner, hf_runner, MODEL, test_configs, test_sampling_params)
@single_gpu_only
@large_gpu_mark(min_gb=16)
def test_with_eagle3_spec_decoding(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
sample_json_schema,
):
"""Check accuracy and acceptance, including drafts that exceed model length."""
spec_config = {
"method": "eagle3",
"num_speculative_tokens": 2,
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
}
# Set small draft model len to force doesn't-fit-in-drafter case.
spec_config_short = spec_config | {"max_model_len": 50}
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params: list[dict[str, Any]] = [
dict(),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(bad_words=["the", " the"], logprobs=2),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, spec_config, False),
(True, "mp", False, spec_config, True),
(True, "uni", False, spec_config_short, True),
(False, "mp", True, spec_config, False),
(True, "mp", True, spec_config, False),
(False, "mp", True, spec_config_short, True),
(True, "uni", True, spec_config, False),
(True, "uni", True, spec_config_short, False),
(True, "mp", True, spec_config, True),
(True, "uni", True, spec_config_short, True),
]
run_tests(
vllm_runner, hf_runner, EAGLE3_TARGET_MODEL, test_configs, test_sampling_params
)
@single_gpu_only
@pytest.mark.skipif(
current_platform.is_xpu(),
reason=("XPU matmul/attention kernels are not batch-invariant"),
)
def test_with_ngram_gpu_spec_decoding(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
monkeypatch: pytest.MonkeyPatch,
):
"""Check ngram accuracy and acceptance across scheduling configurations."""
if current_platform.is_rocm():
# hipBLASLt picks GEMM solutions by batch shape, so sync and async runs
# can flip near-tie greedy tokens and shift ngram acceptance.
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
ngram_gpu_config = {
"method": "ngram_gpu",
"num_speculative_tokens": 3,
"prompt_lookup_max": 3,
"prompt_lookup_min": 2,
}
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, ngram_gpu_config, False),
(True, "mp", False, ngram_gpu_config, True),
(False, "mp", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, False),
(True, "uni", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, True),
]
run_tests(vllm_runner, hf_runner, MODEL, test_configs, [{}, dict(logprobs=2)])
def run_tests(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
model: str,
test_configs: list[tuple],
test_sampling_params: list[dict[str, Any]],
):
"""Compare the shared prefix and independently validate every continuation."""
assert test_configs[0] == (False, "mp", False, None, False), (
"The baseline must use synchronous target-only decoding"
)
outputs = []
for n, config in enumerate(test_configs, 1):
outputs.append(
run_test(
vllm_runner,
model,
f"{n}/{len(test_configs)}",
test_sampling_params,
*config,
)
)
baseline_config, baseline_batches, _ = outputs[0]
# Compare vLLM's own decisions at the first divergence, where histories
# still match. HF then scores each continuation, including after divergence.
# Neither engine forces an attention backend, dtype, or matmul precision.
# Qwen/Llama BF16 controls and Qwen holdouts measured max score error <0.38,
# per-stream request mean <0.073, max greedy gap 0.125, and request sum 0.25.
# Per-request budgets also reject systematic errors below the scalar bounds.
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
# These short CPU reductions cost more to distribute across a thread pool.
with set_default_torch_num_threads(1), hf_runner(model) as hf:
hf.model.eval()
for config, batches, _ in outputs:
assert len(batches) == len(test_sampling_params)
for baseline_batch, batch, overrides in zip(
baseline_batches, batches, test_sampling_params, strict=True
):
assert len(batch) == len(example_prompts), config
params = SamplingParams(**default_params, **overrides)
for i, (baseline, request, prompt) in enumerate(
zip(baseline_batch, batch, example_prompts, strict=True)
):
assert request.prompt_token_ids == hf.tokenizer.encode(prompt)
context = f"config=[{config}], params={overrides}, request={i}"
if params.logprobs is not None:
check_first_divergence(
baseline,
request,
params,
tolerance,
f"baseline=[{baseline_config}], {context}",
)
check_request_accuracy(
hf,
request,
params,
tolerance,
context,
)
print(f"ACCURACY PASSED: config=[{config}], params={overrides}")
baseline_acceptances = next((o[2] for o in outputs if o[2] is not None), None)
if baseline_acceptances is not None:
for settings, (config, _, acceptances) in zip(
test_configs, outputs, strict=True
):
if acceptances is None:
continue
test_preemption, _, _, spec_config, _ = settings
assert spec_config is not None
for baseline, actual, params in zip(
baseline_acceptances, acceptances, test_sampling_params, strict=True
):
context = f"config=[{config}], params={params}"
if spec_config.get("max_model_len") is None:
# Keep the original acceptance-quality floor per batch.
# Preemption recomputes requests and loses n-gram drafts,
# so allow a larger drop there.
relative_drop = 0.10 if test_preemption else 0.05
assert actual >= baseline * (1 - relative_drop), (
f"{context}: acceptance={actual}, baseline={baseline}"
)
else:
assert actual > 0.1, f"{context}: acceptance={actual}"
def run_test(
vllm_runner: type[VllmRunner],
model: str,
test_str: str,
sampling_param_tests: list[dict[str, Any]],
test_preemption: bool,
executor: str,
async_scheduling: bool,
spec_config: dict[str, Any] | None,
test_prefill_chunking: bool,
):
spec_decoding = spec_config is not None
spec_method = (spec_config or {}).get("method", "none")
# Chunked ngram decoding admits fewer concurrent requests under the
# 48-token budget. Its original 33-block cache did not preempt on ROCm.
# A 17-block cache forces contention while every original request fits
# comfortably within 256 tokens (the longest prompt plus output is 67).
cache_blocks = 17 if test_prefill_chunking and spec_method == "ngram_gpu" else 33
cache_arg: dict[str, Any] = (
dict(
num_gpu_blocks_override=cache_blocks,
max_model_len=(cache_blocks - 1) * 16,
)
if test_preemption
else dict(gpu_memory_utilization=0.9, max_model_len=4096)
)
spec_mml = (spec_config or {}).get("max_model_len")
test_config = (
f"executor={executor}, preemption={test_preemption}, "
f"async_sched={async_scheduling}, "
f"chunk_prefill={test_prefill_chunking}, "
f"spec_decoding={spec_decoding}, spec_method={spec_method}, spec_mml={spec_mml}"
)
print("-" * 80)
print(f"---- TESTING {test_str}: {test_config}")
print("-" * 80)
with vllm_runner(
model,
enable_chunked_prefill=test_prefill_chunking,
# Force prefill chunking
max_num_batched_tokens=48 if test_prefill_chunking else None,
enforce_eager=ENFORCE_EAGER,
async_scheduling=async_scheduling,
distributed_executor_backend=executor,
speculative_config=spec_config,
disable_log_stats=False,
enable_prefix_caching=False if current_platform.is_rocm() else None,
**cache_arg,
) as vllm_model:
results = []
acceptance_rates: list[float] | None = [] if spec_decoding else None
for override_params in sampling_param_tests:
metrics_before = vllm_model.llm.get_metrics()
print(f"----------- RUNNING PARAMS: {override_params}")
results.append(
vllm_model.llm.generate(
vllm_model.get_inputs(example_prompts),
sampling_params=SamplingParams(**default_params, **override_params),
)
)
metrics_after = vllm_model.llm.get_metrics()
if acceptance_rates is not None:
acceptance_rate = _get_acceptance_rate(metrics_before, metrics_after)
acceptance_rates.append(acceptance_rate)
print(f"ACCEPTANCE RATE {acceptance_rate}")
if test_preemption:
preemptions = _get_count(
metrics_before, metrics_after, "vllm:num_preemptions"
)
assert preemptions > 0, "preemption test had no preemptions"
# Preserve the original parameter-effect checks across repeated batches.
if len(results) > 1:
baseline = _result_signature(results[0])
for outputs, params in zip(results[1:], sampling_param_tests[1:], strict=True):
assert _result_signature(outputs) != baseline, (
f"{test_config}: sampling parameters had no observable effect: {params}"
)
# The old ROCm filter used schema-only as its first parameter set.
# Retain those comparisons after restoring the ordinary cases too.
schema_batches = [
batch
for batch, params in zip(results, sampling_param_tests, strict=True)
if params.get("structured_outputs") is not None
]
for batch in schema_batches[1:]:
assert _result_signature(batch) != _result_signature(schema_batches[0]), (
f"{test_config}: structured sampling parameters had no effect"
)
return test_config, results, acceptance_rates
def _result_signature(requests):
return [
(
list(request.outputs[0].token_ids),
request.outputs[0].text,
request.prompt_logprobs,
request.outputs[0].logprobs,
)
for request in requests
]
def _get_acceptance_rate(before: list[Metric], after: list[Metric]) -> float:
draft = _get_count(before, after, "vllm:spec_decode_num_draft_tokens")
accept = _get_count(before, after, "vllm:spec_decode_num_accepted_tokens")
assert draft > 0, "speculative test did not draft any tokens"
assert 0 <= accept <= draft, f"invalid acceptance counters: {accept=}, {draft=}"
return accept / draft
def _get_count(before: list[Metric], after: list[Metric], name: str) -> int:
before_val = next(m.value for m in before if m.name == name)
after_val = next(m.value for m in after if m.name == name)
return after_val - before_val
@pytest.mark.parametrize(
"corruption", ["score", "rank", "top_k", "missing", "nan", "positive", "order"]
)
def test_accuracy_checks_reject_incorrect_logprobs(corruption):
second = 2.875 if corruption == "order" else 1.0
reference = torch.tensor([3.0, second, -2.0, -5.0]).log_softmax(-1)
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
scores = {
0: Logprob(logprob=float(reference[0]), rank=1, decoded_token="a"),
1: Logprob(logprob=float(reference[1]), rank=2, decoded_token="b"),
}
check_logprobs(scores, reference, 0, 2, tolerance, "control")
if corruption == "score":
scores[0] = replace(scores[0], logprob=scores[0].logprob - 1.0)
elif corruption == "rank":
scores[1] = replace(scores[1], rank=1)
elif corruption == "top_k":
del scores[1]
scores[3] = Logprob(logprob=float(reference[3]), rank=2, decoded_token="d")
elif corruption == "missing":
del scores[0]
elif corruption == "positive":
scores[0] = replace(scores[0], logprob=0.1)
elif corruption == "order":
scores[0] = replace(scores[0], rank=2)
scores[1] = replace(scores[1], rank=1)
else:
scores[0] = replace(scores[0], logprob=float("nan"))
with pytest.raises(AssertionError):
check_logprobs(scores, reference, 0, 2, tolerance, corruption)
def test_accuracy_checks_distinguish_ties_from_wrong_tokens():
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
logits = torch.tensor([3.0, 2.875, -2.0, -torch.inf])
check_greedy_token(logits, 0, tolerance, "best")
check_greedy_token(logits, 1, tolerance, "near tie")
for token in (2, 3):
with pytest.raises(AssertionError):
check_greedy_token(logits, token, tolerance, "incorrect token")
# top-k may omit a sampled token tied at its boundary. The sampled rank
# can duplicate a sequential top-k rank without corrupting the result.
reference = torch.zeros(4).log_softmax(-1)
scores = {
token: Logprob(logprob=float(reference[token]), rank=rank)
for token, rank in [(3, 1), (0, 1), (1, 2)]
}
check_logprobs(scores, reference, 3, 2, tolerance, "tied top-k")
# A grammar with one allowed token still returns the requested top-k,
# including masked entries whose score is exactly negative infinity.
reference = torch.tensor([0.0, -torch.inf, -torch.inf])
scores = {0: Logprob(0.0, 1), 1: Logprob(-float("inf"), 2)}
check_logprobs(scores, reference, 0, 2, tolerance, "masked top-k")
def test_accuracy_checks_reject_incorrect_stopping():
params = SamplingParams(max_tokens=3)
stop_ids = {2, 3}
for tokens, reason, stop_reason in [
([0, 1, 2], "stop", None),
([0, 1, 3], "stop", 3),
([0, 1, 0], "length", None),
]:
check_stopping(
tokens,
reason,
stop_ids,
params,
"valid stopping at length cap",
eos_token_id=2,
stop_reason=stop_reason,
)
for tokens, reason, stop_reason in [
([0, 2, 1], "length", None),
([0, 1, 2], "length", None),
([0, 1, 2], "stop", 2),
([0, 1, 3], "stop", None),
([0, 1, 3], "stop", 2),
([0, 1, 0], "length", 3),
]:
with pytest.raises(AssertionError):
check_stopping(
tokens,
reason,
stop_ids,
params,
"incorrect stopping",
eos_token_id=2,
stop_reason=stop_reason,
)
def test_accuracy_checks_reject_systematic_sub_bound_errors():
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
reference = torch.tensor([3.0, 2.75, -2.0]).log_softmax(-1)
scores = {i: Logprob(float(reference[i]) - 0.4, i + 1) for i in (0, 1)}
# Each corrupted score fits the scalar bound, but the bias must not pass.
errors = check_logprobs(scores, reference, 0, 2, tolerance, "biased scores")
with pytest.raises(AssertionError, match="mean logprob error"):
check_accuracy_budget([errors], [], tolerance, "biased scores")
gap = check_greedy_token(reference, 1, tolerance, "one ambiguous choice")
with pytest.raises(AssertionError, match="total greedy logit gap"):
check_accuracy_budget([], [gap] * 30, tolerance, "systematically worse choices")
check_accuracy_budget(
[torch.tensor([0.03, 0.07])], [0.125, 0.125], tolerance, "control variation"
)
def _divergence_request(
tokens: list[int], scores: dict[int, float], position: int = 0
) -> RequestOutput:
logprobs: list[dict[int, Logprob]] = [{} for _ in tokens]
logprobs[position] = {
token: Logprob(score, rank)
for rank, (token, score) in enumerate(
sorted(scores.items(), key=lambda item: item[1], reverse=True), 1
)
}
return RequestOutput(
request_id="test",
prompt=None,
prompt_token_ids=[0, 0, 0],
prompt_logprobs=None,
outputs=[
CompletionOutput(
index=0,
text="",
token_ids=tokens,
cumulative_logprob=None,
logprobs=logprobs,
finish_reason="length",
)
],
finished=True,
)
@pytest.mark.parametrize(
"base_scores,actual_scores,error",
[
({0: -0.8, 1: -0.9}, {0: -0.9, 1: -0.8}, None),
({0: -0.8, 1: -0.8}, {0: -0.8, 1: -0.8}, None),
({0: -0.8, 1: -0.9}, {0: -0.8, 1: -0.9}, "actual.*below"),
({0: -0.9, 1: -0.8}, {0: -0.9, 1: -0.8}, "baseline.*below"),
({0: -0.8, 1: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*near-tie"),
({0: -0.8, 1: -0.9}, {0: -1.1, 1: -0.8}, "actual.*near-tie"),
({0: -0.8, 2: -0.9}, {0: -0.9, 1: -0.8}, None),
({0: -0.8, 2: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*lower bound"),
({0: -0.8, 1: -0.9}, {1: -0.8, 2: -1.1}, "actual.*lower bound"),
],
ids=[
"near-tie-rank-reversal",
"exact-tie",
"wrong-near-tie-actual-choice",
"wrong-near-tie-baseline-choice",
"decisive-baseline",
"decisive-actual",
"missing-candidate-inconclusive",
"missing-candidate-decisive-baseline",
"missing-candidate-decisive-actual",
],
)
def test_first_divergence_checks_engine_preferences(base_scores, actual_scores, error):
baseline = _divergence_request([0], base_scores)
actual = _divergence_request([1], actual_scores)
args = (
baseline,
actual,
SamplingParams(temperature=0, logprobs=2),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
"paired engines",
)
if error is None:
check_first_divergence(*args)
else:
with pytest.raises(AssertionError, match=error):
check_first_divergence(*args)
@pytest.mark.parametrize("missing_alternative", [False, True])
def test_first_divergence_uses_generated_penalty_history(missing_alternative):
# Raw ordering favors token 1; one generated 0 reverses the penalized order.
# The prompt contains three more 0s which must not contribute to penalties.
base_scores = {0: -1.5, 1: -0.6}
if missing_alternative:
# The selected 0 is outside top-2. Use the top-k boundary (-0.6),
# excluding the additional sampled token (-1.5), for the missing 1.
base_scores = {0: -1.5, 2: -0.5, 3: -0.6}
baseline = _divergence_request([0, 0, 2], base_scores, position=1)
actual = _divergence_request([0, 1, 3, 4], {0: -1.6, 1: -0.5}, position=1)
check_first_divergence(
baseline,
actual,
SamplingParams(temperature=0, logprobs=2, frequency_penalty=-1),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
"different later histories are validated separately",
)
@pytest.mark.parametrize("mismatch", ["length", "finish_reason", "prompt"])
def test_first_divergence_rejects_mismatches_without_a_token_change(mismatch):
baseline = _divergence_request([0, 1], {})
actual = _divergence_request([0, 1], {})
if mismatch == "length":
actual.outputs[0].token_ids = [0]
elif mismatch == "finish_reason":
actual.outputs[0].finish_reason = "stop"
else:
actual.prompt_token_ids = [1]
with pytest.raises(AssertionError):
check_first_divergence(
baseline,
actual,
SamplingParams(temperature=0, logprobs=2),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
mismatch,
)
@@ -1,94 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""End-to-end checks that ``backend_per_kind`` selects the requested attention
backend for each KV-cache group at runtime.
Uses ``google/gemma-3-1b-it``, which interleaves full-attention and
sliding-window layers, so the model produces separate ``full_attention`` and
``sliding_window`` KV-cache groups.
"""
import pytest
from vllm import LLM
from vllm.config.attention import AttentionConfig
from vllm.platforms import current_platform
MODEL = "google/gemma-3-1b-it"
def _collect_group_backends(worker) -> list[tuple[str, str]]:
"""Runs on the worker: returns (spec_kind, backend_name) per attn group."""
from vllm.v1.kv_cache_interface import get_kv_cache_spec_kind
out: list[tuple[str, str]] = []
for kv_group in worker.model_runner.attn_groups:
for attn_group in kv_group:
kind = get_kv_cache_spec_kind(attn_group.kv_cache_spec)
out.append((kind.value, attn_group.backend.get_name()))
return out
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="backend names are CUDA-specific"
)
@pytest.mark.parametrize(
"backend_per_kind",
[
{"full_attention": "FLASH_ATTN", "sliding_window": "TRITON_ATTN"},
# Swapped, to prove the mapping is causal rather than the default.
{"full_attention": "TRITON_ATTN", "sliding_window": "FLASH_ATTN"},
],
)
def test_backend_per_kind_splits_groups(backend_per_kind, monkeypatch):
# collective_rpc ships the callable to the EngineCore subprocess; the
# secure msgpack encoder can't serialize functions, so opt into the
# pickle fallback (same pattern as test_pooling_chunked_prefill).
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
llm = LLM(
model=MODEL,
attention_config=AttentionConfig(backend_per_kind=backend_per_kind),
enforce_eager=True,
max_model_len=2048,
gpu_memory_utilization=0.4,
)
group_backends = llm.llm_engine.collective_rpc(_collect_group_backends)[0]
kinds = {kind for kind, _ in group_backends}
# gemma3 must actually split into both kinds for this test to be meaningful.
assert "full_attention" in kinds
assert "sliding_window" in kinds
for kind, backend_name in group_backends:
if kind in backend_per_kind:
assert backend_name == backend_per_kind[kind], (
f"{kind} group used {backend_name}, expected {backend_per_kind[kind]}"
)
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="backend names are CUDA-specific"
)
def test_backend_per_kind_overrides_global_backend(monkeypatch):
"""A per-kind entry wins over the global ``backend`` for its kind; other
kinds fall back to the global backend."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
llm = LLM(
model=MODEL,
attention_config=AttentionConfig(
backend="FLASH_ATTN",
backend_per_kind={"sliding_window": "TRITON_ATTN"},
),
enforce_eager=True,
max_model_len=2048,
gpu_memory_utilization=0.4,
)
group_backends = llm.llm_engine.collective_rpc(_collect_group_backends)[0]
for kind, backend_name in group_backends:
if kind == "sliding_window":
assert backend_name == "TRITON_ATTN"
elif kind == "full_attention":
assert backend_name == "FLASH_ATTN"
@@ -1,130 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import pytest
from vllm import LLM, SamplingParams
from vllm.platforms import current_platform
from ....utils import check_answers, prep_prompts
@dataclass
class TestConfig:
sliding_window: int
ln_range: tuple[int, int]
model_config = {
"bigcode/starcoder2-3b": TestConfig(4096, (800, 1100)),
"google/gemma-3-1b-it": TestConfig(4096, (400, 800)),
}
@pytest.mark.parametrize(
"model",
[
"bigcode/starcoder2-3b", # sliding window only
"google/gemma-3-1b-it", # sliding window + full attention
],
)
@pytest.mark.parametrize("batch_size", [5])
@pytest.mark.parametrize("seed", [1])
@pytest.mark.parametrize("disable_hybrid_kv_cache_manager", [True, False])
def test_sliding_window_retrieval(
model, batch_size, seed, disable_hybrid_kv_cache_manager, vllm_runner
):
"""The test does a bunch of assignments "x1 = 10\nx2 = 33\n..." and then
asks for value of one of them (which is outside the sliding window).
If we tell it upfront which we are going to be looking for, then
it answers correctly (mostly).
"""
# NOTE: For ROCm, we have to enforce eager mode to use custom kernel
# implementation of GELU with tanh approximation, as PyTorch's native
# implementation is currently unstable with torch.compile and produces garbage.
enforce_eager = current_platform.is_rocm()
test_config = model_config[model]
with vllm_runner(
model,
max_model_len=None,
enable_chunked_prefill=None,
disable_hybrid_kv_cache_manager=disable_hybrid_kv_cache_manager,
enforce_eager=enforce_eager,
) as runner:
llm = runner.get_llm()
sampling_params = SamplingParams(temperature=0.0, max_tokens=100)
prompts, answer, indices = prep_prompts(
batch_size, ln_range=test_config.ln_range
)
check_length(prompts, llm, test_config.sliding_window)
# Fresh generation
responses = llm.generate(prompts, sampling_params)
check_answers(
indices,
answer,
[response.outputs[0].text for response in responses],
accept_rate=1.0,
)
# Re-generate with the same prompts to test prefix caching
responses = llm.generate(prompts, sampling_params)
check_answers(
indices,
answer,
[response.outputs[0].text for response in responses],
accept_rate=1.0,
)
@pytest.mark.parametrize("model", ["google/gemma-3-1b-it"])
def test_hybrid_kv_cache_manager_output_equivalence(model, vllm_runner):
"""Disabling the hybrid KV cache manager must not change what the model
computes: it promotes the sliding-window layers to full-attention *storage*
only, so the global layers must keep attending globally.
Guards against the group's KV cache spec, which then covers windowed and
global layers alike, imposing its window on the global layers too.
"""
prompts, _, _ = prep_prompts(2, ln_range=model_config[model].ln_range)
sampling_params = SamplingParams(temperature=0.0, max_tokens=32)
enforce_eager = current_platform.is_rocm()
outputs = []
for disable_hybrid in (False, True):
with vllm_runner(
model,
max_model_len=None,
enable_chunked_prefill=None,
disable_hybrid_kv_cache_manager=disable_hybrid,
enforce_eager=enforce_eager,
) as runner:
responses = runner.get_llm().generate(prompts, sampling_params)
outputs.append([response.outputs[0].text for response in responses])
assert outputs[0] == outputs[1]
def check_length(prompts: list[str], llm: LLM, sliding_window: int):
"""Check if the prompt length is valid, i.e., longer than the sliding window
size and shorter than the model's max length.
Args:
prompts: list of prompts
llm: LLM object
sliding_window: Sliding window size
"""
tokenizer = llm.get_tokenizer()
max_model_len = llm.llm_engine.model_config.max_model_len
assert any(len(tokenizer.encode(prompt)) > sliding_window for prompt in prompts), (
"Prompt is too short for test"
)
assert all(len(tokenizer.encode(prompt)) <= max_model_len for prompt in prompts), (
"Prompt is too long for test"
)
@@ -1,122 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import random
import pytest
from vllm import LLM, SamplingParams
from vllm.config import CompilationConfig, CompilationMode
from vllm.platforms import current_platform
from ....utils import check_answers, fork_new_process_for_each_test, prep_prompts
# global seed
SEED = 42
@pytest.fixture
def test_prompts():
"""Adapted from tests/v1/e2e/spec_decode/utils.py."""
prompt_types = ["repeat", "sentence"]
# Setting higher num prompts increases the chance of numerics mismatch
# due to matrix multiplication numerics depending on batch dimension
num_prompts = 10
prompts = []
random.seed(0)
random_prompt_type_choices = random.choices(prompt_types, k=num_prompts)
for kind in random_prompt_type_choices:
word_choices = ["test", "temp", "hello", "where"]
word = random.choice(word_choices)
if kind == "repeat":
prompt = f"""please repeat the word '{word}' 10 times."""
elif kind == "sentence":
prompt = f"""please give a ten-word sentence that
uses the word {word} at least once."""
else:
raise ValueError(f"Unknown prompt type: {kind}")
prompts.append(prompt)
return prompts
use_fork_for_test = (
fork_new_process_for_each_test
if not (current_platform.is_rocm() or current_platform.is_xpu())
else lambda x: x
)
@use_fork_for_test
@pytest.mark.parametrize(
"kv_sharing_fast_prefill,use_v2_model_runner",
[
(False, False),
(True, False),
(True, True),
# (False, True) omitted: fast-prefill-off behavior is runner-generic,
# and skipping it saves ~9 min of mostly torch.compile time in CI. The
# no-silent-fallback assertion below is exercised by the V2 cases.
],
)
@pytest.mark.parametrize("enforce_eager", [True, False])
def test_kv_sharing_fast_prefill(
monkeypatch: pytest.MonkeyPatch,
kv_sharing_fast_prefill: bool,
enforce_eager: bool,
use_v2_model_runner: bool,
):
if not enforce_eager and current_platform.is_rocm():
# Relevant context: https://github.com/vllm-project/vllm/pull/29244
pytest.skip(
"ROCm: torch.compile produces incorrect output for gemma-3n's GELU "
"with tanh approximation. Use enforce_eager=True instead."
)
if not enforce_eager and not use_v2_model_runner and current_platform.is_cuda():
pytest.skip(
"cublasCreate fails with CUBLAS_STATUS_ALLOC_FAILED during memory "
"profiling with torch 2.14: "
"https://github.com/pytorch/pytorch/issues/199944"
)
sampling_params = SamplingParams(temperature=0.0, max_tokens=100)
compilation_config = CompilationConfig(
# This allows vLLM compilation backend to handle allocating and
# managing buffers for cudagraph
cudagraph_copy_inputs=True,
mode=CompilationMode.VLLM_COMPILE
if not enforce_eager
else CompilationMode.NONE,
)
batch_size = 10
with monkeypatch.context() as m:
# Make scheduling deterministic for reproducibility
if current_platform.is_rocm():
# Use spawn to prevent cuda re-initialization error
m.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
else:
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
m.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_model_runner else "0")
prompts, answer, indices = prep_prompts(batch_size)
llm = LLM(
model="google/gemma-3n-E2B-it",
enforce_eager=enforce_eager,
compilation_config=compilation_config,
seed=SEED,
kv_sharing_fast_prefill=kv_sharing_fast_prefill,
attention_backend="TRITON_ATTN",
)
# Guard against a silent fallback to the other model runner.
assert llm.llm_engine.vllm_config.use_v2_model_runner == use_v2_model_runner
responses = llm.generate(prompts, sampling_params)
check_answers(
indices,
answer,
[response.outputs[0].text for response in responses],
accept_rate=1.0,
)
-521
View File
@@ -1,521 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Comprehensive end-to-end tests for `min_tokens` in the V1 engine.
Addresses #21950: verify and add CI coverage.
Covers:
1) Basic functionality
2) Stop strings with `min_tokens` (bug #21987; fix in PR #22014)
3) EOS behavior with `min_tokens` (potential logits-processor bug)
4) Edge cases (min_tokens == max_tokens, min_tokens == 0)
5) Multiple stop conditions
"""
import json
import pytest
from vllm import LLM, SamplingParams
from vllm.exceptions import VLLMValidationError
from vllm.outputs import RequestOutput
from vllm.sampling_params import StructuredOutputsParams
# Test configuration
TEST_MODEL = "facebook/opt-125m" # Small model for fast CI execution
GREEDY = 0.0 # Deterministic generation for consistent testing
class MinTokensTestCase:
"""Data class for min_tokens test scenarios."""
def __init__(
self,
name: str,
min_tokens: int,
max_tokens: int,
stop: str | list[str] | None = None,
expected_min_len: int | None = None,
expected_exact_len: int | None = None,
):
self.name = name
self.min_tokens = min_tokens
self.max_tokens = max_tokens
self.stop = stop
self.expected_min_len = expected_min_len or min_tokens
self.expected_exact_len = expected_exact_len
def __str__(self):
return (
f"{self.name}: min={self.min_tokens}, "
f"max={self.max_tokens}, stop={self.stop}"
)
# Test scenarios covering all critical cases
MIN_TOKENS_TEST_CASES = [
# === BASIC FUNCTIONALITY (should work) ===
MinTokensTestCase(
name="basic_min_tokens_no_stop",
min_tokens=8,
max_tokens=20,
stop=None,
expected_min_len=8,
),
MinTokensTestCase(
name="min_tokens_zero",
min_tokens=0,
max_tokens=10,
stop=None,
expected_min_len=0,
),
MinTokensTestCase(
name="min_equals_max_no_stop",
min_tokens=15,
max_tokens=15,
stop=None,
expected_exact_len=15,
),
# === STOP STRINGS WITH MIN_TOKENS ===
# These tests expose the detokenizer bug where stop strings
# bypass min_tokens
# Using mathematically guaranteed approach with wide stop nets
pytest.param(
MinTokensTestCase(
name="min_tokens_with_comprehensive_stops",
min_tokens=5,
max_tokens=20,
stop=[
"a",
"e",
"i",
"o",
"u",
"t",
"n",
"s",
"r",
"l",
" ",
],
expected_min_len=5,
),
marks=pytest.mark.xfail(
reason=(
"Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"
),
strict=False,
),
id="min_tokens_with_comprehensive_stops",
),
pytest.param(
MinTokensTestCase(
name="min_tokens_with_simple_char_stop",
min_tokens=3,
max_tokens=15,
stop=["e", "a", " "],
expected_min_len=3,
),
marks=pytest.mark.xfail(
reason=(
"Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"
),
strict=False,
),
id="min_tokens_with_simple_char_stop",
),
# === EOS TOKEN WITH MIN_TOKENS (potential LogitsProcessor bug) ===
# These test the MinTokensLogitsProcessor handling of EOS tokens
pytest.param(
MinTokensTestCase(
name="min_equals_max_eos_only",
min_tokens=20,
max_tokens=20,
stop=None, # Relies on default EOS token behavior
expected_exact_len=20,
),
marks=pytest.mark.xfail(
reason=("Potential logits-processor bug: EOS tokens may bypass min_tokens"),
strict=False,
),
id="min_equals_max_eos_only",
),
# === EDGE CASES ===
MinTokensTestCase(
name="large_min_tokens",
min_tokens=50,
max_tokens=60,
stop=None,
expected_min_len=50,
),
MinTokensTestCase(
name="min_tokens_with_empty_stop_list",
min_tokens=5,
max_tokens=15,
stop=[], # Empty stop list
expected_min_len=5,
),
]
@pytest.fixture(scope="module")
def llm_v1():
"""Create V1 LLM instance for testing."""
llm = LLM(
model=TEST_MODEL,
tensor_parallel_size=1,
max_model_len=1024, # Small context for fast testing
enforce_eager=True, # Avoid graph compilation overhead
)
return llm
def test_min_tokens_with_terminal_structured_output(llm_v1: LLM):
"""A grammar whose only legal continuation is EOS must stop under
min_tokens instead of sampling outside the grammar."""
params = SamplingParams(
temperature=GREEDY,
min_tokens=20,
max_tokens=40,
structured_outputs=StructuredOutputsParams(
json=json.dumps({"type": "boolean"})
),
)
output = llm_v1.generate("Answer:", params)[0].outputs[0]
eos_token_id = llm_v1.get_tokenizer().eos_token_id
assert output.finish_reason == "stop"
assert isinstance(json.loads(output.text), bool)
assert output.token_ids[-1] == eos_token_id
assert len(output.token_ids) < params.min_tokens
def get_token_count(output: RequestOutput) -> int:
"""Extract token count from LLM output."""
if not output.outputs:
return 0
return len(output.outputs[0].token_ids)
def assert_min_tokens_satisfied(
output: RequestOutput, test_case: MinTokensTestCase
) -> None:
"""Assert that min_tokens requirement is satisfied."""
token_count = get_token_count(output)
stop_reason = output.outputs[0].stop_reason if output.outputs else "no output"
if test_case.expected_exact_len is not None:
# Exact length requirement
assert token_count == test_case.expected_exact_len, (
f"Expected exactly {test_case.expected_exact_len} tokens, "
f"got {token_count} tokens. "
f"Stop reason: {stop_reason}"
)
else:
# Minimum length requirement
assert token_count >= (test_case.expected_min_len or 0), (
f"Expected at least {test_case.expected_min_len} tokens, "
f"got {token_count} tokens. "
f"Stop reason: {stop_reason}"
)
@pytest.mark.parametrize(
"test_case",
MIN_TOKENS_TEST_CASES,
ids=lambda tc: tc.name,
)
def test_min_tokens_comprehensive(llm_v1: LLM, test_case: MinTokensTestCase):
"""Comprehensive test for min_tokens functionality in V1 engine.
This test covers all critical scenarios for min_tokens:
- Basic functionality (should work)
- Stop strings with min_tokens (known bug)
- EOS tokens with min_tokens (potential bug)
- Edge cases
Args:
llm_v1: V1 LLM instance
test_case: Test scenario parameters
"""
# Known failing cases are handled via param-level xfail marks above.
# Create sampling parameters
sampling_params = SamplingParams(
min_tokens=test_case.min_tokens,
max_tokens=test_case.max_tokens,
stop=test_case.stop,
temperature=GREEDY,
include_stop_str_in_output=True, # Include stop strings for debugging
)
# Use simple prompt. Comprehensive stop lists should catch any generation
prompt = "Hello"
# Generate output
outputs = llm_v1.generate([prompt], sampling_params)
assert len(outputs) == 1, "Expected exactly one output"
output = outputs[0]
# Debug information
token_count = get_token_count(output)
generated_text = output.outputs[0].text if output.outputs else ""
stop_reason = output.outputs[0].stop_reason if output.outputs else "unknown"
print(f"\nTest: {test_case.name}")
print(f"Generated {token_count} tokens")
print(f"Stop reason: {stop_reason}")
print(f"Generated text: {repr(generated_text)}")
print(f"Expected min: {test_case.expected_min_len}")
if test_case.expected_exact_len:
print(f"Expected exact: {test_case.expected_exact_len}")
# Validate min_tokens requirement
assert_min_tokens_satisfied(output, test_case)
def test_min_tokens_basic_functionality(llm_v1: LLM):
"""Test basic min_tokens functionality without stop conditions.
This is a baseline test that should always pass and validates
that min_tokens works correctly in the simple case.
"""
sampling_params = SamplingParams(min_tokens=10, max_tokens=20, temperature=GREEDY)
prompt = "Once upon a time"
outputs = llm_v1.generate([prompt], sampling_params)
assert len(outputs) == 1
token_count = get_token_count(outputs[0])
assert token_count >= 10, f"Expected at least 10 tokens, got {token_count}"
assert token_count <= 20, f"Expected at most 20 tokens, got {token_count}"
@pytest.mark.xfail(
reason=("Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"),
strict=False,
)
def test_min_tokens_stop_strings_bug(llm_v1: LLM):
"""Test the specific bug where stop strings bypass min_tokens.
This test specifically reproduces the bug Calvin is fixing in PR #22014.
It should fail until that fix is merged.
Strategy: Use guaranteed stop characters that will appear
in any generated text.
"""
# If the bug is fixed upstream, this test will XPASS
sampling_params = SamplingParams(
min_tokens=15,
max_tokens=50,
# Common letter; likely appears early
stop=["e"],
temperature=GREEDY,
include_stop_str_in_output=True,
)
# Simple prompt that will generate text containing "e"
prompt = "The quick brown fox"
outputs = llm_v1.generate([prompt], sampling_params)
assert len(outputs) == 1
token_count = get_token_count(outputs[0])
generated_text = outputs[0].outputs[0].text if outputs[0].outputs else ""
# Debug info to understand what happened
print(f"Generated text: {repr(generated_text)}")
print(f"Token count: {token_count}")
print(f"Contains 'e': {'e' in generated_text}")
# This assertion should fail due to the bug - if stop string is found early,
# the model should still continue generating until min_tokens is reached
stop_reason = (
outputs[0].outputs[0].stop_reason if outputs[0].outputs else "no output"
)
assert token_count >= 15, (
"Bug confirmed: "
f"{token_count} tokens < min_tokens=15. "
f"Reason: {stop_reason}. "
f"Text: {repr(generated_text)}"
)
@pytest.mark.xfail(
reason=("Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"),
strict=False,
)
def test_min_tokens_stop_strings_guaranteed_early_trigger(llm_v1: LLM):
"""Guaranteed test for stop strings bypassing min_tokens bug.
Strategy: Use very low temperature and multiple common stop strings
to virtually guarantee early detection, combined with long min_tokens
to ensure the bug is exposed regardless of model behavior.
"""
# If the bug is fixed upstream, this test will XPASS
sampling_params = SamplingParams(
min_tokens=50, # Set high min_tokens to ensure bug detection
max_tokens=200,
# Use multiple very common patterns - at least one will appear
stop=["e", "a", "i", "o", "u", " ", "t", "n", "s", "r"],
temperature=GREEDY,
include_stop_str_in_output=True,
)
# Simple prompt that will generate some text
prompt = "The cat"
outputs = llm_v1.generate([prompt], sampling_params)
assert len(outputs) == 1
token_count = get_token_count(outputs[0])
generated_text = outputs[0].outputs[0].text if outputs[0].outputs else ""
stop_reason = outputs[0].outputs[0].stop_reason if outputs[0].outputs else "unknown"
print(f"Generated text: {repr(generated_text)}")
print(f"Token count: {token_count}")
print(f"Stop reason: {stop_reason}")
# With the bug, this will fail because ANY of the common characters
# will trigger early termination before min_tokens=50 is reached
# It's virtually impossible to generate 50 tokens without hitting
# at least one of: e, a, i, o, u, space, t, n, s, r
finish_reason = (
outputs[0].outputs[0].finish_reason if outputs[0].outputs else "unknown"
)
print(f"Finish reason: {finish_reason}")
if finish_reason == "stop":
assert token_count >= 50, (
"Bug confirmed: "
f"{token_count} tokens < min_tokens=50. "
f"Reason: {finish_reason}. "
f"Text: {repr(generated_text)}"
)
@pytest.mark.xfail(
reason=("Potential logits-processor bug: EOS tokens may bypass min_tokens"),
strict=False,
)
def test_min_tokens_eos_behavior(llm_v1: LLM):
"""Verify EOS handling with and without min_tokens.
- Without min_tokens: expect early EOS -> finish_reason == "stop",
stop_reason is None, and generated tokens < max_tokens (25).
- With min_tokens: EOS should be blocked until min_tokens is reached
(finish_reason == "length"); verify that eos_token_id does not appear
in generated token_ids.
"""
# tokenizer + eos id
tokenizer = llm_v1.get_tokenizer()
eos_token_id = tokenizer.eos_token_id
prompt = "Give a file extension."
max_toks = 32
# Case 1: WITHOUT min_tokens
sp_no_min = SamplingParams(
max_tokens=max_toks,
temperature=GREEDY,
)
out_no_min = llm_v1.generate([prompt], sp_no_min)
assert len(out_no_min) == 1
choice_no_min = out_no_min[0].outputs[0]
ids_no_min = choice_no_min.token_ids or []
finish_no_min = choice_no_min.finish_reason
stop_no_min = choice_no_min.stop_reason
print(
"[no-min] tokens=",
len(ids_no_min),
" finish=",
finish_no_min,
" stop_reason=",
stop_no_min,
)
assert finish_no_min == "stop", (
f"Expected finish_reason 'stop' without min_tokens, got {finish_no_min}"
)
assert stop_no_min is None, (
"For EOS-based stop (no user stop strings), stop_reason should be None."
)
assert len(ids_no_min) < max_toks, (
f"Expected early EOS with < {max_toks} tokens, got {len(ids_no_min)}"
)
# Case 2: WITH min_tokens
sp_with_min = SamplingParams(
min_tokens=max_toks,
max_tokens=max_toks,
temperature=GREEDY,
)
out_with_min = llm_v1.generate([prompt], sp_with_min)
assert len(out_with_min) == 1
choice_with_min = out_with_min[0].outputs[0]
ids_with_min = choice_with_min.token_ids or []
finish_with_min = choice_with_min.finish_reason
stop_with_min = choice_with_min.stop_reason
print(
"[with-min] tokens=",
len(ids_with_min),
" finish=",
finish_with_min,
" stop_reason=",
stop_with_min,
)
# Exact length reached; EOS should have been blocked
assert len(ids_with_min) == max_toks, (
f"Expected exactly {max_toks} tokens with min_tokens; got {len(ids_with_min)}"
)
assert finish_with_min == "length", (
f"Expected finish_reason 'length'; got {finish_with_min}"
)
assert eos_token_id not in ids_with_min, (
"EOS token id should not appear when min_tokens prevents early EOS."
)
def test_min_tokens_validation():
"""Test that SamplingParams correctly validates min_tokens parameters.
This tests the parameter validation logic in SamplingParams.
"""
# Valid cases
SamplingParams(min_tokens=0, max_tokens=10)
SamplingParams(min_tokens=5, max_tokens=10)
SamplingParams(min_tokens=10, max_tokens=10)
# Invalid cases
with pytest.raises(
VLLMValidationError,
match="min_tokens must be greater than or equal to 0",
):
SamplingParams(min_tokens=-1, max_tokens=10)
with pytest.raises(
VLLMValidationError,
match="min_tokens must be less than or equal to max_tokens",
):
SamplingParams(min_tokens=15, max_tokens=10)
if __name__ == "__main__":
"""
Run tests locally for development.
Usage:
cd vllm/
python -m pytest tests/v1/e2e/general/test_min_tokens.py -v
"""
pytest.main([__file__, "-v"])
@@ -1,166 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch.nn as nn
from vllm.platforms import current_platform
prompt = """
Generals gathered in their masses
Just like witches at black masses
Evil minds that plot destruction
Sorcerer of death's construction
In the fields, the bodies burning
As the war machine keeps turning
Death and hatred to mankind
Poisoning their brainwashed minds
Oh, Lord, yeah
Politicians hide themselves away
They only started the war
Why should they go out to fight?
They leave that all to the poor, yeah
Time will tell on their power minds
Making war just for fun
Treating people just like pawns in chess
Wait till their judgment day comes, yeah
Now, in darkness, world stops turning
Ashes where their bodies burning
No more war pigs have the power
Hand of God has struck the hour
Day of Judgment, God is calling
On their knees, the war pigs crawling
Begging mercies for their sins
Satan, laughing, spreads his wings
Oh, Lord, yeah
"""
class WrapperPooler(nn.Module):
def __init__(self, pooler):
super().__init__()
self.pooler = pooler
self.chunks = []
def get_pooling_updates(self, task):
return self.pooler.get_pooling_updates(task)
def forward(
self,
hidden_states,
pooling_metadata,
):
self.chunks.append(hidden_states.shape[0])
return self.pooler(hidden_states, pooling_metadata)
def inject_pooler(self):
model = self.get_model()
wrapper = WrapperPooler(model.pooler)
model.pooler = wrapper
def retrieve_chunks(self):
model = self.get_model()
chunks = model.pooler.chunks
model.pooler.chunks = []
return chunks
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available")
def test_pooling_chunked_prefill(vllm_runner, monkeypatch):
"""Test chunked prefill for pooling models with LastPool."""
with monkeypatch.context() as m:
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
model_id = "Qwen/Qwen3-Embedding-0.6B"
chunk_size = 10
# Cap the token budget to force chunked prefill; the
# long_prefill_token_threshold is not applied to a lone request.
with vllm_runner(
model_id,
runner="pooling",
max_num_batched_tokens=chunk_size,
max_num_seqs=1,
tensor_parallel_size=1,
enforce_eager=True,
enable_chunked_prefill=True,
) as llm:
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
tokenizer = llm.get_llm().get_tokenizer()
tokens = tokenizer(prompt)["input_ids"]
prompt_len = len(tokens)
full_chunks, last_chunk = divmod(prompt_len, chunk_size)
expected_chunks = [chunk_size] * full_chunks
if last_chunk:
expected_chunks.append(last_chunk)
llm.embed([prompt])
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
# Check that PoolerWrapper was called and chunks were received
assert len(chunks) > 1
assert chunks == expected_chunks
# Disable chunked prefill
with vllm_runner(
model_id,
runner="pooling",
tensor_parallel_size=1,
enforce_eager=True,
) as llm:
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
llm.embed([prompt])
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
# Check that PoolerWrapper was called and no chunks were received
assert len(chunks) == 1
assert chunks[0] == prompt_len
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available")
def test_pooling_prefix_cache(vllm_runner, monkeypatch):
"""Test chunked prefill for pooling models with LastPool."""
verses = prompt.split("\n\n")
with monkeypatch.context() as m:
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
model_id = "Qwen/Qwen3-Embedding-0.6B"
with vllm_runner(
model_id,
runner="pooling",
enable_prefix_caching=True,
tensor_parallel_size=1,
enforce_eager=True,
) as llm:
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
tokenizer = llm.get_llm().get_tokenizer()
prompt1 = "\n\n".join([verses[0], verses[1]])
prompt2 = "\n\n".join([verses[0], verses[2]])
tokens1 = tokenizer(prompt1)["input_ids"]
tokens2 = tokenizer(prompt2)["input_ids"]
prompt1_len = len(tokens1)
prompt2_len = len(tokens2)
llm.embed([prompt1])
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
assert len(chunks) == 1
assert chunks[0] == prompt1_len
llm.embed([prompt2])
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
assert len(chunks) == 1
assert chunks[0] <= prompt1_len
assert chunks[0] < prompt2_len
vllm_config = llm.get_llm().llm_engine.vllm_config
cache_config = vllm_config.cache_config
print(f"{cache_config=}")
# Prefixes are cached in blocks
assert (prompt2_len - chunks[0]) % cache_config.block_size == 0
@@ -1,118 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm._aiter_ops import is_aiter_found, rocm_aiter_ops
from vllm.config import CompilationConfig, CompilationMode, CUDAGraphMode
from vllm.envs import disable_envs_cache
from vllm.platforms import current_platform
from ....conftest import VllmRunner
from ....utils import (
assert_rocm_custom_allreduce_backend_state_on_worker,
multi_gpu_test,
)
PROMPTS = ["Hello, my name is", "The capital of France is"]
def _run_generation(
vllm_runner: type[VllmRunner],
monkeypatch: pytest.MonkeyPatch,
compilation_config: CompilationConfig,
*,
model: str,
max_tokens: int,
use_aiter_custom_ar: bool,
quick_reduce_quantization: str,
) -> list[tuple[list[int], str]]:
with monkeypatch.context() as m:
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
m.setenv("VLLM_ROCM_USE_AITER", "1")
m.setenv(
"VLLM_ROCM_USE_AITER_CUSTOM_AR",
"1" if use_aiter_custom_ar else "0",
)
m.setenv("VLLM_ROCM_QUICK_REDUCE_QUANTIZATION", quick_reduce_quantization)
disable_envs_cache()
rocm_aiter_ops.refresh_env_variables()
with vllm_runner(
model,
dtype="half",
tensor_parallel_size=2,
compilation_config=compilation_config,
max_model_len=256,
max_num_seqs=len(PROMPTS),
gpu_memory_utilization=0.7,
) as llm:
llm.get_llm().collective_rpc(
assert_rocm_custom_allreduce_backend_state_on_worker,
args=(use_aiter_custom_ar, quick_reduce_quantization),
)
return llm.generate_greedy(PROMPTS, max_tokens)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm-only")
@pytest.mark.skipif(not is_aiter_found(), reason="AITER is not installed")
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"quick_reduce_quantization",
[
pytest.param("FP", id="quick-reduce-on"),
pytest.param("NONE", id="quick-reduce-off"),
],
)
@pytest.mark.parametrize(
"cudagraph_mode",
[
pytest.param(CUDAGraphMode.NONE, id="cudagraph-none"),
pytest.param(CUDAGraphMode.FULL, id="cudagraph-full"),
],
)
@pytest.mark.parametrize(
"model,max_tokens",
[
pytest.param("facebook/opt-125m", 8, id="opt-125m"),
],
)
def test_rocm_aiter_custom_ar_e2e(
vllm_runner: type[VllmRunner],
monkeypatch: pytest.MonkeyPatch,
cudagraph_mode: CUDAGraphMode,
quick_reduce_quantization: str,
model: str,
max_tokens: int,
):
compilation_mode = (
CompilationMode.NONE
if cudagraph_mode == CUDAGraphMode.NONE
else CompilationMode.VLLM_COMPILE
)
compilation_config = CompilationConfig(
mode=compilation_mode,
cudagraph_mode=cudagraph_mode,
)
baseline_generations = _run_generation(
vllm_runner,
monkeypatch,
compilation_config,
model=model,
max_tokens=max_tokens,
use_aiter_custom_ar=False,
quick_reduce_quantization=quick_reduce_quantization,
)
aiter_custom_ar_generations = _run_generation(
vllm_runner,
monkeypatch,
compilation_config,
model=model,
max_tokens=max_tokens,
use_aiter_custom_ar=True,
quick_reduce_quantization=quick_reduce_quantization,
)
assert aiter_custom_ar_generations == baseline_generations
@@ -1,328 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Batch-sharded sampling must be a drop-in for replicated sampling.
The two boots are compared token for token, which is only meaningful because
both schedule the same batches. With the engine in the caller's process every
request is queued before the first step, so the first prefill has the same
shape in both runs. Give the engine its own process and the comparison turns
into a coin toss: prefill starts before the last requests arrive over IPC, so
one boot batches two requests where the other batches one. The batch shape
sets the GEMM reduction order and can make near-ties flip. A real sharding
bug — rows routed to the wrong request, misaligned gathers — produces
many-nats divergence and scrambled top-k sets."""
import pytest
import torch
from tests.utils import multi_gpu_test
from vllm import LLM, SamplingParams
from vllm.distributed import (
cleanup_dist_env_and_memory,
tensor_model_parallel_all_gather,
)
from vllm.logprobs import Logprob, LogprobsOnePosition
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
GPT_OSS_MODEL = "trl-internal-testing/tiny-GptOssForCausalLM"
GPT_OSS_REVISION = "e82685101216af1953707faa42567d232a5e4d45"
# Misrouted rows move logprobs by nats; anything under this is float noise.
LOGPROB_TOL = 0.5
PROMPTS = [
"The capital of France is",
"The three primary colors are",
"Write a haiku about the ocean.",
"1, 1, 2, 3, 5, 8,",
"The chemical symbol for gold is",
"Once upon a time, in a distant kingdom,",
"Python's GIL stands for",
"The fastest land animal is",
]
# Exercise greedy, seeded random, top-k/top-p, penalties, and logprobs.
SAMPLING_PARAMS = [
SamplingParams(temperature=0.0, max_tokens=32, logprobs=5, prompt_logprobs=1),
SamplingParams(temperature=0.8, seed=42, top_p=0.9, max_tokens=32, logprobs=3),
SamplingParams(temperature=0.7, seed=7, top_k=50, min_p=0.05, max_tokens=32),
SamplingParams(
temperature=0.9,
seed=123,
frequency_penalty=0.5,
repetition_penalty=1.2,
max_tokens=32,
logprobs=2,
),
]
def _is_sharded_sampling_active(worker) -> bool:
return worker.model_runner.batch_sharder is not None
def _local_logits_match_full(worker) -> dict[str, bool]:
"""Reassemble rank-local logits and compare with the full path."""
model = worker.model_runner.model
hidden_size = model.config.hidden_size
dtype = model.lm_head.weight.dtype
hidden_states = torch.linspace(
-1,
1,
steps=2 * hidden_size,
device=worker.model_runner.device,
dtype=dtype,
).view(2, hidden_size)
full_logits = model.compute_logits(hidden_states)
local_logits = model.compute_logits_local(hidden_states)
assert local_logits.shape[-1] == model.lm_head.num_embeddings_per_partition
gathered_logits = tensor_model_parallel_all_gather(local_logits)
gathered_logits = gathered_logits[..., : model.config.vocab_size]
has_full_logits = full_logits is not None
return {
"has_full_logits": has_full_logits,
"matches": not has_full_logits or torch.equal(full_logits, gathered_logits),
}
def _sampling_params(num_prompts: int) -> list[SamplingParams]:
return [SAMPLING_PARAMS[i % len(SAMPLING_PARAMS)] for i in range(num_prompts)]
def _generate(
disable_sharding: bool,
model: str,
prompts: list[str],
sampling_params: list[SamplingParams],
revision: str | None,
):
llm = LLM(
model=model,
revision=revision,
tokenizer_revision=revision,
tensor_parallel_size=2,
enable_batch_sharded_sampling=not disable_sharding,
max_model_len=1024,
# Keep capacity at least as large as the TP size. The actual request
# count may be smaller to exercise an empty rank.
max_num_seqs=len(PROMPTS),
enforce_eager=True,
enable_prefix_caching=False,
gpu_memory_utilization=0.7,
# Timing-based kernel selection is the dominant source of cross-boot
# numeric noise; disable it so the comparison bounds stay tight.
kernel_config={"enable_flashinfer_autotune": False},
)
try:
# Guard against a vacuous comparison: verify every worker is in the
# intended sampling mode.
modes = llm.llm_engine.collective_rpc(_is_sharded_sampling_active)
assert all(mode == (not disable_sharding) for mode in modes), modes
if not disable_sharding:
logits_checks = llm.llm_engine.collective_rpc(_local_logits_match_full)
assert any(check["has_full_logits"] for check in logits_checks)
assert all(check["matches"] for check in logits_checks)
# The second wave reuses request slots freed by the first,
# covering the cross-rank slot-recycling path that ownership uses.
wave1 = llm.generate(prompts, sampling_params)
wave2 = llm.generate(prompts[::-1], sampling_params[::-1])
return wave1 + wave2
finally:
del llm
cleanup_dist_env_and_memory()
def _requested_top_k(lps: LogprobsOnePosition, num_logprobs: int) -> set[int]:
"""Exclude the extra sampled/prompt token, including at rank k+1."""
top = {
token_id
for token_id, logprob in lps.items()
if logprob.rank is not None and 1 <= logprob.rank <= num_logprobs
}
assert len(top) == num_logprobs, (
f"expected {num_logprobs} ranked top-k entries, got {len(top)}"
)
return top
def _assert_logprob_dicts_close(
ref_lps: LogprobsOnePosition,
out_lps: LogprobsOnePosition,
what: str,
num_logprobs: int,
) -> None:
# Allow one boundary entry of the top-k set to swap at a near-tie. Compare
# the top-k alone: counting the sampled token would spend that allowance
# on the extra entry itself whenever only one side carries one.
ref_top = _requested_top_k(ref_lps, num_logprobs)
out_top = _requested_top_k(out_lps, num_logprobs)
shared_top = ref_top & out_top
assert len(shared_top) >= num_logprobs - 1, (
f"{what}: top-k token sets diverge: {sorted(ref_top)} vs {sorted(out_top)}"
)
# Values are comparable for every shared token, sampled one included.
for token_id in set(ref_lps) & set(out_lps):
diff = abs(ref_lps[token_id].logprob - out_lps[token_id].logprob)
assert diff <= LOGPROB_TOL, (
f"{what}[{token_id}]: logprob diff {diff} "
f"({ref_lps[token_id].logprob} vs {out_lps[token_id].logprob})"
)
@pytest.mark.cpu_test
@pytest.mark.parametrize(
("num_logprobs", "ref_ranks", "out_ranks"),
[
(2, {0: 1, 1: 2, 2: 3}, {0: 1, 3: 2, 2: 4}),
(1, {0: 1, 1: 2}, {2: 1, 1: 3}),
(2, {0: 1, 1: 2}, {0: 1, 2: 2, 1: 3}),
(2, {0: 1, 1: 2, 2: 4}, {0: 1, 1: 2, 2: 5}),
(0, {0: 2}, {0: 3}),
],
ids=["decode-boundary", "prompt-boundary", "sampled-in-top-k", "gap", "zero"],
)
def test_logprob_comparison_allows_sampled_token_rank_changes(
num_logprobs: int, ref_ranks: dict[int, int], out_ranks: dict[int, int]
):
ref_lps, out_lps = (
{token: Logprob(-2.0 - rank / 100, rank=rank) for token, rank in ranks.items()}
for ranks in (ref_ranks, out_ranks)
)
_assert_logprob_dicts_close(ref_lps, out_lps, "boundary swap", num_logprobs)
@pytest.mark.cpu_test
def test_logprob_comparison_rejects_multiple_top_k_swaps():
ref = {0: Logprob(-2.0, rank=1), 1: Logprob(-2.01, rank=2)}
out = {2: Logprob(-2.0, rank=1), 3: Logprob(-2.01, rank=2)}
with pytest.raises(AssertionError, match="top-k token sets diverge"):
_assert_logprob_dicts_close(ref, out, "misrouted top-k", num_logprobs=2)
@pytest.mark.cpu_test
def test_logprob_comparison_checks_extra_sampled_token_value():
ref = {0: Logprob(-1.0, rank=1), 1: Logprob(-3.0, rank=3)}
out = {0: Logprob(-1.0, rank=1), 1: Logprob(-4.0, rank=3)}
with pytest.raises(AssertionError, match="logprob diff"):
_assert_logprob_dicts_close(ref, out, "sampled token", num_logprobs=1)
@pytest.mark.cpu_test
@pytest.mark.parametrize("rank", [None, 2])
def test_logprob_comparison_rejects_missing_top_k_rank(rank: int | None):
lps = {0: Logprob(-1.0, rank=rank)}
with pytest.raises(AssertionError, match="expected 1 ranked top-k entries"):
_assert_logprob_dicts_close(lps, lps, "missing rank", num_logprobs=1)
def _assert_outputs_match(ref_outputs, shard_outputs, params) -> None:
assert len(ref_outputs) == len(shard_outputs) == len(params)
divergent = []
for i, (ref, out, sampling_params) in enumerate(
zip(ref_outputs, shard_outputs, params)
):
ref_completion = ref.outputs[0]
out_completion = out.outputs[0]
ref_ids = list(ref_completion.token_ids)
out_ids = list(out_completion.token_ids)
# Logits are only comparable at positions whose context (prompt +
# previously sampled tokens) is identical: every position up to and
# including the first divergence.
prefix = 0
while prefix < min(len(ref_ids), len(out_ids)):
if ref_ids[prefix] != out_ids[prefix]:
break
prefix += 1
if ref_ids != out_ids:
divergent.append((i, prefix))
if ref_completion.logprobs is not None:
assert out_completion.logprobs is not None
assert sampling_params.logprobs is not None
comparable = min(prefix + 1, len(ref_ids), len(out_ids))
for pos in range(comparable):
_assert_logprob_dicts_close(
ref_completion.logprobs[pos],
out_completion.logprobs[pos],
f"prompt {i} logprobs[{pos}]",
sampling_params.logprobs,
)
# The prompt is fixed, so every prompt-logprob position is comparable.
if ref.prompt_logprobs is not None:
assert out.prompt_logprobs is not None
assert sampling_params.prompt_logprobs is not None
for pos, (ref_lps, out_lps) in enumerate(
zip(ref.prompt_logprobs, out.prompt_logprobs)
):
if ref_lps is None or out_lps is None:
assert ref_lps is None and out_lps is None
continue
_assert_logprob_dicts_close(
ref_lps,
out_lps,
f"prompt {i} prompt_logprobs[{pos}]",
sampling_params.prompt_logprobs,
)
assert not divergent, (
f"{len(divergent)}/{len(params)} completions diverged at "
f"(prompt, position) {divergent}; the sampling modes did not agree "
"token for token with in-process scheduling"
)
def _configure_test_environment(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
# Required for the collective_rpc mode check below.
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
# Queue every request before the first step, so both boots schedule the
# same batches -- see the module docstring.
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
("model", "revision", "prompts"),
[
pytest.param(MODEL, None, PROMPTS, id="llama"),
pytest.param(MODEL, None, PROMPTS[:1], id="llama-empty-rank"),
pytest.param(
GPT_OSS_MODEL,
GPT_OSS_REVISION,
PROMPTS,
id="gpt-oss",
),
],
)
def test_sharded_sampling_outputs_match(
monkeypatch: pytest.MonkeyPatch,
model: str,
revision: str | None,
prompts: list[str],
):
"""Generation, logprobs, and prompt logprobs match between batch-sharded
sampling and the replicated fallback."""
_configure_test_environment(monkeypatch)
sampling_params = _sampling_params(len(prompts))
ref_outputs = _generate(
disable_sharding=True,
model=model,
prompts=prompts,
sampling_params=sampling_params,
revision=revision,
)
shard_outputs = _generate(
disable_sharding=False,
model=model,
prompts=prompts,
sampling_params=sampling_params,
revision=revision,
)
expected_params = sampling_params + sampling_params[::-1]
_assert_outputs_match(ref_outputs, shard_outputs, expected_params)
@@ -1,661 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""End-to-end tests for the streaming input feature in AsyncLLM.
These tests verify that:
1. Streaming inputs work correctly with bunched inputs (queued)
2. Streaming inputs work correctly with spaced out inputs
3. Outputs are equivalent whether inputs are bunched or spaced
4. Cancelling the output stream correctly aborts the session
5. Closing the input stream correctly signals completion
6. Queued inputs are cancelled when the session is aborted
"""
import asyncio
from collections.abc import AsyncGenerator
import pytest
import pytest_asyncio
from vllm import SamplingParams
from vllm.engine.protocol import StreamingInput
from vllm.exceptions import VLLMValidationError
from vllm.outputs import RequestOutput
from vllm.platforms import current_platform
from vllm.sampling_params import RequestOutputKind
from vllm.utils.torch_utils import set_default_torch_num_threads
from vllm.v1.engine.async_llm import AsyncLLM
if not current_platform.is_cuda():
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
# Use a small model that doesn't require authentication for fast tests
MODEL = "facebook/opt-125m"
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def engine():
"""Create an AsyncLLM engine for the test.
Note: Using function scope because pytest_asyncio creates a new event loop
for each test, and the output_handler task gets cancelled between tests
with module scope.
"""
from vllm.engine.arg_utils import AsyncEngineArgs
engine_args = AsyncEngineArgs(
model=MODEL, enforce_eager=True, gpu_memory_utilization=0.7
)
with set_default_torch_num_threads(1):
engine = AsyncLLM.from_engine_args(engine_args)
try:
yield engine
finally:
engine.shutdown()
await asyncio.sleep(0.1)
def get_sampling_params(max_tokens: int = 20) -> SamplingParams:
"""Create sampling params for streaming input tests."""
return SamplingParams(
max_tokens=max_tokens,
ignore_eos=True,
output_kind=RequestOutputKind.DELTA,
temperature=0.0, # Deterministic for reproducibility
)
async def collect_outputs(
output_gen: AsyncGenerator[RequestOutput, None],
) -> tuple[list[RequestOutput], str]:
"""Collect all outputs from a generate call, return outputs and full text."""
outputs: list[RequestOutput] = []
full_text = ""
async for output in output_gen:
outputs.append(output)
if output.outputs and output.outputs[0].text:
full_text += output.outputs[0].text
return outputs, full_text
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_bunched(engine: AsyncLLM):
"""Test streaming input where all inputs are sent at once (bunched/queued).
This tests the case where multiple inputs arrive before any completes.
The inputs should be queued and processed in sequence.
"""
request_id = "test_bunched"
sampling_params = get_sampling_params(max_tokens=10)
# Create an input generator that yields all inputs quickly
async def bunched_input_generator() -> AsyncGenerator[StreamingInput, None]:
# Send multiple inputs rapidly - they should be queued
yield StreamingInput(prompt="Hello, my name is")
yield StreamingInput(prompt=" Alice and I like")
yield StreamingInput(prompt=" to code in Python")
outputs, full_text = await collect_outputs(
engine.generate(
bunched_input_generator(),
sampling_params,
request_id,
)
)
# Verify we got outputs
assert len(outputs) > 0, "Should have received outputs"
# Verify the final output is marked as finished
assert outputs[-1].finished, "Last output should be marked as finished"
# Verify intermediate outputs are not marked as finished
for output in outputs[:-1]:
assert not output.finished, "Intermediate outputs should not be finished"
# Verify we generated some text
assert len(full_text) > 0, "Should have generated text"
print(f"Bunched test generated: {full_text}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_spaced(engine: AsyncLLM):
"""Test streaming input where inputs are spaced out.
This tests the case where each input completes processing before the
next one is sent. Each chunk should be prefilled, generate tokens,
then the next chunk should be processed.
"""
request_id = "test_spaced"
sampling_params = get_sampling_params(max_tokens=10)
# Track when each input is sent
input_times: list[float] = []
outputs_per_chunk: list[int] = [0, 0, 0]
current_chunk = 0
async def spaced_input_generator() -> AsyncGenerator[StreamingInput, None]:
nonlocal current_chunk
import time
# First input
input_times.append(time.time())
yield StreamingInput(prompt="Hello, my name is")
current_chunk = 0
# Wait for some outputs to be generated
await asyncio.sleep(0.5)
# Second input
input_times.append(time.time())
current_chunk = 1
yield StreamingInput(prompt=" Alice and I like")
# Wait for some outputs
await asyncio.sleep(0.5)
# Third input
input_times.append(time.time())
current_chunk = 2
yield StreamingInput(prompt=" to code in Python")
outputs: list[RequestOutput] = []
full_text = ""
async for output in engine.generate(
spaced_input_generator(),
sampling_params,
request_id,
):
outputs.append(output)
if output.outputs and output.outputs[0].text:
full_text += output.outputs[0].text
outputs_per_chunk[current_chunk] += 1
# Verify we got outputs
assert len(outputs) > 0, "Should have received outputs"
# Verify the final output is marked as finished
assert outputs[-1].finished, "Last output should be marked as finished"
# Verify we received outputs from multiple chunks
# (with spaced inputs, we should see outputs distributed across chunks)
chunks_with_outputs = sum(1 for c in outputs_per_chunk if c > 0)
assert chunks_with_outputs >= 1, "Should have outputs from at least one chunk"
print(f"Spaced test generated: {full_text}")
print(f"Outputs per chunk: {outputs_per_chunk}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_output_equivalence(engine: AsyncLLM):
"""Test that bunched and spaced inputs produce equivalent outputs.
When the same prompts are provided either bunched or spaced,
the final concatenated output should be the same (with deterministic
sampling).
"""
prompts = ["Hello, my name is", " Bob and I work", " at Anthropic"]
sampling_params = get_sampling_params(max_tokens=15)
# Test bunched inputs
async def bunched_gen() -> AsyncGenerator[StreamingInput, None]:
for prompt in prompts:
yield StreamingInput(prompt=prompt)
_, bunched_text = await collect_outputs(
engine.generate(bunched_gen(), sampling_params, "equiv_bunched")
)
# Test spaced inputs (same prompts, but with delays)
async def spaced_gen() -> AsyncGenerator[StreamingInput, None]:
for prompt in prompts:
yield StreamingInput(prompt=prompt)
await asyncio.sleep(0.3)
_, spaced_text = await collect_outputs(
engine.generate(spaced_gen(), sampling_params, "equiv_spaced")
)
# Both should produce the same output since we use temperature=0
assert bunched_text == spaced_text, (
f"Bunched and spaced should produce same output.\n"
f"Bunched: {bunched_text!r}\n"
f"Spaced: {spaced_text!r}"
)
print(f"Equivalence test passed. Generated: {bunched_text}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_cancel_output_stream(engine: AsyncLLM):
"""Test that cancelling the output stream aborts the entire session.
When the consumer cancels iteration over the output generator,
the session should be aborted including any queued inputs.
"""
request_id = "test_cancel_output"
sampling_params = get_sampling_params(max_tokens=1000)
input_completed = asyncio.Event()
input_task_cancelled = False
async def slow_input_generator() -> AsyncGenerator[StreamingInput, None]:
nonlocal input_task_cancelled
try:
yield StreamingInput(prompt="Tell me a very long story about")
yield StreamingInput(prompt=" a dragon and a knight")
# This should be cancelled before we get here
await asyncio.sleep(10)
yield StreamingInput(prompt=" who become friends")
input_completed.set()
except asyncio.CancelledError:
input_task_cancelled = True
raise
outputs_received = 0
output_gen = engine.generate(slow_input_generator(), sampling_params, request_id)
# Collect a few outputs then cancel
try:
async for output in output_gen:
outputs_received += 1
if outputs_received >= 5:
# Cancel by breaking out of the loop (generator will be GC'd)
break
finally:
# Explicitly close the generator to ensure cleanup
await output_gen.aclose()
# Give time for cleanup
await asyncio.sleep(0.5)
# Verify we got some outputs before cancelling
assert outputs_received >= 5, "Should have received outputs before cancel"
# Verify the input task was cancelled
assert input_task_cancelled, "Input task should have been cancelled"
# Verify the session is properly cleaned up
assert not engine.output_processor.has_unfinished_requests(), (
"Should have no unfinished requests after cancel"
)
print(f"Cancel test passed. Received {outputs_received} outputs before cancel")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_close_signals_completion(engine: AsyncLLM):
"""Test that closing the input stream signals completion.
When the input generator finishes (naturally or via return),
the session should complete with finished=True on the last output.
"""
request_id = "test_close_completion"
sampling_params = get_sampling_params(max_tokens=15)
input_generator_finished = False
async def limited_input_generator() -> AsyncGenerator[StreamingInput, None]:
nonlocal input_generator_finished
yield StreamingInput(prompt="What is 2 + 2? The answer is")
# Generator finishes naturally here
input_generator_finished = True
outputs, _ = await collect_outputs(
engine.generate(limited_input_generator(), sampling_params, request_id)
)
# Verify the input generator completed
assert input_generator_finished, "Input generator should have finished"
# Verify we got a finished output
assert len(outputs) > 0, "Should have received outputs"
assert outputs[-1].finished, "Last output should be marked as finished"
# Verify the session is cleaned up
assert not engine.output_processor.has_unfinished_requests(), (
"Should have no unfinished requests"
)
print("Close completion test passed")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_abort_queued_inputs(engine: AsyncLLM):
"""Test that aborting the session cancels queued inputs.
When multiple inputs are queued and the session is aborted,
all pending inputs should be cancelled.
"""
request_id = "test_abort_queued"
# Use large max_tokens to ensure we have time to queue inputs
sampling_params = get_sampling_params(max_tokens=2000)
inputs_sent = 0
input_cancelled = False
async def many_inputs_generator() -> AsyncGenerator[StreamingInput, None]:
nonlocal inputs_sent, input_cancelled
try:
# Send several inputs to fill the queue
for i in range(10):
yield StreamingInput(prompt=f" Part {i}: Tell me about the number {i}.")
inputs_sent += 1
# Small delay to interleave with output processing
await asyncio.sleep(0.05)
except asyncio.CancelledError:
input_cancelled = True
raise
outputs_received = 0
output_gen = engine.generate(many_inputs_generator(), sampling_params, request_id)
try:
async for output in output_gen:
outputs_received += 1
# Cancel after receiving some outputs
if outputs_received >= 10:
break
finally:
await output_gen.aclose()
# Give time for cleanup
await asyncio.sleep(0.5)
# Verify we received some outputs
assert outputs_received >= 10, "Should have received outputs before abort"
# Verify the input generator was cancelled OR finished naturally
# (it might finish naturally if all inputs were sent before cancel)
assert input_cancelled or inputs_sent == 10, (
f"Input generator should have been cancelled or completed. "
f"cancelled={input_cancelled}, inputs_sent={inputs_sent}"
)
# Verify the session is cleaned up
assert not engine.output_processor.has_unfinished_requests(), (
"Should have no unfinished requests after abort"
)
print(
f"Abort queued test passed. Sent {inputs_sent} inputs, "
f"received {outputs_received} outputs"
)
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_error_propagation(engine: AsyncLLM):
"""Test that errors in the input generator are propagated to the caller."""
request_id = "test_error_propagation"
sampling_params = get_sampling_params(max_tokens=20)
class InputError(Exception):
pass
async def error_input_generator() -> AsyncGenerator[StreamingInput, None]:
yield StreamingInput(prompt="Start with this")
await asyncio.sleep(0.1)
raise InputError("Simulated input error")
# Note: The current implementation catches exceptions and puts them
# in the queue, so we should get the error when iterating outputs
with pytest.raises(InputError, match="Simulated input error"):
async for _ in engine.generate(
error_input_generator(), sampling_params, request_id
):
pass
# Give time for cleanup
await asyncio.sleep(0.3)
# Verify the session is cleaned up
assert not engine.output_processor.has_unfinished_requests(), (
"Should have no unfinished requests after error"
)
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_multiple_concurrent_sessions(engine: AsyncLLM):
"""Test multiple concurrent streaming input sessions.
Multiple streaming sessions should be able to run concurrently
without interfering with each other.
"""
num_sessions = 3
results: list[tuple[str, str]] = []
async def run_session(session_id: int) -> tuple[str, str]:
request_id = f"test_concurrent_{session_id}"
sampling_params = get_sampling_params(max_tokens=10)
prompts = [f"Session {session_id}: Hello", f" world from session {session_id}"]
async def input_gen() -> AsyncGenerator[StreamingInput, None]:
for prompt in prompts:
yield StreamingInput(prompt=prompt)
await asyncio.sleep(0.1)
_, text = await collect_outputs(
engine.generate(input_gen(), sampling_params, request_id)
)
return request_id, text
# Run sessions concurrently
tasks = [asyncio.create_task(run_session(i)) for i in range(num_sessions)]
results = await asyncio.gather(*tasks)
# Verify all sessions completed
assert len(results) == num_sessions
for request_id, text in results:
assert len(text) > 0, f"Session {request_id} should have generated text"
print(f"{request_id}: {text}")
# Verify cleanup
assert not engine.output_processor.has_unfinished_requests()
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_per_chunk_sampling_params(engine: AsyncLLM):
"""Test that per-chunk sampling params are respected.
Each StreamingInput can have its own sampling_params.
"""
request_id = "test_per_chunk_params"
base_params = get_sampling_params(max_tokens=10)
async def variable_params_generator() -> AsyncGenerator[StreamingInput, None]:
# First chunk with base params
yield StreamingInput(prompt="Count to five:", sampling_params=base_params)
# Second chunk with different max_tokens
chunk_params = get_sampling_params(max_tokens=5)
yield StreamingInput(
prompt=" Now count backwards:", sampling_params=chunk_params
)
outputs, full_text = await collect_outputs(
engine.generate(variable_params_generator(), base_params, request_id)
)
assert len(outputs) > 0, "Should have received outputs"
assert outputs[-1].finished, "Last output should be finished"
assert len(full_text) > 0, "Should have generated text"
print(f"Per-chunk params test generated: {full_text}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_empty_generator(engine: AsyncLLM):
"""Test behavior when the input generator yields nothing.
An empty generator should finish without producing output.
"""
request_id = "test_empty_generator"
sampling_params = get_sampling_params(max_tokens=10)
async def empty_generator() -> AsyncGenerator[StreamingInput, None]:
# Don't yield anything
return
yield # Make it a generator
outputs: list[RequestOutput] = []
async for output in engine.generate(empty_generator(), sampling_params, request_id):
outputs.append(output)
assert outputs == []
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_single_chunk(engine: AsyncLLM):
"""Test streaming input with a single chunk.
This is effectively the same as a regular non-streaming request,
but using the streaming input API.
"""
request_id = "test_single_chunk"
sampling_params = get_sampling_params(max_tokens=15)
async def single_chunk_generator() -> AsyncGenerator[StreamingInput, None]:
yield StreamingInput(prompt="What color is the sky? The sky is")
outputs, full_text = await collect_outputs(
engine.generate(single_chunk_generator(), sampling_params, request_id)
)
assert len(outputs) > 0
assert outputs[-1].finished
assert "blue" in full_text.lower() or len(full_text) > 0
print(f"Single chunk test generated: {full_text}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_reuse_request_id(engine: AsyncLLM):
"""Test that request IDs can be reused after a session completes."""
request_id = "test_reuse_id"
sampling_params = get_sampling_params(max_tokens=5)
# First session
async def gen1() -> AsyncGenerator[StreamingInput, None]:
yield StreamingInput(prompt="First session")
_, text1 = await collect_outputs(
engine.generate(gen1(), sampling_params, request_id)
)
# Second session with same ID
async def gen2() -> AsyncGenerator[StreamingInput, None]:
yield StreamingInput(prompt="Second session")
_, text2 = await collect_outputs(
engine.generate(gen2(), sampling_params, request_id)
)
assert len(text1) > 0
assert len(text2) > 0
assert not engine.output_processor.has_unfinished_requests()
print(f"Reuse ID test: session 1: {text1}, session 2: {text2}")
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_validation_errors(engine: AsyncLLM):
"""Test that invalid configurations raise appropriate errors."""
async def dummy_generator() -> AsyncGenerator[StreamingInput, None]:
yield StreamingInput(prompt="test")
# Test n > 1 is rejected
with pytest.raises(
VLLMValidationError, match="Input streaming not currently supported"
):
params_n2 = SamplingParams(max_tokens=10, n=2)
async for _ in engine.generate(dummy_generator(), params_n2, "test_n2"):
pass
# Test FINAL_ONLY is rejected
with pytest.raises(
VLLMValidationError, match="Input streaming not currently supported"
):
params_final = SamplingParams(
max_tokens=10, output_kind=RequestOutputKind.FINAL_ONLY
)
async for _ in engine.generate(dummy_generator(), params_final, "test_final"):
pass
# Test stop strings are rejected
with pytest.raises(
VLLMValidationError, match="Input streaming not currently supported"
):
params_stop = SamplingParams(max_tokens=10, stop=["stop"])
async for _ in engine.generate(dummy_generator(), params_stop, "test_stop"):
pass
@pytest.mark.asyncio(loop_scope="module")
async def test_streaming_input_delayed_generator_exit(engine: AsyncLLM):
"""Test that output generator exits when input generator closes after outputs.
This tests the case where:
1. Multiple inputs are sent and fully processed
2. The engine has finished
3. The input generator doesn't exit until after the engine finishes
4. The output generator should exit properly once the input generator exits
"""
request_id = "test_delayed_exit"
sampling_params = get_sampling_params(max_tokens=10)
engine_finished_event = asyncio.Event()
input_generator_exited = False
finish_count = 0
async def delayed_exit_input_generator() -> AsyncGenerator[StreamingInput, None]:
nonlocal input_generator_exited
# Send all inputs immediately
yield StreamingInput(prompt="Hello, my name is")
yield StreamingInput(prompt=" Alice")
# Wait until the engine has finished generating before exiting
await engine_finished_event.wait()
# Add a small delay to ensure we're testing the "delayed exit" case
await asyncio.sleep(0.1)
input_generator_exited = True
outputs: list[RequestOutput] = []
full_text = ""
async for output in engine.generate(
delayed_exit_input_generator(), sampling_params, request_id
):
outputs.append(output)
if output.outputs and output.outputs[0].text:
full_text += output.outputs[0].text
# Signal when the engine finishes both input chunks (each gets a finish_reason)
# Note: output.finished will be False while input stream is open
if output.outputs and output.outputs[0].finish_reason is not None:
finish_count += 1
if finish_count == 2:
engine_finished_event.set()
# Verify the input generator exited properly
assert input_generator_exited, (
"Input generator should have exited after engine finished"
)
# Verify we got outputs
assert len(outputs) > 0, "Should have received outputs"
# Verify we generated some text
assert len(full_text) > 0, "Should have generated text"
# Verify the session is cleaned up
assert not engine.output_processor.has_unfinished_requests(), (
"Should have no unfinished requests"
)
print(f"Delayed exit test passed. Generated: {full_text}")
@@ -1,156 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import pytest
from tests.evals.gsm8k.gsm8k_eval import evaluate_gsm8k_offline
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ...utils import compute_acceptance_len, compute_acceptance_rate
REGRESSION_TOLERANCE = 0.95
@dataclass(frozen=True)
class DSparkCorrectnessConfig:
model: str
draft_model: str
reference_accuracy: float
reference_acceptance_rate: float
reference_acceptance_len: float
num_speculative_tokens: int = 7
max_model_len: int = 4096
max_num_seqs: int | None = None
num_questions: int = 1319
max_tokens: int = 256
use_chat_completions: bool = False
chat_template_kwargs: dict[str, object] | None = None
attention_backend: str | None = None
gpu_memory_utilization: float = 0.92
enforce_eager: bool = False
disable_flashinfer_sampler: bool = False
language_model_only: bool = False
# References from 12 full GSM8K runs at temperature 1.0: accuracy 0.782-0.814,
# acceptance rate 0.418-0.434, acceptance length 3.928-4.037.
QWEN3_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
model="Qwen/Qwen3-4B-FP8",
draft_model="deepseek-ai/dspark_qwen3_4b_block7",
reference_accuracy=0.801,
reference_acceptance_rate=0.428,
reference_acceptance_len=3.994,
attention_backend="FLASH_ATTN",
)
# References from five 200-question runs at temperature 1.0: accuracy
# 0.900-0.955, acceptance rate 0.578-0.595, acceptance length 5.044-5.167.
GEMMA4_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
model="RedHatAI/gemma-4-12B-it-NVFP4",
draft_model="deepseek-ai/dspark_gemma4_12b_block7",
reference_accuracy=0.92,
reference_acceptance_rate=0.58,
reference_acceptance_len=5.0,
max_num_seqs=32,
num_questions=200,
use_chat_completions=True,
gpu_memory_utilization=0.85,
enforce_eager=True,
disable_flashinfer_sampler=True,
language_model_only=True,
)
# Reference from 200 GSM8K questions at temperature 1.0.
QWEN3_6_DSPARK_SPECULATORS = DSparkCorrectnessConfig(
model="RedHatAI/Qwen3.6-35B-A3B-NVFP4",
draft_model="RedHatAI/Qwen3.6-35B-A3B-speculator.dspark",
reference_accuracy=0.85,
reference_acceptance_rate=0.41,
reference_acceptance_len=4.25,
num_speculative_tokens=8,
max_num_seqs=32,
num_questions=200,
use_chat_completions=True,
chat_template_kwargs={"enable_thinking": False},
gpu_memory_utilization=0.85,
language_model_only=True,
)
@pytest.mark.parametrize(
"config",
[
pytest.param(QWEN3_DSPARK_DEEPSPEC, id="qwen3-deepspec"),
pytest.param(GEMMA4_DSPARK_DEEPSPEC, id="gemma4-deepspec"),
pytest.param(QWEN3_6_DSPARK_SPECULATORS, id="qwen3.6-speculators"),
],
)
def test_dspark_correctness_and_acceptance_rate(
monkeypatch: pytest.MonkeyPatch,
config: DSparkCorrectnessConfig,
vllm_runner,
):
"""Guard GSM8K accuracy and acceptance metrics for DSpark models."""
if config.disable_flashinfer_sampler:
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
speculative_config = {
"method": "dspark",
"model": config.draft_model,
"num_speculative_tokens": config.num_speculative_tokens,
"draft_sample_method": "probabilistic",
}
if config.attention_backend is not None and current_platform.is_cuda():
speculative_config["attention_backend"] = config.attention_backend
runner_config = {
"block_size": None,
"trust_remote_code": True,
"speculative_config": speculative_config,
"max_model_len": config.max_model_len,
"gpu_memory_utilization": config.gpu_memory_utilization,
"enforce_eager": config.enforce_eager,
"enable_chunked_prefill": None,
"enable_prefix_caching": False,
"disable_log_stats": False,
"compilation_config": CompilationConfig(),
}
if config.max_num_seqs is not None:
runner_config["max_num_seqs"] = config.max_num_seqs
if config.language_model_only:
runner_config["language_model_only"] = True
with vllm_runner(config.model, **runner_config) as spec_runner:
spec_llm = spec_runner.llm
results = evaluate_gsm8k_offline(
spec_llm,
num_questions=config.num_questions,
max_tokens=config.max_tokens,
temperature=1.0,
use_chat_completions=config.use_chat_completions,
chat_template_kwargs=config.chat_template_kwargs,
)
accuracy = results["accuracy"]
metrics = spec_llm.get_metrics()
acceptance_rate = compute_acceptance_rate(metrics)
acceptance_len = compute_acceptance_len(metrics)
context = f"DSpark target={config.model}, draft={config.draft_model}"
metrics_summary = (
f"gsm8k_accuracy={accuracy:.3f}, "
f"acceptance_rate={acceptance_rate:.3f}, "
f"acceptance_len={acceptance_len:.3f}"
)
print(f"{context}: {metrics_summary}")
assert accuracy >= config.reference_accuracy * REGRESSION_TOLERANCE, (
f"{context}: {metrics_summary}"
)
assert (
acceptance_rate >= config.reference_acceptance_rate * REGRESSION_TOLERANCE
), f"{context}: {metrics_summary}"
assert (
acceptance_len >= config.reference_acceptance_len * REGRESSION_TOLERANCE
), f"{context}: {metrics_summary}"
@@ -1,56 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ...utils import compute_acceptance_len, get_test_prompts
@single_gpu_only
def test_synthetic_acceptance_rate(vllm_runner):
"""Verify that synthetic rejection sampling produces an acceptance
length close to the requested mean acceptance length."""
num_spec_tokens = 3
expected_acceptance_len = 1.875
tolerance = 0.15
with vllm_runner(
"meta-llama/Llama-3.2-1B-Instruct",
block_size=None,
trust_remote_code=True,
speculative_config={
"method": "eagle3",
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
"num_speculative_tokens": num_spec_tokens,
"max_model_len": 2048,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_length": expected_acceptance_len,
},
max_model_len=2048,
enforce_eager=True,
enable_chunked_prefill=None,
disable_log_stats=False,
compilation_config=CompilationConfig(),
) as spec_runner:
spec_llm = spec_runner.llm
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=50)
spec_llm.chat(
test_prompts,
SamplingParams(temperature=0, max_tokens=64, ignore_eos=True),
)
metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(metrics)
print(
f"Synthetic acceptance length: {acceptance_len:.3f}"
f" (expected={expected_acceptance_len:.3f},"
f" tolerance=±{tolerance})"
)
assert abs(acceptance_len - expected_acceptance_len) <= tolerance, (
f"Synthetic acceptance length {acceptance_len:.3f} is not within"
f" ±{tolerance} of expected {expected_acceptance_len:.3f}"
)
@@ -1,102 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ..utils import compute_acceptance_len
def load_and_process_dataset(data_name: str):
from datasets import load_dataset
if data_name == "gsm8k":
dataset = load_dataset("openai/gsm8k", "main", split="test")
prompt_fmt = (
"{question}\nPlease reason step by step,"
" and put your final answer within \\boxed{{}}."
)
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
elif data_name == "mt-bench":
dataset = load_dataset("HuggingFaceH4/mt_bench_prompts", split="train")
dataset = dataset.map(lambda x: {"turns": x["prompt"]})
elif data_name == "humaneval":
dataset = load_dataset("openai/openai_humaneval", split="test")
prompt_fmt = (
"Write a solution to the following problem and make sure"
" that it passes the tests:\n```python\n{prompt}\n```"
)
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
return dataset
def run_acceptance_length_eval(
monkeypatch: pytest.MonkeyPatch,
vllm_runner,
spec_config: dict[str, Any],
expected_acceptance_lengths: dict[str, float],
chat_template_kwargs: dict[str, Any],
use_mrv2: bool,
):
"""E2E acceptance-rate validation for speculative decoding.
Drives one or more datasets (keyed in ``expected_acceptance_lengths``)
through the spec decode engine and asserts the mean acceptance length
stays within tolerance of the reference figure for each dataset.
"""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if use_mrv2 else "0")
runner_config = spec_config.copy()
model = runner_config.pop("model")
runner_config.setdefault("block_size", None)
runner_config.setdefault("enable_chunked_prefill", None)
runner_config.setdefault("compilation_config", CompilationConfig())
with vllm_runner(model, **runner_config) as spec_runner:
spec_llm = spec_runner.llm
# MT-Bench has 80 prompts and HumanEval has 164; truncate GSM8K.
max_prompts_per_dataset = 200
tokenizer = spec_llm.get_tokenizer()
for dataset_name, expected_len in expected_acceptance_lengths.items():
dataset = load_and_process_dataset(dataset_name)
prev_metrics = None
acceptance_lengths = []
for i in range(min(max_prompts_per_dataset, len(dataset))):
user_content = dataset[i]["turns"][0]
prompt_text = tokenizer.apply_chat_template(
[{"role": "user", "content": user_content}],
tokenize=False,
add_generation_prompt=True,
**chat_template_kwargs,
)
# Greedy (temp=0) so acceptance length is deterministic and comparable
# across runs.
spec_llm.generate(
[prompt_text],
SamplingParams(temperature=0, max_tokens=2048),
use_tqdm=False,
)
current_metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(current_metrics, prev_metrics)
prev_metrics = current_metrics
acceptance_lengths.append(acceptance_len)
mean_acceptance_length = sum(acceptance_lengths) / len(acceptance_lengths)
# Fairly tight tolerance of 95% against the reference figures,
# watching for regressions. Can be relaxed if test is flaky but be sure to
# check for genuine issues such as #40727.
expected_len = expected_len * 0.95
print(
f"acceptance_len for {dataset_name}: {mean_acceptance_length:.2f}"
f" (expected at least {expected_len:.2f})"
)
assert mean_acceptance_length >= expected_len, (
f"acceptance_len for {dataset_name} is below expected threshold: "
f"{mean_acceptance_length:.2f} < {expected_len:.2f}"
)
@@ -1,96 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for sync-free speculative decoding with async scheduling."""
import pytest
# Test configurations: (model, spec_model, method, num_spec_tokens, backend_env)
SPEC_DECODE_CONFIGS = [
pytest.param(
"meta-llama/Llama-3.2-1B-Instruct",
"nm-testing/Llama3_2_1B_speculator.eagle3",
"eagle3",
2,
id="eagle3-llama",
),
pytest.param(
"eagle618/deepseek-v3-random",
"eagle618/eagle-deepseek-v3-random",
"eagle",
2,
id="eagle-mla-deepseek",
),
pytest.param(
"Qwen/Qwen3.5-0.8B-Base",
"Qwen/Qwen3.5-0.8B-Base",
"mtp",
1,
id="mtp-qwen3_5-hybrid",
),
]
@pytest.mark.parametrize(
"model,spec_model,method,num_spec_tokens",
SPEC_DECODE_CONFIGS,
)
def test_no_sync_with_spec_decode(
model: str,
spec_model: str,
method: str,
num_spec_tokens: int,
monkeypatch,
vllm_runner,
):
"""Test generation while the worker rejects unintended GPU-CPU syncs."""
monkeypatch.setenv("VLLM_GPU_SYNC_CHECK", "error")
from vllm import SamplingParams
from vllm.config import CompilationConfig
# Qwen3.5 is a VLM; without this, profile_run runs the ViT warmup
# and peaks well above the 18GB MIG slice used by one of the CI lanes.
# This test only exercises text generation, so the vision tower is
# never needed.
extra_kwargs: dict = {}
if "Qwen3.5" in model:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
with vllm_runner(
model,
block_size=None,
trust_remote_code=False,
max_model_len=256,
speculative_config={
"method": method,
"num_speculative_tokens": num_spec_tokens,
"model": spec_model,
},
enforce_eager=True,
async_scheduling=True,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as runner:
llm = runner.llm
# Assert async scheduling is actually active before running inference.
assert llm.llm_engine.vllm_config.scheduler_config.async_scheduling, (
f"Expected async_scheduling=True for spec decode, got False. "
f"method={method}, target={model}, draft={spec_model}"
)
outputs = llm.generate(
["Hello, my name is"],
SamplingParams(temperature=0, max_tokens=10),
)
assert len(outputs) == 1, (
f"{method} target={model}: expected one request output, got {len(outputs)}"
)
assert outputs[0].outputs, (
f"{method} target={model}: request output has no completion candidates"
)
assert outputs[0].outputs[0].text, (
f"{method} target={model}: generated completion text is empty"
)
@@ -1,423 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import pytest
from tests.utils import multi_gpu_only, single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig, VllmConfig, replace
from vllm.config.kernel import MoEBackend
from vllm.engine.arg_utils import EngineArgs
from vllm.platforms import current_platform
from vllm.v1.spec_decode.draft_model import DraftModelProposer
from ..utils import (
Messages,
compute_acceptance_len,
compute_acceptance_rate,
evaluate_llm_for_gsm8k,
get_instruct_coder_messages,
get_test_prompts,
greedy_sampling,
stochastic_sampling,
)
@dataclass
class ArgsTest:
target_model: str
draft_model: str
sampling_config: SamplingParams
num_speculative_tokens: int
expected_acceptance_rate: float
expected_acceptance_len: float
expected_gsm8k_accuracy: float = 0.0 # skip by default
# Defaults
enforce_eager: bool = True
parallel_drafting: bool = False
target_tensor_parallel_size: int = 1
draft_tensor_parallel_size: int = 1
max_model_len: int = 2048
gpu_memory_utilization: float = 0.5
dataset: str = "test_prompts"
# Doubling 100 to 200 reduces sampling standard error by about 29%.
num_prompts: int = 200
def get_messages(dataset: str, n: int) -> list[Messages]:
if dataset == "test_prompts":
return get_test_prompts(mm_enabled=False, num_prompts=n)
if dataset == "likaixin/InstructCoder":
return get_instruct_coder_messages(n=n)
raise NotImplementedError(f"Dataset '{dataset}' not implemented")
def some_high_acceptance_metrics() -> dict:
return {
"sampling_config": greedy_sampling(),
"num_speculative_tokens": 3,
"expected_acceptance_len": 3.4, # ref: 3.75
"expected_acceptance_rate": 0.8, # ref: 0.9
}
cases = [
# Same model for draft and target, greedy sampling.
ArgsTest(
target_model="Qwen/Qwen3-0.6B",
draft_model="Qwen/Qwen3-0.6B",
sampling_config=greedy_sampling(),
num_speculative_tokens=3, # K
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
expected_acceptance_rate=0.98, # slight epsilon
expected_gsm8k_accuracy=0.25, # ref: 35-40%
),
# Smaller draft model, stochastic sampling.
ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="Qwen/Qwen3-0.6B",
sampling_config=stochastic_sampling(),
num_speculative_tokens=3,
expected_acceptance_len=3.4, # ref: 3.7
expected_acceptance_rate=0.80, # ref: 0.90
expected_gsm8k_accuracy=0.5, # ref: 60%. Note gsm8k always runs greedy sampling
),
]
@pytest.mark.parametrize("args", cases)
@pytest.mark.parametrize("enforce_eager", [True, False])
@single_gpu_only
def test_draft_model_correctness(args: ArgsTest, enforce_eager: bool, vllm_runner):
args.enforce_eager = enforce_eager
assert_draft_model_correctness(args, vllm_runner)
@single_gpu_only
def test_draft_model_realistic_example(vllm_runner):
args = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="Qwen/Qwen3-0.6B",
dataset="likaixin/InstructCoder",
num_speculative_tokens=3,
sampling_config=greedy_sampling(),
enforce_eager=False,
expected_acceptance_len=2.6, # ref: 2.86
expected_acceptance_rate=0.5, # ref: 0.62
)
assert_draft_model_correctness(args, vllm_runner)
@single_gpu_only
def test_draft_model_parallel_drafting(vllm_runner):
args = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="amd/PARD-Qwen3-0.6B",
dataset="likaixin/InstructCoder",
num_speculative_tokens=3,
sampling_config=greedy_sampling(),
parallel_drafting=True,
enforce_eager=False,
expected_acceptance_len=2.3, # ref: 2.52
expected_acceptance_rate=0.4, # ref: 0.51
)
assert_draft_model_correctness(args, vllm_runner)
@pytest.mark.parametrize(
"models",
[
# target_model, draft_model
("Qwen/Qwen3-1.7B-FP8", "Qwen/Qwen3-0.6B"), # target quantized
("Qwen/Qwen3-1.7B", "Qwen/Qwen3-0.6B-FP8"), # draft quantized
],
ids=["target_quantized", "draft_quantized"],
)
@pytest.mark.parametrize("enforce_eager", [True, False])
@single_gpu_only
def test_draft_model_quantization(
models: tuple[str, str], enforce_eager: bool, vllm_runner
):
tgt_model, draft_model = models
sd_case = ArgsTest(
target_model=tgt_model,
draft_model=draft_model,
**some_high_acceptance_metrics(),
enforce_eager=enforce_eager,
)
assert_draft_model_correctness(sd_case, vllm_runner)
@single_gpu_only
def test_draft_model_transformers_backend(vllm_runner):
"""Ensure that Attention prefixes don't collide between the target and
draft models when both models use the Transformers modelling backend."""
sd_case = ArgsTest(
target_model="allenai/OLMo-2-0425-1B-Instruct",
draft_model="allenai/OLMo-2-0425-1B-Instruct",
sampling_config=greedy_sampling(),
num_speculative_tokens=3,
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
expected_acceptance_rate=0.98, # slight epsilon
)
assert_draft_model_correctness(sd_case, vllm_runner)
@multi_gpu_only(num_gpus=2)
def test_draft_model_tensor_parallelism(vllm_runner):
"""Ensure spec decode works when running with TP > 1."""
sd_case = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
target_tensor_parallel_size=2,
draft_model="Qwen/Qwen3-0.6B",
draft_tensor_parallel_size=2,
**some_high_acceptance_metrics(),
enforce_eager=False,
expected_gsm8k_accuracy=0.5,
)
assert_draft_model_correctness(sd_case, vllm_runner)
@multi_gpu_only(num_gpus=2)
def test_draft_model_engine_args_tensor_parallelism():
"""Ensure the vllm_config for the draft model is created correctly,
and independently of the target model (quantization, TP, etc.)"""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B-FP8", # <<< tgt quantized
tensor_parallel_size=2,
speculative_config={
"model": "Qwen/Qwen3-0.6B", # <<< draft not quantized
"method": "draft_model",
"num_speculative_tokens": 3,
"draft_tensor_parallel_size": 1, # <<< valid arg name
},
)
target_config: VllmConfig = engine_args.create_engine_config()
assert target_config.parallel_config.tensor_parallel_size == 2
assert target_config.quant_config.get_name() == "fp8"
speculative_config = target_config.speculative_config
draft_config: VllmConfig = replace(
target_config,
quant_config=None,
parallel_config=replace(
speculative_config.draft_parallel_config,
rank=target_config.parallel_config.rank,
),
model_config=speculative_config.draft_model_config,
)
assert draft_config.parallel_config.tensor_parallel_size == 1
assert draft_config.quant_config is None
@pytest.mark.cpu_test
@pytest.mark.parametrize("dcp_size", [1, 2])
def test_draft_model_inherits_target_dcp_config(monkeypatch, dcp_size):
monkeypatch.setattr(current_platform, "device_count", lambda: 16)
target_config = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=16,
decode_context_parallel_size=dcp_size,
cp_kv_cache_interleave_size=16,
dcp_comm_backend="ag_rs",
distributed_executor_backend="mp",
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
).create_engine_config()
proposer = object.__new__(DraftModelProposer)
proposer.vllm_config = target_config
proposer.speculative_config = target_config.speculative_config
draft_config = proposer._create_draft_vllm_config()
draft_parallel = draft_config.parallel_config
assert draft_parallel.decode_context_parallel_size == dcp_size
assert draft_parallel.cp_kv_cache_interleave_size == 16
assert draft_parallel.dcp_comm_backend == "ag_rs"
assert (
draft_parallel.dcp_q_replicate == target_config.parallel_config.dcp_q_replicate
)
assert draft_parallel is not target_config.parallel_config
assert target_config.parallel_config.decode_context_parallel_size == dcp_size
def _apply_draft_moe_backend(vllm_config: VllmConfig) -> VllmConfig:
"""Replicate SpecDecodeBaseProposer._create_draft_vllm_config logic
so we can test it without instantiating a full proposer."""
spec_cfg = vllm_config.speculative_config
if spec_cfg.moe_backend is not None:
return replace(
vllm_config,
kernel_config=replace(
vllm_config.kernel_config,
moe_backend=spec_cfg.moe_backend,
),
)
return vllm_config
def _platform_moe_backend(monkeypatch: pytest.MonkeyPatch) -> MoEBackend:
if current_platform.is_rocm():
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "1")
return "aiter"
if current_platform.is_cuda():
return "flashinfer_trtllm"
return "auto"
def test_draft_model_moe_backend_override(monkeypatch: pytest.MonkeyPatch):
"""When moe_backend is set in speculative_config, the draft VllmConfig
should use it while the target keeps its own setting."""
target_moe_backend = _platform_moe_backend(monkeypatch)
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
moe_backend=target_moe_backend,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
"moe_backend": "triton",
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == target_moe_backend
assert tgt_config.speculative_config.moe_backend == "triton"
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == "triton"
# Target config must be unaffected.
assert tgt_config.kernel_config.moe_backend == target_moe_backend
def test_draft_model_moe_backend_inherits_target(monkeypatch: pytest.MonkeyPatch):
"""When moe_backend is not set in speculative_config, the draft should
inherit the target's moe_backend."""
target_moe_backend = _platform_moe_backend(monkeypatch)
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
moe_backend=target_moe_backend,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == target_moe_backend
assert tgt_config.speculative_config.moe_backend is None
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == target_moe_backend
assert draft_config is tgt_config
def test_draft_model_moe_backend_default_auto():
"""When neither target nor draft set moe_backend explicitly, both should
default to 'auto'."""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == "auto"
assert tgt_config.speculative_config.moe_backend is None
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == "auto"
assert draft_config is tgt_config
def test_draft_model_engine_args_rejects_invalid_tp_argname():
"""The user should pass "draft_tensor_parallel_size" rather than
"tensor_parallel_size". We enforce this with validation."""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
"tensor_parallel_size": 1, # <<< invalid arg name
},
)
with pytest.raises(ValueError, match="draft_tensor_parallel_size"):
engine_args.create_engine_config()
def assert_draft_model_correctness(args: ArgsTest, vllm_runner):
"""Compare the outputs using and not using speculative decoding.
In the greedy decoding case, the outputs must match EXACTLY."""
test_prompts: list[Messages] = get_messages(
dataset=args.dataset, n=args.num_prompts
)
with vllm_runner(
args.target_model,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
speculative_config={
"model": args.draft_model,
"method": "draft_model",
"num_speculative_tokens": args.num_speculative_tokens,
"max_model_len": args.max_model_len,
"enforce_eager": args.enforce_eager,
"draft_tensor_parallel_size": args.draft_tensor_parallel_size,
"parallel_drafting": args.parallel_drafting,
},
max_num_seqs=100, # limit cudagraph capture runtime
max_model_len=args.max_model_len,
gpu_memory_utilization=args.gpu_memory_utilization,
tensor_parallel_size=args.target_tensor_parallel_size,
enforce_eager=args.enforce_eager,
disable_log_stats=False, # enables get_metrics()
) as spec_runner:
spec_llm = spec_runner.llm
# we don't check the outputs, only check the metrics
spec_llm.chat(test_prompts, args.sampling_config)
metrics = spec_llm.get_metrics()
acceptance_rate: float = compute_acceptance_rate(metrics)
acceptance_len: float = compute_acceptance_len(metrics)
# Need to evaluate after getting metrics to avoid polluting the AR
evaluate_llm_for_gsm8k(
spec_llm, expected_accuracy_threshold=args.expected_gsm8k_accuracy
)
print(
f"spec-decode: target={args.target_model}, draft={args.draft_model}, "
f"temperature={args.sampling_config.temperature:.2f}, "
f"acceptance_rate={acceptance_rate:.2f}, "
f"acceptance_len={acceptance_len:.2f}, "
)
context = (
f"draft_model target={args.target_model}, draft={args.draft_model}, "
f"eager={args.enforce_eager}, "
f"acceptance_rate={acceptance_rate:.3f}, "
f"acceptance_len={acceptance_len:.3f}"
)
assert acceptance_rate >= args.expected_acceptance_rate, (
f"{context}; expected acceptance_rate >= "
f"{args.expected_acceptance_rate:.3f}"
)
assert acceptance_len >= args.expected_acceptance_len, (
f"{context}; expected acceptance_len >= {args.expected_acceptance_len:.3f}"
)
# draft_model supports async scheduling; assert it is active by default.
has_async = spec_llm.llm_engine.vllm_config.scheduler_config.async_scheduling
assert has_async, "Expected async_scheduling=True for draft_model spec decode"
@@ -1,134 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""This script contains:
1. test lora with speculative decoding for batch inference
"""
import pytest
import torch
import vllm.envs as envs
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.lora.request import LoRARequest
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from ..utils import assert_request_outputs_match
LORA_TEST_PROMPT_MAP: dict[str, str] = {}
LORA_TEST_PROMPT_MAP["premjatin/qwen-linear-algebra-coder"] = """
### INSTRUCTION:
You are an AI assistant that generates Python code to solve linear
algebra problems.
### PROBLEM:
Find the eigenvalues and eigenvectors of the following 3x3 matrix:
[[3, 2, 0],
[2, 3, 0],
[0, 0, 2]]
### OUTPUT FORMAT (STRICT):
Numbers should be represented as integers only.
### PYTHON SOLUTION:
"""
SEED = 42
@pytest.mark.parametrize(
"model_setup",
[
(
"eagle3",
"Qwen/Qwen3-1.7B",
"AngelSlim/Qwen3-1.7B_eagle3",
"premjatin/qwen-linear-algebra-coder",
1,
)
],
)
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="Requires CUDA or ROCm"
)
def test_batch_inference_correctness(
monkeypatch: pytest.MonkeyPatch,
model_setup: tuple[str, str, str, str, int],
vllm_runner,
):
"""Compare the outputs of a LLM with only Lora and a LLM with both SD and Lora.
Should be the same and no failure when doing batch inference.
model_setup: (method, model_name, spec_model_name, lora_path, tp_size)
"""
with monkeypatch.context() as m:
m.setenv("VLLM_BATCH_INVARIANT", "1")
m.setattr(envs, "VLLM_BATCH_INVARIANT", True)
set_random_seed(SEED)
m.setattr(torch.backends.cudnn, "benchmark", False)
m.setattr(torch.backends.cudnn, "deterministic", True)
method, model_name, spec_model_name, lora_path, tp_size = model_setup
prompts = [LORA_TEST_PROMPT_MAP[lora_path]] * 100
lora_request = LoRARequest("adapter", 1, lora_path)
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, top_k=-1, seed=SEED, max_tokens=128
)
# without speculative decoding
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
max_model_len=2048,
max_num_seqs=4,
enable_lora=True,
max_loras=1,
max_cpu_loras=1,
max_lora_rank=16,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as ref_runner:
ref_outputs = ref_runner.llm.generate(
prompts, sampling_params, lora_request=lora_request
)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config={
"method": method,
"model": spec_model_name,
"num_speculative_tokens": 3,
"max_model_len": 2048,
},
max_model_len=2048,
max_num_seqs=4,
enable_lora=True,
max_loras=1,
max_cpu_loras=1,
max_lora_rank=16,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
lora_spec_outputs = spec_runner.llm.generate(
prompts, sampling_params, lora_request=lora_request
)
# Under greedy verification, the spec-decode output should equal the
# non-spec output (modulo FP noise from the target's verify-path matmul
# running at seqlen num_speculative_tokens+1 vs 1). 90% leaves slack.
assert_request_outputs_match(
ref_outputs,
lora_spec_outputs,
required_matches=int(0.90 * len(ref_outputs)) + 1,
context=(
f"LoRA + {method}: target={model_name}, draft={spec_model_name}, "
f"adapter={lora_path}"
),
)
@@ -1,59 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from tests.utils import multi_gpu_test
from tests.v1.e2e.spec_decode.utils import compute_acceptance_len
from vllm import LLM, SamplingParams
from vllm.distributed import cleanup_dist_env_and_memory
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
DRAFT = "nm-testing/Llama3_2_1B_speculator.eagle3"
PROMPTS = [
"The capital of France is",
"2 + 2 equals",
"In one word, the color of the sky is",
"Q: If a train travels 60 miles in 1.5 hours, what is its average speed?\nA:",
]
ACCEPTANCE_TOLERANCE = 0.95
def _run(pp_size: int) -> float:
llm = LLM(
model=MODEL,
tensor_parallel_size=1,
pipeline_parallel_size=pp_size,
max_model_len=512,
gpu_memory_utilization=0.45,
disable_log_stats=False,
compilation_config={"cudagraph_mode": "FULL_AND_PIECEWISE"},
speculative_config={
"method": "eagle3",
"model": DRAFT,
"num_speculative_tokens": 3,
},
)
try:
llm.generate(
PROMPTS,
SamplingParams(temperature=0.0, max_tokens=32, ignore_eos=True),
)
acceptance = compute_acceptance_len(llm.get_metrics())
assert acceptance > 1
return acceptance
finally:
del llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
@multi_gpu_test(num_gpus=4)
def test_eagle3_pipeline_parallel_acceptance():
baseline = _run(1)
for pp_size in (2, 4):
parallel = _run(pp_size)
assert parallel >= baseline * ACCEPTANCE_TOLERANCE, (
f"PP={pp_size} acceptance regressed: {parallel:.3f} < "
f"{baseline:.3f} * {ACCEPTANCE_TOLERANCE}"
)
@@ -1,172 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import (
get_attn_backend_list_based_on_platform,
single_gpu_only,
)
from vllm import SamplingParams
from vllm.platforms import current_platform
from .utils import _run_eagle_correctness
@single_gpu_only
@pytest.mark.skipif(
current_platform.is_device_capability_family(100),
reason="DeepSeek head_dim=192 not supported on SM100/SM110 (Blackwell)",
)
@pytest.mark.parametrize(
[
"model_setup",
"mm_enabled",
"enable_chunked_prefill",
"model_impl",
"expected_accuracy_threshold",
],
[
(
(
"eagle",
"eagle618/deepseek-v3-random",
"eagle618/eagle-deepseek-v3-random",
1,
),
False,
False,
"auto",
0.0,
),
],
ids=["deepseek_eagle"],
)
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_correctness_light(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
_run_eagle_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
enable_chunked_prefill,
model_impl,
attn_backend,
vllm_runner,
)
@single_gpu_only
@pytest.mark.parametrize(
[
"model_setup",
"mm_enabled",
"enable_chunked_prefill",
"model_impl",
"expected_accuracy_threshold",
],
[
(
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
False,
False,
"auto",
0.8,
),
pytest.param(
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
False,
False,
"transformers",
0.8,
# TODO(hmellor): figure out why memory usage is so high
marks=pytest.mark.skipif(
not current_platform.is_rocm(),
reason="Feature is experimental and uses too much memory in CUDA CI",
),
),
(
(
"eagle3",
"Qwen/Qwen3-VL-8B-Instruct",
"taobao-mnn/Qwen3-VL-8B-Instruct-Eagle3",
1,
),
False,
False,
"auto",
0.8,
),
pytest.param(
(
"eagle3",
"Qwen/Qwen2.5-VL-7B-Instruct",
"Rayzl/qwen2.5-vl-7b-eagle3-sgl",
1,
),
False,
False,
"auto",
0.7,
# TODO: Re-measure the reference threshold when re-enabling this case.
# Text-only mode starts but loses target correctness with ROCm/TRITON;
# full multimodal profiling currently fails during engine startup.
marks=pytest.mark.skip(
reason="Qwen2.5-VL Eagle3 is not yet reliable in this test setup"
),
),
(
(
"eagle3",
"meta-llama/Llama-3.1-8B-Instruct",
"yuhuili/EAGLE3-LLaMA3.1-Instruct-8B",
1,
),
False,
False,
"auto",
0.7,
),
],
ids=[
"qwen3_eagle3",
"qwen3_eagle3-transformers",
"qwen3_vl_eagle3",
"qwen2_5_vl_eagle3",
"llama3_eagle3",
],
)
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_correctness_medium(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
_run_eagle_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
enable_chunked_prefill,
model_impl,
attn_backend,
vllm_runner,
)
-135
View File
@@ -1,135 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
_skip_if_insufficient_gpus_for_tp,
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
def _run_eagle_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
"""Compare the outputs of an original LLM and a speculative LLM
which should be the same when using eagle speculative decoding.
"""
method, model_name, spec_model_name, tp_size = model_setup
_skip_if_insufficient_gpus_for_tp(tp_size)
test_prompts = get_test_prompts(mm_enabled)
extra_kwargs: dict[str, Any] = {}
if not mm_enabled and "Qwen3-VL" in model_name:
# These cases only exercise text generation. Avoid profiling an unused
# vision tower, which adds substantial memory to both reference runs.
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
if "Llama-4-Scout" in model_name and attn_backend == "FLASH_ATTN":
if current_platform.is_rocm():
print(
"FLASH_ATTN for spec_decode not supported on "
"ROCm currently. Changing to FLEX_ATTENTION backend."
)
attention_config = {"backend": "FLEX_ATTENTION"}
else:
attention_config = None
else:
attention_config = {"backend": attn_backend}
if attn_backend == "TRITON_ATTN" and not current_platform.is_rocm():
pytest.skip(
"TRITON_ATTN does not support "
"multi-token eagle spec decode on current platform"
)
with monkeypatch.context() as m:
m.setenv("VLLM_MLA_DISABLE", "1")
if attn_backend == "ROCM_AITER_FA" and current_platform.is_rocm():
if "deepseek" in model_name.lower():
m.setenv("VLLM_ROCM_USE_AITER", "1")
m.delenv("VLLM_MLA_DISABLE", raising=False)
attention_config = {"backend": "ROCM_AITER_MLA"}
else:
m.setenv("VLLM_ROCM_USE_AITER", "1")
max_model_len = 2048
max_num_batched_tokens = 128 if enable_chunked_prefill else max_model_len
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=False,
max_model_len=max_model_len,
tensor_parallel_size=tp_size,
attention_config=attention_config,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as ref_runner:
evaluate_llm_for_gsm8k(
ref_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config={
"method": method,
"model": spec_model_name,
"num_speculative_tokens": 3,
"max_model_len": max_model_len,
},
max_model_len=max_model_len,
max_num_batched_tokens=max_num_batched_tokens,
enable_chunked_prefill=enable_chunked_prefill,
model_impl=model_impl,
attention_config=attention_config,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as spec_runner:
# EAGLE/EAGLE3 supports async scheduling by default.
has_async = (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
)
assert has_async, (
f"Expected async scheduling for {method}: target={model_name}, "
f"draft={spec_model_name}, backend={attn_backend}; got {has_async}"
)
evaluate_llm_for_gsm8k(
spec_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.6 * len(ref_outputs)) + 1,
context=(
f"{method} target={model_name}, draft={spec_model_name}, "
f"backend={attn_backend}"
),
)
@@ -1,110 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
_skip_if_insufficient_gpus_for_tp,
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
def check_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
"""Compare the outputs of a original LLM and a speculative LLM
which should be the same when using MTP speculative decoding. Due to some variance
in the engine, it is possible for some outputs to differ, so we expect that at least
6/10 output tokens match exactly, and that the GSM8k accuracy is above a precomputed
reference threshold for each model.
"""
method, model_name, tp_size, draft_model = model_setup
_skip_if_insufficient_gpus_for_tp(tp_size)
# Generate test prompts inside the function instead of using fixture
test_prompts = get_test_prompts(mm_enabled)
with monkeypatch.context() as m:
m.setenv("VLLM_MLA_DISABLE", "1")
attn_backend = "TRITON_ATTN" if current_platform.is_rocm() else "auto"
# Skip multimodal profiling for models that don't need it in this test.
extra_kwargs: dict[str, Any] = {}
if "Qwen3.5" in model_name:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
elif "gemma-4" in model_name:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "audio": 0}
with vllm_runner(
model_name,
block_size=None,
max_model_len=2048,
tensor_parallel_size=tp_size,
trust_remote_code=True,
attention_backend=attn_backend,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as ref_runner:
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
evaluate_llm_for_gsm8k(
ref_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
speculative_config: dict[str, Any] = {
"method": method,
"num_speculative_tokens": 1,
"max_model_len": 2048,
}
if draft_model is not None:
speculative_config["model"] = draft_model
speculative_config["num_speculative_tokens"] = 2
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config=speculative_config,
max_model_len=2048,
attention_backend=attn_backend,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as spec_runner:
# MTP supports async scheduling by default.
has_async = (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
)
assert has_async, (
f"Expected async scheduling for {method}: target={model_name}, "
f"draft={draft_model}; got {has_async}"
)
evaluate_llm_for_gsm8k(
spec_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
# Heuristic: expect at least 80% of the prompts to match exactly
# Upon failure, inspect the outputs to check for inaccuracy.
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context=f"{method} target={model_name}, draft={draft_model}",
)
@@ -1,44 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.platforms import current_platform
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
pytest.param(
("mtp", "ZixiQi/DeepSeek-V3-4layers-MTP-FP8", 1, None),
False,
0.0,
marks=pytest.mark.skipif(
current_platform.is_device_capability_family(100),
reason="DeepSeek MTP: TRTLLM MoE top_k check fails on Blackwell",
),
), # dummy model
],
ids=["deepseek"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,39 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
(
("mtp", "google/gemma-4-E4B-it", 1, "google/gemma-4-E4B-it-assistant"),
False,
0.50,
), # gemma4 MTP with assistant model, ref: ~62%
],
ids=["gemma4-e4b"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,36 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
# Reference accuracy: 65%-70%.
(("mtp", "XiaomiMiMo/MiMo-7B-Base", 1, None), False, 0.5),
],
ids=["mimo"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,149 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.platforms import current_platform
from ...utils import (
assert_request_outputs_match,
compute_acceptance_len,
get_test_prompts,
)
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
(
("mtp", "Qwen/Qwen3.5-0.8B-Base", 1, None),
False,
0.20,
), # hybrid + MTP, ref: ~34%-35%
],
ids=["qwen3_5-hybrid"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@single_gpu_only
def test_mtp_draft_lm_head_quantization(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
vllm_runner,
):
"""A quantized draft copy of the shared lm_head only changes drafting:
greedy outputs match stock MTP and acceptance stays within 10%."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
prompts = get_test_prompts(mm_enabled=False)
results = {}
# NVFP4 needs a CUDA W4A16 kernel.
quants = (None, "fp8", "nvfp4") if current_platform.is_cuda() else (None, "fp8")
for quant in quants:
with vllm_runner(
"Qwen/Qwen3.5-0.8B-Base",
block_size=None,
enable_chunked_prefill=None,
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
speculative_config={
"method": "mtp",
"num_speculative_tokens": 3,
"draft_lm_head_quantization": quant,
},
disable_log_stats=False,
) as runner:
outputs = runner.llm.chat(prompts, sampling_config)
results[quant] = (outputs, compute_acceptance_len(runner.llm.get_metrics()))
ref_outputs, ref_al = results.pop(None)
for quant, (outputs, al) in results.items():
assert_request_outputs_match(
ref_outputs,
outputs,
# Not bit-exact: a different acceptance length changes the target's
# verify batch shapes, which can flip a near-tied greedy token.
required_matches=int(0.8 * len(ref_outputs)) + 1,
context=f"draft_lm_head_quantization={quant}",
)
assert al >= 0.9 * ref_al, (
f"{quant}: acceptance length {al:.3f} vs {ref_al:.3f}"
)
@single_gpu_only
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
)
def test_mtp_draft_lm_head_quantization_survives_sleep_and_reload(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
vllm_runner,
):
"""The quantized draft head is derived from the target head: it must come
back intact after a level 1 sleep and be re-derived after a target weight
reload, so outputs and acceptance match the run before."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
prompts = get_test_prompts(mm_enabled=False)
with vllm_runner(
"Qwen/Qwen3.5-0.8B-Base",
block_size=None,
enable_chunked_prefill=None,
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
speculative_config={
"method": "mtp",
"num_speculative_tokens": 3,
"draft_lm_head_quantization": "nvfp4",
},
enable_sleep_mode=True,
disable_log_stats=False,
) as runner:
llm = runner.llm
def run():
before = llm.get_metrics()
outputs = llm.chat(prompts, sampling_config)
return outputs, compute_acceptance_len(llm.get_metrics(), before)
ref_outputs, ref_al = run()
llm.sleep(level=1)
llm.wake_up()
outputs, al = run()
assert_request_outputs_match(
ref_outputs,
outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context="after level 1 sleep",
)
assert al == pytest.approx(ref_al, rel=0.03)
llm.collective_rpc("reload_weights")
outputs, al = run()
assert_request_outputs_match(
ref_outputs,
outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context="after weight reload",
)
assert al == pytest.approx(ref_al, rel=0.03)
@@ -1,115 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig, CUDAGraphMode
from vllm.platforms import current_platform
from ...utils import get_spec_decode_metric_value
PLACEHOLDER_REGRESSION_MODEL = "Qwen/Qwen3.5-0.8B-Base"
PLACEHOLDER_REGRESSION_PROMPT = "The capital of France is"
PLACEHOLDER_REGRESSION_MAX_TOKENS = 16
PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID = 42
PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS = 3
@pytest.mark.parametrize(
"cudagraph_mode",
[CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL_AND_PIECEWISE],
ids=["piecewise", "full-and-piecewise"],
)
@single_gpu_only
def test_mtp_rejected_placeholders_match_greedy_token_ids(
cudagraph_mode: CUDAGraphMode,
vllm_runner,
):
"""Rejected MTP padding must not alter the non-speculative token stream."""
common_kwargs: dict[str, Any] = {
"block_size": None,
"max_model_len": 256,
"max_num_seqs": 1,
"trust_remote_code": True,
"enable_chunked_prefill": None,
"limit_mm_per_prompt": {"image": 0, "video": 0},
"attention_backend": ("TRITON_ATTN" if current_platform.is_rocm() else "auto"),
}
sampling_params = SamplingParams(
temperature=0.0,
max_tokens=PLACEHOLDER_REGRESSION_MAX_TOKENS,
ignore_eos=True,
allowed_token_ids=[PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID],
logprobs=1,
)
def generate_token_ids(runner) -> tuple[int, ...]:
outputs = runner.llm.generate([PLACEHOLDER_REGRESSION_PROMPT], sampling_params)
assert outputs and outputs[0].outputs, "Expected one completion"
token_ids = tuple(outputs[0].outputs[0].token_ids)
assert len(token_ids) == PLACEHOLDER_REGRESSION_MAX_TOKENS
return token_ids
def compilation_config() -> CompilationConfig:
return CompilationConfig(
cudagraph_mode=cudagraph_mode,
cudagraph_capture_sizes=[1, PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS + 1],
)
with vllm_runner(
PLACEHOLDER_REGRESSION_MODEL,
compilation_config=compilation_config(),
**common_kwargs,
) as ref_runner:
ref_mode = (
ref_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
)
assert ref_mode == cudagraph_mode
ref_token_ids = generate_token_ids(ref_runner)
expected_token_ids = (PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID,) * (
PLACEHOLDER_REGRESSION_MAX_TOKENS
)
assert ref_token_ids == expected_token_ids
with vllm_runner(
PLACEHOLDER_REGRESSION_MODEL,
speculative_config={
"method": "mtp",
"num_speculative_tokens": PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
"max_model_len": 256,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_rates": [0.0]
* PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
},
disable_log_stats=False,
compilation_config=compilation_config(),
**common_kwargs,
) as spec_runner:
spec_mode = (
spec_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
)
assert spec_mode == cudagraph_mode
spec_token_ids = generate_token_ids(spec_runner)
metrics = spec_runner.llm.get_metrics()
num_drafts = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_drafts"
)
num_draft_tokens = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_draft_tokens"
)
num_accepted_tokens = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_accepted_tokens"
)
assert num_drafts > 0, "MTP drafter did not run"
assert num_draft_tokens > 0, "MTP drafter did not produce draft tokens"
assert num_accepted_tokens == 0, "Synthetic sampler accepted a draft token"
assert spec_token_ids == ref_token_ids, (
f"MTP changed greedy token ids under {cudagraph_mode.name}:\n"
f" reference={ref_token_ids}\n"
f" speculative={spec_token_ids}"
)
@@ -1,173 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
evaluate_llm_for_gsm8k,
get_spec_decode_metric_value,
get_test_prompts,
)
@pytest.fixture
def disable_vllm_compile_cache_on_rocm(request: pytest.FixtureRequest) -> None:
if current_platform.is_rocm():
request.getfixturevalue("disable_vllm_compile_cache")
@pytest.mark.parametrize(
"speculative_config",
[
{
"method": "ngram",
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": 3,
},
{
"method": "suffix",
"suffix_decoding_max_spec_factor": 2.0,
},
],
)
@pytest.mark.usefixtures("disable_vllm_compile_cache_on_rocm")
@single_gpu_only
def test_ngram_and_suffix_correctness(
speculative_config: dict,
model_name: str,
vllm_runner,
):
with vllm_runner(
model_name,
block_size=None,
# Keep LLM defaults; VllmRunner only provides lifecycle cleanup here.
trust_remote_code=False,
enable_chunked_prefill=None,
speculative_config=speculative_config,
max_model_len=4096,
# Preserve LLM's default compilation/cudagraph configuration. Without
# this, VllmRunner injects its reduced test-only capture sizes.
compilation_config=CompilationConfig(),
) as runner:
evaluate_llm_for_gsm8k(runner.llm)
@pytest.mark.parametrize("async_scheduling", [True], ids=["async"])
@single_gpu_only
def test_ngram_gpu_default_with_async_scheduling(
async_scheduling: bool,
vllm_runner,
):
"""Test ngram_gpu speculative decoding (k=3) correctness with and without
async scheduling, validated via GSM8K accuracy.
Uses Qwen/Qwen3-8B (ref GSM8K accuracy: 87%-92%).
"""
qwen3_model = "Qwen/Qwen3-8B"
with vllm_runner(
qwen3_model,
block_size=None,
trust_remote_code=False,
speculative_config={
"method": "ngram_gpu",
"prompt_lookup_max": 3,
"prompt_lookup_min": 2,
"num_speculative_tokens": 2,
},
max_model_len=4096,
async_scheduling=async_scheduling,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
# Assert the resolved async_scheduling config matches what was requested.
assert (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
== async_scheduling
)
evaluate_llm_for_gsm8k(spec_runner.llm, expected_accuracy_threshold=0.8)
@single_gpu_only
def test_suffix_decoding_acceptance(
sampling_config: SamplingParams,
model_name: str,
vllm_runner,
):
"""Check that suffix decoding caching takes effect and improves acceptance
lengths and acceptance rates over multiple runs of the same prompts.
"""
test_prompts = get_test_prompts(mm_enabled=False)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=False,
speculative_config={
"method": "suffix",
"suffix_decoding_max_spec_factor": 2.0,
"suffix_decoding_max_cached_requests": 1000,
},
max_model_len=1024,
disable_log_stats=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
# Run several times and check that the accepted tokens increase.
num_draft = []
num_accept = []
for _ in range(10): # Run multiple times to warm up the cache.
spec_runner.llm.chat(test_prompts, sampling_config)
# Collect draft and acceptance stats.
metrics = spec_runner.llm.get_metrics()
num_draft.append(
get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_draft_tokens"
)
)
num_accept.append(
get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_accepted_tokens"
)
)
# Calculate the acceptance rates for the first and last runs.
first_accept_tokens = num_accept[0]
first_draft_tokens = num_draft[0]
assert first_draft_tokens > 0, (
"Suffix decoder produced no draft tokens on the first run: "
f"accepted={first_accept_tokens}, drafted={first_draft_tokens}"
)
first_accept_rate = first_accept_tokens / first_draft_tokens
# Take the diff since the stats are cumulative.
last_accept_tokens = num_accept[-1] - num_accept[-2]
last_draft_tokens = num_draft[-1] - num_draft[-2]
assert last_draft_tokens > 0, (
"Suffix decoder produced no draft tokens on the last run: "
f"accepted_delta={last_accept_tokens}, drafted_delta={last_draft_tokens}; "
f"cumulative_drafted={num_draft[-2:]}"
)
last_accept_rate = last_accept_tokens / last_draft_tokens
summary = (
f"first accepted/drafted={first_accept_tokens}/{first_draft_tokens} "
f"(rate={first_accept_rate:.3f}); last delta accepted/drafted="
f"{last_accept_tokens}/{last_draft_tokens} (rate={last_accept_rate:.3f})"
)
# Expect the acceptance length to improve.
assert first_accept_tokens < last_accept_tokens, (
f"Expected accepted tokens to increase after cache warmup; {summary}"
)
# Expect the acceptance rate to improve.
assert first_accept_rate < last_accept_rate, (
f"Expected acceptance rate to increase after cache warmup; {summary}"
)
# Heuristic: expect at least 80.0% acceptance rate at the end.
assert last_accept_rate > 0.80, f"Expected final acceptance rate > 0.80; {summary}"
@@ -1,106 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ..utils import (
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
@pytest.mark.parametrize(
["model_path", "expected_accuracy_threshold"],
[
# Measured reference: 75%-80%.
("RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3", 0.72),
# Measured reference: 87%-92%.
("RedHatAI/Qwen3-8B-speculator.eagle3", 0.84),
],
ids=["llama3_eagle3_speculator", "qwen3_eagle3_speculator"],
)
@single_gpu_only
def test_speculators_model_integration(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_path: str,
expected_accuracy_threshold: float,
vllm_runner,
):
"""Test that speculators models work with the simplified integration.
This verifies the `vllm serve <speculator-model>` use case where
speculative config is automatically detected from the model config
without requiring explicit --speculative-config argument.
Tests:
1. Speculator model is correctly detected
2. Verifier model is extracted from speculator config
3. Speculative decoding is automatically enabled
4. Text generation works correctly
5. GSM8k accuracy of the model passes a sanity check when speculative decoding on
6. Output matches reference (non-speculative) generation
"""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
# Generate test prompts
test_prompts = get_test_prompts(mm_enabled=False)
# First run: Direct speculator model (simplified integration)
with vllm_runner(
model_path,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
max_model_len=4096,
gpu_memory_utilization=0.92,
) as spec_runner:
evaluate_llm_for_gsm8k(
spec_runner.llm, expected_accuracy_threshold=expected_accuracy_threshold
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
# Verify speculative config was auto-detected
assert spec_runner.llm.llm_engine.vllm_config.speculative_config is not None, (
f"Speculative config should be auto-detected for {model_path}"
)
spec_config = spec_runner.llm.llm_engine.vllm_config.speculative_config
assert spec_config.num_speculative_tokens > 0, (
f"Expected positive speculative tokens, "
f"got {spec_config.num_speculative_tokens}"
)
# Verify draft model is set to the speculator model
assert spec_config.model == model_path, (
f"Draft model should be {model_path}, got {spec_config.model}"
)
# Extract verifier model for reference run
verifier_model = spec_runner.llm.llm_engine.vllm_config.model_config.model
# Second run: Reference without speculative decoding
with vllm_runner(
verifier_model,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
max_model_len=4096,
gpu_memory_utilization=0.92,
) as ref_runner:
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
# Heuristic: expect at least 66% of prompts to match exactly
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.66 * len(ref_outputs)),
context=f"speculator={model_path}, verifier={verifier_model}",
)
@@ -1,268 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
from contextlib import AsyncExitStack
from dataclasses import dataclass, replace
from typing import Any
import pytest
import torch
from tests.utils import multi_gpu_marks
from vllm import LLM, SamplingParams
from vllm.config import CompilationConfig
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.platforms import current_platform
from vllm.sampling_params import RequestOutputKind
from vllm.v1.engine.async_llm import AsyncLLM
from vllm.v1.metrics.reader import Metric
DEEPSEEK_MTP_MAIN_RANDOM = "luccafong/deepseek_mtp_main_random"
DEEPSEEK_MTP_DRAFT_RANDOM = "luccafong/deepseek_mtp_draft_random"
PROMPT = "The capital of France is"
MAX_TOKENS = 8
MAX_MODEL_LEN = 2048
GPU_MEM_UTIL = 0.85
# Spec / no-spec greedy output should match, but exact match is not guaranteed
# across parallelism layouts (reduction order can flip near-tie argmaxes), so
# gate on a similarity ratio like the spec-decode E2E tests.
MIN_MATCH_RATIO = 0.8
def _token_match_ratio(a: tuple[int, ...], b: tuple[int, ...]) -> float:
n = min(len(a), len(b))
return sum(x == y for x, y in zip(a, b)) / n if n else 0.0
@dataclass(frozen=True)
class InlineConfig:
id: str
tp_size: int = 1
pp_size: int = 1
enable_expert_parallel: bool = False
enable_eplb: bool = False
skip_reason: str | None = None
INLINE_CONFIGS = [
InlineConfig(id="tp2", tp_size=2),
InlineConfig(id="ep2", tp_size=2, enable_expert_parallel=True),
InlineConfig(
id="ep2_eplb",
tp_size=2,
enable_expert_parallel=True,
enable_eplb=True,
),
InlineConfig(id="pp2", pp_size=2),
]
def _inline_kwargs(config: InlineConfig, *, with_spec: bool) -> dict[str, Any]:
kwargs: dict[str, Any] = {
"model": DEEPSEEK_MTP_MAIN_RANDOM,
"tensor_parallel_size": config.tp_size,
"pipeline_parallel_size": config.pp_size,
"enable_expert_parallel": config.enable_expert_parallel,
"max_model_len": MAX_MODEL_LEN,
"gpu_memory_utilization": GPU_MEM_UTIL,
"enforce_eager": True,
"trust_remote_code": True,
"disable_log_stats": False,
# MLA + batch invariance currently disables prefix caching at runtime
# (see vllm/v1/attention/backends/mla/common.py); set explicitly so the
# configuration is unambiguous.
"enable_prefix_caching": False,
}
if config.enable_eplb:
kwargs["enable_eplb"] = True
# Rearrangement first fires after step_interval // 4 forward steps
# (the step counter starts at 3/4 of step_interval, see
# vllm/distributed/eplb/eplb_state.py). Keep these small so the EPLB
# routine actually runs within the short MAX_TOKENS generation instead
# of never triggering.
kwargs["eplb_config"] = {
"num_redundant_experts": config.tp_size,
"window_size": 2,
"step_interval": 4,
"log_balancedness": False,
}
if with_spec:
kwargs["speculative_config"] = {
"method": "mtp",
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
"num_speculative_tokens": 1,
}
return kwargs
def _generate_token_ids_inline(llm: LLM) -> tuple[int, ...]:
outputs = llm.generate(
[PROMPT],
SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS, ignore_eos=True),
)
assert outputs and outputs[0].outputs, "expected one completion"
token_ids = tuple(outputs[0].outputs[0].token_ids)
assert len(token_ids) == MAX_TOKENS, (
f"expected {MAX_TOKENS} generated tokens, got {len(token_ids)}: {token_ids}"
)
return token_ids
def _spec_decode_num_drafts(metrics: list[Metric]) -> int:
name2metric = {m.name: m for m in metrics}
counter = name2metric.get("vllm:spec_decode_num_drafts")
assert counter is not None, (
"spec_decode_num_drafts metric missing; check disable_log_stats=False"
)
return int(counter.value)
def _enable_batch_invariance(monkeypatch: pytest.MonkeyPatch) -> None:
# This test exercises DeepSeek MLA prefill. ROCm's upstream FlashAttention
# varlen API lacks the num_splits argument used by batch invariance, so
# explicitly override any ambient setting on that path.
if current_platform.is_cuda():
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
else:
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
@pytest.mark.parametrize(
"config",
[
pytest.param(c, id=c.id, marks=multi_gpu_marks(num_gpus=2))
for c in INLINE_CONFIGS
],
)
def test_deepseek_mtp_load_inline(
monkeypatch: pytest.MonkeyPatch,
config: InlineConfig,
vllm_runner,
):
"""MTP loads and drafts under TP/EP/EPLB; spec output matches no-spec greedy."""
if config.skip_reason is not None:
pytest.skip(config.skip_reason)
# Reduces run-to-run nondeterminism so spec / no-spec stay close;
# see tests/v1/distributed/test_eagle_dp.py for the same pattern.
_enable_batch_invariance(monkeypatch)
spec_kwargs = _inline_kwargs(config, with_spec=True)
spec_model = spec_kwargs.pop("model")
with vllm_runner(
spec_model,
block_size=None,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**spec_kwargs,
) as spec_runner:
spec_tokens = _generate_token_ids_inline(spec_runner.llm)
n_drafts = _spec_decode_num_drafts(spec_runner.llm.get_metrics())
no_spec_kwargs = _inline_kwargs(config, with_spec=False)
no_spec_model = no_spec_kwargs.pop("model")
with vllm_runner(
no_spec_model,
block_size=None,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**no_spec_kwargs,
) as no_spec_runner:
no_spec_tokens = _generate_token_ids_inline(no_spec_runner.llm)
# Non-vacuity: a silently-broken MTP drafter that falls back to
# verifier-only decoding would still produce matching output below.
assert n_drafts > 0, (
f"MTP drafter never fired under {config.id}: vllm:spec_decode_num_drafts == 0"
)
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
print(f"\n{config.id}: spec/no-spec match_ratio={match_ratio:.3f}")
assert match_ratio >= MIN_MATCH_RATIO, (
f"Spec / no-spec output divergence under {config.id}: "
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
f" spec_tokens = {spec_tokens}\n"
f" no_spec_tokens= {no_spec_tokens}"
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"dp_size",
[
pytest.param(2, marks=pytest.mark.distributed(num_gpus=2), id="dp2"),
pytest.param(1, id="dp1"),
],
)
async def test_deepseek_mtp_load_dp(monkeypatch: pytest.MonkeyPatch, dp_size: int):
"""MTP loads under DP (on and off) via AsyncLLM; spec matches no-spec greedy."""
if torch.accelerator.device_count() < dp_size:
pytest.skip(f"dp{dp_size} requires at least {dp_size} GPUs")
_enable_batch_invariance(monkeypatch)
base_args = AsyncEngineArgs(
model=DEEPSEEK_MTP_MAIN_RANDOM,
tensor_parallel_size=1,
data_parallel_size=dp_size,
data_parallel_backend="mp",
max_model_len=MAX_MODEL_LEN,
gpu_memory_utilization=GPU_MEM_UTIL,
enforce_eager=True,
trust_remote_code=True,
enable_prefix_caching=False,
)
spec_args = replace(
base_args,
speculative_config={
"method": "mtp",
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
"num_speculative_tokens": 1,
},
)
sampling_params = SamplingParams(
max_tokens=MAX_TOKENS,
ignore_eos=True,
output_kind=RequestOutputKind.FINAL_ONLY,
temperature=0.0,
)
async def _generate(args: AsyncEngineArgs, request_id: str) -> tuple[int, ...]:
try:
async with AsyncExitStack() as stack:
engine = AsyncLLM.from_engine_args(args)
stack.callback(engine.shutdown)
async for out in engine.generate(
request_id=request_id,
prompt=PROMPT,
sampling_params=sampling_params,
):
token_ids = tuple(out.outputs[0].token_ids)
assert len(token_ids) == MAX_TOKENS, (
f"{request_id}: expected {MAX_TOKENS} generated tokens, "
f"got {len(token_ids)}: {token_ids}"
)
return token_ids
raise AssertionError("AsyncLLM produced no output")
finally:
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
spec_tokens = await asyncio.wait_for(
_generate(spec_args, f"deepseek-mtp-dp{dp_size}-spec"), timeout=600
)
no_spec_tokens = await asyncio.wait_for(
_generate(base_args, f"deepseek-mtp-dp{dp_size}-no-spec"), timeout=600
)
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
print(f"\ndp{dp_size}: spec/no-spec match_ratio={match_ratio:.3f}")
assert match_ratio >= MIN_MATCH_RATIO, (
f"Spec / no-spec output divergence under dp{dp_size}: "
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
f" spec_tokens = {spec_tokens}\n"
f" no_spec_tokens= {no_spec_tokens}"
)
@@ -1,103 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Batch-sharded sampling must be a drop-in for replicated sampling under
speculative decoding.
The non-spec arm of this claim lives in tests/v1/e2e/general/
test_sharded_sampling.py. Spec decode is the harder case: draft tokens give
each request a different number of logits rows, so the shard plan's
per-request arithmetic and the rejection sampler are both exercised.
"""
import pytest
import torch
from tests.utils import wait_for_memory_to_settle
from vllm import LLM, SamplingParams
from vllm.distributed import cleanup_dist_env_and_memory
from .utils import _skip_if_insufficient_gpus_for_tp, get_test_prompts, greedy_sampling
# Even with in-process scheduling, near-tie tokens still flip on up to 3 of 20
# prompts in CI, greedy and seeded. A sharding bug diverges wholesale instead.
MAX_DIVERGENT_PROMPTS = 3
def _is_sharded_sampling_active(worker) -> bool:
return worker.model_runner.batch_sharder is not None
def test_mtp_sharded_sampling_equivalence(monkeypatch: pytest.MonkeyPatch):
"""Batch-sharded sampling must match replicated sampling under MTP spec
decoding, up to measured near-tie noise."""
tp_size = 2
_skip_if_insufficient_gpus_for_tp(tp_size)
model_name = "Qwen/Qwen3.5-0.8B-Base"
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=20)
with monkeypatch.context() as m:
# Batch-sharded sampling only exists in the V2 model runner.
m.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
# Required for the collective_rpc mode check below.
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
# Queue every request before the first step, so both boots schedule
# the same batches -- see tests/v1/e2e/general/test_sharded_sampling.py.
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
def run(disable_sharding: bool):
llm = LLM(
model=model_name,
tensor_parallel_size=tp_size,
enable_batch_sharded_sampling=not disable_sharding,
speculative_config={
"method": "mtp",
"num_speculative_tokens": 1,
"max_model_len": 2048,
},
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
# More requests than ranks, so round-robin slot ownership
# splits the batch across both ranks.
max_num_seqs=len(test_prompts),
# Timing-based kernel selection is the dominant source of
# cross-boot numeric noise; disable for a tight comparison.
kernel_config={"enable_flashinfer_autotune": False},
)
try:
# Guard against a vacuous comparison: verify every worker is
# in the intended sampling mode.
modes = llm.llm_engine.collective_rpc(_is_sharded_sampling_active)
assert all(mode == (not disable_sharding) for mode in modes)
greedy = llm.chat(test_prompts, greedy_sampling())
seeded = llm.chat(
test_prompts,
SamplingParams(temperature=1.0, seed=33, max_tokens=10),
)
return greedy, seeded
finally:
del llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
wait_for_memory_to_settle()
ref_greedy, ref_seeded = run(disable_sharding=True)
shard_greedy, shard_seeded = run(disable_sharding=False)
# A sharding bug shows up as wholesale divergence, not isolated flips.
for name, ref_outputs, shard_outputs in (
("greedy", ref_greedy, shard_greedy),
("seeded", ref_seeded, shard_seeded),
):
divergent = []
for i, (ref, out) in enumerate(zip(ref_outputs, shard_outputs)):
if list(ref.outputs[0].token_ids) != list(out.outputs[0].token_ids):
divergent.append(i)
print(
f"{name} prompt {i} diverged:\n"
f" replicated: {ref.outputs[0].text!r}\n"
f" sharded: {out.outputs[0].text!r}"
)
assert len(divergent) <= MAX_DIVERGENT_PROMPTS, (
f"{name}: {len(divergent)}/{len(ref_outputs)} prompts diverged "
f"at {divergent}, beyond near-tie noise"
)
@@ -1,136 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU chunked-prefill / prefix-caching correctness for linear-attention models."""
import os
import pytest
from tests.models.utils import check_logprobs_close
from vllm import LLM, SamplingParams
from vllm.inputs import TokensPrompt
from vllm.platforms import current_platform
pytestmark = pytest.mark.cpu_model
if not current_platform.is_cpu():
pytest.skip("skipping CPU-only tests", allow_module_level=True)
# Bound the KV cache so the run does not scale with host memory; these engines
# only need a few thousand tokens.
os.environ.setdefault("VLLM_CPU_KVCACHE_SPACE", "1")
MODEL = "Qwen/Qwen3.5-0.8B"
CHUNK_TOKENS = 128 # max_num_batched_tokens for the chunked engine
NUM_LOGPROBS = 5
SP = SamplingParams(max_tokens=32, temperature=0, logprobs=NUM_LOGPROBS)
def _long_prompt(repeat: int) -> str:
return "Solve the following arithmetic step by step. " * repeat + "What is 7*8?"
# Prompts long enough to span several CHUNK_TOKENS-sized chunks; a single-chunk
# prompt is bit-identical to full prefill regardless of the bug.
PROMPTS = [_long_prompt(r) for r in (40, 60, 80)]
# Spans several full cache blocks; prefix caching only reuses complete blocks.
PREFIX_PROMPT = "You are a helpful assistant. " * 230 + " Now answer: what is 2+2?"
def _make_llm(**overrides) -> LLM:
base = dict(
model=MODEL,
dtype="bfloat16",
max_model_len=2048,
enforce_eager=True,
trust_remote_code=True,
)
base.update(overrides)
return LLM(**base)
def _tuples(outputs) -> list[tuple[list[int], str, object]]:
"""(token_ids, text, sample_logprobs) per request, for check_logprobs_close."""
return [
(list(o.outputs[0].token_ids), o.outputs[0].text, o.outputs[0].logprobs)
for o in outputs
]
@pytest.fixture(scope="module")
def full_prefill_refs():
"""Reference (ids, text, logprobs) for PROMPTS and PREFIX_PROMPT, full prefill."""
llm = _make_llm(enable_chunked_prefill=False, enable_prefix_caching=False)
refs = _tuples(llm.generate(PROMPTS, SP))
prefix_ref = _tuples(llm.generate([PREFIX_PROMPT], SP))[0]
del llm
return refs, prefix_ref
def test_chunked_prefill_matches_full_prefill(full_prefill_refs):
"""Batched multi-chunk prefill must stay close to per-prompt full prefill.
Prompts are scheduled together so the scheduler interleaves prefill chunks
across requests (the cross-request path where the accuracy gap was strongest).
"""
refs, _ = full_prefill_refs
llm = _make_llm(
enable_chunked_prefill=True,
max_num_batched_tokens=CHUNK_TOKENS,
enable_prefix_caching=False,
)
got = _tuples(llm.generate(PROMPTS, SP))
del llm
check_logprobs_close(
outputs_0_lst=refs,
outputs_1_lst=got,
name_0="full_prefill",
name_1="chunked_prefill",
)
def test_prefix_cache_hit_matches_cold_cache(full_prefill_refs):
"""A prefix-cache hit must stay close to the cold-cache (reference) output.
The warm run continues prefill from the restored GDN state; the
num_cached_tokens check guards against a vacuous (no-hit) pass.
"""
_, ref = full_prefill_refs
llm = _make_llm(enable_prefix_caching=True)
llm.generate([PREFIX_PROMPT], SP) # prime the cache
warm_out = llm.generate([PREFIX_PROMPT], SP)[0]
warm = _tuples([warm_out])[0]
del llm
assert warm_out.num_cached_tokens > 0, (
"expected a prefix-cache hit but num_cached_tokens=0; "
"PREFIX_PROMPT may be shorter than one cache block"
)
check_logprobs_close(
outputs_0_lst=[ref],
outputs_1_lst=[warm],
name_0="cold_cache",
name_1="warm_cache",
)
def test_prefix_cache_hit_reaches_last_full_block():
"""A repeated prompt must hit every full block of the hybrid block size.
The workers raise the block size to fit the GDN state pages, and the
engine core reruns its config checks after its handshake; the raised size
must survive them, or the prefill's state checkpoint misses the block
boundaries and nothing is reused. One chunk holds the whole prompt.
"""
llm = _make_llm(enable_prefix_caching=True, max_num_batched_tokens=2048)
block_size = llm.llm_engine.vllm_config.cache_config.block_size
# Ends mid-block: only the last full block's state can be reused.
num_tokens = block_size + block_size // 2
assert num_tokens <= 2048
prompt = TokensPrompt(prompt_token_ids=[1000 + i for i in range(num_tokens)])
sp = SamplingParams(max_tokens=1)
hits = [llm.generate(prompt, sp)[0].num_cached_tokens for _ in range(2)]
del llm
assert hits == [0, block_size]
-167
View File
@@ -1,167 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU speculative-decoding end-to-end correctness."""
import os
import pytest
from tests.models.utils import check_logprobs_close
from tests.v1.e2e.spec_decode.utils import compute_acceptance_len
from vllm import LLM, SamplingParams
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
pytestmark = pytest.mark.cpu_model
if not current_platform.is_cpu():
pytest.skip("skipping CPU-only tests", allow_module_level=True)
# Bound the KV cache so the run does not scale with host memory.
os.environ.setdefault("VLLM_CPU_KVCACHE_SPACE", "1")
MODEL = "Qwen/Qwen3-0.6B"
NUM_LOGPROBS = 5
SP = SamplingParams(max_tokens=48, temperature=0, logprobs=NUM_LOGPROBS)
# Repetitive prompts so the ngram proposer finds matches and actually drafts;
# without hits the run is indistinguishable from plain decoding.
PROMPTS = [
"The capital of France is Paris. The capital of Italy is Rome. "
"The capital of Spain is Madrid. The capital of France is",
"def add(a, b):\n return a + b\n\ndef sub(a, b):\n return a - b\n\n"
"def mul(a, b):\n return",
"one two three four five one two three four five one two three four",
]
def _make_llm(**overrides) -> LLM:
base = dict(
model=MODEL,
dtype="bfloat16",
max_model_len=1024,
disable_log_stats=False,
)
base.update(overrides)
return LLM(**base)
def _tuples(outputs) -> list[tuple[list[int], str, object]]:
return [
(list(o.outputs[0].token_ids), o.outputs[0].text, o.outputs[0].logprobs)
for o in outputs
]
@pytest.fixture(scope="module")
def baseline_refs():
llm = _make_llm()
refs = _tuples(llm.generate(PROMPTS, SP))
del llm
return refs
def _spec_metric(llm: LLM, name: str) -> float:
for metric in llm.get_metrics():
if metric.name == name:
return float(getattr(metric, "value", 0.0))
return 0.0
def test_ngram_spec_decode_matches_baseline(baseline_refs):
"""Greedy output must be unchanged by speculative decoding.
The drafted-token check keeps the test from passing vacuously when the
proposer silently produces nothing.
"""
llm = _make_llm(
speculative_config={
"method": "ngram",
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": 3,
},
)
got = _tuples(llm.generate(PROMPTS, SP))
drafted = _spec_metric(llm, "vllm:spec_decode_num_draft_tokens")
accepted = _spec_metric(llm, "vllm:spec_decode_num_accepted_tokens")
del llm
assert drafted > 0, "ngram proposer drafted no tokens; the test would be vacuous"
assert accepted > 0, f"no draft tokens accepted out of {drafted} drafted"
check_logprobs_close(
outputs_0_lst=baseline_refs,
outputs_1_lst=got,
name_0="no_spec_decode",
name_1="ngram_spec_decode",
)
SMOKE_PROMPTS = [
"The capital of France is",
"2 + 2 equals",
"In one word, the color of the sky is",
"Q: If a train travels 60 miles in 1.5 hours, what is its average speed?\nA:",
]
SMOKE_SP = SamplingParams(temperature=0.0, max_tokens=32, ignore_eos=True)
# Methods routed to the V2 runner, using the same target/draft pairs as the GPU
# suite. MTP needs no separate draft checkpoint: its speculator layer is
# trained jointly with, and shipped inside, the target model's own weights.
SMOKE_CONFIGS = [
pytest.param(
"meta-llama/Llama-3.2-1B-Instruct",
{
"method": "eagle3",
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
"num_speculative_tokens": 3,
},
id="eagle3",
),
pytest.param(
"Qwen/Qwen3-4B",
{
"method": "dflash",
"model": "z-lab/Qwen3-4B-DFlash-b16",
# The checkpoint allows 16, but accepted tokens plateau around 64
# regardless, so a larger draft only burns CPU on rejected tokens.
"num_speculative_tokens": 4,
},
id="dflash",
),
pytest.param(
"Qwen/Qwen3.5-0.8B",
{
"method": "mtp",
"num_speculative_tokens": 3,
},
id="mtp",
),
]
# Measured 1.85 (eagle3), 1.99 (dflash), 2.29 (mtp) on CPU; this floor leaves
# room for numeric drift while still failing if speculation stops paying off.
MIN_ACCEPTANCE_LEN = 1.5
@pytest.mark.skipif(
not HAS_TRITON, reason="the V2 runner needs triton-cpu, which CI builds"
)
@pytest.mark.parametrize("model,speculative_config", SMOKE_CONFIGS)
def test_v2_speculator_smoke(model: str, speculative_config: dict):
"""Gates that drafts are accepted often enough for speculation to pay off."""
llm = _make_llm(model=model, speculative_config=speculative_config)
try:
assert llm.llm_engine.vllm_config.use_v2_model_runner, (
f"{speculative_config['method']} fell back to the V1 runner; "
"this test is meant to cover the V2 path"
)
llm.generate(SMOKE_PROMPTS, SMOKE_SP)
acceptance = compute_acceptance_len(llm.get_metrics())
assert acceptance >= MIN_ACCEPTANCE_LEN, (
f"acceptance length {acceptance:.3f} below {MIN_ACCEPTANCE_LEN}; "
"drafts are being rejected far more than expected"
)
finally:
del llm
-212
View File
@@ -1,212 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm import SamplingParams
from vllm.platforms import current_platform
from vllm.v1.kv_cache_interface import MambaSpec
from ...utils import large_gpu_mark
QWEN_MODEL = "Qwen/Qwen3.5-4B"
QWEN_KV_CACHE_BYTES = 12 << 30
HYBRID_MTP_MODELS = [
pytest.param(
QWEN_MODEL,
marks=[large_gpu_mark(min_gb=30)],
id="qwen",
),
pytest.param(
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4",
marks=[large_gpu_mark(min_gb=80)]
+ [
pytest.mark.skipif(
not current_platform.is_cuda(),
reason="modelopt quantization is supported only on CUDA",
)
],
id="nemotron",
),
]
# A trivial request with a short prompt to ensure we run a mixed batch
SMALL_MESSAGE = [
{
"role": "user",
"content": "The secret beta value is 64. What is the secret beta?",
}
]
# Sample prompt with a bunch of filler in between the critical fact and the request.
# Both parts need to be processed properly for the model to generate the correct answer
MESSAGES = [
{
"role": "user",
"content": (
"Important: The secret number is 42. "
"The sky is green in this hypothetical world. "
"Apples grow on trees in the forest. "
"Rivers flow through the valleys and mountains. "
"Birds sing songs in the early morning light. "
"The weather today is sunny with clear skies ahead. "
"Flowers bloom in the garden during spring season. "
"Now answer with ONLY the number and nothing else: "
"What is the secret number plus one?"
),
}
]
@pytest.mark.parametrize(
"model_name",
HYBRID_MTP_MODELS,
)
@pytest.mark.parametrize("enable_prefix_caching", [False, True])
def test_mtp_speculative_mixed_batch_short_prefill(
vllm_runner, model_name, enable_prefix_caching
):
"""Test to ensure MTP speculative decoding correctly handles
short prefill chunks that fall below the reorder_batch_threshold."""
# Set so large that both prefills will be classified as decodes in a mixed batch
# note, with prefix caching we require chunk_size >= mamba_block_size
chunk_size = 256 if not enable_prefix_caching else 2048
num_draft_tokens = 100
with vllm_runner(
model_name,
speculative_config={
"method": "mtp",
"num_speculative_tokens": num_draft_tokens,
},
max_num_batched_tokens=chunk_size,
max_num_seqs=4,
max_model_len=512,
kv_cache_memory_bytes=QWEN_KV_CACHE_BYTES if model_name == QWEN_MODEL else None,
enforce_eager=True,
tensor_parallel_size=1,
trust_remote_code=True,
enable_chunked_prefill=True,
enable_prefix_caching=enable_prefix_caching,
) as llm:
sampling_params = SamplingParams(
temperature=0.0,
max_tokens=128,
)
# First small message gets prefilled first, under normal conditions since the
# batch is not yet mixed. Then the second prefill arrives as a mixed batch, but
# is shorter than num_speculative_tokens, so it gets misclassified as a decode
# and processed with the wrong state management logic, causing the critical
# fact from the first chunk to be lost and the model to generate nonsense.
outputs = llm.get_llm().chat(
[SMALL_MESSAGE, MESSAGES],
sampling_params,
chat_template_kwargs={"enable_thinking": False},
)
responses = []
for output in outputs:
generated_text = output.outputs[0].text
print(f"Generated text: {generated_text!r}")
responses.append(generated_text)
assert "64" in responses[0], (
"The first response should contain the correct value of 64."
)
assert "43" in responses[1], (
"The second response should contain the correct value of 42+1=43."
)
def _get_mamba_block_size(llm) -> int:
scheduler = llm.llm_engine.engine_core.engine_core.scheduler
block_sizes = {
group.kv_cache_spec.block_size
for group in scheduler.kv_cache_config.kv_cache_groups
if isinstance(group.kv_cache_spec, MambaSpec)
}
assert len(block_sizes) == 1
block_size = block_sizes.pop()
assert scheduler.cache_config.block_size == block_size
return block_size
def _build_access_code_manual(tokenizer, target_tokens: int) -> tuple[str, list[str]]:
codes = ["605341", "693278", "597596", "751982"]
header = "Memorize this facility manual and its access codes.\n\n"
facts = "".join(
f"The access code for vault-{i:02d} is {code}.\n"
for i, code in enumerate(codes)
)
filler = "Routine facility inspections are recorded in the audit ledger every day. "
manual = header + facts
while len(tokenizer.encode(manual)) < target_tokens:
manual = header + filler + manual.removeprefix(header)
return manual, codes
@large_gpu_mark(min_gb=30)
def test_qwen_mtp_mamba_prefix_cache_hit_is_bounded(vllm_runner, monkeypatch):
"""MTP must not extend a hybrid Mamba hit past the attention hit."""
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
with vllm_runner(
QWEN_MODEL,
tensor_parallel_size=1,
max_model_len=8192,
kv_cache_memory_bytes=QWEN_KV_CACHE_BYTES,
block_size=None,
enforce_eager=True,
enable_chunked_prefill=True,
enable_prefix_caching=True,
speculative_config={"method": "mtp", "num_speculative_tokens": 2},
) as runner:
llm = runner.get_llm()
block_size = _get_mamba_block_size(llm)
manual, codes = _build_access_code_manual(
llm.get_tokenizer(), 2 * block_size - 192
)
manual_tokens = len(llm.get_tokenizer().encode(manual))
assert block_size < manual_tokens < 2 * block_size
wave1_prompts = [
manual
+ f"\nDescribe the audit procedure for vault-{i:02d} in detail.\nAnswer:"
for i in range(len(codes))
]
decode_tokens = 2 * block_size - manual_tokens + 96
wave1_params = SamplingParams(
temperature=0.0,
min_tokens=decode_tokens,
max_tokens=decode_tokens,
ignore_eos=True,
)
wave1_outputs = llm.generate(wave1_prompts, wave1_params)
wave2_prompts = [
prompt
+ output.outputs[0].text
+ f"\n\nWhat is the access code for vault-{i:02d}? Answer:"
for i, (prompt, output) in enumerate(zip(wave1_prompts, wave1_outputs))
]
warm_params = SamplingParams(temperature=0.0, max_tokens=24, stop=["\n"])
cold_params = SamplingParams(
temperature=0.0,
max_tokens=24,
stop=["\n"],
skip_reading_prefix_cache=True,
)
warm_outputs = llm.generate(wave2_prompts, warm_params)
cold_outputs = llm.generate(wave2_prompts, cold_params)
cached_tokens = [output.num_cached_tokens for output in warm_outputs]
assert max(cached_tokens) == block_size
for arm, outputs in (("warm", warm_outputs), ("cold", cold_outputs)):
missed = [
i
for i, (code, output) in enumerate(zip(codes, outputs))
if code not in output.outputs[0].text
]
assert not missed, f"{arm} cache missed access codes for prompts {missed}"