feat(constrained): two-phase reasoning grammar + --enable-strict-thinking (#23953)
This commit is contained in:
@@ -269,10 +269,13 @@ class TestCreateGrammarBackend(unittest.TestCase):
|
||||
GRAMMAR_BACKEND_REGISTRY.clear()
|
||||
GRAMMAR_BACKEND_REGISTRY.update(self._saved)
|
||||
|
||||
def _make_server_args(self, backend="none", reasoning_parser=None):
|
||||
def _make_server_args(
|
||||
self, backend="none", reasoning_parser=None, enable_strict_thinking=False
|
||||
):
|
||||
args = MagicMock()
|
||||
args.grammar_backend = backend
|
||||
args.reasoning_parser = reasoning_parser
|
||||
args.enable_strict_thinking = enable_strict_thinking
|
||||
args.constrained_json_whitespace_pattern = None
|
||||
args.constrained_json_disable_any_whitespace = False
|
||||
return args
|
||||
@@ -282,6 +285,11 @@ class TestCreateGrammarBackend(unittest.TestCase):
|
||||
result = create_grammar_backend(args, None, 32000)
|
||||
self.assertIsNone(result)
|
||||
|
||||
def test_none_backend_with_strict_thinking_raises(self):
|
||||
args = self._make_server_args("none", enable_strict_thinking=True)
|
||||
with self.assertRaisesRegex(ValueError, "enable-strict-thinking"):
|
||||
create_grammar_backend(args, None, 32000)
|
||||
|
||||
def test_invalid_backend_raises(self):
|
||||
args = self._make_server_args("nonexistent_backend")
|
||||
with self.assertRaises(ValueError):
|
||||
@@ -316,7 +324,7 @@ class TestCreateGrammarBackend(unittest.TestCase):
|
||||
mock_inner = MagicMock(spec=BaseGrammarBackend)
|
||||
register_grammar_backend("inner_r", lambda *a: mock_inner)
|
||||
|
||||
args = self._make_server_args("inner_r", reasoning_parser="deepseek")
|
||||
args = self._make_server_args("inner_r", reasoning_parser="deepseek-r1")
|
||||
tokenizer = MagicMock()
|
||||
|
||||
result = create_grammar_backend(args, tokenizer, 32000)
|
||||
@@ -382,13 +390,15 @@ class TestCreateGrammarBackend(unittest.TestCase):
|
||||
)
|
||||
|
||||
mock_backend = MagicMock(spec=BaseGrammarBackend)
|
||||
mock_backend.is_support_token_filter = False
|
||||
mock_outlines_cls.return_value = mock_backend
|
||||
args = self._make_server_args("outlines", reasoning_parser="deepseek")
|
||||
args = self._make_server_args("outlines", reasoning_parser="deepseek-r1")
|
||||
tokenizer = MagicMock()
|
||||
# encode must return a single-token list for think_start/end tokens
|
||||
tokenizer.encode.return_value = [42]
|
||||
|
||||
result = create_grammar_backend(args, tokenizer, 32000, think_end_id=42)
|
||||
self.assertIsInstance(result, ReasonerGrammarBackend)
|
||||
self.assertEqual(result.think_end_id, 42)
|
||||
self.assertIs(result.grammar_backend, mock_backend)
|
||||
|
||||
@patch("sglang.srt.constrained.outlines_backend.OutlinesGrammarBackend")
|
||||
@@ -396,7 +406,7 @@ class TestCreateGrammarBackend(unittest.TestCase):
|
||||
"""Without think_end_id passed in, no reasoner wrapping."""
|
||||
mock_backend = MagicMock(spec=BaseGrammarBackend)
|
||||
mock_outlines_cls.return_value = mock_backend
|
||||
args = self._make_server_args("outlines", reasoning_parser="deepseek")
|
||||
args = self._make_server_args("outlines", reasoning_parser="deepseek-r1")
|
||||
tokenizer = MagicMock(spec=[]) # No think_end_id attribute
|
||||
|
||||
result = create_grammar_backend(args, tokenizer, 32000, think_end_id=None)
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
"""
|
||||
End-to-end tests for strict reasoning + constrained decoding.
|
||||
|
||||
Tests that the full pipeline works:
|
||||
- AC-5.1: Strict reasoning + JSON schema constrained generation
|
||||
- AC-5.2: Strict reasoning + tool call parsing (basic validation only)
|
||||
|
||||
These tests launch a real server with a small model and verify
|
||||
the constrained decoding pipeline produces valid output.
|
||||
"""
|
||||
|
||||
import json
|
||||
import unittest
|
||||
|
||||
import requests
|
||||
|
||||
from sglang.srt.utils import kill_process_tree
|
||||
from sglang.test.ci.ci_register import register_cuda_ci
|
||||
from sglang.test.test_utils import (
|
||||
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
||||
CustomTestCase,
|
||||
popen_launch_server,
|
||||
)
|
||||
|
||||
register_cuda_ci(est_time=120, suite="stage-b-test-1-gpu-small")
|
||||
|
||||
MODEL = "Qwen/Qwen3-0.6B"
|
||||
BASE_URL = "http://127.0.0.1:39877"
|
||||
API_KEY = "sk-test-1234"
|
||||
|
||||
|
||||
class TestConstrainedReasoningE2E(CustomTestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.model = MODEL
|
||||
cls.base_url = BASE_URL
|
||||
cls.api_key = API_KEY
|
||||
cls.process = popen_launch_server(
|
||||
cls.model,
|
||||
cls.base_url,
|
||||
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
||||
api_key=cls.api_key,
|
||||
other_args=[
|
||||
"--reasoning-parser",
|
||||
"qwen3",
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
kill_process_tree(cls.process.pid)
|
||||
|
||||
def _chat(self, **kwargs):
|
||||
default = {
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What is 2+2? Answer with just the number.",
|
||||
}
|
||||
],
|
||||
"temperature": 0,
|
||||
"max_tokens": 256,
|
||||
}
|
||||
default.update(kwargs)
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json=default,
|
||||
timeout=60,
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200, f"Request failed: {resp.text}")
|
||||
return resp.json()
|
||||
|
||||
def test_reasoning_with_json_schema(self):
|
||||
"""AC-5.1: Reasoning + JSON schema produces valid JSON output."""
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"answer": {"type": "integer"},
|
||||
},
|
||||
"required": ["answer"],
|
||||
}
|
||||
data = self._chat(
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "answer_schema",
|
||||
"schema": schema,
|
||||
},
|
||||
},
|
||||
chat_template_kwargs={"enable_thinking": True},
|
||||
separate_reasoning=True,
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
content = choice["message"]["content"] or ""
|
||||
|
||||
# Content should be valid JSON conforming to schema when non-empty.
|
||||
# With small models + separate_reasoning, content may be empty if the
|
||||
# model puts everything in reasoning_content. That's acceptable.
|
||||
if content.strip():
|
||||
try:
|
||||
parsed = json.loads(content)
|
||||
self.assertIn("answer", parsed)
|
||||
self.assertIsInstance(parsed["answer"], int)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
# Small models may produce imperfect JSON
|
||||
self.assertTrue(
|
||||
content.strip().startswith("{"),
|
||||
f"Expected JSON-like output, got: {content!r}",
|
||||
)
|
||||
|
||||
# Content should NOT contain <think> tags (those go to reasoning_content)
|
||||
self.assertNotIn("<think>", content)
|
||||
|
||||
def test_reasoning_disabled_with_json_schema(self):
|
||||
"""JSON schema still works when reasoning is explicitly disabled."""
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"answer": {"type": "integer"},
|
||||
},
|
||||
"required": ["answer"],
|
||||
}
|
||||
data = self._chat(
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "answer_schema",
|
||||
"schema": schema,
|
||||
},
|
||||
},
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
content = choice["message"]["content"]
|
||||
|
||||
# Should still produce valid JSON
|
||||
parsed = json.loads(content)
|
||||
self.assertIn("answer", parsed)
|
||||
|
||||
def test_reasoning_with_separate_output(self):
|
||||
"""Reasoning content is correctly separated from normal content."""
|
||||
data = self._chat(
|
||||
chat_template_kwargs={"enable_thinking": True},
|
||||
separate_reasoning=True,
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
content = choice["message"]["content"]
|
||||
reasoning = choice["message"].get("reasoning_content")
|
||||
|
||||
# Content should not contain think tags
|
||||
self.assertNotIn("<think>", content)
|
||||
self.assertNotIn("</think>", content)
|
||||
|
||||
def test_tool_call_after_reasoning(self):
|
||||
"""AC-5.2: Tool call parsing works with reasoning enabled."""
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {"type": "string"},
|
||||
},
|
||||
"required": ["location"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
data = self._chat(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What's the weather in Paris?",
|
||||
}
|
||||
],
|
||||
tools=tools,
|
||||
chat_template_kwargs={"enable_thinking": True},
|
||||
separate_reasoning=True,
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
# The model may or may not produce tool calls (depends on model capability)
|
||||
# but the response should be well-formed (no crashes)
|
||||
self.assertIn("message", choice)
|
||||
self.assertIn("finish_reason", choice)
|
||||
# finish_reason should be either "stop" or "tool_calls"
|
||||
self.assertIn(choice["finish_reason"], ["stop", "tool_calls", "length"])
|
||||
|
||||
|
||||
class TestStrictThinkingE2E(CustomTestCase):
|
||||
"""E2E tests with --enable-strict-thinking flag.
|
||||
|
||||
Validates that the strict thinking flag is correctly propagated through
|
||||
the full pipeline: server_args -> grammar_backend -> ReasonerGrammarBackend
|
||||
-> token filtering during thinking phase.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.model = MODEL
|
||||
cls.base_url = "http://127.0.0.1:39878"
|
||||
cls.api_key = API_KEY
|
||||
cls.process = popen_launch_server(
|
||||
cls.model,
|
||||
cls.base_url,
|
||||
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
||||
api_key=cls.api_key,
|
||||
other_args=[
|
||||
"--reasoning-parser",
|
||||
"qwen3",
|
||||
"--enable-strict-thinking",
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
kill_process_tree(cls.process.pid)
|
||||
|
||||
def _chat(self, **kwargs):
|
||||
default = {
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What is 2+2? Answer with just the number.",
|
||||
}
|
||||
],
|
||||
"temperature": 0,
|
||||
"max_tokens": 256,
|
||||
}
|
||||
default.update(kwargs)
|
||||
resp = requests.post(
|
||||
f"{self.base_url}/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json=default,
|
||||
timeout=60,
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200, f"Request failed: {resp.text}")
|
||||
return resp.json()
|
||||
|
||||
def test_strict_thinking_with_json_schema(self):
|
||||
"""Strict thinking + JSON schema: server starts and produces valid output."""
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"answer": {"type": "integer"},
|
||||
},
|
||||
"required": ["answer"],
|
||||
}
|
||||
data = self._chat(
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "answer_schema",
|
||||
"schema": schema,
|
||||
},
|
||||
},
|
||||
chat_template_kwargs={"enable_thinking": True},
|
||||
separate_reasoning=True,
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
content = choice["message"]["content"] or ""
|
||||
|
||||
if content.strip():
|
||||
try:
|
||||
parsed = json.loads(content)
|
||||
self.assertIn("answer", parsed)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
self.assertTrue(
|
||||
content.strip().startswith("{"),
|
||||
f"Expected JSON-like output, got: {content!r}",
|
||||
)
|
||||
|
||||
# Think tags must not leak into content
|
||||
self.assertNotIn("<think>", content)
|
||||
|
||||
def test_strict_thinking_disabled_per_request(self):
|
||||
"""When thinking is disabled per-request, strict server still works."""
|
||||
data = self._chat(
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
self.assertIn("message", choice)
|
||||
self.assertIn("finish_reason", choice)
|
||||
# Should complete normally without errors
|
||||
self.assertIn(choice["finish_reason"], ["stop", "length"])
|
||||
|
||||
def test_strict_thinking_separate_reasoning(self):
|
||||
"""Strict thinking with separate_reasoning produces well-formed output."""
|
||||
data = self._chat(
|
||||
chat_template_kwargs={"enable_thinking": True},
|
||||
separate_reasoning=True,
|
||||
)
|
||||
|
||||
choice = data["choices"][0]
|
||||
content = choice["message"]["content"] or ""
|
||||
|
||||
# Think tags must not leak into content
|
||||
self.assertNotIn("<think>", content)
|
||||
self.assertNotIn("</think>", content)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -24,6 +24,7 @@ from sglang.srt.constrained.base_grammar_backend import (
|
||||
InvalidGrammarObject,
|
||||
)
|
||||
from sglang.srt.constrained.grammar_manager import GrammarManager
|
||||
from sglang.srt.constrained.reasoner_grammar_backend import ReasonerGrammarObject
|
||||
from sglang.test.ci.ci_register import register_cpu_ci
|
||||
|
||||
register_cpu_ci(2.0, "stage-a-test-cpu")
|
||||
@@ -48,7 +49,12 @@ def _make_scheduler(grammar_backend_name="none", skip_tokenizer=False):
|
||||
|
||||
|
||||
def _make_req(
|
||||
json_schema=None, regex=None, ebnf=None, structural_tag=None, rid="req-1"
|
||||
json_schema=None,
|
||||
regex=None,
|
||||
ebnf=None,
|
||||
structural_tag=None,
|
||||
rid="req-1",
|
||||
custom_params=None,
|
||||
):
|
||||
"""Create a mock request with sampling params."""
|
||||
req = MagicMock()
|
||||
@@ -57,6 +63,7 @@ def _make_req(
|
||||
req.sampling_params.regex = regex
|
||||
req.sampling_params.ebnf = ebnf
|
||||
req.sampling_params.structural_tag = structural_tag
|
||||
req.sampling_params.custom_params = custom_params
|
||||
req.require_reasoning = False
|
||||
req.grammar = None
|
||||
req.grammar_key = None
|
||||
@@ -256,6 +263,39 @@ class TestProcessReqWithGrammar(unittest.TestCase):
|
||||
self.assertTrue(mgr.has_waiting_grammars())
|
||||
self.assertEqual(len(mgr), 1)
|
||||
|
||||
def test_cache_hit_applies_request_thinking_budget(self):
|
||||
mgr = self._make_mgr()
|
||||
grammar_obj = ReasonerGrammarObject(
|
||||
grammar=None, think_end_id=0, max_think_tokens=99
|
||||
)
|
||||
mgr.grammar_backend.get_cached_or_future_value.return_value = (
|
||||
grammar_obj,
|
||||
True,
|
||||
)
|
||||
|
||||
req = _make_req(
|
||||
json_schema="schema",
|
||||
custom_params={"thinking_budget": 7},
|
||||
)
|
||||
mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertEqual(req.grammar.max_think_tokens, 7)
|
||||
|
||||
def test_strict_reasoning_grammar_applies_request_thinking_budget(self):
|
||||
mgr = self._make_mgr()
|
||||
mgr._enable_strict_thinking = True
|
||||
grammar_obj = ReasonerGrammarObject(
|
||||
grammar=None, think_end_id=0, max_think_tokens=99
|
||||
)
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.return_value = grammar_obj
|
||||
|
||||
req = _make_req(custom_params={"thinking_budget": 3})
|
||||
req.require_reasoning = True
|
||||
mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertIs(req.grammar, grammar_obj)
|
||||
self.assertEqual(req.grammar.max_think_tokens, 3)
|
||||
|
||||
|
||||
class TestAbortRequests(unittest.TestCase):
|
||||
"""Test abort_requests handling."""
|
||||
@@ -494,8 +534,8 @@ class TestGetReadyGrammarRequests(unittest.TestCase):
|
||||
req.set_finish_with_abort.assert_called_once()
|
||||
self.assertIn("timed out", req.set_finish_with_abort.call_args[0][0])
|
||||
|
||||
def test_future_exception_propagates(self):
|
||||
"""A future that raised an exception should propagate on .result()."""
|
||||
def test_future_exception_creates_invalid_grammar_object(self):
|
||||
"""A future that raised an exception should create InvalidGrammarObject, not crash."""
|
||||
mgr = self._make_mgr()
|
||||
|
||||
future = Future()
|
||||
@@ -506,8 +546,32 @@ class TestGetReadyGrammarRequests(unittest.TestCase):
|
||||
req.grammar_key = ("json", "crash")
|
||||
mgr.grammar_queue.append(req)
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
mgr.get_ready_grammar_requests()
|
||||
result = mgr.get_ready_grammar_requests()
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertIsInstance(result[0].grammar, InvalidGrammarObject)
|
||||
req.set_finish_with_abort.assert_called_once()
|
||||
|
||||
def test_ready_future_applies_request_budget_without_polluting_cache(self):
|
||||
mgr = self._make_mgr()
|
||||
|
||||
grammar_obj = ReasonerGrammarObject(
|
||||
grammar=None, think_end_id=0, max_think_tokens=99
|
||||
)
|
||||
future = Future()
|
||||
future.set_result(grammar_obj)
|
||||
|
||||
req = _make_req(json_schema="schema", custom_params={"thinking_budget": 4})
|
||||
req.grammar = future
|
||||
req.grammar_key = ("json", "schema")
|
||||
mgr.grammar_queue.append(req)
|
||||
|
||||
result = mgr.get_ready_grammar_requests()
|
||||
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertEqual(req.grammar.max_think_tokens, 4)
|
||||
cached_key, cached_value = mgr.grammar_backend.set_cache.call_args[0]
|
||||
self.assertEqual(cached_key, ("json", "schema"))
|
||||
self.assertEqual(cached_value.max_think_tokens, 99)
|
||||
|
||||
@patch("sglang.srt.constrained.grammar_manager.torch.distributed.all_gather_object")
|
||||
def test_multi_rank_sync_intersects_ready_unions_failed(self, mock_all_gather):
|
||||
@@ -579,5 +643,100 @@ class TestGetReadyGrammarRequests(unittest.TestCase):
|
||||
self.assertEqual(len(mgr.grammar_queue), 0)
|
||||
|
||||
|
||||
class TestStrictReasoningPaths(unittest.TestCase):
|
||||
"""Test _enable_strict_thinking code paths in GrammarManager."""
|
||||
|
||||
def _make_mgr(self):
|
||||
scheduler = _make_scheduler()
|
||||
scheduler.server_args.skip_tokenizer_init = True
|
||||
mgr = GrammarManager(scheduler)
|
||||
mgr.grammar_backend = MagicMock(spec=BaseGrammarBackend)
|
||||
mgr._enable_strict_thinking = True
|
||||
return mgr
|
||||
|
||||
def test_strict_unconstrained_request_gets_strict_grammar(self):
|
||||
"""Request without json_schema/regex/ebnf should get strict-only grammar."""
|
||||
mgr = self._make_mgr()
|
||||
grammar_obj = MagicMock()
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.return_value = grammar_obj
|
||||
|
||||
req = _make_req() # No constraint
|
||||
req.require_reasoning = True
|
||||
result = mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertFalse(result) # Not added to grammar queue
|
||||
self.assertIs(req.grammar, grammar_obj)
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.assert_called_once_with(True)
|
||||
|
||||
def test_strict_unconstrained_no_reasoning_flag(self):
|
||||
"""Unconstrained request with require_reasoning=False still gets strict grammar."""
|
||||
mgr = self._make_mgr()
|
||||
grammar_obj = MagicMock()
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.return_value = grammar_obj
|
||||
|
||||
req = _make_req()
|
||||
req.require_reasoning = False
|
||||
mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertIs(req.grammar, grammar_obj)
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.assert_called_once_with(False)
|
||||
|
||||
def test_strict_unconstrained_none_grammar_is_fine(self):
|
||||
"""If init_strict_reasoning_grammar returns None, req.grammar stays None."""
|
||||
mgr = self._make_mgr()
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.return_value = None
|
||||
|
||||
req = _make_req()
|
||||
req.require_reasoning = True
|
||||
mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertIsNone(req.grammar)
|
||||
|
||||
def test_strict_constrained_request_uses_normal_dispatch(self):
|
||||
"""Request with json_schema should go through normal dispatch, not strict path."""
|
||||
mgr = self._make_mgr()
|
||||
future = MagicMock(spec=Future)
|
||||
mgr.grammar_backend.get_cached_or_future_value.return_value = (future, False)
|
||||
|
||||
req = _make_req(json_schema='{"type": "object"}')
|
||||
req.require_reasoning = True
|
||||
result = mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertTrue(result) # Added to grammar queue
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.assert_not_called()
|
||||
|
||||
def test_strict_not_set_skips_strict_path(self):
|
||||
"""When _enable_strict_thinking=False, unconstrained requests get no grammar."""
|
||||
mgr = self._make_mgr()
|
||||
mgr._enable_strict_thinking = False
|
||||
|
||||
req = _make_req()
|
||||
req.require_reasoning = True
|
||||
mgr.process_req_with_grammar(req)
|
||||
|
||||
self.assertIsNone(req.grammar)
|
||||
mgr.grammar_backend.init_strict_reasoning_grammar.assert_not_called()
|
||||
|
||||
def test_future_exception_creates_invalid_grammar(self):
|
||||
"""Future.result() raising should create InvalidGrammarObject, not crash."""
|
||||
mgr = self._make_mgr()
|
||||
|
||||
future = Future()
|
||||
future.set_exception(RuntimeError("compilation failed"))
|
||||
|
||||
req = _make_req(json_schema='{"type": "object"}')
|
||||
req.require_reasoning = True
|
||||
req.grammar = future
|
||||
req.grammar_key = ("json", '{"type": "object"}')
|
||||
mgr.grammar_queue.append(req)
|
||||
|
||||
mgr.SGLANG_GRAMMAR_POLL_INTERVAL = 0.001
|
||||
result = mgr.get_ready_grammar_requests()
|
||||
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertIsInstance(result[0].grammar, InvalidGrammarObject)
|
||||
req.set_finish_with_abort.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,413 +1,453 @@
|
||||
"""
|
||||
Unit tests for sglang.srt.constrained.reasoner_grammar_backend.
|
||||
|
||||
Test Coverage:
|
||||
- ReasonerGrammarObject: state transitions, accept_token during thinking
|
||||
vs post-thinking, rollback across think boundary, fill_vocab_mask gating,
|
||||
copy semantics, finished delegation, delegation of jump methods
|
||||
- ReasonerGrammarBackend: dispatch wrapping, invalid grammar passthrough,
|
||||
None grammar passthrough, reasoning init on wrapped object
|
||||
|
||||
Usage:
|
||||
python -m pytest test_reasoner_grammar_backend.py -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, call
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from sglang.srt.constrained.base_grammar_backend import (
|
||||
BaseGrammarBackend,
|
||||
BaseGrammarObject,
|
||||
InvalidGrammarObject,
|
||||
)
|
||||
import torch
|
||||
|
||||
from sglang.srt.constrained.base_grammar_backend import BaseGrammarBackend
|
||||
from sglang.srt.constrained.reasoner_grammar_backend import (
|
||||
ReasonerGrammarBackend,
|
||||
ReasonerGrammarObject,
|
||||
)
|
||||
from sglang.srt.constrained.torch_ops.token_filter_torch_ops import (
|
||||
set_token_filter_torch,
|
||||
)
|
||||
from sglang.test.ci.ci_register import register_cpu_ci
|
||||
|
||||
register_cpu_ci(2.0, "stage-a-test-cpu")
|
||||
|
||||
THINK_END_ID = 99
|
||||
|
||||
class _DummyTokenizer:
|
||||
def __init__(self, token_map):
|
||||
self._token_map = token_map
|
||||
|
||||
def encode(self, text, add_special_tokens=False):
|
||||
return list(self._token_map.get(text, []))
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectStateTransitions(unittest.TestCase):
|
||||
"""Test thinking state machine in ReasonerGrammarObject."""
|
||||
class _DummyGrammarBackend(BaseGrammarBackend):
|
||||
def __init__(self, support_token_filter=True):
|
||||
super().__init__()
|
||||
self._support_token_filter = support_token_filter
|
||||
self._dispatch_result = None
|
||||
|
||||
def _make(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
return ReasonerGrammarObject(grammar, THINK_END_ID), grammar
|
||||
@property
|
||||
def is_support_token_filter(self):
|
||||
return self._support_token_filter
|
||||
|
||||
def test_initial_state_thinking(self):
|
||||
obj, _ = self._make()
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
@staticmethod
|
||||
def allocate_vocab_mask(vocab_size, batch_size, device):
|
||||
return torch.zeros((batch_size, (vocab_size + 31) // 32), dtype=torch.int32)
|
||||
|
||||
def test_transfer_state_during_thinking(self):
|
||||
"""Regular tokens during thinking don't change state."""
|
||||
obj, _ = self._make()
|
||||
obj.transfer_state(10)
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
@staticmethod
|
||||
def move_vocab_mask(vocab_mask, device):
|
||||
return vocab_mask
|
||||
|
||||
def test_transfer_state_think_end_token(self):
|
||||
"""Think end token transitions from -1 to 0."""
|
||||
obj, _ = self._make()
|
||||
obj.transfer_state(THINK_END_ID)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
@staticmethod
|
||||
def apply_vocab_mask(logits, vocab_mask):
|
||||
return None
|
||||
|
||||
def test_transfer_state_increments_after_thinking(self):
|
||||
"""After thinking ends, each token increments counter."""
|
||||
obj, _ = self._make()
|
||||
obj.tokens_after_think_end = 0
|
||||
obj.transfer_state(10)
|
||||
self.assertEqual(obj.tokens_after_think_end, 1)
|
||||
obj.transfer_state(20)
|
||||
self.assertEqual(obj.tokens_after_think_end, 2)
|
||||
@staticmethod
|
||||
def set_token_filter(
|
||||
vocab_mask, token_ids, batch_idx, is_allowed=True, reset_vocab_mask=True
|
||||
):
|
||||
set_token_filter_torch(
|
||||
vocab_mask, token_ids, batch_idx, is_allowed, reset_vocab_mask
|
||||
)
|
||||
|
||||
def test_think_end_after_thinking_already_ended(self):
|
||||
"""Second think_end_id after thinking ended just increments."""
|
||||
obj, _ = self._make()
|
||||
obj.tokens_after_think_end = 3
|
||||
obj.transfer_state(THINK_END_ID)
|
||||
self.assertEqual(obj.tokens_after_think_end, 4)
|
||||
|
||||
def test_rollback_state_from_post_thinking(self):
|
||||
obj, _ = self._make()
|
||||
obj.tokens_after_think_end = 3
|
||||
obj.rollback_state()
|
||||
self.assertEqual(obj.tokens_after_think_end, 2)
|
||||
|
||||
def test_rollback_state_at_boundary(self):
|
||||
"""Rollback from 0 goes back to -1 (thinking)."""
|
||||
obj, _ = self._make()
|
||||
obj.tokens_after_think_end = 0
|
||||
obj.rollback_state()
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
def test_rollback_state_during_thinking(self):
|
||||
"""Rollback during thinking stays at -1."""
|
||||
obj, _ = self._make()
|
||||
obj.rollback_state()
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
def _init_value_dispatch(self, key, reasoning):
|
||||
return self._dispatch_result
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectAcceptToken(unittest.TestCase):
|
||||
"""Test accept_token behavior with thinking/post-thinking states."""
|
||||
|
||||
def _make(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
return ReasonerGrammarObject(grammar, THINK_END_ID), grammar
|
||||
|
||||
def test_accept_during_thinking_skips_grammar(self):
|
||||
"""During thinking phase, inner grammar should NOT receive tokens."""
|
||||
obj, grammar = self._make()
|
||||
obj.accept_token(10)
|
||||
grammar.accept_token.assert_not_called()
|
||||
# State should still be -1
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
def test_accept_think_end_token(self):
|
||||
"""Think end token transitions state but doesn't call inner grammar (state was -1 before transfer)."""
|
||||
obj, grammar = self._make()
|
||||
# tokens_after_think_end is -1, so grammar.accept_token is not called
|
||||
# But wait: accept_token checks `>= 0` BEFORE transfer_state
|
||||
# At call time tokens_after_think_end == -1, so grammar.accept_token skipped
|
||||
obj.accept_token(THINK_END_ID)
|
||||
grammar.accept_token.assert_not_called()
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
|
||||
def test_accept_after_thinking_calls_grammar(self):
|
||||
"""After thinking ends, tokens go to inner grammar."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 0
|
||||
obj.accept_token(42)
|
||||
grammar.accept_token.assert_called_once_with(42)
|
||||
self.assertEqual(obj.tokens_after_think_end, 1)
|
||||
|
||||
def test_accept_sequence_through_thinking_and_generation(self):
|
||||
"""Full sequence: think tokens -> think_end -> generation tokens."""
|
||||
obj, grammar = self._make()
|
||||
|
||||
# Thinking phase
|
||||
obj.accept_token(1)
|
||||
obj.accept_token(2)
|
||||
self.assertEqual(grammar.accept_token.call_count, 0)
|
||||
|
||||
# Think end
|
||||
obj.accept_token(THINK_END_ID)
|
||||
self.assertEqual(grammar.accept_token.call_count, 0)
|
||||
|
||||
# Generation phase
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(20)
|
||||
self.assertEqual(grammar.accept_token.call_count, 2)
|
||||
grammar.accept_token.assert_has_calls([call(10), call(20)])
|
||||
def _allowed_token_ids(vocab_mask, token_ids):
|
||||
allowed = []
|
||||
for token_id in token_ids:
|
||||
elem = token_id // 32
|
||||
bit = token_id % 32
|
||||
if int(vocab_mask[0, elem].item()) & (1 << bit):
|
||||
allowed.append(token_id)
|
||||
return allowed
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectRollback(unittest.TestCase):
|
||||
"""Test rollback across thinking boundary."""
|
||||
class TestReasonerGrammarObject(unittest.TestCase):
|
||||
def _make_strict_object(self):
|
||||
return ReasonerGrammarObject(
|
||||
grammar=None,
|
||||
think_end_id=7,
|
||||
think_excluded_token_ids=[3, 5],
|
||||
max_think_tokens=2,
|
||||
enable_token_filter=True,
|
||||
token_filter_fn=set_token_filter_torch,
|
||||
allocate_vocab_mask_fn=lambda vocab_size, batch_size, device: torch.zeros(
|
||||
(batch_size, (vocab_size + 31) // 32), dtype=torch.int32
|
||||
),
|
||||
move_vocab_mask_fn=lambda vocab_mask, device: vocab_mask,
|
||||
apply_vocab_mask_fn=lambda logits, vocab_mask: None,
|
||||
)
|
||||
|
||||
def _make(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
return ReasonerGrammarObject(grammar, THINK_END_ID), grammar
|
||||
|
||||
def test_rollback_within_generation(self):
|
||||
"""Rollback entirely within generation phase."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 5
|
||||
obj.rollback(3)
|
||||
grammar.rollback.assert_called_once_with(3)
|
||||
self.assertEqual(obj.tokens_after_think_end, 2)
|
||||
|
||||
def test_rollback_across_boundary(self):
|
||||
"""Rollback that crosses from generation back into thinking."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 2
|
||||
obj.rollback(4)
|
||||
# Only 2 tokens were post-thinking, so inner grammar rolls back 2
|
||||
grammar.rollback.assert_called_once_with(2)
|
||||
# After 4 rollback_state calls from 2: 2->1->0->-1->-1
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
def test_rollback_during_thinking(self):
|
||||
"""Rollback during thinking phase doesn't touch inner grammar."""
|
||||
obj, grammar = self._make()
|
||||
obj.rollback(3)
|
||||
grammar.rollback.assert_not_called()
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
def test_rollback_zero(self):
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 2
|
||||
obj.rollback(0)
|
||||
grammar.rollback.assert_not_called()
|
||||
self.assertEqual(obj.tokens_after_think_end, 2)
|
||||
|
||||
def test_rollback_exactly_to_boundary(self):
|
||||
"""Rollback exactly the number of post-thinking tokens."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 3
|
||||
obj.rollback(3)
|
||||
grammar.rollback.assert_called_once_with(3)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
|
||||
def test_rollback_far_beyond_all_tokens(self):
|
||||
"""Rollback k much larger than tokens_after_think_end clamps grammar rollback."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 2
|
||||
obj.rollback(100)
|
||||
# Inner grammar only rolls back the 2 post-thinking tokens
|
||||
grammar.rollback.assert_called_once_with(2)
|
||||
# State bottoms out at -1
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
def test_accept_then_rollback_roundtrip(self):
|
||||
"""Accept tokens then rollback should restore original state."""
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 0 # Just finished thinking
|
||||
|
||||
# Accept 3 generation tokens
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(20)
|
||||
obj.accept_token(30)
|
||||
self.assertEqual(obj.tokens_after_think_end, 3)
|
||||
self.assertEqual(grammar.accept_token.call_count, 3)
|
||||
|
||||
# Rollback all 3
|
||||
obj.rollback(3)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
grammar.rollback.assert_called_once_with(3)
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectVocabMask(unittest.TestCase):
|
||||
"""Test vocab mask gating based on thinking state."""
|
||||
|
||||
def _make(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
return ReasonerGrammarObject(grammar, THINK_END_ID), grammar
|
||||
|
||||
def test_fill_during_thinking_skips(self):
|
||||
obj, grammar = self._make()
|
||||
obj.fill_vocab_mask("mask", 0)
|
||||
grammar.fill_vocab_mask.assert_not_called()
|
||||
|
||||
def test_fill_after_thinking_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 0
|
||||
obj.fill_vocab_mask("mask", 0)
|
||||
grammar.fill_vocab_mask.assert_called_once_with("mask", 0)
|
||||
|
||||
def test_fill_well_into_generation(self):
|
||||
obj, grammar = self._make()
|
||||
obj.tokens_after_think_end = 5
|
||||
obj.fill_vocab_mask("mask", 2)
|
||||
grammar.fill_vocab_mask.assert_called_once_with("mask", 2)
|
||||
|
||||
def test_fill_at_think_end_boundary(self):
|
||||
"""After accepting think_end token, fill_vocab_mask should delegate."""
|
||||
obj, grammar = self._make()
|
||||
# Simulate: accept think_end, state goes from -1 to 0
|
||||
obj.accept_token(THINK_END_ID)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
obj.fill_vocab_mask("mask", 0)
|
||||
grammar.fill_vocab_mask.assert_called_once_with("mask", 0)
|
||||
|
||||
def test_allocate_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
obj.allocate_vocab_mask(32000, 4, "cpu")
|
||||
grammar.allocate_vocab_mask.assert_called_once_with(32000, 4, "cpu")
|
||||
|
||||
def test_move_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
obj.move_vocab_mask("mask", "cuda")
|
||||
grammar.move_vocab_mask.assert_called_once_with("mask", "cuda")
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectDelegation(unittest.TestCase):
|
||||
"""Test that non-state methods delegate to inner grammar."""
|
||||
|
||||
def _make(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
return ReasonerGrammarObject(grammar, THINK_END_ID), grammar
|
||||
|
||||
def test_is_terminated_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
grammar.is_terminated.return_value = True
|
||||
self.assertTrue(obj.is_terminated())
|
||||
|
||||
def test_finished_getter_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
grammar.finished = True
|
||||
self.assertTrue(obj.finished)
|
||||
|
||||
def test_finished_setter_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
obj.finished = True
|
||||
self.assertTrue(grammar.finished)
|
||||
|
||||
def test_try_jump_forward_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
grammar.try_jump_forward.return_value = ([1, 2], "ab")
|
||||
result = obj.try_jump_forward("tokenizer")
|
||||
grammar.try_jump_forward.assert_called_once_with("tokenizer")
|
||||
self.assertEqual(result, ([1, 2], "ab"))
|
||||
|
||||
def test_jump_forward_str_state_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
grammar.jump_forward_str_state.return_value = ("str", 5)
|
||||
result = obj.jump_forward_str_state("helper")
|
||||
self.assertEqual(result, ("str", 5))
|
||||
|
||||
def test_jump_and_retokenize_delegates(self):
|
||||
obj, grammar = self._make()
|
||||
obj.jump_and_retokenize([1], [2], 3)
|
||||
grammar.jump_and_retokenize.assert_called_once_with([1], [2], 3)
|
||||
|
||||
def test_apply_vocab_mask_property(self):
|
||||
obj, grammar = self._make()
|
||||
grammar.apply_vocab_mask = "mask_fn"
|
||||
self.assertEqual(obj.apply_vocab_mask, "mask_fn")
|
||||
|
||||
def test_copy_creates_new_wrapper(self):
|
||||
obj, grammar = self._make()
|
||||
grammar_copy = MagicMock(spec=BaseGrammarObject)
|
||||
grammar.copy.return_value = grammar_copy
|
||||
|
||||
copied = obj.copy()
|
||||
self.assertIsInstance(copied, ReasonerGrammarObject)
|
||||
self.assertIsNot(copied, obj)
|
||||
self.assertIs(copied.grammar, grammar_copy)
|
||||
self.assertEqual(copied.think_end_id, THINK_END_ID)
|
||||
|
||||
def test_copy_does_not_share_state(self):
|
||||
"""Modifying copy's state should not affect the original."""
|
||||
obj, grammar = self._make()
|
||||
grammar_copy = MagicMock(spec=BaseGrammarObject)
|
||||
grammar.copy.return_value = grammar_copy
|
||||
|
||||
copied = obj.copy()
|
||||
copied.tokens_after_think_end = 5
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectMaybeInitReasoning(unittest.TestCase):
|
||||
"""Test maybe_init_reasoning state initialization."""
|
||||
|
||||
def test_reasoning_true_sets_thinking(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
obj = ReasonerGrammarObject(grammar, THINK_END_ID)
|
||||
def test_strict_thinking_phase_excludes_configured_tokens(self):
|
||||
obj = self._make_strict_object()
|
||||
obj.maybe_init_reasoning(True)
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
mask = obj.allocate_vocab_mask(64, 1, "cpu")
|
||||
|
||||
def test_reasoning_false_skips_thinking(self):
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
obj = ReasonerGrammarObject(grammar, THINK_END_ID)
|
||||
obj.maybe_init_reasoning(False)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
obj.fill_vocab_mask(mask, 0)
|
||||
|
||||
def test_reasoning_toggle(self):
|
||||
"""Toggling reasoning resets state regardless of current position."""
|
||||
grammar = MagicMock(spec=BaseGrammarObject)
|
||||
obj = ReasonerGrammarObject(grammar, THINK_END_ID)
|
||||
obj.tokens_after_think_end = 5 # Deep into generation
|
||||
allowed = _allowed_token_ids(mask, [0, 1, 3, 5, 7, 8])
|
||||
self.assertEqual(allowed, [0, 1, 7, 8])
|
||||
|
||||
def test_budget_exhaustion_allows_only_think_end(self):
|
||||
obj = self._make_strict_object()
|
||||
obj.maybe_init_reasoning(True)
|
||||
self.assertEqual(obj.tokens_after_think_end, -1)
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(11)
|
||||
mask = obj.allocate_vocab_mask(64, 1, "cpu")
|
||||
|
||||
obj.maybe_init_reasoning(False)
|
||||
self.assertEqual(obj.tokens_after_think_end, 0)
|
||||
obj.fill_vocab_mask(mask, 0)
|
||||
|
||||
allowed = _allowed_token_ids(mask, [0, 1, 3, 5, 7, 8, 10, 11])
|
||||
self.assertEqual(allowed, [7])
|
||||
|
||||
def test_strict_only_wrapper_exposes_backend_mask_hooks(self):
|
||||
obj = self._make_strict_object()
|
||||
mask = obj.allocate_vocab_mask(64, 2, "cpu")
|
||||
|
||||
self.assertEqual(mask.shape, (2, 2))
|
||||
self.assertIs(obj.move_vocab_mask(mask, "cpu"), mask)
|
||||
self.assertIsNotNone(obj.apply_vocab_mask)
|
||||
|
||||
|
||||
class TestReasonerGrammarBackend(unittest.TestCase):
|
||||
"""Test ReasonerGrammarBackend dispatch wrapping."""
|
||||
def setUp(self):
|
||||
self._prev_budget = os.environ.get("SGLANG_MAX_THINK_TOKENS")
|
||||
|
||||
def _make(self):
|
||||
inner = MagicMock(spec=BaseGrammarBackend)
|
||||
backend = ReasonerGrammarBackend(inner, THINK_END_ID)
|
||||
return backend, inner
|
||||
def tearDown(self):
|
||||
if self._prev_budget is None:
|
||||
os.environ.pop("SGLANG_MAX_THINK_TOKENS", None)
|
||||
else:
|
||||
os.environ["SGLANG_MAX_THINK_TOKENS"] = self._prev_budget
|
||||
|
||||
def test_wraps_valid_grammar(self):
|
||||
backend, inner = self._make()
|
||||
mock_grammar = MagicMock(spec=BaseGrammarObject)
|
||||
inner._init_value_dispatch.return_value = mock_grammar
|
||||
def _make_parser(self):
|
||||
detector = SimpleNamespace(
|
||||
think_start_token="<think>",
|
||||
think_end_token="</think>",
|
||||
think_excluded_tokens=["<tool_call>", "</tool_call>"],
|
||||
)
|
||||
return SimpleNamespace(detector=detector)
|
||||
|
||||
result = backend._init_value_dispatch(("json", "schema"), True)
|
||||
self.assertIsInstance(result, ReasonerGrammarObject)
|
||||
self.assertIs(result.grammar, mock_grammar)
|
||||
self.assertEqual(result.think_end_id, THINK_END_ID)
|
||||
def _make_tokenizer(self, start_ids=None, end_ids=None):
|
||||
return _DummyTokenizer(
|
||||
{
|
||||
"<think>": [1] if start_ids is None else start_ids,
|
||||
"</think>": [2] if end_ids is None else end_ids,
|
||||
"<tool_call>": [3],
|
||||
"</tool_call>": [4],
|
||||
}
|
||||
)
|
||||
|
||||
def test_passes_through_invalid_grammar(self):
|
||||
backend, inner = self._make()
|
||||
invalid = InvalidGrammarObject("bad grammar")
|
||||
inner._init_value_dispatch.return_value = invalid
|
||||
def test_init_strict_reasoning_grammar_uses_token_filter_and_budget(self):
|
||||
os.environ["SGLANG_MAX_THINK_TOKENS"] = "2"
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
reasoner = ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(),
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
|
||||
result = backend._init_value_dispatch(("json", "schema"), False)
|
||||
self.assertIs(result, invalid)
|
||||
self.assertIsInstance(result, InvalidGrammarObject)
|
||||
obj = reasoner.init_strict_reasoning_grammar(reasoning=True)
|
||||
|
||||
def test_passes_through_none(self):
|
||||
backend, inner = self._make()
|
||||
inner._init_value_dispatch.return_value = None
|
||||
self.assertIsInstance(obj, ReasonerGrammarObject)
|
||||
self.assertTrue(obj.enable_token_filter)
|
||||
self.assertEqual(obj.max_think_tokens, 2)
|
||||
self.assertEqual(obj.think_excluded_token_ids, [3, 4])
|
||||
|
||||
result = backend._init_value_dispatch(("json", "schema"), False)
|
||||
self.assertIsNone(result)
|
||||
def test_init_strict_reasoning_grammar_none_when_strict_disabled(self):
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
reasoner = ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(),
|
||||
enable_strict_thinking=False,
|
||||
)
|
||||
|
||||
def test_inits_reasoning_on_wrapped(self):
|
||||
backend, inner = self._make()
|
||||
mock_grammar = MagicMock(spec=BaseGrammarObject)
|
||||
inner._init_value_dispatch.return_value = mock_grammar
|
||||
self.assertIsNone(reasoner.init_strict_reasoning_grammar(reasoning=True))
|
||||
|
||||
result = backend._init_value_dispatch(("json", "schema"), True)
|
||||
# reasoning=True → tokens_after_think_end should be -1
|
||||
self.assertEqual(result.tokens_after_think_end, -1)
|
||||
def test_wraps_inner_grammar_with_reasoning_state_machine(self):
|
||||
os.environ["SGLANG_MAX_THINK_TOKENS"] = "1"
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
inner_grammar = MagicMock()
|
||||
backend._dispatch_result = inner_grammar
|
||||
reasoner = ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(),
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
|
||||
def test_inits_no_reasoning_on_wrapped(self):
|
||||
backend, inner = self._make()
|
||||
mock_grammar = MagicMock(spec=BaseGrammarObject)
|
||||
inner._init_value_dispatch.return_value = mock_grammar
|
||||
wrapped = reasoner._init_value_dispatch(("json", "{}"), reasoning=True)
|
||||
self.assertIsInstance(wrapped, ReasonerGrammarObject)
|
||||
wrapped.accept_token(10)
|
||||
inner_grammar.accept_token.assert_not_called()
|
||||
wrapped.accept_token(2)
|
||||
wrapped.accept_token(42)
|
||||
inner_grammar.accept_token.assert_called_once_with(42)
|
||||
|
||||
result = backend._init_value_dispatch(("json", "schema"), False)
|
||||
# reasoning=False → tokens_after_think_end should be 0
|
||||
self.assertEqual(result.tokens_after_think_end, 0)
|
||||
def test_accepts_multi_token_think_start_marker(self):
|
||||
"""think_start_token can be multi-token (e.g., GPT-OSS) since it's not used."""
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
reasoner = ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(start_ids=[1, 2]),
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
self.assertIsNotNone(reasoner)
|
||||
|
||||
def test_rejects_multi_token_think_end_marker(self):
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "must encode to exactly one token"):
|
||||
ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(end_ids=[2, 3]),
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
|
||||
def test_rejects_unencodable_excluded_token(self):
|
||||
backend = _DummyGrammarBackend(support_token_filter=True)
|
||||
parser = self._make_parser()
|
||||
parser.detector.think_excluded_tokens = ["<unknown>"]
|
||||
tokenizer = _DummyTokenizer(
|
||||
{
|
||||
"<think>": [1],
|
||||
"</think>": [2],
|
||||
}
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "could not be encoded"):
|
||||
ReasonerGrammarBackend(
|
||||
backend,
|
||||
parser,
|
||||
tokenizer,
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
|
||||
def test_strict_mode_fails_when_backend_lacks_token_filter(self):
|
||||
backend = _DummyGrammarBackend(support_token_filter=False)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "does not support token filtering"):
|
||||
ReasonerGrammarBackend(
|
||||
backend,
|
||||
self._make_parser(),
|
||||
self._make_tokenizer(),
|
||||
enable_strict_thinking=True,
|
||||
)
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectRollback(unittest.TestCase):
|
||||
"""Tests for rollback correctness at the THINKING→GENERATION boundary."""
|
||||
|
||||
def _make_object_with_mock_grammar(self):
|
||||
inner_grammar = MagicMock()
|
||||
inner_grammar.is_terminated.return_value = False
|
||||
obj = ReasonerGrammarObject(
|
||||
grammar=inner_grammar,
|
||||
think_end_id=7,
|
||||
think_excluded_token_ids=[3, 5],
|
||||
max_think_tokens=-1,
|
||||
enable_token_filter=True,
|
||||
token_filter_fn=set_token_filter_torch,
|
||||
allocate_vocab_mask_fn=lambda vs, bs, d: torch.zeros(
|
||||
(bs, (vs + 31) // 32), dtype=torch.int32
|
||||
),
|
||||
move_vocab_mask_fn=lambda vm, d: vm,
|
||||
apply_vocab_mask_fn=lambda l, vm: None,
|
||||
)
|
||||
return obj, inner_grammar
|
||||
|
||||
def test_rollback_at_generation_boundary_returns_to_thinking(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
# Accept 3 thinking tokens then think_end_id
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(11)
|
||||
obj.accept_token(12)
|
||||
obj.accept_token(7) # think_end_id → tokens_after_end = 0
|
||||
|
||||
self.assertTrue(obj._is_generation())
|
||||
self.assertEqual(obj.tokens_after_end, 0)
|
||||
|
||||
# Rollback 1 step: should return to THINKING
|
||||
obj.rollback(1)
|
||||
self.assertTrue(obj._is_thinking())
|
||||
self.assertEqual(obj.tokens_in_think, 3)
|
||||
self.assertEqual(obj.tokens_after_end, -1)
|
||||
# Grammar should not have been rolled back (no generation tokens were accepted)
|
||||
inner_grammar.rollback.assert_not_called()
|
||||
|
||||
def test_rollback_spanning_both_phases(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
# 2 thinking tokens + think_end + 3 generation tokens
|
||||
obj.accept_token(10) # think
|
||||
obj.accept_token(11) # think
|
||||
obj.accept_token(7) # think_end_id
|
||||
obj.accept_token(20) # gen 1
|
||||
obj.accept_token(21) # gen 2
|
||||
obj.accept_token(22) # gen 3
|
||||
|
||||
self.assertEqual(obj.tokens_after_end, 3)
|
||||
|
||||
# Rollback 5: should roll back 3 generation tokens + think_end + 1 thinking token
|
||||
obj.rollback(5)
|
||||
self.assertTrue(obj._is_thinking())
|
||||
self.assertEqual(obj.tokens_in_think, 1)
|
||||
# Grammar should be rolled back by 3 (only generation tokens)
|
||||
inner_grammar.rollback.assert_called_once_with(3)
|
||||
|
||||
def test_rollback_generation_tokens_only(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
obj.accept_token(10) # think
|
||||
obj.accept_token(7) # think_end_id
|
||||
obj.accept_token(20) # gen 1
|
||||
obj.accept_token(21) # gen 2
|
||||
|
||||
# Rollback 1: should only roll back 1 generation token
|
||||
obj.rollback(1)
|
||||
self.assertTrue(obj._is_generation())
|
||||
self.assertEqual(obj.tokens_after_end, 1)
|
||||
inner_grammar.rollback.assert_called_once_with(1)
|
||||
|
||||
def test_rollback_thinking_tokens_does_not_touch_grammar(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(11)
|
||||
obj.accept_token(12)
|
||||
|
||||
obj.rollback(2)
|
||||
self.assertTrue(obj._is_thinking())
|
||||
self.assertEqual(obj.tokens_in_think, 1)
|
||||
inner_grammar.rollback.assert_not_called()
|
||||
inner_grammar.accept_token.assert_not_called()
|
||||
|
||||
def test_copy_preserves_state(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(7) # think_end_id → GENERATION
|
||||
obj.accept_token(20)
|
||||
|
||||
self.assertEqual(obj.tokens_in_think, 1)
|
||||
self.assertEqual(obj.tokens_after_end, 1)
|
||||
|
||||
copy = obj.copy()
|
||||
# State counters must be preserved for speculative decoding
|
||||
self.assertEqual(copy.tokens_in_think, 1)
|
||||
self.assertEqual(copy.tokens_after_end, 1)
|
||||
self.assertTrue(copy._is_generation())
|
||||
self.assertIsNotNone(copy.grammar)
|
||||
inner_grammar.copy.assert_called_once()
|
||||
|
||||
def test_copy_preserves_thinking_state(self):
|
||||
obj, inner_grammar = self._make_object_with_mock_grammar()
|
||||
obj.maybe_init_reasoning(True)
|
||||
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(11)
|
||||
|
||||
copy = obj.copy()
|
||||
self.assertEqual(copy.tokens_in_think, 2)
|
||||
self.assertEqual(copy.tokens_after_end, -1)
|
||||
self.assertTrue(copy._is_thinking())
|
||||
|
||||
|
||||
class TestReasonerGrammarObjectFillVocabMask(unittest.TestCase):
|
||||
"""Tests for fill_vocab_mask behavior in different states."""
|
||||
|
||||
def test_thinking_phase_does_not_consult_inner_grammar(self):
|
||||
inner_grammar = MagicMock()
|
||||
# Must return a real tensor for allocate_vocab_mask since fill_vocab_mask
|
||||
# delegates to allocate_vocab_mask via self.grammar when grammar is not None
|
||||
inner_grammar.allocate_vocab_mask.side_effect = lambda vs, bs, d: torch.zeros(
|
||||
(bs, (vs + 31) // 32), dtype=torch.int32
|
||||
)
|
||||
obj = ReasonerGrammarObject(
|
||||
grammar=inner_grammar,
|
||||
think_end_id=7,
|
||||
think_excluded_token_ids=[3, 5],
|
||||
max_think_tokens=-1,
|
||||
enable_token_filter=True,
|
||||
token_filter_fn=set_token_filter_torch,
|
||||
allocate_vocab_mask_fn=lambda vs, bs, d: torch.zeros(
|
||||
(bs, (vs + 31) // 32), dtype=torch.int32
|
||||
),
|
||||
move_vocab_mask_fn=lambda vm, d: vm,
|
||||
apply_vocab_mask_fn=lambda l, vm: None,
|
||||
)
|
||||
obj.maybe_init_reasoning(True)
|
||||
mask = obj.allocate_vocab_mask(64, 1, "cpu")
|
||||
|
||||
obj.fill_vocab_mask(mask, 0)
|
||||
|
||||
inner_grammar.fill_vocab_mask.assert_not_called()
|
||||
# Excluded tokens (3, 5) should be blocked
|
||||
allowed = _allowed_token_ids(mask, [0, 1, 3, 5, 7, 8])
|
||||
self.assertEqual(allowed, [0, 1, 7, 8])
|
||||
|
||||
def test_generation_phase_consults_inner_grammar(self):
|
||||
inner_grammar = MagicMock()
|
||||
inner_grammar.allocate_vocab_mask.side_effect = lambda vs, bs, d: torch.zeros(
|
||||
(bs, (vs + 31) // 32), dtype=torch.int32
|
||||
)
|
||||
obj = ReasonerGrammarObject(
|
||||
grammar=inner_grammar,
|
||||
think_end_id=7,
|
||||
think_excluded_token_ids=[3, 5],
|
||||
max_think_tokens=-1,
|
||||
enable_token_filter=True,
|
||||
token_filter_fn=set_token_filter_torch,
|
||||
allocate_vocab_mask_fn=lambda vs, bs, d: torch.zeros(
|
||||
(bs, (vs + 31) // 32), dtype=torch.int32
|
||||
),
|
||||
move_vocab_mask_fn=lambda vm, d: vm,
|
||||
apply_vocab_mask_fn=lambda l, vm: None,
|
||||
)
|
||||
obj.maybe_init_reasoning(True)
|
||||
obj.accept_token(10)
|
||||
obj.accept_token(7) # think_end_id → GENERATION
|
||||
|
||||
mask = obj.allocate_vocab_mask(64, 1, "cpu")
|
||||
obj.fill_vocab_mask(mask, 0)
|
||||
|
||||
inner_grammar.fill_vocab_mask.assert_called_once_with(mask, 0)
|
||||
|
||||
def test_non_strict_thinking_is_noop(self):
|
||||
inner_grammar = MagicMock()
|
||||
obj = ReasonerGrammarObject(
|
||||
grammar=inner_grammar,
|
||||
think_end_id=7,
|
||||
think_excluded_token_ids=None,
|
||||
max_think_tokens=-1,
|
||||
enable_token_filter=False,
|
||||
token_filter_fn=None,
|
||||
)
|
||||
obj.maybe_init_reasoning(True)
|
||||
mask = torch.zeros((1, 2), dtype=torch.int32)
|
||||
|
||||
obj.fill_vocab_mask(mask, 0)
|
||||
|
||||
inner_grammar.fill_vocab_mask.assert_not_called()
|
||||
# Mask should remain all zeros (no filtering)
|
||||
self.assertTrue(torch.all(mask == 0))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
Unit tests for token filter operations (Triton and Torch paths).
|
||||
|
||||
Verifies that both implementations produce identical bitmask output
|
||||
for the same inputs, ensuring parity across GPU and CPU paths.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
|
||||
from sglang.srt.constrained.torch_ops.token_filter_torch_ops import (
|
||||
set_token_filter_torch,
|
||||
)
|
||||
from sglang.test.ci.ci_register import register_cpu_ci
|
||||
|
||||
register_cpu_ci(2.0, "stage-a-test-cpu")
|
||||
|
||||
# Conditionally import Triton path
|
||||
_has_cuda = torch.cuda.is_available()
|
||||
if _has_cuda:
|
||||
from sglang.srt.constrained.triton_ops.token_filter_ops import (
|
||||
set_token_filter_triton,
|
||||
)
|
||||
|
||||
|
||||
def _get_allowed_tokens(vocab_mask, batch_idx, max_token_id):
|
||||
"""Extract allowed token IDs from a bitmask row."""
|
||||
allowed = []
|
||||
for token_id in range(max_token_id):
|
||||
elem = token_id // 32
|
||||
bit = token_id % 32
|
||||
val = int(vocab_mask[batch_idx, elem].item())
|
||||
if val & (1 << bit):
|
||||
allowed.append(token_id)
|
||||
return allowed
|
||||
|
||||
|
||||
class TestSetTokenFilterTorch(unittest.TestCase):
|
||||
"""Tests for the Torch token filter implementation."""
|
||||
|
||||
def test_allow_tokens_from_blank_mask(self):
|
||||
vocab_mask = torch.zeros((1, 4), dtype=torch.int32) # 128 tokens
|
||||
set_token_filter_torch(vocab_mask, [0, 5, 31, 32, 63], 0, is_allowed=True)
|
||||
|
||||
allowed = _get_allowed_tokens(vocab_mask, 0, 64)
|
||||
self.assertEqual(allowed, [0, 5, 31, 32, 63])
|
||||
|
||||
def test_block_tokens_from_full_mask(self):
|
||||
vocab_mask = torch.full((1, 4), -1, dtype=torch.int32) # all bits set
|
||||
set_token_filter_torch(
|
||||
vocab_mask, [3, 5], 0, is_allowed=False, reset_vocab_mask=False
|
||||
)
|
||||
|
||||
allowed = _get_allowed_tokens(vocab_mask, 0, 64)
|
||||
self.assertNotIn(3, allowed)
|
||||
self.assertNotIn(5, allowed)
|
||||
self.assertIn(0, allowed)
|
||||
self.assertIn(1, allowed)
|
||||
|
||||
def test_reset_then_allow(self):
|
||||
vocab_mask = torch.full((1, 2), -1, dtype=torch.int32)
|
||||
set_token_filter_torch(
|
||||
vocab_mask, [7], 0, is_allowed=True, reset_vocab_mask=True
|
||||
)
|
||||
|
||||
allowed = _get_allowed_tokens(vocab_mask, 0, 64)
|
||||
self.assertEqual(allowed, [7])
|
||||
|
||||
def test_reset_then_block(self):
|
||||
vocab_mask = torch.zeros((1, 2), dtype=torch.int32)
|
||||
set_token_filter_torch(
|
||||
vocab_mask, [3, 5], 0, is_allowed=False, reset_vocab_mask=True
|
||||
)
|
||||
|
||||
allowed = _get_allowed_tokens(vocab_mask, 0, 64)
|
||||
self.assertNotIn(3, allowed)
|
||||
self.assertNotIn(5, allowed)
|
||||
# All other tokens should be allowed (reset to -1 for block mode)
|
||||
self.assertIn(0, allowed)
|
||||
self.assertIn(7, allowed)
|
||||
|
||||
def test_empty_token_list(self):
|
||||
vocab_mask = torch.zeros((1, 2), dtype=torch.int32)
|
||||
set_token_filter_torch(
|
||||
vocab_mask, [], 0, is_allowed=True, reset_vocab_mask=True
|
||||
)
|
||||
|
||||
allowed = _get_allowed_tokens(vocab_mask, 0, 64)
|
||||
self.assertEqual(allowed, [])
|
||||
|
||||
def test_batch_indexing(self):
|
||||
vocab_mask = torch.zeros((3, 2), dtype=torch.int32)
|
||||
set_token_filter_torch(vocab_mask, [1], 0, is_allowed=True)
|
||||
set_token_filter_torch(vocab_mask, [2], 1, is_allowed=True)
|
||||
set_token_filter_torch(vocab_mask, [3], 2, is_allowed=True)
|
||||
|
||||
self.assertEqual(_get_allowed_tokens(vocab_mask, 0, 64), [1])
|
||||
self.assertEqual(_get_allowed_tokens(vocab_mask, 1, 64), [2])
|
||||
self.assertEqual(_get_allowed_tokens(vocab_mask, 2, 64), [3])
|
||||
|
||||
|
||||
@unittest.skipUnless(_has_cuda, "CUDA not available")
|
||||
class TestTritonTorchParity(unittest.TestCase):
|
||||
"""Tests that Triton and Torch produce identical output."""
|
||||
|
||||
def _compare_outputs(self, token_ids, is_allowed, reset):
|
||||
vocab_size = 128
|
||||
num_elements = (vocab_size + 31) // 32
|
||||
|
||||
torch_mask = torch.zeros((1, num_elements), dtype=torch.int32)
|
||||
triton_mask = torch.zeros((1, num_elements), dtype=torch.int32, device="cuda")
|
||||
|
||||
set_token_filter_torch(
|
||||
torch_mask,
|
||||
token_ids,
|
||||
0,
|
||||
is_allowed=is_allowed,
|
||||
reset_vocab_mask=reset,
|
||||
)
|
||||
set_token_filter_triton(
|
||||
triton_mask,
|
||||
token_ids,
|
||||
0,
|
||||
is_allowed=is_allowed,
|
||||
reset_vocab_mask=reset,
|
||||
)
|
||||
|
||||
triton_cpu = triton_mask.cpu()
|
||||
self.assertTrue(
|
||||
torch.equal(torch_mask, triton_cpu),
|
||||
f"Mismatch: torch={torch_mask} triton={triton_cpu}",
|
||||
)
|
||||
|
||||
def test_parity_allow_tokens(self):
|
||||
self._compare_outputs([0, 5, 31, 32, 63, 100], is_allowed=True, reset=True)
|
||||
|
||||
def test_parity_block_tokens(self):
|
||||
self._compare_outputs([3, 5, 10], is_allowed=False, reset=True)
|
||||
|
||||
def test_parity_empty_tokens(self):
|
||||
self._compare_outputs([], is_allowed=True, reset=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user