Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): cap private reasoning with a per-profile thinking budget on SGLang (#700)

svonava6c33b38a834e
diff --git a/packages/sie_server/models/google__gemma-4-31B-it.yaml b/packages/sie_server/models/google__gemma-4-31B-it.yaml
index 67ef3648d..d9ac579f5 100644
--- a/packages/sie_server/models/google__gemma-4-31B-it.yaml
+++ b/packages/sie_server/models/google__gemma-4-31B-it.yaml
@@ -561,3 +561,37 @@ profiles:
- "--mm-process-config"
- '{"image":{"max_soft_tokens":1120}}'
- "--constrained-json-disable-any-whitespace"
+ # ``h100-96k-hires-thinking-no-spec`` with private reasoning capped at 512
+ # tokens: the adapter closes the thought channel there and the json_schema
+ # grammar then constrains the answer. The launch is otherwise identical, so
+ # grammar requests keep this profile. On the 24 Screenshot DEV24 screens
+ # (two passes per run, default sampling) two 512-token runs scored 32/48
+ # complete records at 96.9% of fields and 30/48 at 96.1%, against 32/48 at
+ # 96.9% uncapped, with about 45% fewer output tokens per screen.
+ h100-96k-hires-thinking-budget512-no-spec:
+ extends: h100-96k-hires
+ max_output_tokens: 32768
+ chat_template_kwargs:
+ enable_thinking: true
+ adapter_options:
+ loadtime:
+ max_seq_length: 98304
+ mem_fraction_static: 0.88
+ thinking_budget: 512
+ served_model_name: google/gemma-4-31B-it
+ attention_backend: triton
+ grammar_backend: xgrammar
+ json_number_max_digits: 19
+ reasoning_parser: gemma4
+ tool_call_parser: gemma4
+ speculative_needs_extra_buffer: false
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--quantization"
+ - "fp8"
+ - "--kv-cache-dtype"
+ - "fp8_e4m3"
+ - "--mm-process-config"
+ - '{"image":{"max_soft_tokens":1120}}'
+ - "--constrained-json-disable-any-whitespace"
diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.py
index dbb3ee1d1..8360d0722 100644
--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py
+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py
@@ -45,6 +45,11 @@ _REASONING_BOUNDARIES: dict[ReasoningFormat, tuple[str, str]] = {
"qwen3": (_THINK_OPEN, _THINK_CLOSE),
"gemma4": (_GEMMA_CHANNEL_OPEN + "thought\n", _GEMMA_CHANNEL_CLOSE),
}
+# The single control tokens that open and close each family's reasoning block.
+REASONING_CONTROL_TOKENS: dict[ReasoningFormat, tuple[str, str]] = {
+ "qwen3": (_THINK_OPEN, _THINK_CLOSE),
+ "gemma4": (_GEMMA_CHANNEL_OPEN, _GEMMA_CHANNEL_CLOSE),
+}
# Finish reason values surfaced to gateway / client. ``cancelled`` lands when
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sie_thinking_budget.py b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sie_thinking_budget.py
new file mode 100644
index 000000000..adcc5740f
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sie_thinking_budget.py
@@ -0,0 +1,85 @@
+"""Close a model's private reasoning block once it reaches a token budget.
+
+The SGLang generation child imports this module by name: its directory is on
+the child's ``PYTHONPATH``, and the adapter sends ``PROCESSOR_REFERENCE``, a
+pickle that names :class:`ThinkingBudgetLogitProcessor` instead of carrying
+code. SGLang resolves it when the launch sets ``--enable-custom-logit-processor``.
+
+Each request carries its budget and the tokenizer's reasoning control tokens
+in ``custom_params[PARAM]``. Once the open block has produced ``budget`` tokens,
+the processor forces a newline (when the tokenizer has a single newline token)
+and then the closing token, the way SGLang's own ``ThinkingBudgetLogitProcessor``
+does. After the block closes it leaves the logits alone, so a reasoning-aware
+grammar constrains the answer exactly as it does without a budget.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import MutableMapping, Sequence
+from typing import Any
+
+PARAM = "sie_thinking_budget"
+_STATE = "_sie_thinking_budget_state"
+# Protocol-0 pickle of a module-level reference: no code travels with the request.
+PROCESSOR_REFERENCE = json.dumps({"callable": b"csie_thinking_budget\nThinkingBudgetLogitProcessor\n.".hex()})
+
+
+def forced_token(spec: Any, state: MutableMapping[str, Any], output_ids: Sequence[int]) -> int | None:
+ """Return the token to force at the next step, or ``None`` to leave the logits alone.
+
+ ``spec`` holds ``budget``, the ``open`` and ``close`` token ids, an optional
+ ``newline`` id, and ``open_in_prompt`` when the rendered prompt already
+ opened the block. ``state`` persists per request between steps, so each
+ step reads only the tokens generated since the previous one.
+ """
+ if not isinstance(spec, dict) or state.get("closed"):
+ return None
+ try:
+ budget = int(spec["budget"])
+ open_id = int(spec["open"])
+ close_id = int(spec["close"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ newline_id = spec.get("newline")
+ scanned = int(state.get("scanned", 0))
+ if scanned > len(output_ids):
+ state.clear()
+ scanned = 0
+ if "open_at" not in state:
+ state["open_at"] = -1 if spec.get("open_in_prompt") else None
+ open_at = state["open_at"]
+ for index in range(scanned, len(output_ids)):
+ token = output_ids[index]
+ if token == close_id and open_at is not None:
+ state["closed"] = True
+ state["scanned"] = index + 1
+ return None
+ if token == open_id:
+ open_at = index
+ state["open_at"] = open_at
+ state["scanned"] = len(output_ids)
+ if open_at is None or len(output_ids) - open_at - 1 < budget:
+ return None
+ if isinstance(newline_id, int) and (not output_ids or output_ids[-1] != newline_id):
+ return newline_id
+ return close_id
+
+
+class ThinkingBudgetLogitProcessor:
+ """SGLang custom logit processor that enforces each request's thinking budget."""
+
+ def __call__(self, logits: Any, custom_param_list: list[dict[str, Any] | None] | None = None) -> Any:
+ if not custom_param_list:
+ return logits
+ for row, params in enumerate(custom_param_list):
+ if not params:
+ continue
+ req = params.get("__req__")
+ if req is None:
+ continue
+ token = forced_token(params.get(PARAM), params.setdefault(_STATE, {}), req.output_ids)
+ if token is not None:
+ logits[row, :] = float("-inf")
+ logits[row, token] = 0.0
+ return logits
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 790e1937a..0e315a5cd 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -40,18 +40,23 @@ from typing import Any, Literal, cast
import httpx
from sie_server.adapters._generation_base import (
+ REASONING_CONTROL_TOKENS,
FinishReason,
GenerationAdapter,
GenerationChunk,
GenerationError,
GenerationInvalidRequestError,
GenerationResult,
+ ReasoningFormat,
reasoning_expected_after_prompt,
+ reasoning_starts_in_prompt,
resolve_reasoning_format,
)
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters.sglang import _server
+from sie_server.adapters.sglang._compat.sie_thinking_budget import PARAM as THINKING_BUDGET_PARAM
+from sie_server.adapters.sglang._compat.sie_thinking_budget import PROCESSOR_REFERENCE as THINKING_BUDGET_PROCESSOR
from sie_server.observability.generation_diagnostics import GenerationStreamTimer
from sie_server.types.grammar import (
OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC,
@@ -184,6 +189,51 @@ def _validate_json_number_max_digits(value: Any, grammar_backend: str | None) ->
return value
+def _validate_thinking_budget(value: Any, reasoning_parser: str | None) -> int | None:
+ """Return a usable reasoning-token budget, or None when the profile sets none."""
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ msg = f"thinking_budget must be a positive integer, got {value!r}"
+ raise ValueError(msg)
+ if reasoning_parser not in REASONING_CONTROL_TOKENS:
+ msg = (
+ f"thinking_budget needs a reasoning_parser with known control tokens "
+ f"({', '.join(sorted(REASONING_CONTROL_TOKENS))}), got {reasoning_parser!r}"
+ )
+ raise ValueError(msg)
+ return value
+
+
+def _reasoning_control_token_ids(
+ model_name_or_path: str,
+ *,
+ revision: str | None,
+ trust_remote_code: bool,
+ reasoning_format: ReasoningFormat,
+) -> dict[str, int | None]:
+ """Resolve the reasoning block's open and close token ids, and a newline id, from the tokenizer.
+
+ Raises:
+ ValueError: When a control token does not encode to exactly one id.
+ """
+ from transformers import AutoTokenizer
+
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_name_or_path, revision=revision, trust_remote_code=trust_remote_code
+ )
+ ids: dict[str, int | None] = {}
+ for key, text in zip(("open", "close"), REASONING_CONTROL_TOKENS[reasoning_format], strict=True):
+ encoded = tokenizer.encode(text, add_special_tokens=False)
+ if len(encoded) != 1:
+ msg = f"thinking_budget needs {text!r} to be one token for {model_name_or_path}, got {encoded!r}"
+ raise ValueError(msg)
+ ids[key] = int(encoded[0])
+ newline = tokenizer.encode("\n", add_special_tokens=False)
+ ids["newline"] = int(newline[0]) if len(newline) == 1 else None
+ return ids
+
+
def _mamba_strategy_value(extra_launch_args: list[str], flag: str) -> str | None:
"""Return the value passed to the mamba strategy ``flag``, or ``None``.
@@ -509,10 +559,17 @@ class SGLangGenerationAdapter(GenerationAdapter):
# bound needs the ``xgrammar`` backend, which the child's sitecustomize
# patches.
json_number_max_digits: int | None = None,
+ # Most tokens a request may spend inside the model's private reasoning
+ # block before the adapter closes it; the answer, and any grammar on
+ # it, then follows as usual. None leaves reasoning unbounded and the
+ # launch unchanged. Needs a reasoning parser with known control tokens.
+ thinking_budget: int | None = None,
**kwargs: Any, # accept extra args from loader for compatibility
) -> None:
_ = kwargs
self._json_number_max_digits = _validate_json_number_max_digits(json_number_max_digits, grammar_backend)
+ self._thinking_budget = _validate_thinking_budget(thinking_budget, reasoning_parser)
+ self._thinking_budget_tokens: dict[str, int | None] | None = None
self._model_name_or_path = str(model_name_or_path)
self._max_seq_length = max_seq_length
self._mem_fraction_static = mem_fraction_static
@@ -684,6 +741,24 @@ class SGLangGenerationAdapter(GenerationAdapter):
"""Return the child parser used to separate private reasoning output."""
return self._reasoning_parser
+ @property
+ def thinking_budget(self) -> int | None:
+ """Return the profile's reasoning-token budget, or None when reasoning is unbounded."""
+ return self._thinking_budget
+
+ def _thinking_budget_spec(self, prompt: str) -> dict[str, int | bool | None] | None:
+ """Return the budget fields the SGLang child's processor reads for one reasoning request."""
+ tokens = self._thinking_budget_tokens
+ if self._thinking_budget is None or tokens is None:
+ return None
+ return {
+ "budget": self._thinking_budget,
+ "open": tokens["open"],
+ "close": tokens["close"],
+ "newline": tokens["newline"],
+ "open_in_prompt": reasoning_starts_in_prompt(prompt, resolve_reasoning_format(None, self)),
+ }
+
@property
def image_token_budget(self) -> int | None:
"""Return the most visual tokens ONE image of a single-image request can expand to.
@@ -747,6 +822,13 @@ class SGLangGenerationAdapter(GenerationAdapter):
model_name_or_path=self._model_name_or_path,
revision=self._revision,
)
+ if self._thinking_budget is not None:
+ self._thinking_budget_tokens = _reasoning_control_token_ids(
+ self._model_name_or_path,
+ revision=self._revision,
+ trust_remote_code=self._trust_remote_code,
+ reasoning_format=resolve_reasoning_format(None, self),
+ )
port = _server.find_free_port()
self._port = port
self._server_url = f"http://localhost:{port}"
@@ -839,6 +921,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
cmd.extend(["--reasoning-parser", self._reasoning_parser])
if self._tool_call_parser:
cmd.extend(["--tool-call-parser", self._tool_call_parser])
+ if self._thinking_budget is not None:
+ cmd.append("--enable-custom-logit-processor")
cmd.extend(self._speculative_launch_args(self._speculative))
# Multi-LoRA serving: one base, N adapters, per-request selection via
# ``sampling_params["lora_path"]``. Only emitted when the profile
@@ -1561,6 +1645,10 @@ class SGLangGenerationAdapter(GenerationAdapter):
# further compile-time validation happens inside the backend.
sampling_params["ebnf"] = grammar.value
+ thinking_budget = self._thinking_budget_spec(prompt) if require_reasoning else None
+ if thinking_budget is not None:
+ sampling_params["custom_params"] = {THINKING_BUDGET_PARAM: thinking_budget}
+
# Multi-candidate (``n > 1`` and/or ``best_of``): ask SGLang for all
# candidates in one non-streaming call (``sampling_params["n"]`` → native
# parallel sampling) and emit them as one terminal chunk's ``candidates``
@@ -1596,6 +1684,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
sbody["image_data"] = image_data
if require_reasoning:
sbody["require_reasoning"] = True
+ if thinking_budget is not None:
+ sbody["custom_logit_processor"] = THINKING_BUDGET_PROCESSOR
if video_data:
sbody["video_data"] = video_data
if logprobs:
@@ -1753,6 +1843,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
nbody["image_data"] = image_data
if require_reasoning:
nbody["require_reasoning"] = True
+ if thinking_budget is not None:
+ nbody["custom_logit_processor"] = THINKING_BUDGET_PROCESSOR
if video_data:
nbody["video_data"] = video_data
if logprobs or rank:
@@ -1873,6 +1965,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
body["image_data"] = image_data
if require_reasoning:
body["require_reasoning"] = True
+ if thinking_budget is not None:
+ body["custom_logit_processor"] = THINKING_BUDGET_PROCESSOR
if video_data:
body["video_data"] = video_data
# OpenAI ``logprobs`` → SGLang ``return_logprob`` (top-level body
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 5eabe8395..5285528ef 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -3988,3 +3988,204 @@ def test_generate_n_gt_one_reports_cached_tokens_with_prompt_tokens(mock_async_c
(term,) = asyncio.run(_collect())
assert term.prompt_tokens == 40
assert term.cached_tokens == 32
+
+
+_BUDGET_TOKENS = {"open": 100, "close": 101, "newline": 107}
+
+
[email protected]("value", [0, -1, True, "512", 1.5])
+def test_thinking_budget_must_be_a_positive_integer(value: object) -> None:
+ with pytest.raises(ValueError, match="thinking_budget must be a positive integer"):
+ SGLangGenerationAdapter(
+ model_name_or_path="google/gemma-4-31B-it", reasoning_parser="gemma4", thinking_budget=value
+ )
+
+
[email protected]("reasoning_parser", [None, "glm45"])
+def test_thinking_budget_needs_known_reasoning_control_tokens(reasoning_parser: str | None) -> None:
+ with pytest.raises(ValueError, match="thinking_budget needs a reasoning_parser"):
+ SGLangGenerationAdapter(
+ model_name_or_path="google/gemma-4-31B-it", reasoning_parser=reasoning_parser, thinking_budget=512
+ )
+
+
[email protected]("thinking_budget", [None, 512])
+@patch("sie_server.adapters.sglang.generation._reasoning_control_token_ids", return_value=_BUDGET_TOKENS)
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_load_enables_custom_logit_processors_only_for_a_thinking_budget(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+ mock_token_ids: MagicMock,
+ thinking_budget: int | None,
+) -> None:
+ mock_find_port.return_value = 30005
+ mock_process = MagicMock()
+ mock_process.poll.return_value = None
+ mock_popen.return_value = mock_process
+ mock_requests_get.return_value = MagicMock(status_code=200)
+ adapter = SGLangGemmaAdapter(
+ model_name_or_path="google/gemma-4-31B-it",
+ served_model_name="google/gemma-4-31B-it",
+ reasoning_parser="gemma4",
+ grammar_backend="xgrammar",
+ thinking_budget=thinking_budget,
+ )
+
+ adapter.load("cuda:0")
+
+ cmd = mock_popen.call_args[0][0]
+ assert ("--enable-custom-logit-processor" in cmd) is (thinking_budget is not None)
+ assert mock_token_ids.called is (thinking_budget is not None)
+ if thinking_budget is not None:
+ assert mock_token_ids.call_args.kwargs["reasoning_format"] == "gemma4"
+
+
+def _posted_budget_body(
+ mock_async_client: MagicMock,
+ prompt: str,
+ *,
+ reasoning_parser: str,
+ thinking_budget: int | None = 512,
+ n: int | None = None,
+ stream: bool = False,
+) -> dict[str, Any]:
+ finish = '"meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}'
+ if n is not None and not stream:
+ response = MagicMock()
+ response.json = MagicMock(
+ return_value=[
+ {
+ "text": "{}",
+ "meta_info": {"finish_reason": {"type": "stop"}, "completion_tokens": 1, "prompt_tokens": 1},
+ }
+ ]
+ * n
+ )
+ response.raise_for_status = MagicMock()
+ response.aread = AsyncMock()
+ response.__aenter__ = AsyncMock(return_value=response)
+ client_instance = _make_client_with_stream(_FakeStreamingResponse([]))
+ client_instance.stream.return_value = response
+ elif n is not None:
+ lines = [f'data: {{"index": {index}, "text": "{{}}", {finish}}}' for index in range(n)] + ["data: [DONE]"]
+ client_instance = _make_client_with_stream(_FakeStreamingResponse(lines))
+ else:
+ client_instance = _make_client_with_stream(_FakeStreamingResponse([f'data: {{"text": "{{}}", {finish}}}']))
+ mock_async_client.return_value = client_instance
+ adapter = SGLangGemmaAdapter(
+ model_name_or_path="google/gemma-4-31B-it",
+ served_model_name="google/gemma-4-31B-it",
+ reasoning_parser=reasoning_parser,
+ grammar_backend="xgrammar",
+ thinking_budget=thinking_budget,
+ )
+ adapter._server_url = "http://localhost:30005"
+ if thinking_budget is not None:
+ adapter._thinking_budget_tokens = dict(_BUDGET_TOKENS)
+ grammar = GrammarSpec(kind="json_schema", value={"type": "object", "properties": {"a": {"type": "string"}}})
+
+ async def _drain() -> None:
+ async for _ in adapter.generate(prompt=prompt, max_new_tokens=64, n=n, stream=stream, grammar=grammar):
+ pass
+
+ asyncio.run(_drain())
+ return client_instance.stream.call_args.kwargs["json"]
+
+
[email protected](("n", "stream"), [(None, True), (2, True), (2, False)])
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_a_thinking_budget_rides_with_the_reasoning_aware_grammar(
+ mock_async_client: MagicMock, n: int | None, stream: bool
+) -> None:
+ body = _posted_budget_body(mock_async_client, _GEMMA_THINKING_PROMPT, reasoning_parser="gemma4", n=n, stream=stream)
+
+ # The grammar still applies: SGLang constrains the answer once the closing
+ # token the budget forces (or the model emits) ends the reasoning block.
+ assert body["require_reasoning"] is True
+ assert json.loads(body["sampling_params"]["json_schema"])["type"] == "object"
+ assert body["custom_logit_processor"] == generation_module.THINKING_BUDGET_PROCESSOR
+ assert body["sampling_params"]["custom_params"] == {
+ generation_module.THINKING_BUDGET_PARAM: {
+ "budget": 512,
+ "open": 100,
+ "close": 101,
+ "newline": 107,
+ "open_in_prompt": False,
+ }
+ }
+
+
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_a_thinking_budget_counts_from_a_block_the_prompt_opened(mock_async_client: MagicMock) -> None:
+ body = _posted_budget_body(
+ mock_async_client, "<|im_start|>assistant\n<think>\n", reasoning_parser="qwen3", stream=True
+ )
+
+ assert body["sampling_params"]["custom_params"][generation_module.THINKING_BUDGET_PARAM]["open_in_prompt"] is True
+
+
+ ("prompt", "thinking_budget"),
+ [(_GEMMA_ANSWER_ONLY_PROMPT, 512), (_GEMMA_THINKING_PROMPT, None)],
+)
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_no_budget_fields_without_reasoning_or_without_a_budget(
+ mock_async_client: MagicMock, prompt: str, thinking_budget: int | None
+) -> None:
+ body = _posted_budget_body(
+ mock_async_client, prompt, reasoning_parser="gemma4", thinking_budget=thinking_budget, stream=True
+ )
+
+ assert "custom_logit_processor" not in body
+ assert "custom_params" not in body["sampling_params"]
+
+
+class _FakeTokenizer:
+ def __init__(self, vocab: dict[str, list[int]]) -> None:
+ self._vocab = vocab
+
+ def encode(self, text: str, add_special_tokens: bool = True) -> list[int]:
+ assert add_special_tokens is False
+ return self._vocab[text]
+
+
+ ("reasoning_format", "vocab", "expected"),
+ [
+ (
+ "gemma4",
+ {"<" + "|channel" + ">": [100], "<" + "channel|" + ">": [101], "\n": [107]},
+ {"open": 100, "close": 101, "newline": 107},
+ ),
+ (
+ "qwen3",
+ {"<think>": [151667], "</think>": [151668], "\n": [198]},
+ {"open": 151667, "close": 151668, "newline": 198},
+ ),
+ ("qwen3", {"<think>": [1], "</think>": [2], "\n": [3, 4]}, {"open": 1, "close": 2, "newline": None}),
+ ],
+)
+def test_reasoning_control_token_ids_come_from_the_tokenizer(
+ reasoning_format: str, vocab: dict[str, list[int]], expected: dict[str, int | None]
+) -> None:
+ with patch("transformers.AutoTokenizer.from_pretrained", return_value=_FakeTokenizer(vocab)) as loader:
+ ids = generation_module._reasoning_control_token_ids(
+ "org/model", revision="abc", trust_remote_code=True, reasoning_format=reasoning_format
+ )
+
+ assert ids == expected
+ assert loader.call_args.kwargs == {"revision": "abc", "trust_remote_code": True}
+
+
+def test_reasoning_control_tokens_must_be_single_tokens() -> None:
+ vocab = {"<think>": [1, 2], "</think>": [3], "\n": [4]}
+ with (
+ patch("transformers.AutoTokenizer.from_pretrained", return_value=_FakeTokenizer(vocab)),
+ pytest.raises(ValueError, match="to be one token"),
+ ):
+ generation_module._reasoning_control_token_ids(
+ "org/model", revision=None, trust_remote_code=False, reasoning_format="qwen3"
+ )
diff --git a/packages/sie_server/tests/adapters/test_sglang_launch_flags.py b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
index 46727e6b4..60bc54b66 100644
--- a/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
+++ b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
@@ -43,6 +43,8 @@ _DECLARED_IN_PINNED_ENGINE = frozenset(
"--context-length",
"--disable-cuda-graph",
"--dtype",
+ # Emitted only when a profile sets ``thinking_budget``.
+ "--enable-custom-logit-processor",
"--enable-lora",
"--grammar-backend",
"--is-embedding",
diff --git a/packages/sie_server/tests/adapters/test_sglang_thinking_budget.py b/packages/sie_server/tests/adapters/test_sglang_thinking_budget.py
new file mode 100644
index 000000000..228411e05
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_sglang_thinking_budget.py
@@ -0,0 +1,112 @@
+"""The SGLang child's thinking-budget logit processor."""
+
+from __future__ import annotations
+
+import json
+import pickle
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+import torch
+from sie_server.adapters.sglang._compat import sie_thinking_budget as budget_module
+from sie_server.adapters.sglang._compat.sie_thinking_budget import (
+ PARAM,
+ PROCESSOR_REFERENCE,
+ ThinkingBudgetLogitProcessor,
+ forced_token,
+)
+
+OPEN, CLOSE, NEWLINE = 100, 101, 107
+SPEC = {"budget": 4, "open": OPEN, "close": CLOSE, "newline": NEWLINE, "open_in_prompt": False}
+COMPAT_DIR = Path(budget_module.__file__).parent
+
+
+def _run(spec: dict, steps: list[list[int]]) -> list[int | None]:
+ state: dict = {}
+ return [forced_token(spec, state, output) for output in steps]
+
+
+def test_nothing_is_forced_before_the_block_opens_or_inside_the_budget() -> None:
+ assert _run(SPEC, [[], [5], [5, 6]]) == [None, None, None]
+ assert _run(SPEC, [[OPEN], [OPEN, 1], [OPEN, 1, 2, 3]]) == [None, None, None]
+
+
+def test_the_budget_forces_a_newline_then_the_closing_token() -> None:
+ assert _run(SPEC, [[OPEN, 1, 2, 3, 4]]) == [NEWLINE]
+ assert _run(SPEC, [[OPEN, 1, 2, 3, NEWLINE]]) == [CLOSE]
+ assert _run({**SPEC, "newline": None}, [[OPEN, 1, 2, 3, 4]]) == [CLOSE]
+
+
+def test_the_answer_after_the_closing_token_is_left_to_the_grammar() -> None:
+ # Once the block closes, the processor never touches the logits again, so a
+ # reasoning-aware grammar constrains the answer as it does without a budget.
+ steps = [[OPEN, 1, 2, 3, NEWLINE], [OPEN, 1, 2, 3, NEWLINE, CLOSE]]
+ steps += [[*steps[-1], *range(200, 200 + n)] for n in (1, 10, 50)]
+ assert _run(SPEC, steps) == [CLOSE, None, None, None, None]
+
+
+def test_a_block_the_model_closes_on_its_own_is_left_alone() -> None:
+ assert _run(SPEC, [[OPEN, 1, CLOSE], [OPEN, 1, CLOSE, 9, 9, 9, 9, 9, 9]]) == [None, None]
+
+
+def test_a_block_opened_by_the_prompt_counts_from_the_first_generated_token() -> None:
+ spec = {**SPEC, "open_in_prompt": True}
+ assert _run(spec, [[1, 2, 3], [1, 2, 3, 4]]) == [None, NEWLINE]
+
+
+def test_a_shorter_output_resets_the_scan() -> None:
+ state: dict = {}
+ assert forced_token(SPEC, state, [OPEN, 1, 2]) is None
+ assert forced_token(SPEC, state, [5]) is None
+ assert state["open_at"] is None
+
+
[email protected]("spec", [None, {}, {"budget": "x", "open": OPEN, "close": CLOSE}])
+def test_a_missing_or_malformed_spec_forces_nothing(spec: object) -> None:
+ assert forced_token(spec, {}, [OPEN, 1, 2, 3, 4, 5]) is None
+
+
+def test_the_processor_rewrites_only_the_rows_at_their_budget() -> None:
+ logits = torch.zeros(3, 128)
+ params: list[dict[str, Any] | None] = [
+ {PARAM: SPEC, "__req__": SimpleNamespace(output_ids=[OPEN, 1, 2, 3, NEWLINE])},
+ {PARAM: SPEC, "__req__": SimpleNamespace(output_ids=[OPEN, 1])},
+ None,
+ ]
+
+ out = ThinkingBudgetLogitProcessor()(logits, params)
+
+ assert out[0, CLOSE] == 0.0
+ assert torch.isinf(out[0, :CLOSE]).all()
+ assert torch.isinf(out[0, CLOSE + 1 :]).all()
+ assert torch.equal(out[1], torch.zeros(128))
+ assert torch.equal(out[2], torch.zeros(128))
+
+
+def test_the_processor_keeps_per_request_state_between_steps() -> None:
+ req = SimpleNamespace(output_ids=[OPEN, 1])
+ state: dict[str, Any] = {PARAM: SPEC, "__req__": req}
+ params: list[dict[str, Any] | None] = [state]
+ processor = ThinkingBudgetLogitProcessor()
+ processor(torch.zeros(1, 128), params)
+ req.output_ids = [OPEN, 1, CLOSE, 7]
+ processor(torch.zeros(1, 128), params)
+
+ assert state["_sie_thinking_budget_state"]["closed"] is True
+
+
+def test_the_reference_names_the_module_the_sglang_child_imports(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The adapter sends a pickled module-level reference, never code: the child
+ # resolves it from the compat directory on its PYTHONPATH.
+ monkeypatch.syspath_prepend(str(COMPAT_DIR))
+ monkeypatch.delitem(sys.modules, "sie_thinking_budget", raising=False)
+ payload = bytes.fromhex(json.loads(PROCESSOR_REFERENCE)["callable"])
+
+ loaded = pickle.loads(payload) # noqa: S301 - a fixed, code-owned module reference
+
+ assert loaded.__module__ == "sie_thinking_budget"
+ assert loaded.__name__ == ThinkingBudgetLogitProcessor.__name__
+ assert set(payload) <= set(range(128))
diff --git a/packages/sie_server/tests/config/test_gemma_screenshot_profile.py b/packages/sie_server/tests/config/test_gemma_screenshot_profile.py
index 1cf73b07e..42ae3f853 100644
--- a/packages/sie_server/tests/config/test_gemma_screenshot_profile.py
+++ b/packages/sie_server/tests/config/test_gemma_screenshot_profile.py
@@ -61,3 +61,32 @@ def test_hires_thinking_variant_keeps_stock_sampling_and_the_bare_contract() ->
assert bare_generate.max_output_tokens == 4096
assert bare_generate.context_length == 8192
assert bare_generate.chat_template_kwargs == {"enable_thinking": False}
+
+
+BUDGET_PROFILE = "h100-96k-hires-thinking-budget512-no-spec"
+
+
+def test_budget_profile_is_the_thinking_launch_with_a_512_token_reasoning_cap() -> None:
+ config = load_model_config(MODEL_FILE)
+ budget = config.resolve_profile(BUDGET_PROFILE)
+ thinking = config.resolve_profile(PROFILE)
+
+ budget_launch = dict(budget.loadtime)
+ assert budget_launch.pop("thinking_budget") == 512
+ assert "thinking_budget" not in thinking.loadtime
+ assert budget_launch == thinking.loadtime
+ assert budget.runtime == thinking.runtime
+ assert budget.adapter_path == thinking.adapter_path
+ assert budget.max_output_tokens == thinking.max_output_tokens == 32768
+ assert budget.chat_template_kwargs == thinking.chat_template_kwargs == {"enable_thinking": True}
+ assert budget.max_batch_tokens == budget.kv_budget_tokens == 98304
+
+
+def test_budget_variant_materializes_the_thinking_generation_contract() -> None:
+ configs = expand_profile_variants([load_model_config(MODEL_FILE)])
+ budget = configs[f"{MODEL_ID}:{BUDGET_PROFILE}"]
+ thinking = configs[f"{MODEL_ID}:{PROFILE}"]
+
+ assert budget.tasks.generate == thinking.tasks.generate
+ assert thinking_mode_is_enabled(budget)
+ assert thinking_blocks_must_be_hidden(budget)
diff --git a/packages/sie_server/tests/config/test_generation_mode_profiles.py b/packages/sie_server/tests/config/test_generation_mode_profiles.py
index fce1dc7e7..007e9e11f 100644
--- a/packages/sie_server/tests/config/test_generation_mode_profiles.py
+++ b/packages/sie_server/tests/config/test_generation_mode_profiles.py
@@ -50,6 +50,7 @@ _HARDWARE_THINKING_PROFILES = {
"long-context-thinking-no-spec",
"h100-96k-thinking-no-spec",
"h100-96k-hires-thinking-no-spec",
+ "h100-96k-hires-thinking-budget512-no-spec",
),
}
diff --git a/packages/sie_server/tests/core/test_grammar_routing.py b/packages/sie_server/tests/core/test_grammar_routing.py
index 6b79dc7f1..f07836926 100644
--- a/packages/sie_server/tests/core/test_grammar_routing.py
+++ b/packages/sie_server/tests/core/test_grammar_routing.py
@@ -128,6 +128,8 @@ def test_all_existing_gemma_grammar_routes_are_preserved(tmp_path: Path) -> None
"h100-96k-hires-no-spec": "h100-96k-hires-no-spec",
"h100-96k-hires-out8k": "h100-96k-hires-out8k-no-spec",
"h100-96k-hires-out8k-no-spec": "h100-96k-hires-out8k-no-spec",
+ "h100-96k-hires-thinking-no-spec": "h100-96k-hires-thinking-no-spec",
+ "h100-96k-hires-thinking-budget512-no-spec": "h100-96k-hires-thinking-budget512-no-spec",
}
for profile, serving_profile in expected.items():
requested = _GEMMA_ID if not profile else f"{_GEMMA_ID}:{profile}"