[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}")