Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(server): default grammar-constrained generation to greedy sampling (#453)

svonavab1c88878833f
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index f5f44b297..7074a0001 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -229,6 +229,15 @@ answer = client.chat_completions(
print(answer["choices"][0]["message"]["content"])
```
+Requests that constrain decoding with a grammar (`response_format` with a
+`json_schema` or `json_object` type, the Responses `text.format`, or a native
+`grammar`) default to greedy decoding: temperature, `presence_penalty`, and
+`frequency_penalty` are 0 unless the request sets them. The model profile's
+sampling recipe still applies to every other request. Some profiles ship a
+chat recipe (Qwen3.8 uses temperature 0.7 and presence penalty 1.5) that makes
+extracted values change between identical calls; set `temperature` explicitly
+to sample a constrained request.
+
The worker renders the selected model's template and applies served template
settings with operator configuration taking precedence over request kwargs.
Granite Guardian's shipped risk dimension is `harm`; prose requesting a
diff --git a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
index 20aa6b1f3..02199a1fb 100644
--- a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
@@ -72,7 +72,9 @@ profiles:
first_chunk_timeout_s: 90
inter_chunk_timeout_s: 15
overall_timeout_s: 600
- # Official Qwen3.8 non-thinking sampling recipe.
+ # Official Qwen3.8 non-thinking sampling recipe. Grammar-constrained
+ # requests default to temperature 0 and no presence penalty instead
+ # (see GRAMMAR_SAMPLING_DEFAULTS in core/runtime_options.py).
default_sampling:
temperature: 0.7
top_p: 0.8
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index b8a9c1dfd..4e8198874 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -53,6 +53,7 @@ from sie_server.api.validation import validate_machine_profile_header, validate_
from sie_server.config.model import validate_chat_template_kwargs
from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.inference_output import ScoreOutput
+from sie_server.core.runtime_options import grammar_default_sampling
from sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_items
from sie_server.core.timing import RequestTiming
from sie_server.core.video_frames import (
@@ -293,6 +294,14 @@ def _response_format_constrains_decoding(response_format: Any) -> bool:
return isinstance(response_format, dict) and response_format.get("type") not in (None, "text")
+def _effective_default_sampling(runtime: dict[str, Any], body: dict[str, Any]) -> Any:
+ """Return the profile sampler defaults, or the grammar defaults when ``response_format`` constrains decoding."""
+ default_sampling = runtime.get("default_sampling")
+ if _response_format_constrains_decoding(body.get("response_format")):
+ return grammar_default_sampling(default_sampling)
+ return default_sampling
+
+
def _strict_response_format_grammar(response_format: Any) -> GrammarSpec | None:
"""Return the JSON Schema grammar a strict ``response_format`` requires."""
if not isinstance(response_format, dict) or response_format.get("type") != "json_schema":
@@ -649,7 +658,7 @@ def _prepare_sglang_body(
profile = config.resolve_profile("default")
runtime = dict(profile.runtime)
- default_sampling = runtime.get("default_sampling")
+ default_sampling = _effective_default_sampling(runtime, body)
if isinstance(default_sampling, dict):
for config_field, chat_field in _DEFAULT_SAMPLING_TO_CHAT_FIELD.items():
if config_field in default_sampling and proxied.get(chat_field) is None:
diff --git a/packages/sie_server/src/sie_server/core/runtime_options.py b/packages/sie_server/src/sie_server/core/runtime_options.py
index c1d656555..b24797803 100644
--- a/packages/sie_server/src/sie_server/core/runtime_options.py
+++ b/packages/sie_server/src/sie_server/core/runtime_options.py
@@ -134,6 +134,19 @@ _GENERATION_SAMPLING_KEYS = {
"min_new_tokens": "min_tokens",
"seed": "seed",
}
+# Sampler defaults for a grammar-constrained request (``json_schema``,
+# ``regex``, or ``ebnf``). They sit above the profile's ``default_sampling``
+# and below every caller-set value (typed request fields and
+# ``options.default_sampling``). A profile's chat recipe is tuned for prose:
+# sampled temperature makes extracted values change between identical calls,
+# and presence or frequency penalties push against the repeated keys, quotes,
+# and braces that JSON needs. ``top_p``, ``top_k``, and ``min_p`` have no
+# effect at temperature 0, so they are left as the profile sets them.
+GRAMMAR_SAMPLING_DEFAULTS: dict[str, float] = {
+ "temperature": 0.0,
+ "presence_penalty": 0.0,
+ "frequency_penalty": 0.0,
+}
def _is_finite_number(value: object) -> bool:
@@ -145,6 +158,26 @@ def _is_finite_number(value: object) -> bool:
return False
+def grammar_default_sampling(
+ profile_sampling: object,
+ request_sampling: object = None,
+) -> dict[str, Any]:
+ """Return the sampler defaults for a grammar-constrained request.
+
+ Layers, lowest first: the profile's ``default_sampling``,
+ :data:`GRAMMAR_SAMPLING_DEFAULTS`, then the request's
+ ``options.default_sampling``. Typed request fields still win over the
+ result because callers only fill fields the request left unset.
+ """
+ merged: dict[str, Any] = {}
+ if isinstance(profile_sampling, dict):
+ merged.update(cast("dict[str, Any]", profile_sampling))
+ merged.update(GRAMMAR_SAMPLING_DEFAULTS)
+ if isinstance(request_sampling, dict):
+ merged.update(cast("dict[str, Any]", request_sampling))
+ return merged
+
+
def apply_generation_runtime_options(
config: ModelConfig,
request_options: dict[str, Any] | None,
@@ -156,6 +189,10 @@ def apply_generation_runtime_options(
``**options`` seam. Validate the currently governed runtime surface and
translate it here so unsupported options fail closed instead of leaking to
adapter kwargs or being silently ignored.
+
+ When ``generate_params`` carries a ``grammar``, the sampler defaults come
+ from :func:`grammar_default_sampling`: temperature and the presence and
+ frequency penalties default to 0 unless the caller set them.
"""
if request_options is not None and not isinstance(request_options, dict):
raise ValueError("'options' must be an object")
@@ -190,6 +227,8 @@ def apply_generation_runtime_options(
request_sampling = request_options.get("default_sampling") if request_options else None
if isinstance(profile_sampling, dict) and isinstance(request_sampling, dict):
runtime["default_sampling"] = {**profile_sampling, **request_sampling}
+ if generate_params.get("grammar") is not None:
+ runtime["default_sampling"] = grammar_default_sampling(profile_sampling, request_sampling)
result = dict(generate_params)
# The typed request maximum is a hard caller limit. Reject an explicit
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 6285c5792..4cba854ed 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -535,6 +535,79 @@ def test_cuda_chat_blocking_proxies_profile_defaults_and_returns_openai_shape(
registry.touch_lru.assert_called_once_with(requested_model)
+def _sglang_body_config(default_sampling: dict[str, Any]) -> SimpleNamespace:
+ profile = SimpleNamespace(runtime={"default_sampling": default_sampling}, loadtime={})
+ return SimpleNamespace(
+ tasks=SimpleNamespace(generate=SimpleNamespace(max_output_tokens=512, chat_template_kwargs={})),
+ resolve_profile=MagicMock(return_value=profile),
+ )
+
+
+_CHAT_RECIPE = {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}
+
+
+def _prepare_body(body: dict[str, Any]) -> dict[str, Any]:
+ adapter = SGLangGenerationAdapter(model_name_or_path="upstream/repo", served_model_name="served")
+ return openai_local._prepare_sglang_body(
+ body,
+ config=_sglang_body_config(dict(_CHAT_RECIPE)),
+ adapter=adapter,
+ max_completion_tokens=body.get("max_completion_tokens"),
+ max_tokens=None,
+ seed=None,
+ )
+
+
[email protected]("format_type", ["json_schema", "json_object"])
+def test_cuda_chat_response_format_defaults_to_greedy_without_penalties(format_type: str) -> None:
+ response_format: dict[str, Any] = {"type": format_type}
+ if format_type == "json_schema":
+ response_format["json_schema"] = {"name": "record", "schema": {"type": "object"}}
+
+ proxied = _prepare_body(
+ {
+ "messages": [{"role": "user", "content": "Extract"}],
+ "max_completion_tokens": 64,
+ "response_format": response_format,
+ }
+ )
+
+ assert proxied["temperature"] == 0.0
+ assert proxied["presence_penalty"] == 0.0
+ assert proxied["frequency_penalty"] == 0.0
+ assert proxied["top_p"] == 0.8
+ assert proxied["top_k"] == 20
+
+
+def test_cuda_chat_response_format_keeps_explicit_sampler_fields() -> None:
+ proxied = _prepare_body(
+ {
+ "messages": [{"role": "user", "content": "Extract"}],
+ "max_completion_tokens": 64,
+ "temperature": 0.6,
+ "presence_penalty": 0.5,
+ "response_format": {"type": "json_schema", "json_schema": {"name": "r", "schema": {"type": "object"}}},
+ }
+ )
+
+ assert proxied["temperature"] == 0.6
+ assert proxied["presence_penalty"] == 0.5
+ assert proxied["frequency_penalty"] == 0.0
+
+
[email protected]("response_format", [None, {"type": "text"}])
+def test_cuda_chat_without_grammar_keeps_profile_recipe(response_format: dict[str, Any] | None) -> None:
+ body: dict[str, Any] = {"messages": [{"role": "user", "content": "Hi"}], "max_completion_tokens": 64}
+ if response_format is not None:
+ body["response_format"] = response_format
+
+ proxied = _prepare_body(body)
+
+ assert proxied["temperature"] == 0.7
+ assert proxied["presence_penalty"] == 1.5
+ assert "frequency_penalty" not in proxied
+
+
def test_cuda_chat_stream_sanitizes_split_reasoning_and_closes_upstream(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.py
index e3de524ad..2752a9d14 100644
--- a/packages/sie_server/tests/core/test_runtime_options.py
+++ b/packages/sie_server/tests/core/test_runtime_options.py
@@ -253,6 +253,93 @@ def test_generation_frequency_penalty_and_seed_defaults_apply() -> None:
assert resolved["seed"] == -(1 << 63)
+_CHAT_RECIPE = {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}
+_JSON_GRAMMAR = {"json_schema": {"type": "object", "properties": {"injured": {"type": "integer"}}}}
+
+
+def _chat_recipe_config() -> ModelConfig:
+ config = _generation_config()
+ config.profiles["default"].adapter_options.runtime["default_sampling"] = dict(_CHAT_RECIPE)
+ return config
+
+
[email protected]("grammar", [_JSON_GRAMMAR, {"regex": "(yes|no)"}])
+def test_generation_grammar_request_defaults_to_greedy_without_penalties(grammar: dict[str, Any]) -> None:
+ resolved = apply_generation_runtime_options(
+ _chat_recipe_config(),
+ None,
+ {"prompt": "hi", "max_new_tokens": 64, "grammar": grammar},
+ )
+
+ assert resolved["temperature"] == 0.0
+ assert resolved["presence_penalty"] == 0.0
+ assert resolved["frequency_penalty"] == 0.0
+ # Inert at temperature 0; kept as the profile sets them.
+ assert resolved["top_p"] == 0.8
+ assert resolved["top_k"] == 20
+ assert resolved["grammar"] == grammar
+
+
+def test_generation_grammar_request_keeps_explicit_sampler_fields() -> None:
+ resolved = apply_generation_runtime_options(
+ _chat_recipe_config(),
+ None,
+ {
+ "prompt": "hi",
+ "max_new_tokens": 64,
+ "grammar": _JSON_GRAMMAR,
+ "temperature": 0.9,
+ "presence_penalty": 0.4,
+ },
+ )
+
+ assert resolved["temperature"] == 0.9
+ assert resolved["presence_penalty"] == 0.4
+ assert resolved["frequency_penalty"] == 0.0
+
+
+def test_generation_grammar_request_keeps_request_default_sampling() -> None:
+ resolved = apply_generation_runtime_options(
+ _chat_recipe_config(),
+ {"default_sampling": {"temperature": 0.3, "presence_penalty": 1.0}},
+ {"prompt": "hi", "max_new_tokens": 64, "grammar": _JSON_GRAMMAR},
+ )
+
+ assert resolved["temperature"] == 0.3
+ assert resolved["presence_penalty"] == 1.0
+ assert resolved["top_p"] == 0.8
+
+
+def test_generation_grammar_request_without_profile_sampling_is_greedy() -> None:
+ config = _generation_config()
+ del config.profiles["default"].adapter_options.runtime["default_sampling"]
+
+ resolved = apply_generation_runtime_options(
+ config,
+ None,
+ {"prompt": "hi", "max_new_tokens": 64, "grammar": _JSON_GRAMMAR},
+ )
+
+ assert resolved["temperature"] == 0.0
+ assert resolved["presence_penalty"] == 0.0
+ assert "top_p" not in resolved
+
+
[email protected]("grammar", [None, "absent"])
+def test_generation_unconstrained_request_keeps_profile_recipe(grammar: object) -> None:
+ params: dict[str, Any] = {"prompt": "hi", "max_new_tokens": 64}
+ if grammar != "absent":
+ params["grammar"] = grammar
+
+ resolved = apply_generation_runtime_options(_chat_recipe_config(), None, params)
+
+ assert resolved["temperature"] == 0.7
+ assert resolved["top_p"] == 0.8
+ assert resolved["top_k"] == 20
+ assert resolved["presence_penalty"] == 1.5
+ assert resolved.get("frequency_penalty") is None
+
+
def test_generation_profile_default_min_new_tokens_caps_to_explicit_max() -> None:
config = _generation_config()
config.profiles["default"].adapter_options.runtime["default_sampling"]["min_new_tokens"] = 10
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index 9c5f7d3f0..9e5454150 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -3678,6 +3678,74 @@ def test_validate_generate_caps_profile_min_new_tokens_to_explicit_max() -> None
assert result.min_tokens == 1
+def _chat_recipe_generation_config() -> ModelConfig:
+ config = _make_generation_config()
+ config.profiles["default"].adapter_options.runtime["default_sampling"] = {
+ "temperature": 0.7,
+ "top_p": 0.8,
+ "top_k": 20,
+ "presence_penalty": 1.5,
+ }
+ return config
+
+
+ "grammar",
+ [
+ {"kind": "json_schema", "value": {"type": "object"}},
+ {"kind": "regex", "value": "(yes|no)"},
+ ],
+)
+def test_validate_generate_grammar_work_item_defaults_to_greedy(grammar: dict[str, Any]) -> None:
+ result = StreamingProcessor._validate_generate_params(
+ _make_work_item(
+ generate={
+ "messages": [{"role": "user", "content": "Extract"}],
+ "max_new_tokens": 64,
+ "grammar": grammar,
+ }
+ ),
+ _chat_recipe_generation_config(),
+ )
+
+ assert not isinstance(result, _ValidationError)
+ assert result.grammar is not None
+ assert result.temperature == 0.0
+ assert result.presence_penalty == 0.0
+ assert result.frequency_penalty == 0.0
+ assert result.top_p == 0.8
+
+
+def test_validate_generate_grammar_work_item_keeps_explicit_temperature() -> None:
+ result = StreamingProcessor._validate_generate_params(
+ _make_work_item(
+ generate={
+ "messages": [{"role": "user", "content": "Extract"}],
+ "max_new_tokens": 64,
+ "temperature": 0.5,
+ "grammar": {"kind": "json_schema", "value": {"type": "object"}},
+ }
+ ),
+ _chat_recipe_generation_config(),
+ )
+
+ assert not isinstance(result, _ValidationError)
+ assert result.temperature == 0.5
+ assert result.presence_penalty == 0.0
+
+
+def test_validate_generate_unconstrained_work_item_keeps_profile_recipe() -> None:
+ result = StreamingProcessor._validate_generate_params(
+ _make_work_item(messages=[{"role": "user", "content": "Hi"}]),
+ _chat_recipe_generation_config(),
+ )
+
+ assert not isinstance(result, _ValidationError)
+ assert result.temperature == 0.7
+ assert result.presence_penalty == 1.5
+ assert result.frequency_penalty is None
+
+
@pytest.mark.parametrize(
"chat_template_kwargs",
[