[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:
@@ -1,321 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import json
|
||||
import time
|
||||
from concurrent.futures import Future
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm.config import StructuredOutputsConfig, VllmConfig
|
||||
from vllm.config.model import ModelConfig
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
from vllm.config.speculative import SpeculativeConfig
|
||||
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
|
||||
from vllm.tokenizers import get_tokenizer
|
||||
from vllm.v1.request import Request
|
||||
from vllm.v1.structured_output import StructuredOutputManager
|
||||
from vllm.v1.structured_output.backend_guidance import (
|
||||
GuidanceBackend,
|
||||
process_for_additional_properties,
|
||||
)
|
||||
from vllm.v1.structured_output.backend_types import StructuredOutputOptions
|
||||
|
||||
TOKENIZER = "openai-community/gpt2"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def mistral_tokenizer():
|
||||
return get_tokenizer(
|
||||
tokenizer_name="mistralai/Mistral-Small-3.2-24B-Instruct-2506",
|
||||
tokenizer_mode="mistral",
|
||||
)
|
||||
|
||||
|
||||
def test_backend_guidance_rollback_terminated():
|
||||
# Test that the backend guidance successfully rollbacks from a
|
||||
# terminated state. This can happen with speculative decoding,
|
||||
# where the draft model proposes EOS and it is verified by the
|
||||
# guidance backend. In that case we are in a stopped state, but
|
||||
# it should be reverted in case EOS is not accepted by the target
|
||||
# model.
|
||||
structured_outputs_config = StructuredOutputsConfig(backend="guidance")
|
||||
vllm_config = VllmConfig(structured_outputs_config=structured_outputs_config)
|
||||
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
|
||||
|
||||
backend = GuidanceBackend(
|
||||
vllm_config,
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=50257,
|
||||
)
|
||||
|
||||
grammar = backend.compile_grammar(
|
||||
StructuredOutputOptions.JSON, '{"type": "object"}'
|
||||
)
|
||||
|
||||
prompt = tokenizer.encode('{"a": "b"}')
|
||||
assert len(prompt) > 1
|
||||
dummy_wrong = tokenizer.encode('{"a"}')
|
||||
for token in prompt:
|
||||
assert grammar.accept_tokens("", [token])
|
||||
assert not grammar.is_terminated()
|
||||
assert grammar.accept_tokens("", [tokenizer.eos_token_id])
|
||||
assert grammar.is_terminated()
|
||||
# Giving any other token should also be accepted
|
||||
assert grammar.accept_tokens("", dummy_wrong)
|
||||
# Rollback is done from where state was terminated, so from '}' not EOS
|
||||
grammar.rollback(len(prompt) - 1)
|
||||
assert not grammar.is_terminated()
|
||||
assert grammar.validate_tokens([tokenizer.eos_token_id]) == []
|
||||
assert grammar.validate_tokens(dummy_wrong) != dummy_wrong
|
||||
assert grammar.accept_tokens("", prompt[1:])
|
||||
assert not grammar.is_terminated()
|
||||
assert grammar.accept_tokens("", [tokenizer.eos_token_id])
|
||||
assert grammar.is_terminated()
|
||||
# Rollback of <= 0 should not change the terminated state
|
||||
grammar.rollback(0)
|
||||
assert grammar.is_terminated()
|
||||
grammar.rollback(-1)
|
||||
assert grammar.is_terminated()
|
||||
|
||||
|
||||
def test_grammar_bitmask_with_specdec():
|
||||
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
|
||||
prompt = tokenizer.encode('{"a": "b"}')
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(tokenizer=TOKENIZER),
|
||||
structured_outputs_config=StructuredOutputsConfig(backend="guidance"),
|
||||
speculative_config=SpeculativeConfig(model="[ngram]", num_speculative_tokens=3),
|
||||
)
|
||||
structured_output_manager = StructuredOutputManager(vllm_config)
|
||||
|
||||
for i in range(1, 2):
|
||||
sampling_params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(
|
||||
json='{"type": "object"}',
|
||||
),
|
||||
)
|
||||
sampling_params.structured_outputs._backend = "guidance" # type: ignore[union-attr]
|
||||
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
|
||||
|
||||
my_req_id = f"my_req_id_{i}"
|
||||
request = Request(
|
||||
my_req_id,
|
||||
prompt_token_ids=prompt[:i],
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
)
|
||||
|
||||
structured_output_manager.grammar_init(request)
|
||||
|
||||
def grammar_bitmask(req: Request, tokens: list[int]) -> None:
|
||||
structured_output_manager.grammar_bitmask(
|
||||
requests={req.request_id: req},
|
||||
structured_output_request_ids=[req.request_id],
|
||||
scheduled_spec_decode_tokens={req.request_id: tokens},
|
||||
)
|
||||
# At this point, we rolled-back, so should not be terminated
|
||||
assert req.structured_output_request is not None
|
||||
grammar = req.structured_output_request.grammar
|
||||
assert grammar is not None and not isinstance(grammar, Exception)
|
||||
assert not grammar.is_terminated()
|
||||
|
||||
# The grammar might not yet be compiled, so we wait for it
|
||||
assert request.structured_output_request is not None
|
||||
while not request.structured_output_request._check_grammar_completion():
|
||||
continue
|
||||
|
||||
grammar = request.structured_output_request.grammar
|
||||
assert grammar is not None and not isinstance(grammar, Exception)
|
||||
assert grammar.accept_tokens(request.request_id, prompt[:i])
|
||||
|
||||
grammar_bitmask(request, prompt[i:] + [tokenizer.eos_token_id])
|
||||
grammar_bitmask(
|
||||
request, prompt[i:] + [tokenizer.eos_token_id] + prompt
|
||||
) # EOS not the final token
|
||||
grammar_bitmask(request, prompt[i:]) # EOS not present
|
||||
grammar_bitmask(request, prompt[i:] + [tokenizer.eos_token_id])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_grammar", [True, False])
|
||||
def test_grammar_init_async_and_sync(async_grammar):
|
||||
"""Test grammar initialization works correctly in both async and sync modes.
|
||||
|
||||
This test validates that the distributed_executor_backend config option
|
||||
correctly controls whether grammar compilation happens asynchronously
|
||||
(via executor.submit) or synchronously. When set to "external_launcher",
|
||||
grammar compilation is synchronous to avoid deadlocks.
|
||||
"""
|
||||
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
|
||||
prompt = tokenizer.encode('{"a": "b"}')
|
||||
|
||||
# Use "external_launcher" for sync mode, None for async mode
|
||||
executor_backend = None if async_grammar else "external_launcher"
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(tokenizer=TOKENIZER),
|
||||
structured_outputs_config=StructuredOutputsConfig(backend="guidance"),
|
||||
parallel_config=ParallelConfig(distributed_executor_backend=executor_backend),
|
||||
)
|
||||
structured_output_manager = StructuredOutputManager(vllm_config)
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(
|
||||
json='{"type": "object"}',
|
||||
),
|
||||
)
|
||||
sampling_params.structured_outputs._backend = "guidance" # type: ignore[union-attr]
|
||||
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
|
||||
|
||||
request = Request(
|
||||
"test_request",
|
||||
prompt_token_ids=prompt,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
)
|
||||
|
||||
structured_output_manager.grammar_init(request)
|
||||
|
||||
# Check the internal _grammar type immediately after init
|
||||
# Before _check_grammar_completion is called, async mode should have a Future
|
||||
assert request.structured_output_request is not None
|
||||
raw_grammar = request.structured_output_request._grammar
|
||||
if async_grammar:
|
||||
assert isinstance(raw_grammar, Future), (
|
||||
"Async mode should store a Future before completion"
|
||||
)
|
||||
else:
|
||||
assert not isinstance(raw_grammar, Future), (
|
||||
"Sync mode should store the grammar directly, not a Future"
|
||||
)
|
||||
|
||||
# Wait for grammar to be ready (handles both async and sync cases)
|
||||
start_time = time.time()
|
||||
while not request.structured_output_request._check_grammar_completion():
|
||||
if time.time() - start_time > 5: # 5-second timeout
|
||||
pytest.fail("Grammar compilation timed out")
|
||||
time.sleep(0.01)
|
||||
|
||||
# After completion, _grammar should no longer be a Future
|
||||
assert not isinstance(request.structured_output_request._grammar, Future)
|
||||
|
||||
# Verify grammar is properly initialized and functional
|
||||
grammar = request.structured_output_request.grammar
|
||||
assert grammar is not None and not isinstance(grammar, Exception)
|
||||
assert not grammar.is_terminated()
|
||||
|
||||
# Verify the grammar can accept valid tokens
|
||||
assert grammar.accept_tokens(request.request_id, prompt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"request_type,grammar_spec",
|
||||
[
|
||||
pytest.param(
|
||||
StructuredOutputOptions.JSON,
|
||||
'{"type": "object"}',
|
||||
id="json",
|
||||
),
|
||||
pytest.param(
|
||||
StructuredOutputOptions.GRAMMAR,
|
||||
'start: "hello" | "world"',
|
||||
id="lark",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_mistral_tokenizer_compile_grammar(
|
||||
mistral_tokenizer,
|
||||
request_type: StructuredOutputOptions,
|
||||
grammar_spec: str,
|
||||
) -> None:
|
||||
vllm_config = VllmConfig(
|
||||
structured_outputs_config=StructuredOutputsConfig(backend="guidance"),
|
||||
)
|
||||
backend = GuidanceBackend(
|
||||
vllm_config,
|
||||
tokenizer=mistral_tokenizer,
|
||||
vocab_size=mistral_tokenizer.vocab_size,
|
||||
)
|
||||
assert backend.ll_tokenizer is mistral_tokenizer.llg_tokenizer
|
||||
|
||||
grammar = backend.compile_grammar(request_type, grammar_spec)
|
||||
assert grammar is not None
|
||||
assert not grammar.is_terminated()
|
||||
|
||||
|
||||
def test_process_for_additional_properties_preserves_literals() -> None:
|
||||
"""Literal values under const/enum/default/examples must not be rewritten
|
||||
when they contain a 'properties' or 'patternProperties' key (#58695)."""
|
||||
feature = {
|
||||
"type": "Feature",
|
||||
"geometry": None,
|
||||
"properties": {"name": "HQ"},
|
||||
"patternProperties": {"^x": "y"},
|
||||
}
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"const_field": {"const": feature},
|
||||
"enum_field": {"enum": [feature]},
|
||||
"default_field": {"type": "object", "default": feature},
|
||||
"examples_field": {"type": "object", "examples": [feature]},
|
||||
"properties": {"type": "string"},
|
||||
"const": {
|
||||
"type": "object",
|
||||
"properties": {"id": {"type": "integer"}},
|
||||
},
|
||||
},
|
||||
"$defs": {
|
||||
"item": {
|
||||
"type": "object",
|
||||
"properties": {"label": {"type": "string"}},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
processed = process_for_additional_properties(schema)
|
||||
|
||||
assert processed["additionalProperties"] is False
|
||||
assert processed["$defs"]["item"]["additionalProperties"] is False
|
||||
assert processed["properties"]["const"]["additionalProperties"] is False
|
||||
assert "additionalProperties" not in processed["properties"]
|
||||
assert processed["properties"]["const_field"]["const"] == feature
|
||||
assert processed["properties"]["enum_field"]["enum"] == [feature]
|
||||
assert processed["properties"]["default_field"]["default"] == feature
|
||||
assert processed["properties"]["examples_field"]["examples"] == [feature]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keyword", ["const", "enum"])
|
||||
def test_disable_additional_properties_accepts_literal_with_properties_key(
|
||||
keyword: str,
|
||||
) -> None:
|
||||
"""GuidanceBackend with disable_additional_properties=True must accept the
|
||||
original literal value under const/enum and reject injected
|
||||
additionalProperties (#58695)."""
|
||||
feature = {"type": "Feature", "geometry": None, "properties": {"name": "HQ"}}
|
||||
rewritten = {**feature, "additionalProperties": False}
|
||||
schema = {keyword: feature if keyword == "const" else [feature]}
|
||||
|
||||
vllm_config = VllmConfig(
|
||||
structured_outputs_config=StructuredOutputsConfig(
|
||||
backend="guidance",
|
||||
disable_additional_properties=True,
|
||||
)
|
||||
)
|
||||
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
|
||||
backend = GuidanceBackend(
|
||||
vllm_config,
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=50257,
|
||||
)
|
||||
grammar = backend.compile_grammar(
|
||||
StructuredOutputOptions.JSON,
|
||||
json.dumps(schema),
|
||||
)
|
||||
|
||||
valid_tokens = tokenizer.encode(json.dumps(feature)) + [tokenizer.eos_token_id]
|
||||
rewritten_tokens = tokenizer.encode(json.dumps(rewritten)) + [
|
||||
tokenizer.eos_token_id
|
||||
]
|
||||
|
||||
assert grammar.validate_tokens(valid_tokens) == valid_tokens
|
||||
assert grammar.validate_tokens(rewritten_tokens) != rewritten_tokens
|
||||
@@ -1,117 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import xgrammar as xgr
|
||||
|
||||
from vllm.config import StructuredOutputsConfig, VllmConfig
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionToolsParam,
|
||||
)
|
||||
from vllm.parser.plamo3 import (
|
||||
BEGIN_TOOL_ARGUMENTS,
|
||||
BEGIN_TOOL_NAME,
|
||||
BEGIN_TOOL_REQUEST,
|
||||
BEGIN_TOOL_REQUESTS,
|
||||
END_TOOL_ARGUMENTS,
|
||||
END_TOOL_NAME,
|
||||
END_TOOL_REQUEST,
|
||||
END_TOOL_REQUESTS,
|
||||
)
|
||||
from vllm.tool_parsers.structural_tag_registry import get_model_structural_tag
|
||||
from vllm.v1.structured_output.backend_types import StructuredOutputOptions
|
||||
from vllm.v1.structured_output.backend_xgrammar import XgrammarBackend
|
||||
|
||||
|
||||
class Plamo3Tokenizer:
|
||||
"""Minimal stand-in for PLaMo's remote-code PythonBackend tokenizer."""
|
||||
|
||||
eos_token_id = 0
|
||||
|
||||
def __init__(self, tokens: list[str]) -> None:
|
||||
self._vocab = {token: token_id for token_id, token in enumerate(tokens)}
|
||||
|
||||
def get_vocab(self) -> dict[str, int]:
|
||||
return self._vocab
|
||||
|
||||
def init_xgrammar(self):
|
||||
stop_token_ids = [self.eos_token_id]
|
||||
tokenizer_info = xgr.TokenizerInfo(
|
||||
encoded_vocab=list(self._vocab),
|
||||
vocab_type=xgr.VocabType.BYTE_FALLBACK,
|
||||
vocab_size=len(self._vocab),
|
||||
stop_token_ids=stop_token_ids,
|
||||
)
|
||||
return tokenizer_info, stop_token_ids
|
||||
|
||||
|
||||
def make_vllm_config() -> VllmConfig:
|
||||
config = VllmConfig(
|
||||
structured_outputs_config=StructuredOutputsConfig(backend="xgrammar"),
|
||||
)
|
||||
config.model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(model_type="plamo3")
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def test_plamo3_python_tokenizer_compiles_and_accepts_structural_tag():
|
||||
call_tokens = [
|
||||
BEGIN_TOOL_REQUESTS,
|
||||
BEGIN_TOOL_REQUEST,
|
||||
BEGIN_TOOL_NAME,
|
||||
"get_weather",
|
||||
END_TOOL_NAME,
|
||||
BEGIN_TOOL_ARGUMENTS,
|
||||
'{"city":"Tokyo"}',
|
||||
END_TOOL_ARGUMENTS,
|
||||
END_TOOL_REQUEST,
|
||||
END_TOOL_REQUESTS,
|
||||
]
|
||||
tokenizer = Plamo3Tokenizer(["<eos>", *call_tokens])
|
||||
backend = XgrammarBackend(
|
||||
make_vllm_config(),
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=len(tokenizer.get_vocab()),
|
||||
)
|
||||
tools = [
|
||||
ChatCompletionToolsParam(
|
||||
type="function",
|
||||
function={
|
||||
"name": "get_weather",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
"strict": True,
|
||||
},
|
||||
)
|
||||
]
|
||||
tag = get_model_structural_tag("plamo3", tools, "required", reasoning=False)
|
||||
assert tag is not None
|
||||
|
||||
grammar = backend.compile_grammar(
|
||||
StructuredOutputOptions.STRUCTURAL_TAG,
|
||||
tag.model_dump_json(),
|
||||
)
|
||||
token_ids = [tokenizer.get_vocab()[token] for token in call_tokens]
|
||||
assert grammar.accept_tokens("plamo3", token_ids)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ['"', "あ"])
|
||||
def test_plamo3_grammar_matches_decoded_bytes(value):
|
||||
pieces = [f"<0x{byte:02X}>" for byte in value.encode("utf-8")]
|
||||
tokenizer = Plamo3Tokenizer(list(dict.fromkeys(["<eos>", value, *pieces])))
|
||||
backend = XgrammarBackend(
|
||||
make_vllm_config(),
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=len(tokenizer.get_vocab()),
|
||||
)
|
||||
for tokens in ([value], pieces):
|
||||
grammar = backend.compile_grammar(StructuredOutputOptions.REGEX, value)
|
||||
assert grammar.accept_tokens(
|
||||
"plamo3", [tokenizer.get_vocab()[token] for token in tokens]
|
||||
)
|
||||
@@ -1,439 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Request-time validation of structured output requests."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from transformers import MistralCommonBackend, TokenizersBackend
|
||||
|
||||
from vllm.config import StructuredOutputsConfig
|
||||
from vllm.exceptions import VLLMClientError, VLLMValidationError
|
||||
from vllm.sampling_params import (
|
||||
MAX_STRUCTURED_OUTPUT_JSON_NESTING,
|
||||
STRUCTURAL_TAG_WRAPPER_NESTING,
|
||||
SamplingParams,
|
||||
StructuredOutputsParams,
|
||||
)
|
||||
from vllm.tokenizers import mistral as mistral_tokenizers
|
||||
from vllm.v1.structured_output import backend_guidance
|
||||
from vllm.v1.structured_output.backend_lm_format_enforcer import (
|
||||
validate_structured_output_request_lm_format_enforcer,
|
||||
)
|
||||
from vllm.v1.structured_output.backend_outlines import (
|
||||
validate_structured_output_request_outlines,
|
||||
)
|
||||
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
JSON_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"invoice_id": {"type": "string"},
|
||||
"customer": {"type": "string"},
|
||||
},
|
||||
"required": ["invoice_id", "customer"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
class _StubModelConfig:
|
||||
def __init__(self, is_diffusion: bool):
|
||||
self.is_diffusion = is_diffusion
|
||||
|
||||
|
||||
def test_structured_outputs_rejected_for_diffusion_models():
|
||||
"""Diffusion LLMs denoise the canvas in parallel, which is incompatible
|
||||
with the token-by-token grammar FSM. The request must fail with a clear
|
||||
validation error instead of an FSM rejection mid-generation (#45436)."""
|
||||
params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(json=JSON_SCHEMA)
|
||||
)
|
||||
with pytest.raises(VLLMValidationError, match="not yet supported for diffusion"):
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=True),
|
||||
StructuredOutputsConfig(),
|
||||
tokenizer=None,
|
||||
)
|
||||
|
||||
|
||||
def test_plain_request_allowed_for_diffusion_models():
|
||||
"""Requests without structured outputs are unaffected by the guard."""
|
||||
params = SamplingParams()
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=True),
|
||||
StructuredOutputsConfig(),
|
||||
tokenizer=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"structured_outputs, match",
|
||||
[
|
||||
(StructuredOutputsParams(json_object=False), "json_object must be True"),
|
||||
(StructuredOutputsParams(json=""), "json cannot be an empty string"),
|
||||
(
|
||||
StructuredOutputsParams(structural_tag=""),
|
||||
"structural_tag cannot be an empty string",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_degenerate_structured_outputs_rejected(structured_outputs, match):
|
||||
"""json_object=False and an empty json schema pass the `is not None`
|
||||
exclusivity check but resolve to no structured-output key, so they must be
|
||||
rejected at request validation (-> 400). Empty `structural_tag` is rejected
|
||||
for the same reason: `json.loads("")` in `compile_grammar` would otherwise
|
||||
raise JSONDecodeError and surface as a per-request engine error."""
|
||||
params = SamplingParams(structured_outputs=structured_outputs)
|
||||
with pytest.raises(VLLMValidationError, match=match):
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(),
|
||||
tokenizer=object(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"regex",
|
||||
[
|
||||
"\x00", # a lone leading NUL
|
||||
"\x00\x01\x02\x1f", # a NUL followed by other control chars
|
||||
"[0-9]\x00", # an embedded NUL
|
||||
],
|
||||
)
|
||||
def test_regex_with_nul_byte_rejected(regex):
|
||||
"""A NUL byte is never meaningful in a structured-outputs regex and is not
|
||||
handled by xgrammar's native regex converter. It must be rejected at request
|
||||
validation in every backend mode (a clean 400), instead of reaching that
|
||||
native code or silently falling back to another backend in the default
|
||||
'auto' mode."""
|
||||
params = SamplingParams(structured_outputs=StructuredOutputsParams(regex=regex))
|
||||
|
||||
# Rejected before backend selection, so it is a 400 even in 'auto' mode
|
||||
# (which would otherwise catch the error and fall back to another backend).
|
||||
with pytest.raises(VLLMValidationError, match="NUL"):
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(),
|
||||
tokenizer=object(),
|
||||
)
|
||||
|
||||
# The xgrammar backend also rejects it directly (defense in depth), before
|
||||
# the pattern reaches the native from_regex call.
|
||||
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
|
||||
|
||||
with pytest.raises(ValueError, match="NUL"):
|
||||
validate_xgrammar_grammar(params)
|
||||
|
||||
|
||||
def _nested_array_schema(levels: int) -> str:
|
||||
# Built as text: json.dumps on a deeply nested dict would itself recurse.
|
||||
wrappers = levels - 1
|
||||
return (
|
||||
'{"type": "array", "items": ' * wrappers + '{"type": "string"}' + "}" * wrappers
|
||||
)
|
||||
|
||||
|
||||
def _structural_tag(schema: str) -> str:
|
||||
return (
|
||||
'{"type": "structural_tag", "format": {"type": "json_schema", '
|
||||
f'"json_schema": {schema}}}}}'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"structured_outputs",
|
||||
[
|
||||
pytest.param(
|
||||
{"json": _nested_array_schema(MAX_STRUCTURED_OUTPUT_JSON_NESTING + 1)},
|
||||
id="json-str-over-limit",
|
||||
),
|
||||
pytest.param(
|
||||
{"json": json.loads(_nested_array_schema(2_000))},
|
||||
id="json-dict-past-recursion-limit",
|
||||
),
|
||||
pytest.param(
|
||||
{"json": _nested_array_schema(200_000)},
|
||||
id="json-str-past-json-loads-recursion-limit",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"structural_tag": _structural_tag(
|
||||
_nested_array_schema(
|
||||
MAX_STRUCTURED_OUTPUT_JSON_NESTING
|
||||
+ STRUCTURAL_TAG_WRAPPER_NESTING
|
||||
)
|
||||
)
|
||||
},
|
||||
id="structural-tag-over-limit",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"backend", ["auto", "xgrammar", "guidance", "outlines", "lm-format-enforcer"]
|
||||
)
|
||||
def test_deeply_nested_schema_rejected(structured_outputs, backend):
|
||||
"""Converting a schema to a grammar gets steeply more expensive with nesting
|
||||
and runs on the API server; past the recursion limit it used to escape as a
|
||||
RecursionError (HTTP 500 with an empty message). Deep nesting must be a
|
||||
validation error before any backend touches the schema."""
|
||||
params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(**structured_outputs)
|
||||
)
|
||||
with pytest.raises(VLLMValidationError, match="nested too deeply"):
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(backend=backend),
|
||||
tokenizer=object(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["json", "structural_tag"])
|
||||
def test_xgrammar_validation_rejects_deeply_nested_schema(field):
|
||||
"""Request parsing and tool parsers call validate_xgrammar_grammar directly,
|
||||
before _validate_structured_outputs, so it must check nesting itself."""
|
||||
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
|
||||
|
||||
schema = _nested_array_schema(2_000)
|
||||
value = _structural_tag(schema) if field == "structural_tag" else schema
|
||||
params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(**{field: value})
|
||||
)
|
||||
with pytest.raises(VLLMValidationError, match="nested too deeply"):
|
||||
validate_xgrammar_grammar(params)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["json", "structural_tag"])
|
||||
def test_schema_at_nesting_limit_accepted(field):
|
||||
"""A structural tag wraps its schema in a few more levels (more for the
|
||||
tags tool parsers generate), which must not count against the schema."""
|
||||
schema = _nested_array_schema(MAX_STRUCTURED_OUTPUT_JSON_NESTING)
|
||||
value = _structural_tag(schema) if field == "structural_tag" else schema
|
||||
structured_outputs = StructuredOutputsParams(**{field: value})
|
||||
SamplingParams(structured_outputs=structured_outputs)._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(),
|
||||
tokenizer=object(),
|
||||
)
|
||||
assert structured_outputs._backend == "xgrammar"
|
||||
|
||||
|
||||
INVALID_JSON_SCHEMA = {"type": "object", "properties": {"name": {"type": "str"}}}
|
||||
STRUCTURAL_TAG = (
|
||||
'{"type": "structural_tag", "format": {"type": "const_string", "value": "hi"}}'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend, structured_outputs",
|
||||
[
|
||||
("xgrammar", StructuredOutputsParams(json=INVALID_JSON_SCHEMA)),
|
||||
("outlines", StructuredOutputsParams(json=INVALID_JSON_SCHEMA)),
|
||||
("auto", StructuredOutputsParams(json=INVALID_JSON_SCHEMA)),
|
||||
("auto", StructuredOutputsParams(json='{"type": ')),
|
||||
("xgrammar", StructuredOutputsParams(grammar="not a grammar")),
|
||||
("guidance", StructuredOutputsParams(grammar="not a grammar")),
|
||||
("lm-format-enforcer", StructuredOutputsParams(grammar="not a grammar")),
|
||||
("outlines", StructuredOutputsParams(regex="(")),
|
||||
("guidance", StructuredOutputsParams(structural_tag='{"nope": 1}')),
|
||||
("outlines", StructuredOutputsParams(structural_tag=STRUCTURAL_TAG)),
|
||||
("lm-format-enforcer", StructuredOutputsParams(structural_tag=STRUCTURAL_TAG)),
|
||||
("outlines", StructuredOutputsParams(json_object=True)),
|
||||
],
|
||||
)
|
||||
def test_unsupported_grammar_is_a_client_error(backend, structured_outputs):
|
||||
"""Only `VLLMClientError` survives `AsyncLLM.generate` untouched; anything else
|
||||
is wrapped in `EngineGenerateError` and served as a 500 instead of a 400."""
|
||||
params = SamplingParams(structured_outputs=structured_outputs)
|
||||
with pytest.raises(VLLMClientError):
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(backend=backend),
|
||||
tokenizer=object(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend, structured_outputs",
|
||||
[
|
||||
("xgrammar", StructuredOutputsParams(json_object=True)),
|
||||
("xgrammar", StructuredOutputsParams(regex="[0-9]+")),
|
||||
("xgrammar", StructuredOutputsParams(regex="")),
|
||||
("xgrammar", StructuredOutputsParams(json={})),
|
||||
("lm-format-enforcer", StructuredOutputsParams(json_object=True)),
|
||||
("lm-format-enforcer", StructuredOutputsParams(regex="")),
|
||||
("lm-format-enforcer", StructuredOutputsParams(json={})),
|
||||
("outlines", StructuredOutputsParams(regex="")),
|
||||
("outlines", StructuredOutputsParams(json={})),
|
||||
],
|
||||
)
|
||||
def test_supported_spec_is_not_rejected(backend, structured_outputs):
|
||||
"""Supported specs, including the falsy but valid regex="" and json={}, must
|
||||
not reach the validators' final rejection."""
|
||||
params = SamplingParams(structured_outputs=structured_outputs)
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(backend=backend),
|
||||
tokenizer=object(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"validate",
|
||||
[
|
||||
validate_structured_output_request_outlines,
|
||||
validate_structured_output_request_lm_format_enforcer,
|
||||
validate_xgrammar_grammar,
|
||||
],
|
||||
ids=["outlines", "lm-format-enforcer", "xgrammar"],
|
||||
)
|
||||
def test_unhandled_spec_is_a_validation_error(validate):
|
||||
"""json_object=False is rejected before backend selection, so only a direct
|
||||
validator call reaches the final branch; it must still be a 400."""
|
||||
params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(json_object=False)
|
||||
)
|
||||
with pytest.raises(VLLMValidationError, match="does not support this"):
|
||||
validate(params)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"schema, expected_backend",
|
||||
[
|
||||
# multipleOf is unsupported by xgrammar.
|
||||
(
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"n": {"type": "integer", "multipleOf": 2}},
|
||||
},
|
||||
"guidance",
|
||||
),
|
||||
(
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"n": {"type": ["number", "null"], "multipleOf": 3}},
|
||||
},
|
||||
"guidance",
|
||||
),
|
||||
(
|
||||
{
|
||||
"type": ["string", "null"],
|
||||
"pattern": "^a+$",
|
||||
"maxLength": 2,
|
||||
},
|
||||
"guidance",
|
||||
),
|
||||
# patternProperties + properties is also unsupported by guidance.
|
||||
(
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"a": {"type": "string"}},
|
||||
"patternProperties": {"^a$": {"type": "string"}},
|
||||
},
|
||||
"outlines",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_auto_backend_falls_back_on_unsupported_schema(schema, expected_backend):
|
||||
"""`auto` falls back on rejection, so it must catch what the validators raise."""
|
||||
params = SamplingParams(structured_outputs=StructuredOutputsParams(json=schema))
|
||||
# trick to create tokenizer that guidance backend accepts
|
||||
tokenizer = object.__new__(TokenizersBackend)
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(backend="auto"),
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
assert params.structured_outputs is not None
|
||||
assert params.structured_outputs._backend == expected_backend
|
||||
|
||||
|
||||
# ================================================
|
||||
# Test validate_structured_outputs functionality
|
||||
# ================================================
|
||||
|
||||
|
||||
class TestValidateStructuredOutputs:
|
||||
class TestPR52298Regression:
|
||||
class _StubSlowTokenizer:
|
||||
is_fast = False
|
||||
|
||||
class _StubVllmMistralTokenizer:
|
||||
IS_MISTRAL_TOKENIZER = True
|
||||
|
||||
def __init__(self, is_tekken: bool):
|
||||
self.is_tekken = is_tekken
|
||||
self.llg_tokenizer = object()
|
||||
|
||||
@staticmethod
|
||||
def _validate_guidance(tokenizer):
|
||||
params = SamplingParams(
|
||||
structured_outputs=StructuredOutputsParams(json=JSON_SCHEMA)
|
||||
)
|
||||
params._validate_structured_outputs(
|
||||
_StubModelConfig(is_diffusion=False),
|
||||
StructuredOutputsConfig(backend="guidance"),
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
return params
|
||||
|
||||
def _make_tokenizer(self, tokenizer_id: str):
|
||||
if tokenizer_id == "slow-hf":
|
||||
return self._StubSlowTokenizer()
|
||||
if tokenizer_id == "plain-object":
|
||||
return object()
|
||||
if tokenizer_id == "raw-mistral-common":
|
||||
return object.__new__(MistralCommonBackend)
|
||||
if tokenizer_id == "vllm-mistral-non-tekken":
|
||||
return self._StubVllmMistralTokenizer(is_tekken=False)
|
||||
if tokenizer_id == "fast-hf":
|
||||
return object.__new__(TokenizersBackend)
|
||||
if tokenizer_id == "vllm-mistral-tekken":
|
||||
return self._StubVllmMistralTokenizer(is_tekken=True)
|
||||
raise ValueError(tokenizer_id)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tokenizer_id, patch_mistral",
|
||||
[
|
||||
pytest.param("slow-hf", False, id="slow-hf"),
|
||||
pytest.param("plain-object", False, id="plain-object"),
|
||||
pytest.param("raw-mistral-common", False, id="raw-mistral-common"),
|
||||
pytest.param(
|
||||
"vllm-mistral-non-tekken",
|
||||
True,
|
||||
id="vllm-mistral-non-tekken",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_unsupported_tokenizer(self, monkeypatch, tokenizer_id, patch_mistral):
|
||||
if patch_mistral:
|
||||
monkeypatch.setattr(
|
||||
mistral_tokenizers,
|
||||
"MistralTokenizer",
|
||||
self._StubVllmMistralTokenizer,
|
||||
)
|
||||
with pytest.raises(VLLMValidationError):
|
||||
self._validate_guidance(self._make_tokenizer(tokenizer_id))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tokenizer_id, patch_mistral",
|
||||
[
|
||||
pytest.param("fast-hf", False, id="fast-hf"),
|
||||
pytest.param("vllm-mistral-tekken", True, id="vllm-mistral-tekken"),
|
||||
],
|
||||
)
|
||||
def test_supported_tokenizer(self, monkeypatch, tokenizer_id, patch_mistral):
|
||||
if patch_mistral:
|
||||
monkeypatch.setattr(
|
||||
mistral_tokenizers,
|
||||
"MistralTokenizer",
|
||||
self._StubVllmMistralTokenizer,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
backend_guidance,
|
||||
"validate_guidance_grammar",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
params = self._validate_guidance(self._make_tokenizer(tokenizer_id))
|
||||
assert params.structured_outputs._backend == "guidance"
|
||||
Reference in New Issue
Block a user