Skip to content

armgit / sie

Public Imported from GitHub
0

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

release: v0.6.28

github-actions[bot]adf5a9edc559
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b17394e26..a76d65c35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## v0.6.28
+
+- chore(release): refresh locks and generated sources
+- chore(main): release 0.6.28
+- fix(server): stage drafts for local models
+- fix(server): pin speculative draft launches
+- feat(server): optimize non-thinking generation profiles
+
## v0.6.27
- chore(release): refresh locks and generated sources
diff --git a/Cargo.lock b/Cargo.lock
index 54c1a858f..51ba074ee 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3583,7 +3583,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "sie-audio-prep"
-version = "0.6.27"
+version = "0.6.28"
dependencies = [
"audioadapter-buffers",
"opusic-sys",
@@ -3597,7 +3597,7 @@ dependencies = [
[[package]]
name = "sie-gateway"
-version = "0.6.27"
+version = "0.6.28"
dependencies = [
"arc-swap",
"async-nats",
@@ -3655,7 +3655,7 @@ dependencies = [
[[package]]
name = "sie-server-sidecar"
-version = "0.6.27"
+version = "0.6.28"
dependencies = [
"anyhow",
"async-nats",
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index e8a44e466..13f9b4fb2 100644
--- a/deploy/helm/sie-cluster/Chart.yaml
+++ b/deploy/helm/sie-cluster/Chart.yaml
@@ -4,8 +4,8 @@ description: >-
SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,
and observability
type: application
-version: 0.6.27 # x-release-please-version
-appVersion: v0.6.27 # x-release-please-version
+version: 0.6.28 # x-release-please-version
+appVersion: v0.6.28 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index acbd0575f..8ca571dd1 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-chroma"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for ChromaDB"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.toml
index 05ff0f9d3..baaa3056a 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for CrewAI"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.toml
index 539a45fa2..5c7200b32 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for DSPy"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.toml
index 95a5bc6d3..bd779b475 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for Haystack"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.toml
index 109c9965c..a9258681c 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for LanceDB"
requires-python = ">=3.12"
dependencies = [
diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.toml
index dbe0b193f..1eedcfd5a 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index 884c66ab0..61ede5565 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index 967f9af2f..41dde17d7 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for Qdrant"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.json
index 327a19ba0..32795825c 100644
--- a/integrations/sie_ts_chroma/package.json
+++ b/integrations/sie_ts_chroma/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-chroma",
- "version": "0.6.27",
+ "version": "0.6.28",
"description": "SIE embedding function for ChromaDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.json
index e030bc4de..af6902691 100644
--- a/integrations/sie_ts_lancedb/package.json
+++ b/integrations/sie_ts_lancedb/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-lancedb",
- "version": "0.6.27",
+ "version": "0.6.28",
"description": "SIE embedding function and reranker for LanceDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.json
index 2abbd0958..835813e1f 100644
--- a/integrations/sie_ts_langchain/package.json
+++ b/integrations/sie_ts_langchain/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-langchain",
- "version": "0.6.27",
+ "version": "0.6.28",
"description": "SIE embeddings integration for LangChain.js",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.json
index 9483587d9..6ae5c50a2 100644
--- a/integrations/sie_ts_llamaindex/package.json
+++ b/integrations/sie_ts_llamaindex/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-llamaindex",
- "version": "0.6.27",
+ "version": "0.6.28",
"description": "SIE embeddings integration for LlamaIndex.TS",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.toml
index c540ba005..b8a6d5fad 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.6.27"
+version = "0.6.28"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.toml
index cbd2e54d5..bf5a5e287 100644
--- a/packages/sie_audio_prep/Cargo.toml
+++ b/packages/sie_audio_prep/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-audio-prep"
-version = "0.6.27"
+version = "0.6.28"
edition = "2021"
license = "Apache-2.0"
description = "Bounded, shared audio decoding and resampling for SIE workers."
diff --git a/packages/sie_audio_prep/build_wheel.py b/packages/sie_audio_prep/build_wheel.py
index bda5a7d5e..d3576d68a 100644
--- a/packages/sie_audio_prep/build_wheel.py
+++ b/packages/sie_audio_prep/build_wheel.py
@@ -16,7 +16,7 @@ import zipfile
from pathlib import Path
MATURIN_VERSION = "1.13.3"
-AUDIO_PREP_VERSION = "0.6.27" # x-release-please-version
+AUDIO_PREP_VERSION = "0.6.28" # x-release-please-version
AUDIO_WHEEL_COMPATIBILITY = "manylinux_2_28"
AUDIO_WHEEL_FILENAME = f"sie_audio_prep-{AUDIO_PREP_VERSION}-cp312-abi3-{AUDIO_WHEEL_COMPATIBILITY}_x86_64.whl"
AUDIO_WHEEL_REMOTE = f"/opt/sie/wheels/{AUDIO_WHEEL_FILENAME}"
diff --git a/packages/sie_audio_prep/pyproject.toml b/packages/sie_audio_prep/pyproject.toml
index 864a7710f..f75c6a1a3 100644
--- a/packages/sie_audio_prep/pyproject.toml
+++ b/packages/sie_audio_prep/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "maturin"
[project]
name = "sie-audio-prep"
-version = "0.6.27"
+version = "0.6.28"
description = "Bounded, shared audio decoding and resampling for SIE workers."
requires-python = ">=3.12,<3.13"
license = { text = "Apache-2.0" }
diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index a093669d1..fbaafc19a 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.6.27"
+version = "0.6.28"
edition = "2021"
publish = false
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 217c3dc8d..07bc32a60 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -3745,7 +3745,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.6.27"
+ "version": "0.6.28"
},
"openapi": "3.1.0",
"paths": {
diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rs
index 17124b2c1..a97812f0e 100644
--- a/packages/sie_gateway/src/handlers/config_api.rs
+++ b/packages/sie_gateway/src/handlers/config_api.rs
@@ -733,7 +733,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -927,7 +930,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("nonexistent.module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rs
index b52609ac6..1530457f7 100644
--- a/packages/sie_gateway/src/handlers/models.rs
+++ b/packages/sie_gateway/src/handlers/models.rs
@@ -358,7 +358,10 @@ mod route_tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -387,7 +390,10 @@ mod route_tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -398,7 +404,10 @@ mod route_tests {
profiles.insert(
"candle".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),
),
@@ -429,7 +438,10 @@ mod route_tests {
profiles.insert(
"candle".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),
),
@@ -533,7 +545,10 @@ mod route_tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -551,7 +566,10 @@ mod route_tests {
profiles.insert(
"a100".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(8192),
compute_precision: None,
diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rs
index cd76a1791..1abd24e37 100644
--- a/packages/sie_gateway/src/handlers/pools.rs
+++ b/packages/sie_gateway/src/handlers/pools.rs
@@ -306,7 +306,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
.to_string(),
@@ -323,7 +326,10 @@ mod tests {
profiles.insert(
"fp8".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
.to_string(),
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 1ee1df37a..31c6b2da1 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -6686,10 +6686,11 @@ async fn resolve_generation_route(
/// out-of-schema keys, truncates mid-JSON), so a model whose default profile is
/// speculative points ``grammar_profile`` at a non-speculative profile. The
/// target is resolved off the request's *base* model
-/// (``ModelRegistry::grammar_route_variant``), so an explicit sibling-variant
-/// id (``…:a100-40gb``, also speculative) reroutes to ``{base}:{grammar_profile}``
-/// too, and the grammar-safe variant itself is a no-op (same bundle/pool/lane —
-/// only the worker-loaded model changes). Call this BEFORE the capability/LoRA
+/// (``ModelRegistry::grammar_route_variant``). An explicit sibling variant may
+/// name a profile-scoped non-speculative twin that preserves its context,
+/// hardware launch shape, and thinking mode; otherwise it uses the model-wide
+/// fallback. The grammar-safe variant itself is a no-op (same bundle/pool/lane
+/// — only the worker-loaded model changes). Call this BEFORE the capability/LoRA
/// gates and resolve those gates against the routed variant: the variant
/// preserves the base capabilities but narrows the profile-scoped LoRA
/// allow-list, so a gate run against the base would accept an adapter the
@@ -14287,7 +14288,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -19795,7 +19799,10 @@ mod tests {
let registry = empty_registry();
let mk = || ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -19806,7 +19813,11 @@ mod tests {
profiles.insert("default".to_string(), mk());
// A non-`default` profile expands into the `org/g:no-spec` variant
// entry that grammar routing dispatches to.
- profiles.insert("no-spec".to_string(), mk());
+ let mut no_spec = mk();
+ no_spec.adapter_options = Some(serde_json::json!({
+ "loadtime": {"speculative": {"enabled": false}},
+ }));
+ profiles.insert("no-spec".to_string(), no_spec);
// `tasks.generate.grammar_profile: no-spec` is what surfaces on
// `info_extras.grammar_profile` — the field the handlers read.
let tasks: serde_yaml::Value = serde_yaml::from_str(
@@ -19884,7 +19895,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -19925,7 +19939,10 @@ mod tests {
let registry = empty_registry();
let default_profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -19935,12 +19952,18 @@ mod tests {
extends: None,
};
let nospec_profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
adapter_options: Some(serde_json::json!({
- "loadtime": { "lora_paths": { "a2": "org/a2" } }
+ "loadtime": {
+ "lora_paths": { "a2": "org/a2" },
+ "speculative": { "enabled": false }
+ }
})),
extends: None,
};
@@ -19999,7 +20022,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rs
index 42aaa29d0..92a34dc84 100644
--- a/packages/sie_gateway/src/nats/manager.rs
+++ b/packages/sie_gateway/src/nats/manager.rs
@@ -698,7 +698,10 @@ adapters:
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:Adapter".to_string(),
),
diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rs
index 2d38849c4..e4334ea36 100644
--- a/packages/sie_gateway/src/state/config_bootstrap.rs
+++ b/packages/sie_gateway/src/state/config_bootstrap.rs
@@ -841,7 +841,10 @@ mod tests {
profiles: HashMap::from([(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:Adapter".to_string(),
),
diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rs
index a2fc1ee77..ad92a0162 100644
--- a/packages/sie_gateway/src/state/model_registry.rs
+++ b/packages/sie_gateway/src/state/model_registry.rs
@@ -656,7 +656,7 @@ impl ModelRegistry {
}
let adapter_modules = Self::base_route_adapter_modules_from_profiles(&config.profiles);
- Ok(ModelEntry {
+ let entry = ModelEntry {
name: model_name.clone(),
canonical_base_model: model_name,
canonical_profile: "default".to_string(),
@@ -666,7 +666,70 @@ impl ModelRegistry {
profile_names,
profile_configs,
info_extras,
- })
+ };
+ Self::validate_profile_grammar_fallbacks(&entry)?;
+ Ok(entry)
+ }
+
+ fn validate_profile_grammar_fallbacks(entry: &ModelEntry) -> Result<(), String> {
+ if let Some(global_target) = entry.info_extras.grammar_profile.as_deref() {
+ // A temporarily missing global target remains a runtime
+ // MissingVariant outcome for config-skew compatibility. When the
+ // target is present, fail closed on chained fallbacks.
+ if let Some(target) = entry.profile_configs.get(global_target) {
+ if target.grammar_profile.is_some() {
+ return Err(format!(
+ "tasks.generate.grammar_profile target '{global_target}' must not declare another grammar_profile"
+ ));
+ }
+ if !Self::profile_does_not_enable_speculation(target) {
+ return Err(format!(
+ "tasks.generate.grammar_profile target '{global_target}' must not enable speculation"
+ ));
+ }
+ }
+ }
+ for (profile_name, profile) in &entry.profile_configs {
+ let Some(target_name) = profile.grammar_profile.as_deref() else {
+ continue;
+ };
+ if profile_name == "default" {
+ return Err(
+ "Profile 'default' must use tasks.generate.grammar_profile rather than a profile-scoped fallback"
+ .to_string(),
+ );
+ }
+ if target_name == "default" || target_name == profile_name {
+ return Err(format!(
+ "Profile '{profile_name}' grammar_profile must name a non-default sibling profile, got '{target_name}'"
+ ));
+ }
+ if !entry.profile_configs.contains_key(target_name) {
+ return Err(format!(
+ "Profile '{profile_name}' grammar_profile '{target_name}' is not defined"
+ ));
+ }
+ if entry
+ .profile_configs
+ .get(target_name)
+ .and_then(|target| target.grammar_profile.as_ref())
+ .is_some()
+ {
+ return Err(format!(
+ "Profile '{profile_name}' grammar_profile target '{target_name}' must not declare another grammar_profile"
+ ));
+ }
+ if !Self::profile_scoped_grammar_fallback_is_compatible(
+ entry,
+ profile_name,
+ target_name,
+ ) {
+ return Err(format!(
+ "Profile '{profile_name}' grammar_profile '{target_name}' must preserve adapter, precision, batch, KV/output limits, tokenizer mode and load-time settings while explicitly disabling speculation"
+ ));
+ }
+ }
+ Ok(())
}
fn normalize_model_pool(pool: Option<&str>) -> Result<Option<String>, String> {
@@ -770,7 +833,10 @@ impl ModelRegistry {
fn empty_profile_config() -> crate::types::model::ProfileConfig {
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: None,
max_batch_tokens: None,
compute_precision: None,
@@ -810,6 +876,16 @@ impl ModelRegistry {
if profile.max_output_tokens.is_some() {
resolved.max_output_tokens = profile.max_output_tokens;
}
+ if profile.kv_budget_tokens.is_some() {
+ resolved.kv_budget_tokens = profile.kv_budget_tokens;
+ }
+ // Routing metadata is profile-local rather than inherited. This
+ // prevents a grammar-safe child from inheriting its parent's
+ // fallback and recursively pointing at itself.
+ resolved.grammar_profile = profile.grammar_profile.clone();
+ if profile.chat_template_kwargs.is_some() {
+ resolved.chat_template_kwargs = profile.chat_template_kwargs.clone();
+ }
resolved.adapter_options = ModelRegistry::merge_adapter_options(
resolved.adapter_options,
profile.adapter_options.clone(),
@@ -845,7 +921,10 @@ impl ModelRegistry {
(
name.clone(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: canon.kv_budget_tokens,
max_output_tokens: existing_output_caps.get(name).copied(),
+ grammar_profile: canon.grammar_profile.clone(),
+ chat_template_kwargs: canon.chat_template_kwargs.clone(),
adapter_path: canon.adapter_path.clone(),
max_batch_tokens: canon.max_batch_tokens,
compute_precision: canon.compute_precision.clone(),
@@ -877,10 +956,14 @@ impl ModelRegistry {
.get("default")
.cloned()
.unwrap_or(CanonicalProfile {
+ kv_budget_tokens: None,
adapter_path: None,
max_batch_tokens: None,
compute_precision: None,
+ max_output_tokens: None,
adapter_options: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
});
let profile = entry.profile_configs.get(profile_name)?;
@@ -893,6 +976,16 @@ impl ModelRegistry {
if profile.compute_precision.is_some() {
resolved.compute_precision = profile.compute_precision.clone();
}
+ if profile.max_output_tokens.is_some() {
+ resolved.max_output_tokens = profile.max_output_tokens;
+ }
+ if profile.kv_budget_tokens.is_some() {
+ resolved.kv_budget_tokens = profile.kv_budget_tokens;
+ }
+ resolved.grammar_profile = profile.grammar_profile.clone();
+ if profile.chat_template_kwargs.is_some() {
+ resolved.chat_template_kwargs = profile.chat_template_kwargs.clone();
+ }
resolved.adapter_options =
Self::merge_adapter_options(resolved.adapter_options, profile.adapter_options.clone());
Some(resolved)
@@ -1103,13 +1196,16 @@ impl ModelRegistry {
/// ``ModelInfoExtras::grammar_profile``), grammar requests must run on the
/// ``{base}:{grammar_profile}`` profile variant rather than a speculative
/// one — NEXTN/MTP speculative decoding bypasses SGLang's Outlines grammar
- /// FSM. An explicit variant that inherits the grammar profile, uses its
- /// adapter/backend, and keeps speculation disabled remains selected.
+ /// FSM. An explicit variant may declare a profile-scoped grammar fallback
+ /// that preserves its context/hardware/thinking launch shape while
+ /// disabling speculation. A variant that directly inherits the model-wide
+ /// grammar profile and is already safe remains selected.
///
/// The routing target is resolved off the request's *base* model, so the
/// rewrite fires regardless of which id the caller named:
/// - base id (``Qwen/Qwen3.5-4B``) → ``…:no-spec``
/// - sibling variant (``…:a100-40gb``, NEXTN) → ``…:no-spec``
+ /// - scoped variant (``…:h200-256k``) → ``…:h200-256k-no-spec``
/// - target variant (``…:no-spec``) → ``Keep`` (already safe)
/// - inheriting variant (``…:h100-fp8``) → ``Keep`` (already safe)
/// - no ``grammar_profile`` declared → ``Keep``
@@ -1138,12 +1234,12 @@ impl ModelRegistry {
}
}
- /// Resolve the *base* model id and its declared ``grammar_profile`` for a
- /// possibly-variant request id. The hint lives on the base entry only —
- /// variant entries clear it (see ``narrow_info_extras_to_profile``) so a
- /// variant never recursively re-routes — so an explicit sibling-variant id
- /// (e.g. ``…:a100-40gb``) resolves the *base's* profile here. Returns
- /// ``None`` when no ``grammar_profile`` is declared.
+ /// Resolve the *base* model id and grammar fallback for a possibly-variant
+ /// request id. The model-wide hint lives on the base entry; an explicit
+ /// profile may override it with ``profiles.<name>.grammar_profile``. The
+ /// variant entry itself clears the model-wide hint to prevent recursive
+ /// ``{base}:{profile}:{grammar_profile}`` routing, so both hints are read
+ /// from the canonical base entry here.
fn base_grammar_profile(snap: &RegistrySnapshot, model: &str) -> Option<(String, String)> {
let canonical = Self::canonical_model_name(snap, model)?;
// Base entry carrying the hint.
@@ -1158,6 +1254,22 @@ impl ModelRegistry {
// hint). Strip the trailing ``:profile`` and read the base entry's hint.
let (base, source_profile) = canonical.rsplit_once(':')?;
let base_entry = snap.models.get(base)?;
+ // A declared profile-scoped fallback is already a concrete safe
+ // target. Keep it instead of applying the model-wide fallback again.
+ if base_entry
+ .profile_configs
+ .values()
+ .any(|profile| profile.grammar_profile.as_deref() == Some(source_profile))
+ {
+ return Some((base.to_string(), source_profile.to_string()));
+ }
+ let scoped = base_entry
+ .profile_configs
+ .get(source_profile)
+ .and_then(|profile| profile.grammar_profile.clone());
+ if let Some(scoped) = scoped {
+ return Some((base.to_string(), scoped));
+ }
let gp = base_entry.info_extras.grammar_profile.clone()?;
let target_profile = if base_entry
.info_extras
@@ -1173,6 +1285,41 @@ impl ModelRegistry {
Some((base.to_string(), target_profile))
}
+ fn profile_scoped_grammar_fallback_is_compatible(
+ entry: &ModelEntry,
+ source_profile: &str,
+ target_profile: &str,
+ ) -> bool {
+ let (Some(source), Some(target)) = (
+ entry.profile_configs.get(source_profile),
+ entry.profile_configs.get(target_profile),
+ ) else {
+ return false;
+ };
+ source.adapter_path == target.adapter_path
+ && source.kv_budget_tokens == target.kv_budget_tokens
+ && source.max_batch_tokens == target.max_batch_tokens
+ && source.compute_precision == target.compute_precision
+ && source.max_output_tokens == target.max_output_tokens
+ && source.chat_template_kwargs == target.chat_template_kwargs
+ && Self::profile_explicitly_disables_speculation(target)
+ && Self::profile_loadtime_without_speculation(source)
+ == Self::profile_loadtime_without_speculation(target)
+ }
+
+ fn profile_loadtime_without_speculation(
+ profile: &CanonicalProfile,
+ ) -> Option<serde_json::Map<String, serde_json::Value>> {
+ let mut loadtime = profile
+ .adapter_options
+ .as_ref()?
+ .get("loadtime")?
+ .as_object()?
+ .clone();
+ loadtime.remove("speculative");
+ Some(loadtime)
+ }
+
fn profile_is_grammar_compatible(
entry: &ModelEntry,
profile: &str,
@@ -1199,6 +1346,13 @@ impl ModelRegistry {
)
}
+ fn profile_does_not_enable_speculation(profile: &CanonicalProfile) -> bool {
+ match Self::profile_loadtime_value(profile, "speculative") {
+ None => true,
+ Some(value) => matches!(value.get("enabled"), Some(serde_json::Value::Bool(false))),
+ }
+ }
+
fn profile_extra_launch_args_are_compatible(
candidate: &CanonicalProfile,
grammar: &CanonicalProfile,
@@ -2140,6 +2294,7 @@ impl ModelRegistry {
.collect();
let mut affected_model_names = vec![sie_id.clone()];
if let Some(base_entry) = snap.models.get(sie_id).cloned() {
+ Self::validate_profile_grammar_fallbacks(&base_entry)?;
let old_variants: Vec<String> = snap
.models
.keys()
@@ -2287,7 +2442,10 @@ mod tests {
extends: Option<&str>,
) -> crate::types::model::ProfileConfig {
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: adapter_path.map(str::to_string),
max_batch_tokens,
compute_precision: None,
@@ -2389,7 +2547,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2427,7 +2588,10 @@ mod tests {
let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
let mk = || ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2482,6 +2646,27 @@ mod tests {
"raw-grammar-override",
serde_json::json!({"extra_launch_args": ["--grammar-backend", "xgrammar"]}),
);
+ let mut scoped = mk();
+ scoped.grammar_profile = Some("h200-256k-no-spec".to_string());
+ scoped.adapter_options = Some(serde_json::json!({
+ "loadtime": {
+ "max_seq_length": 262144,
+ "grammar_backend": "outlines",
+ "speculative": {"enabled": true, "algorithm": "nextn"},
+ "extra_launch_args": ["--quantization", "fp8", "--kv-cache-dtype", "fp8_e4m3"],
+ },
+ }));
+ profiles.insert("h200-256k".to_string(), scoped);
+ let mut scoped_fallback = mk();
+ scoped_fallback.adapter_options = Some(serde_json::json!({
+ "loadtime": {
+ "max_seq_length": 262144,
+ "grammar_backend": "outlines",
+ "speculative": {"enabled": false},
+ "extra_launch_args": ["--quantization", "fp8", "--kv-cache-dtype", "fp8_e4m3"],
+ },
+ }));
+ profiles.insert("h200-256k-no-spec".to_string(), scoped_fallback);
// ``tasks.generate.grammar_profile: no-spec`` is the routing hint the
// gateway reads off the base entry.
let tasks: serde_yaml::Value =
@@ -2527,6 +2712,16 @@ mod tests {
registry.grammar_route_variant("ORG/G:H100-FP8"),
GrammarRoute::Keep
);
+ // A profile-scoped fallback preserves the exact long-context launch
+ // shape and rewrites only to its declared non-speculative twin.
+ assert_eq!(
+ registry.grammar_route_variant("org/g:h200-256k"),
+ GrammarRoute::Rewrite("org/g:h200-256k-no-spec".to_string())
+ );
+ assert_eq!(
+ registry.grammar_route_variant("org/g:h200-256k-no-spec"),
+ GrammarRoute::Keep
+ );
// Inheritance is only a signal, not proof: incompatible structured or
// raw launch settings must still fall back to ``no-spec``.
for profile in [
@@ -2548,6 +2743,48 @@ mod tests {
registry.grammar_route_variant("org/g:no-spec"),
GrammarRoute::Keep
);
+
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), mk());
+ let mut fast = mk();
+ fast.grammar_profile = Some("safe".to_string());
+ fast.adapter_options = Some(serde_json::json!({
+ "loadtime": {
+ "grammar_backend": "outlines",
+ "speculative": {"enabled": true},
+ },
+ }));
+ profiles.insert("fast".to_string(), fast);
+ let mut safe = mk();
+ safe.adapter_options = Some(serde_json::json!({
+ "loadtime": {
+ "grammar_backend": "outlines",
+ "speculative": {"enabled": false},
+ },
+ }));
+ profiles.insert("safe".to_string(), safe);
+ let tasks: serde_yaml::Value = serde_yaml::from_str("generate: {}\n").unwrap();
+ registry
+ .add_model_config(ModelConfig {
+ name: "org/scoped-only".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: Some(tasks),
+ })
+ .unwrap();
+ assert_eq!(
+ registry.grammar_route_variant("org/scoped-only:fast"),
+ GrammarRoute::Rewrite("org/scoped-only:safe".to_string())
+ );
+ assert_eq!(
+ registry.grammar_route_variant("org/scoped-only:safe"),
+ GrammarRoute::Keep
+ );
}
#[test]
@@ -2568,7 +2805,10 @@ mod tests {
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2593,6 +2833,182 @@ mod tests {
assert_eq!(registry.grammar_route_variant("org/n"), GrammarRoute::Keep);
}
+ #[test]
+ fn test_profile_scoped_grammar_fallback_rejects_launch_shape_mismatch() {
+ use crate::types::model::{ModelConfig, ProfileConfig};
+ use std::collections::HashMap as StdHashMap;
+
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+ fs::write(
+ bundles_dir.join("default.yaml"),
+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",
+ )
+ .unwrap();
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+ let profile = |speculative: bool, max_seq_length: u32| ProfileConfig {
+ kv_budget_tokens: None,
+ max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
+ max_batch_tokens: Some(4096),
+ compute_precision: None,
+ adapter_options: Some(serde_json::json!({
+ "loadtime": {
+ "max_seq_length": max_seq_length,
+ "grammar_backend": "outlines",
+ "speculative": {"enabled": speculative},
+ },
+ })),
+ extends: None,
+ };
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), profile(true, 8192));
+ profiles.insert("unsafe".to_string(), profile(true, 8192));
+ let tasks: serde_yaml::Value =
+ serde_yaml::from_str("generate:\n grammar_profile: unsafe\n").unwrap();
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/unsafe-global-target".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: Some(tasks),
+ })
+ .unwrap_err();
+ assert!(error.contains("must not enable speculation"));
+
+ let default = profile(false, 8192);
+ let mut source = profile(true, 262_144);
+ source.grammar_profile = Some("safe".to_string());
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), default);
+ profiles.insert("fast".to_string(), source);
+ profiles.insert("safe".to_string(), profile(false, 8192));
+
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/mismatch".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap_err();
+ assert!(error
+ .contains("must preserve adapter, precision, batch, KV/output limits, tokenizer mode"));
+
+ let default = profile(false, 8192);
+ let mut source = profile(true, 262_144);
+ source.grammar_profile = Some("safe".to_string());
+ source.chat_template_kwargs = Some(serde_json::json!({"enable_thinking": true}));
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), default);
+ profiles.insert("fast".to_string(), source);
+ profiles.insert("safe".to_string(), profile(false, 262_144));
+
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/mode-mismatch".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap_err();
+ assert!(error.contains("tokenizer mode"));
+
+ let default = profile(false, 8192);
+ let mut source = profile(true, 262_144);
+ source.grammar_profile = Some("safe".to_string());
+ source.max_output_tokens = Some(32_768);
+ let mut safe = profile(false, 262_144);
+ safe.max_output_tokens = Some(4_096);
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), default);
+ profiles.insert("fast".to_string(), source);
+ profiles.insert("safe".to_string(), safe);
+
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/output-cap-mismatch".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap_err();
+ assert!(error.contains("KV/output limits"));
+
+ let default = profile(false, 8192);
+ let mut source = profile(true, 262_144);
+ source.grammar_profile = Some("safe".to_string());
+ source.kv_budget_tokens = Some(262_144);
+ let mut safe = profile(false, 262_144);
+ safe.kv_budget_tokens = Some(98_304);
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), default);
+ profiles.insert("fast".to_string(), source);
+ profiles.insert("safe".to_string(), safe);
+
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/kv-budget-mismatch".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap_err();
+ assert!(error.contains("KV/output limits"));
+
+ let default = profile(false, 8192);
+ let mut source = profile(true, 262_144);
+ source.grammar_profile = Some("safe".to_string());
+ let mut safe = profile(false, 262_144);
+ safe.grammar_profile = Some("deeper".to_string());
+ let mut profiles = StdHashMap::new();
+ profiles.insert("default".to_string(), default);
+ profiles.insert("fast".to_string(), source);
+ profiles.insert("safe".to_string(), safe);
+ profiles.insert("deeper".to_string(), profile(false, 262_144));
+
+ let error = registry
+ .add_model_config(ModelConfig {
+ name: "org/chained-fallback".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap_err();
+ assert!(error.contains("must not declare another grammar_profile"));
+ }
+
#[test]
fn test_grammar_route_variant_from_filesystem_profile_inheritance() {
let (_dir, bundles_dir, models_dir) = create_test_dirs();
@@ -2654,7 +3070,10 @@ profiles:
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2706,7 +3125,10 @@ profiles:
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2719,7 +3141,10 @@ profiles:
profiles.insert(
"bad/name".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -2881,7 +3306,10 @@ profiles:
profiles.insert(
"experimental".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),
),
@@ -3253,12 +3681,16 @@ profiles:
..ModelInfoExtras::default()
};
let profile = CanonicalProfile {
+ kv_budget_tokens: None,
adapter_path: None,
max_batch_tokens: None,
compute_precision: None,
+ max_output_tokens: None,
adapter_options: Some(serde_json::json!({
"loadtime": {"max_seq_length": 32768}
})),
+ grammar_profile: None,
+ chat_template_kwargs: None,
};
let variant = ModelRegistry::narrow_info_extras_to_profile(&base, "long", &profile);
@@ -3357,7 +3789,10 @@ profiles:
profiles.insert(
"default".to_string(),
ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:Adapter".to_string(),
),
@@ -3630,7 +4065,10 @@ adapters:
m.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
.to_string(),
@@ -3678,7 +4116,10 @@ adapters:
profiles.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -3718,7 +4159,10 @@ encode:
profiles.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -3729,7 +4173,10 @@ encode:
profiles.insert(
"alt".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(2048),
compute_precision: None,
@@ -3788,7 +4235,10 @@ adapters:
profiles.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -3823,7 +4273,10 @@ encode:
profiles.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(4096),
compute_precision: None,
@@ -3834,7 +4287,10 @@ encode:
profiles.insert(
"alt".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("module:Adapter".to_string()),
max_batch_tokens: Some(2048),
compute_precision: None,
@@ -3879,7 +4335,10 @@ encode:
m.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(adapter_path.to_string()),
max_batch_tokens: Some(max_batch_tokens),
compute_precision: None,
@@ -4124,7 +4583,10 @@ adapters:
m.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
.to_string(),
@@ -4183,7 +4645,10 @@ adapters:
m.insert(
"a100-40gb".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
.to_string(),
@@ -4842,7 +5307,10 @@ adapters:
m.insert(
"default".to_string(),
crate::types::model::ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some(
"sie_server.adapters.sentence_transformer:A".to_string(),
),
diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rs
index b832641dc..67ce2ea75 100644
--- a/packages/sie_gateway/src/types/model.rs
+++ b/packages/sie_gateway/src/types/model.rs
@@ -35,10 +35,10 @@ pub struct ModelInfoExtras {
/// ``tasks.generate.grammar_profile`` from the model YAML — the name of a
/// profile that grammar-constrained requests must be served on. When set,
/// the chat/completions/generate handlers rewrite a grammar request's model
- /// id to the ``{model}:{grammar_profile}`` variant unless an explicitly
- /// requested, directly inheriting variant preserves the resolved
- /// grammar-safe launch contract. ``None`` when the model has no ``generate``
- /// task or does not declare the field (no rewrite).
+ /// id to the ``{model}:{grammar_profile}`` variant unless the requested
+ /// profile declares its own grammar-safe sibling or a directly inheriting
+ /// variant already preserves the resolved contract. ``None`` when the
+ /// model has no ``generate`` task or does not declare the field.
pub grammar_profile: Option<String>,
/// Direct ``profiles.<name>.extends`` relationships. The gateway keeps
/// these only to evaluate explicit variants that inherit the configured
@@ -393,6 +393,8 @@ pub struct ModelConfig {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ProfileConfig {
+ #[serde(default)]
+ pub kv_budget_tokens: Option<u32>,
#[serde(default)]
pub adapter_path: Option<String>,
#[serde(default)]
@@ -401,6 +403,15 @@ pub struct ProfileConfig {
pub compute_precision: Option<String>,
#[serde(default)]
pub max_output_tokens: Option<u32>,
+ /// Optional profile-scoped grammar fallback. This lets a concrete
+ /// long-context or thinking route name a non-speculative sibling that
+ /// preserves its launch shape instead of using the model-wide fallback.
+ #[serde(default)]
+ pub grammar_profile: Option<String>,
+ /// Per-profile tokenizer/chat mode overrides. Grammar fallbacks must
+ /// preserve these exactly so routing cannot switch thinking mode.
+ #[serde(default)]
+ pub chat_template_kwargs: Option<serde_json::Value>,
#[serde(default)]
pub adapter_options: Option<serde_json::Value>,
#[serde(default)]
@@ -502,10 +513,14 @@ impl ModelEntry {
#[derive(Debug, Clone, PartialEq)]
pub struct CanonicalProfile {
+ pub kv_budget_tokens: Option<u32>,
pub adapter_path: Option<String>,
pub max_batch_tokens: Option<u32>,
pub compute_precision: Option<String>,
+ pub max_output_tokens: Option<u32>,
pub adapter_options: Option<serde_json::Value>,
+ pub grammar_profile: Option<String>,
+ pub chat_template_kwargs: Option<serde_json::Value>,
}
impl CanonicalProfile {
@@ -528,10 +543,14 @@ impl CanonicalProfile {
.and_then(canonicalize_adapter_options);
Self {
+ kv_budget_tokens: profile.kv_budget_tokens,
adapter_path: profile.adapter_path.clone(),
max_batch_tokens: profile.max_batch_tokens,
compute_precision: profile.compute_precision.clone(),
+ max_output_tokens: profile.max_output_tokens,
adapter_options,
+ grammar_profile: profile.grammar_profile.clone(),
+ chat_template_kwargs: profile.chat_template_kwargs.clone(),
}
}
}
@@ -576,7 +595,10 @@ mod tests {
#[test]
fn test_canonical_profile_basic() {
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: Some(serde_json::json!({"enable_thinking": true})),
adapter_path: Some("module:Adapter".into()),
max_batch_tokens: Some(4096),
compute_precision: Some("float16".into()),
@@ -587,13 +609,20 @@ mod tests {
assert_eq!(canonical.adapter_path, Some("module:Adapter".into()));
assert_eq!(canonical.max_batch_tokens, Some(4096));
assert_eq!(canonical.compute_precision, Some("float16".into()));
+ assert_eq!(
+ canonical.chat_template_kwargs,
+ Some(serde_json::json!({"enable_thinking": true}))
+ );
assert!(canonical.adapter_options.is_none());
}
#[test]
fn test_canonical_profile_strips_null_only_options() {
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -607,7 +636,10 @@ mod tests {
#[test]
fn test_canonical_profile_strips_false_only_options() {
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -622,7 +654,10 @@ mod tests {
fn test_canonical_profile_keeps_meaningful_options() {
let opts = serde_json::json!({"batch_size": 32, "key": null});
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -636,7 +671,10 @@ mod tests {
#[test]
fn test_canonical_profile_drops_empty_nested_option_maps() {
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -672,7 +710,10 @@ mod tests {
let canonicalize = |opts: &serde_json::Value| {
CanonicalProfile::from_profile(&ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -731,7 +772,10 @@ mod tests {
#[test]
fn test_canonical_profile_keeps_nonzero_numbers() {
let profile = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: None,
compute_precision: None,
@@ -745,7 +789,10 @@ mod tests {
#[test]
fn test_canonical_profile_equality() {
let p1 = ProfileConfig {
+ kv_budget_tokens: None,
max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
adapter_path: Some("mod:A".into()),
max_batch_tokens: Some(4096),
compute_precision: None,
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index 07eb334e2..ec521b80b 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.6.27"
+version = "0.6.28"
description = "Search Inference Engine - Python SDK"
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
diff --git a/packages/sie_sdk/src/sie_sdk/cache.py b/packages/sie_sdk/src/sie_sdk/cache.py
index b474a9620..7e9f5525d 100644
--- a/packages/sie_sdk/src/sie_sdk/cache.py
+++ b/packages/sie_sdk/src/sie_sdk/cache.py
@@ -93,7 +93,11 @@ def get_cache_config() -> CacheConfig:
)
-def is_model_cached(model_id: str, config: CacheConfig | None = None) -> bool:
+def is_model_cached(
+ model_id: str,
+ config: CacheConfig | None = None,
+ revision: str | None = None,
+) -> bool:
"""Check if a model is already in local cache.
Uses HuggingFace Hub's cache structure to check for the model.
@@ -101,6 +105,8 @@ def is_model_cached(model_id: str, config: CacheConfig | None = None) -> bool:
Args:
model_id: HuggingFace model ID (e.g., "BAAI/bge-m3").
config: Cache configuration. If None, reads from environment.
+ revision: Exact snapshot commit, branch, or tag to require. Branches
+ and tags resolve through the local Hugging Face ``refs`` cache.
Returns:
True if model appears to be cached locally.
@@ -113,11 +119,31 @@ def is_model_cached(model_id: str, config: CacheConfig | None = None) -> bool:
if not cache_dir.exists():
return False
- # Check for any snapshot directory with files
+ # Check for a snapshot directory with files. When a revision is requested,
+ # do not let an unrelated cached snapshot satisfy the immutable pin.
snapshots_dir = cache_dir / "snapshots"
if not snapshots_dir.exists():
return False
+ if revision is not None:
+ revision_path = Path(revision)
+ if not revision_path.parts or revision == "." or revision_path.is_absolute() or ".." in revision_path.parts:
+ return False
+ resolved_revision = revision
+ ref_path = cache_dir / "refs" / revision
+ if ref_path.is_file():
+ resolved_revision = ref_path.read_text().strip()
+ resolved_path = Path(resolved_revision)
+ if (
+ not resolved_path.parts
+ or resolved_revision == "."
+ or resolved_path.is_absolute()
+ or ".." in resolved_path.parts
+ ):
+ return False
+ snapshot = snapshots_dir / resolved_revision
+ return snapshot.is_dir() and any(snapshot.iterdir())
+
return any(snapshot.is_dir() and any(snapshot.iterdir()) for snapshot in snapshots_dir.iterdir())
@@ -149,13 +175,13 @@ def ensure_model_cached(
config = get_cache_config()
# Check local cache first
- if is_model_cached(model_id, config):
+ if is_model_cached(model_id, config, revision=revision):
logger.debug("Model %s found in local cache", model_id)
return _get_model_cache_path(model_id, config)
# Try cluster cache if configured
if config.cluster_cache:
- if _download_from_cluster_cache(model_id, config):
+ if _download_from_cluster_cache(model_id, config) and is_model_cached(model_id, config, revision=revision):
logger.info("Downloaded %s from cluster cache", model_id)
return _get_model_cache_path(model_id, config)
diff --git a/packages/sie_sdk/tests/test_cache.py b/packages/sie_sdk/tests/test_cache.py
index 8ac2a7dc2..3e2d68564 100644
--- a/packages/sie_sdk/tests/test_cache.py
+++ b/packages/sie_sdk/tests/test_cache.py
@@ -113,6 +113,20 @@ class TestIsModelCached:
assert is_model_cached("BAAI/bge-m3", config) is True
+ def test_model_cached_requires_exact_revision_when_pinned(self, tmp_path: Path) -> None:
+ revision = "a" * 40
+ model_dir = tmp_path / "models--BAAI--bge-m3" / "snapshots" / revision
+ model_dir.mkdir(parents=True)
+ (model_dir / "config.json").write_text("{}")
+
+ config = CacheConfig(local_cache=tmp_path)
+
+ assert is_model_cached("BAAI/bge-m3", config, revision=revision) is True
+ assert is_model_cached("BAAI/bge-m3", config, revision="b" * 40) is False
+ assert is_model_cached("BAAI/bge-m3", config, revision="../outside") is False
+ assert is_model_cached("BAAI/bge-m3", config, revision="") is False
+ assert is_model_cached("BAAI/bge-m3", config, revision=".") is False
+
def test_model_cached_empty_snapshot(self, tmp_path: Path) -> None:
"""Returns False for model with empty snapshot directory."""
model_dir = tmp_path / "models--BAAI--bge-m3" / "snapshots" / "abc123"
diff --git a/packages/sie_server/bundles/gemma.yaml b/packages/sie_server/bundles/gemma.yaml
index 80952b0c7..e7b495e26 100644
--- a/packages/sie_server/bundles/gemma.yaml
+++ b/packages/sie_server/bundles/gemma.yaml
@@ -18,9 +18,10 @@ platform: cuda13
# model configs set via adapter_options.loadtime.disable_cuda_graph).
#
# Kept SEPARATE from the `sglang` bundle so its Qwen3.x default/non-thinking
-# profiles stay on sglang 0.5.10.post1 / torch 2.9.1. Qwen3.6-27B reasoning
-# variants opt into this image through the generic strict-thinking adapter;
-# the rest of the Qwen catalog remains untouched.
+# profiles stay on sglang 0.5.10.post1 / torch 2.9.1. Qwen3.6-27B native-window
+# variants opt into this image through the generic CUDA 13 adapter; their
+# thinking variants add the strict-thinking behavior. The rest of the Qwen
+# catalog remains untouched.
#
# VERSION NOTE: Gemma 4 first shipped in sglang 0.5.11, but 0.5.11's bundled
# JIT kernel (jit_kernel/csrc/elementwise/activation.cuh) fails to compile
@@ -35,9 +36,10 @@ platform: cuda13
# torch out of sie-server core would remove that (tracked follow-up in #1415).
#
# Distinct thin adapter modules scope routing here because bundle compatibility
-# keys on module paths. Gemma models use `...sglang.gemma`; reasoning profiles
-# that need the newer token filter use `...sglang.cuda13`. Qwen routes without
-# that explicit adapter remain on the shared `sglang` bundle.
+# keys on module paths. Gemma models use `...sglang.gemma`; Qwen profiles that
+# require the newer generic engine or token filter use `...sglang.cuda13`.
+# Qwen routes without that explicit adapter remain on the shared `sglang`
+# bundle.
adapters:
- sie_server.adapters.sglang.gemma
- sie_server.adapters.sglang.cuda13
diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
index b057feeee..d4d9c2c77 100644
--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
@@ -110,10 +110,10 @@ profiles:
num_steps: 2
eagle_topk: 1
num_draft_tokens: 2
- # ``--mamba-scheduler-strategy extra_buffer`` is the required
- # pair-flag for NEXTN spec on the hybrid Gated-DeltaNet architecture.
- # Keep it paired with ``--disable-overlap-schedule`` for all NEXTN
- # launch profiles.
+ # On this conservative CUDA 12 profile, keep ``extra_buffer`` paired
+ # with ``--disable-overlap-schedule``. The measured CUDA 13 EAGLE
+ # native-window profiles below intentionally retain SPEC_V2 overlap
+ # scheduling with the same mamba buffer strategy.
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
@@ -302,11 +302,12 @@ profiles:
min_new_tokens: 10
stop_tokens:
- "<|im_end|>"
- # Explicit native-window candidate for one H100-80GB admission. Keep this
+ # Explicit native-window shape for one H100-80GB admission. Keep this
# standalone (rather than extending ``h100-fp8``) so the matching
# ``long-context-thinking`` child can inherit it without forbidden profile
- # chaining. Online FP8 limits weight memory; KV remains BF16 until measured
- # H100 evidence proves a lower-precision cache is necessary and faithful.
+ # chaining. The CUDA 13 engine's trained-in EAGLE draft, CUDA graphs, and
+ # overlap schedule sustain the same batch-one decode rate at 32K, 128K, and
+ # 256K. Online FP8 limits weight memory; KV remains BF16.
long-context:
# Qwen's official non-thinking serving recipe uses max_tokens=32768.
# Keep the bare 8K profile at 4096 while exposing that decode ceiling only
@@ -314,20 +315,24 @@ profiles:
max_output_tokens: 32768
max_batch_tokens: 262144
compute_precision: bfloat16
- adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter
+ grammar_profile: long-context-no-spec
kv_budget_tokens: 262144
adapter_options:
loadtime:
max_seq_length: 262144
- mem_fraction_static: 0.95
+ mem_fraction_static: 0.90
served_model_name: Qwen/Qwen3.6-27B
- disable_cuda_graph: true
attention_backend: triton
grammar_backend: xgrammar
reasoning_parser: qwen3
tool_call_parser: qwen3_coder
speculative:
- enabled: false
+ enabled: true
+ algorithm: eagle
+ num_steps: 3
+ eagle_topk: 1
+ num_draft_tokens: 4
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
@@ -335,7 +340,8 @@ profiles:
- "fp8"
- "--mamba-scheduler-strategy"
- "extra_buffer"
- - "--disable-overlap-schedule"
+ - "--page-size"
+ - "64"
runtime:
first_chunk_timeout_s: 900
inter_chunk_timeout_s: 30
@@ -348,17 +354,66 @@ profiles:
min_new_tokens: 10
stop_tokens:
- "<|im_end|>"
- # Same measured 256K launch/admission envelope with Qwen thinking enabled.
- long-context-thinking:
+ # Grammar-safe twin of the measured 256K H100 launch. It preserves every
+ # load-time axis except EAGLE, which must be disabled for constrained decode.
+ long-context-no-spec:
extends: long-context
+ adapter_options:
+ loadtime:
+ max_seq_length: 262144
+ mem_fraction_static: 0.90
+ served_model_name: Qwen/Qwen3.6-27B
+ attention_backend: triton
+ grammar_backend: xgrammar
+ reasoning_parser: qwen3
+ tool_call_parser: qwen3_coder
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--mm-process-config"
+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--quantization"
+ - "fp8"
+ - "--mamba-scheduler-strategy"
+ - "extra_buffer"
+ - "--page-size"
+ - "64"
+ # Keep the already-released thinking route on its conservative non-speculative
+ # launch while the EAGLE + strict-thinking startup failure is resolved in the
+ # follow-up release. This block is standalone so its aliases can inherit it
+ # without inheriting the optimized non-thinking launch above.
+ long-context-thinking:
+ grammar_profile: long-context-thinking-no-spec
# Official Qwen3.6 thinking examples use max_tokens=81920.
max_output_tokens: 81920
+ max_batch_tokens: 262144
+ compute_precision: bfloat16
# SGLang 0.5.13's strict-thinking token filter prevents a premature EOS
# from leaving the whole answer inside the private reasoning channel.
adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter
+ kv_budget_tokens: 262144
chat_template_kwargs:
enable_thinking: true
adapter_options:
+ loadtime:
+ max_seq_length: 262144
+ mem_fraction_static: 0.95
+ served_model_name: Qwen/Qwen3.6-27B
+ disable_cuda_graph: true
+ attention_backend: triton
+ grammar_backend: xgrammar
+ reasoning_parser: qwen3
+ tool_call_parser: qwen3_coder
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--mm-process-config"
+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--quantization"
+ - "fp8"
+ - "--mamba-scheduler-strategy"
+ - "extra_buffer"
+ - "--disable-overlap-schedule"
runtime:
first_chunk_timeout_s: 900
inter_chunk_timeout_s: 30
@@ -371,53 +426,27 @@ profiles:
min_new_tokens: 10
stop_tokens:
- "<|im_end|>"
+ # Dedicated constrained-decoding identity for the conservative thinking
+ # launch. It is intentionally identical until the optimized thinking
+ # follow-up has its own measured speculative/non-speculative pair.
+ long-context-thinking-no-spec:
+ extends: long-context-thinking
# Hardware-explicit aliases for the exact H100-80GB native-window shape.
# Machine placement remains a separate gateway decision; these names make
# the validated context/GPU pairing discoverable to callers.
h100-256k:
extends: long-context
+ grammar_profile: long-context-no-spec
h100-256k-thinking:
- extends: long-context
- max_output_tokens: 81920
- adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter
- chat_template_kwargs:
- enable_thinking: true
- adapter_options:
- runtime:
- first_chunk_timeout_s: 900
- inter_chunk_timeout_s: 30
- overall_timeout_s: 1800
- default_sampling:
- temperature: 1.0
- top_p: 0.95
- top_k: 20
- presence_penalty: 0.0
- min_new_tokens: 10
- stop_tokens:
- - "<|im_end|>"
+ extends: long-context-thinking
+ grammar_profile: long-context-thinking-no-spec
# Explicit reasoning mode uses the validated native-window H100 lane. Qwen's
# model card recommends at least 128K context for thinking; keeping this alias
# on the 8K base lane would expose a mode that routinely truncates before its
# private thought closes. The bare model remains non-thinking and answer-only.
thinking:
- extends: long-context
- max_output_tokens: 81920
- adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter
- chat_template_kwargs:
- enable_thinking: true
- adapter_options:
- runtime:
- first_chunk_timeout_s: 900
- inter_chunk_timeout_s: 30
- overall_timeout_s: 1800
- default_sampling:
- temperature: 1.0
- top_p: 0.95
- top_k: 20
- presence_penalty: 0.0
- min_new_tokens: 10
- stop_tokens:
- - "<|im_end|>"
+ extends: long-context-thinking
+ grammar_profile: long-context-thinking-no-spec
# Throughput profile (H100-80GB) — the flagship's batch story. The
# ``default`` NEXTN-spec shape is latency-optimized single-stream and
# throughput-FLAT (~44 tok/s aggregate c=1→32, effective batch ≈1 —
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 4f91f5100..0ae23b365 100644
--- a/packages/sie_server/models/google__gemma-4-31B-it.yaml
+++ b/packages/sie_server/models/google__gemma-4-31B-it.yaml
@@ -17,6 +17,9 @@ tasks:
# and expose the native-window candidates through explicit profiles below.
context_length: 8192
max_output_tokens: 4096
+ # Frozen-KV MTP is not used for constrained decoding. Route grammar
+ # requests to the matching non-speculative H100 sibling below.
+ grammar_profile: no-spec
capabilities:
grammar: ["json_schema", "regex"]
streaming: true
@@ -25,9 +28,10 @@ tasks:
enable_thinking: false
max_sequence_length: 8192
profiles:
- # Bare-id serving defaults to the requested H100-80GB FP8 shape. Speculative
- # decoding and CUDA graphs stay off for the first smoke so online
- # quantization, multimodal load, and grammar behavior are isolated.
+ # Bare-id serving defaults to the measured H100-80GB FP8 + paired-MTP shape.
+ # Three verification steps and four draft tokens preserve the assistant's
+ # near-perfect acceptance while avoiding the prompt-sensitive tail measured
+ # with the deeper 5/6 and 8/9 settings.
default:
max_batch_tokens: 16384
compute_precision: bfloat16
@@ -35,15 +39,21 @@ profiles:
kv_budget_tokens: 8192
adapter_options:
loadtime:
- mem_fraction_static: 0.90
+ mem_fraction_static: 0.80
served_model_name: google/gemma-4-31B-it
- disable_cuda_graph: true
attention_backend: triton
grammar_backend: xgrammar
reasoning_parser: gemma4
tool_call_parser: gemma4
+ speculative_needs_extra_buffer: false
speculative:
- enabled: false
+ enabled: true
+ algorithm: nextn
+ num_steps: 3
+ eagle_topk: 1
+ num_draft_tokens: 4
+ draft_model: google/gemma-4-31B-it-assistant
+ draft_model_revision: 627c5ec1458b9086b841a91e0512fd31fd2fbbf1
extra_launch_args:
- "--quantization"
- "fp8"
@@ -59,6 +69,24 @@ profiles:
min_new_tokens: 1
stop_tokens:
- "<end_of_turn>"
+ # Grammar-safe sibling of the bare H100 profile. Keep the complete load-time
+ # block because extending profiles replace, rather than merge, that block.
+ no-spec:
+ extends: default
+ adapter_options:
+ loadtime:
+ mem_fraction_static: 0.80
+ served_model_name: google/gemma-4-31B-it
+ attention_backend: triton
+ grammar_backend: xgrammar
+ reasoning_parser: gemma4
+ tool_call_parser: gemma4
+ speculative_needs_extra_buffer: false
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--quantization"
+ - "fp8"
# Caller-visible FP8 alias; select the H100-80GB machine profile separately.
h100-fp8:
extends: default
@@ -66,11 +94,9 @@ profiles:
# H100 96K shape so the generic reasoning alias has the same decode budget as
# its hardware-explicit twin; the bare route remains answer-only.
thinking:
- extends: h100-96k
- max_output_tokens: 32768
- chat_template_kwargs:
- enable_thinking: true
- # Explicit native-window candidate for one H200 admission. Keep the profile
+ extends: h100-96k-thinking
+ grammar_profile: h100-96k-thinking-no-spec
+ # Explicit native-window shape for one H200 admission. Keep the profile
# standalone so the thinking and hardware-explicit aliases can inherit the
# exact CUDA 13 launch shape without profile chaining. Online FP8 limits
# weight memory, and FP8 E4M3 limits KV memory; the release gate separately
@@ -80,6 +106,7 @@ profiles:
max_batch_tokens: 262144
compute_precision: bfloat16
adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter
+ grammar_profile: long-context-no-spec
kv_budget_tokens: 262144
adapter_options:
loadtime:
@@ -87,13 +114,19 @@ profiles:
# Leave transient FP8 GEMM workspace outside SGLang's static pool.
mem_fraction_static: 0.90
served_model_name: google/gemma-4-31B-it
- disable_cuda_graph: true
attention_backend: triton
grammar_backend: xgrammar
reasoning_parser: gemma4
tool_call_parser: gemma4
+ speculative_needs_extra_buffer: false
speculative:
- enabled: false
+ enabled: true
+ algorithm: nextn
+ num_steps: 3
+ eagle_topk: 1
+ num_draft_tokens: 4
+ draft_model: google/gemma-4-31B-it-assistant
+ draft_model_revision: 627c5ec1458b9086b841a91e0512fd31fd2fbbf1
extra_launch_args:
- "--quantization"
- "fp8"
@@ -110,44 +143,109 @@ profiles:
min_new_tokens: 1
stop_tokens:
- "<end_of_turn>"
- # Same measured 256K launch/admission envelope with Gemma thinking enabled.
- long-context-thinking:
+ # Grammar-safe twin of the measured H200 256K launch. Frozen-KV MTP is the
+ # only load-time difference because constrained decode must use the grammar
+ # FSM on every emitted token.
+ long-context-no-spec:
extends: long-context
+ adapter_options:
+ loadtime:
+ max_seq_length: 262144
+ mem_fraction_static: 0.90
+ served_model_name: google/gemma-4-31B-it
+ attention_backend: triton
+ grammar_backend: xgrammar
+ 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"
+ # Preserve the already-released thinking route as a standalone conservative
+ # non-speculative launch. Optimized thinking is intentionally deferred to a
+ # follow-up release instead of inheriting the non-thinking MTP change above.
+ long-context-thinking:
+ grammar_profile: long-context-thinking-no-spec
# The 4K control truncated otherwise-correct reasoning on 2/10 MMLU-Pro
# rows. A 32K cap leaves ample room for the final answer without changing
# the profile's sampling defaults or forcing callers to request it.
max_output_tokens: 32768
+ max_batch_tokens: 262144
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter
+ kv_budget_tokens: 262144
chat_template_kwargs:
enable_thinking: true
+ adapter_options:
+ loadtime:
+ max_seq_length: 262144
+ mem_fraction_static: 0.90
+ served_model_name: google/gemma-4-31B-it
+ disable_cuda_graph: true
+ attention_backend: triton
+ grammar_backend: xgrammar
+ reasoning_parser: gemma4
+ tool_call_parser: gemma4
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--quantization"
+ - "fp8"
+ - "--kv-cache-dtype"
+ - "fp8_e4m3"
+ runtime:
+ first_chunk_timeout_s: 900
+ inter_chunk_timeout_s: 30
+ overall_timeout_s: 1800
+ default_sampling:
+ temperature: 1.0
+ top_p: 0.95
+ top_k: 64
+ min_new_tokens: 1
+ stop_tokens:
+ - "<end_of_turn>"
+ long-context-thinking-no-spec:
+ extends: long-context-thinking
# H200 has enough memory for the native window. These aliases expose the
# tested hardware/context pairing while machine placement remains separate.
h200-256k:
extends: long-context
+ grammar_profile: long-context-no-spec
h200-256k-thinking:
- extends: long-context
- max_output_tokens: 32768
- chat_template_kwargs:
- enable_thinking: true
- # On H100-80GB this launch shape measured a 107,538-token KV capacity. Cap
- # the public profile at 96K to leave room for the chat template and decode;
- # never use SGLang auto-truncation to simulate a larger accepted context.
+ extends: long-context-thinking
+ grammar_profile: long-context-thinking-no-spec
+ # On H100-80GB this MTP launch shape measured a 108,896-token KV capacity.
+ # Cap the public profile at 96K to leave room for the chat template and
+ # decode; never use SGLang auto-truncation to simulate a larger accepted
+ # context.
h100-96k:
max_batch_tokens: 98304
compute_precision: bfloat16
adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter
+ grammar_profile: h100-96k-no-spec
kv_budget_tokens: 98304
adapter_options:
loadtime:
max_seq_length: 98304
mem_fraction_static: 0.90
served_model_name: google/gemma-4-31B-it
- disable_cuda_graph: true
attention_backend: triton
grammar_backend: xgrammar
reasoning_parser: gemma4
tool_call_parser: gemma4
+ speculative_needs_extra_buffer: false
speculative:
- enabled: false
+ enabled: true
+ algorithm: nextn
+ num_steps: 3
+ eagle_topk: 1
+ num_draft_tokens: 4
+ draft_model: google/gemma-4-31B-it-assistant
+ draft_model_revision: 627c5ec1458b9086b841a91e0512fd31fd2fbbf1
extra_launch_args:
- "--quantization"
- "fp8"
@@ -164,8 +262,61 @@ profiles:
min_new_tokens: 1
stop_tokens:
- "<end_of_turn>"
- h100-96k-thinking:
+ h100-96k-no-spec:
extends: h100-96k
+ adapter_options:
+ loadtime:
+ max_seq_length: 98304
+ mem_fraction_static: 0.90
+ served_model_name: google/gemma-4-31B-it
+ attention_backend: triton
+ grammar_backend: xgrammar
+ 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"
+ h100-96k-thinking:
+ grammar_profile: h100-96k-thinking-no-spec
max_output_tokens: 32768
+ max_batch_tokens: 98304
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter
+ kv_budget_tokens: 98304
chat_template_kwargs:
enable_thinking: true
+ adapter_options:
+ loadtime:
+ max_seq_length: 98304
+ mem_fraction_static: 0.90
+ served_model_name: google/gemma-4-31B-it
+ disable_cuda_graph: true
+ attention_backend: triton
+ grammar_backend: xgrammar
+ reasoning_parser: gemma4
+ tool_call_parser: gemma4
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--quantization"
+ - "fp8"
+ - "--kv-cache-dtype"
+ - "fp8_e4m3"
+ runtime:
+ first_chunk_timeout_s: 900
+ inter_chunk_timeout_s: 30
+ overall_timeout_s: 1800
+ default_sampling:
+ temperature: 1.0
+ top_p: 0.95
+ top_k: 64
+ min_new_tokens: 1
+ stop_tokens:
+ - "<end_of_turn>"
+ h100-96k-thinking-no-spec:
+ extends: h100-96k-thinking
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 7f066a19f..20c560f0d 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -3,7 +3,7 @@
"info": {
"title": "SIE Server",
"description": "Search Inference Engine - GPU inference server for search workloads",
- "version": "0.6.27"
+ "version": "0.6.28"
},
"paths": {
"/healthz": {
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 5c13e240c..1b53a4ae1 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.6.27"
+version = "0.6.28"
description = "Search Inference Engine - GPU inference server for search workloads"
requires-python = ">=3.12,<3.13"
license = { text = "Apache-2.0" }
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py
index bafd688a9..2f41a0bcd 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py
@@ -3,7 +3,11 @@ from typing import Any
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
-class SGLangStrictThinkingAdapter(SGLangGenerationAdapter):
+class SGLangCuda13Adapter(SGLangGenerationAdapter):
+ """Route generic generation through the CUDA 13 SGLang bundle."""
+
+
+class SGLangStrictThinkingAdapter(SGLangCuda13Adapter):
"""CUDA 13 SGLang lane that guarantees a closed private thought block.
SGLang 0.5.13 can suppress premature EOS tokens until the model emits its
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 877fc6181..1ff19c218 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -323,7 +323,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
self._guard = guard or {}
# Generic speculative-decoding surface accepts
# ``{enabled, algorithm, num_steps?, eagle_topk?,
- # num_draft_tokens?, draft_model?}``; translated by
+ # num_draft_tokens?, draft_model?, draft_model_revision?}``; translated by
# ``_speculative_launch_args`` into SGLang CLI flags. Default-on
# for Qwen3.5-4B (NEXTN/MTP trained in); intentionally off for
# Qwen3-4B-Instruct-2507 (no NEXTN heads — see the
@@ -646,6 +646,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
- ``NEXTN`` (a.k.a. MTP in SGLang 0.5.x — multi-token prediction
via trained-in draft heads; required for Qwen3.5-4B's
``MTP: trained with multi-steps`` capability).
+ - ``EAGLE`` (the current SGLang Qwen3.6 MTP spelling; uses the
+ checkpoint's trained-in draft heads without an external model).
- ``EAGLE3`` (requires an external draft model whose
architecture is registered with transformers; blocked for
Qwen3-4B-Instruct-2507 on the pinned stack — see the
@@ -661,8 +663,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
Top-level gate. When False (or block missing), returns
``[]`` — caller still gets the unchanged baseline command.
``algorithm`` (str, required when enabled)
- One of ``nextn``, ``eagle3``, ``ngram`` (case-insensitive).
- Surfaced verbatim to SGLang's ``--speculative-algo``.
+ One of ``nextn``, ``eagle``, ``eagle3``, ``ngram`` (case-insensitive).
+ Surfaced verbatim to SGLang's ``--speculative-algorithm``.
``num_steps`` (int, optional)
``--speculative-num-steps``. Qwen3.5-4B's documented
NEXTN recipe uses 3.
@@ -675,8 +677,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
window is set by separate SGLang knobs we leave at
defaults — see ``qwen3-4b-speculative-side.yaml`` header).
``draft_model`` (str, optional)
- ``--speculative-draft-model-path``. EAGLE3 needs this;
- NEXTN/NGRAM do not.
+ ``--speculative-draft-model-path``. EAGLE3 needs this; paired
+ assistant variants of NEXTN may also use it.
+ ``draft_model_revision`` (str, optional)
+ ``--speculative-draft-model-revision``. Immutable checkpoint
+ revision for ``draft_model``; model-config validation requires a
+ full 40-character commit SHA when present.
Unknown keys are intentionally ignored (with a debug log) so a
future SGLang flag can be wired here without forcing a
@@ -691,19 +697,19 @@ class SGLangGenerationAdapter(GenerationAdapter):
logger.warning(
"speculative.enabled=true but algorithm missing/invalid (%r); "
"skipping --speculative-* flags. Set algorithm to one of "
- "'nextn' | 'eagle3' | 'ngram'.",
+ "'nextn' | 'eagle' | 'eagle3' | 'ngram'.",
algorithm_raw,
)
return []
algorithm = algorithm_raw.strip().upper()
- if algorithm not in {"NEXTN", "EAGLE3", "NGRAM"}:
+ if algorithm not in {"NEXTN", "EAGLE", "EAGLE3", "NGRAM"}:
logger.warning(
"speculative.algorithm=%r is not in the recognised set "
- "{NEXTN, EAGLE3, NGRAM}; forwarding to SGLang anyway "
+ "{NEXTN, EAGLE, EAGLE3, NGRAM}; forwarding to SGLang anyway "
"(it will reject if unsupported).",
algorithm_raw,
)
- args: list[str] = ["--speculative-algo", algorithm]
+ args: list[str] = ["--speculative-algorithm", algorithm]
num_steps = spec.get("num_steps")
if isinstance(num_steps, int) and num_steps > 0:
@@ -729,12 +735,22 @@ class SGLangGenerationAdapter(GenerationAdapter):
draft_model = spec.get("draft_model")
if isinstance(draft_model, str) and draft_model.strip():
args.extend(["--speculative-draft-model-path", draft_model.strip()])
+ draft_model_revision = spec.get("draft_model_revision")
+ if isinstance(draft_model_revision, str) and draft_model_revision.strip():
+ args.extend(["--speculative-draft-model-revision", draft_model_revision.strip()])
+ elif draft_model_revision is not None:
+ logger.debug(
+ "speculative.draft_model_revision=%r ignored (need non-empty str)",
+ draft_model_revision,
+ )
elif algorithm == "EAGLE3":
logger.warning(
"speculative.algorithm=EAGLE3 without speculative.draft_model — "
"SGLang will fail to start. Set speculative.draft_model to the "
"EAGLE3 draft checkpoint path."
)
+ elif spec.get("draft_model_revision") is not None:
+ logger.debug("speculative.draft_model_revision ignored without draft_model")
logger.info("speculative decoding enabled: %s (args=%s)", algorithm, args)
return args
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 34e150f5b..8c2a6fa83 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -240,9 +240,10 @@ class GenerateTask(BaseModel):
When set, the gateway rewrites such a request's model id to the
``{sie_id}:{grammar_profile}`` variant so it is served by that profile,
while unconstrained requests keep the request's resolved profile. A
- directly inheriting explicit variant may remain selected only when its
- resolved adapter/backend and launch settings preserve the gateway's
- grammar-safe contract; incompatible descendants still rewrite. This exists
+ profile may override this with its own grammar-safe sibling so context,
+ hardware launch shape, and thinking mode remain unchanged. A directly
+ inheriting explicit variant may remain selected when its resolved launch
+ settings are already grammar-safe. This exists
because some throughput optimisations are incompatible with
decode-time grammar enforcement — notably NEXTN/MTP speculative decoding
bypasses SGLang's Outlines FSM (leaks out-of-schema keys, truncates
@@ -327,6 +328,28 @@ class AdapterOptions(BaseModel):
raise ValueError(msg)
return self
+ @model_validator(mode="after")
+ def validate_speculative_draft_model(self) -> "AdapterOptions":
+ """Validate the optional immutable speculative-draft checkpoint pin."""
+ speculative = self.loadtime.get("speculative")
+ if not isinstance(speculative, Mapping):
+ return self
+
+ revision = speculative.get("draft_model_revision")
+ if revision is None:
+ return self
+ draft_model = speculative.get("draft_model")
+ if not isinstance(draft_model, str) or not draft_model:
+ msg = "loadtime.speculative.draft_model_revision requires a non-empty draft_model repo id"
+ raise ValueError(msg)
+ if not isinstance(revision, str) or not is_immutable_revision(revision):
+ msg = (
+ f"loadtime.speculative.draft_model_revision={revision!r} is not an immutable "
+ "40-char commit SHA; pin the resolved draft checkpoint commit"
+ )
+ raise ValueError(msg)
+ return self
+
class ProfileAdaptiveBatching(BaseModel):
"""Per-model adaptive batching overrides.
@@ -380,6 +403,12 @@ class ProfileConfig(BaseModel):
mode on the profile identity while preserving the bare model's safer
non-thinking default. The profile mapping is merged over the task mapping;
request-time kwargs are still applied later by the generation processor.
+
+ ``grammar_profile`` optionally overrides the model-level grammar fallback
+ for this concrete profile. It must name a non-default sibling profile. The
+ gateway uses it only for constrained requests, allowing a long-context or
+ thinking profile to route to a non-speculative twin without losing its
+ context window, hardware launch shape, or tokenizer mode.
"""
model_config = ConfigDict(extra="forbid")
@@ -394,6 +423,7 @@ class ProfileConfig(BaseModel):
admission_enabled: bool | None = None
max_output_tokens: int | None = Field(default=None, gt=0)
chat_template_kwargs: dict[str, Any] | None = None
+ grammar_profile: str | None = None
@field_validator("chat_template_kwargs")
@classmethod
@@ -414,6 +444,7 @@ class ResolvedProfile(BaseModel):
admission_enabled: bool | None = None
max_output_tokens: int | None = None
chat_template_kwargs: MappingProxyType[str, Any] | None = None
+ grammar_profile: str | None = None
# Coarse per-family KV-bytes-per-token constants used by the derived-budget
@@ -676,6 +707,27 @@ class ModelConfig(BaseModel):
raise ValueError(msg)
return refs
+ def speculative_draft_revisions(self) -> dict[str, str | None]:
+ """Enabled speculative draft repos mapped to their optional immutable pins."""
+ refs: dict[str, str | None] = {}
+ for name, profile in self.profiles.items():
+ speculative = profile.adapter_options.loadtime.get("speculative")
+ if not isinstance(speculative, Mapping) or not speculative.get("enabled"):
+ continue
+ draft_model = speculative.get("draft_model")
+ if not isinstance(draft_model, str) or not draft_model:
+ continue
+ revision = speculative.get("draft_model_revision")
+ if draft_model not in refs or refs[draft_model] is None:
+ refs[draft_model] = revision
+ elif revision is not None and refs[draft_model] != revision:
+ msg = (
+ f"Model '{self.sie_id}' pins speculative draft '{draft_model}' to two different "
+ f"revisions ({refs[draft_model]} vs {revision}, latest seen in profile '{name}')"
+ )
+ raise ValueError(msg)
+ return refs
+
@model_validator(mode="after")
def validate_lora_revision_consistency(self) -> "ModelConfig":
# Surfaces the conflicting-pin error at register/config-load time rather
@@ -683,6 +735,11 @@ class ModelConfig(BaseModel):
self.lora_revisions()
return self
+ @model_validator(mode="after")
+ def validate_speculative_draft_revision_consistency(self) -> "ModelConfig":
+ self.speculative_draft_revisions()
+ return self
+
@model_validator(mode="after")
def validate_profiles(self) -> "ModelConfig":
if not self.profiles:
@@ -703,8 +760,37 @@ class ModelConfig(BaseModel):
if gp == "default":
msg = "tasks.generate.grammar_profile must not be 'default' (it names a non-default variant profile)"
raise ValueError(msg)
+ if self.profiles[gp].grammar_profile is not None:
+ msg = f"tasks.generate.grammar_profile target '{gp}' must not declare another grammar_profile"
+ raise ValueError(msg)
for name, profile in self.profiles.items():
+ if profile.grammar_profile is not None:
+ grammar_profile = profile.grammar_profile
+ if self.tasks.generate is None:
+ msg = f"Profile '{name}' sets grammar_profile on a model without a generation task"
+ raise ValueError(msg)
+ if name == "default":
+ msg = "Profile 'default' must use tasks.generate.grammar_profile rather than a profile-scoped fallback"
+ raise ValueError(msg)
+ if grammar_profile not in self.profiles:
+ msg = (
+ f"Profile '{name}' grammar_profile '{grammar_profile}' is not defined. "
+ f"Available: {list(self.profiles)}"
+ )
+ raise ValueError(msg)
+ if grammar_profile in {"default", name}:
+ msg = (
+ f"Profile '{name}' grammar_profile must name a non-default sibling profile, "
+ f"got '{grammar_profile}'"
+ )
+ raise ValueError(msg)
+ if self.profiles[grammar_profile].grammar_profile is not None:
+ msg = (
+ f"Profile '{name}' grammar_profile target '{grammar_profile}' "
+ "must not declare another grammar_profile"
+ )
+ raise ValueError(msg)
if profile.chat_template_kwargs is not None and self.tasks.generate is None:
msg = f"Profile '{name}' sets 'chat_template_kwargs' on a model without a generation task"
raise ValueError(msg)
@@ -727,6 +813,44 @@ class ModelConfig(BaseModel):
msg = f"Profile '{name}' must have 'max_batch_tokens' set (or use 'extends')"
raise ValueError(msg)
+ if self.tasks.generate is not None and self.tasks.generate.grammar_profile is not None:
+ grammar_profile = self.tasks.generate.grammar_profile
+ target = self._resolve_profile_uncached(grammar_profile)
+ target_speculative = target.loadtime.get("speculative")
+ if target_speculative is not None and (
+ not isinstance(target_speculative, dict) or target_speculative.get("enabled") is not False
+ ):
+ msg = f"tasks.generate.grammar_profile target '{grammar_profile}' must not enable speculation"
+ raise ValueError(msg)
+
+ for name, profile in self.profiles.items():
+ if profile.grammar_profile is None:
+ continue
+ source = self._resolve_profile_uncached(name)
+ target = self._resolve_profile_uncached(profile.grammar_profile)
+ source_loadtime = dict(source.loadtime)
+ target_loadtime = dict(target.loadtime)
+ source_loadtime.pop("speculative", None)
+ target_loadtime.pop("speculative", None)
+ target_speculative = target.loadtime.get("speculative")
+ compatible = (
+ source.adapter_path == target.adapter_path
+ and source.max_batch_tokens == target.max_batch_tokens
+ and source.compute_precision == target.compute_precision
+ and source.kv_budget_tokens == target.kv_budget_tokens
+ and source.max_output_tokens == target.max_output_tokens
+ and source.chat_template_kwargs == target.chat_template_kwargs
+ and target_speculative == {"enabled": False}
+ and source_loadtime == target_loadtime
+ )
+ if not compatible:
+ msg = (
+ f"Profile '{name}' grammar_profile '{profile.grammar_profile}' must preserve "
+ "adapter, precision, batch, KV/output limits, tokenizer mode, and load-time "
+ "settings while explicitly disabling speculation"
+ )
+ raise ValueError(msg)
+
# KV-budget admission control. For models declaring
# ``tasks.generate``, every profile (after parent merge) must
# provide a positive ``kv_budget_tokens``. The actual
@@ -863,6 +987,7 @@ class ModelConfig(BaseModel):
if profile.chat_template_kwargs is not None
else None
),
+ grammar_profile=profile.grammar_profile,
)
# Resolve via parent — validators guarantee parent exists and has no chaining
@@ -904,6 +1029,10 @@ class ModelConfig(BaseModel):
chat_template_kwargs = (
profile.chat_template_kwargs if profile.chat_template_kwargs is not None else parent.chat_template_kwargs
)
+ # Routing metadata is profile-local rather than inherited. An alias
+ # must opt into the same fallback explicitly, and the fallback profile
+ # itself must not inherit a route back to itself.
+ grammar_profile = profile.grammar_profile
if max_batch_tokens is None:
msg = f"Resolved profile '{name}': max_batch_tokens must be set"
@@ -925,6 +1054,7 @@ class ModelConfig(BaseModel):
chat_template_kwargs=(
MappingProxyType(dict(chat_template_kwargs)) if chat_template_kwargs is not None else None
),
+ grammar_profile=grammar_profile,
)
@property
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index 3c69c1cf2..1785373ef 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -250,6 +250,7 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:
chat_template_kwargs=(
dict(resolved.chat_template_kwargs) if resolved.chat_template_kwargs is not None else None
),
+ grammar_profile=resolved.grammar_profile,
)
else:
variant_default = profile.model_copy(update={"extends": None})
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 91931e5fc..96d5a3704 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -245,32 +245,47 @@ class ModelLoader:
"""
from sie_sdk.cache import ensure_model_cached, get_cache_config
- # Only applies to HF models (not local weights_path)
model_id = config.hf_id
- if model_id is None:
- return # Local weights, no caching needed
-
- # Check disk pressure and evict LRU models if needed before download
- if self._disk_cache is not None:
- evicted = self._disk_cache.ensure_space_before_download(model_id)
- if evicted:
- logger.info(
- "Pre-download disk eviction: freed %d model(s): %s",
- len(evicted),
- evicted,
- )
-
cache_config = get_cache_config()
- # Ensure model is cached (downloads if needed)
- # This now handles the full 3-tier hierarchy internally
- cached_path = ensure_model_cached(model_id, cache_config)
-
- # Update access time for LRU tracking
- if self._disk_cache is not None:
- self._disk_cache.touch(model_id)
+ # Base-model caching applies only to HF models, while an external
+ # speculative assistant still needs staging for local weights_path.
+ if model_id is not None:
+ if self._disk_cache is not None:
+ evicted = self._disk_cache.ensure_space_before_download(model_id)
+ if evicted:
+ logger.info(
+ "Pre-download disk eviction: freed %d model(s): %s",
+ len(evicted),
+ evicted,
+ )
- logger.debug("Model %s available at %s", model_id, cached_path)
+ cached_path = ensure_model_cached(model_id, cache_config, revision=config.hf_revision)
+ if self._disk_cache is not None:
+ self._disk_cache.touch(model_id)
+ logger.debug("Model %s available at %s", model_id, cached_path)
+
+ # External speculative assistants are separate checkpoints. Stage each
+ # enabled draft before starting SGLang so a worker never depends on an
+ # engine-owned, moving-branch download during launch.
+ for draft_model, revision in config.speculative_draft_revisions().items():
+ if self._disk_cache is not None:
+ evicted = self._disk_cache.ensure_space_before_download(draft_model)
+ if evicted:
+ logger.info(
+ "Pre-download disk eviction for speculative draft: freed %d model(s): %s",
+ len(evicted),
+ evicted,
+ )
+ draft_path = ensure_model_cached(draft_model, cache_config, revision=revision)
+ if self._disk_cache is not None:
+ self._disk_cache.touch(draft_model)
+ logger.debug(
+ "Speculative draft %s@%s available at %s",
+ draft_model,
+ revision or "default",
+ draft_path,
+ )
async def ensure_weights_cached_async(self, name: str, config: ModelConfig) -> None:
"""Async version of :meth:`ensure_weights_cached`.
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index b0e2ef82e..4f702908d 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -111,6 +111,43 @@ def test_mamba_scheduler_strategy_value(args: list[str], expected: str | None) -
assert _mamba_scheduler_strategy_value(args) == expected
+def test_speculative_launch_args_support_qwen_eagle_and_gemma_assistant() -> None:
+ assert SGLangGenerationAdapter._speculative_launch_args(
+ {
+ "enabled": True,
+ "algorithm": "eagle",
+ "num_steps": 3,
+ "eagle_topk": 1,
+ "num_draft_tokens": 4,
+ }
+ ) == [
+ "--speculative-algorithm",
+ "EAGLE",
+ "--speculative-num-steps",
+ "3",
+ "--speculative-eagle-topk",
+ "1",
+ "--speculative-num-draft-tokens",
+ "4",
+ ]
+ assert SGLangGenerationAdapter._speculative_launch_args(
+ {
+ "enabled": True,
+ "algorithm": "nextn",
+ "num_steps": 3,
+ "eagle_topk": 1,
+ "num_draft_tokens": 4,
+ "draft_model": "google/gemma-4-31B-it-assistant",
+ "draft_model_revision": "6" * 40,
+ }
+ )[-4:] == [
+ "--speculative-draft-model-path",
+ "google/gemma-4-31B-it-assistant",
+ "--speculative-draft-model-revision",
+ "6" * 40,
+ ]
+
+
def test_unloaded_generate_raises(adapter) -> None:
# ``generate`` is now an async generator function; the loaded-check
# fires when we first try to drive the iterator, not at call time.
diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.py
index 3cb0caa88..f4b9c15db 100644
--- a/packages/sie_server/tests/config/test_config.py
+++ b/packages/sie_server/tests/config/test_config.py
@@ -1088,7 +1088,7 @@ class TestKvBudgetTokensValidator:
class TestGrammarProfile:
- """``tasks.generate.grammar_profile`` validation (grammar-request routing)."""
+ """Model- and profile-scoped grammar-request routing validation."""
@staticmethod
def _config(grammar_profile: str | None, *, with_no_spec: bool = True) -> ModelConfig:
@@ -1097,6 +1097,7 @@ class TestGrammarProfile:
adapter_path="sie_server.adapters.test:TestAdapter",
max_batch_tokens=8192,
kv_budget_tokens=1024,
+ adapter_options=AdapterOptions(loadtime={"speculative": {"enabled": True}}),
),
}
if with_no_spec:
@@ -1104,6 +1105,7 @@ class TestGrammarProfile:
adapter_path="sie_server.adapters.test:TestAdapter",
max_batch_tokens=8192,
kv_budget_tokens=1024,
+ adapter_options=AdapterOptions(loadtime={"speculative": {"enabled": False}}),
)
return ModelConfig(
sie_id="gen-model",
@@ -1130,6 +1132,87 @@ class TestGrammarProfile:
with pytest.raises(ValidationError, match="must not be 'default'"):
self._config("default")
+ def test_global_grammar_profile_rejects_chained_target(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["safe-2"] = ProfileConfig(
+ adapter_path="sie_server.adapters.test:TestAdapter",
+ max_batch_tokens=8192,
+ kv_budget_tokens=1024,
+ adapter_options=AdapterOptions(loadtime={"speculative": {"enabled": False}}),
+ )
+ config.profiles["no-spec"].grammar_profile = "safe-2"
+ with pytest.raises(ValidationError, match="must not declare another grammar_profile"):
+ ModelConfig.model_validate(config.model_dump())
+
+ def test_global_grammar_profile_must_not_enable_speculation(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["no-spec"].adapter_options = AdapterOptions(loadtime={"speculative": {"enabled": True}})
+ with pytest.raises(ValidationError, match="must not enable speculation"):
+ ModelConfig.model_validate(config.model_dump())
+
+ def test_profile_scoped_grammar_profile_is_local_and_resolves(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["fast"] = ProfileConfig(
+ extends="default",
+ grammar_profile="no-spec",
+ kv_budget_tokens=1024,
+ )
+ config = ModelConfig.model_validate(config.model_dump())
+
+ assert config.resolve_profile("fast").grammar_profile == "no-spec"
+ assert config.resolve_profile("no-spec").grammar_profile is None
+
+ def test_profile_scoped_grammar_profile_does_not_require_global_fallback(self) -> None:
+ config = self._config(None)
+ config.profiles["fast"] = ProfileConfig(
+ extends="default",
+ grammar_profile="no-spec",
+ kv_budget_tokens=1024,
+ )
+ config = ModelConfig.model_validate(config.model_dump())
+
+ assert config.tasks.generate is not None
+ assert config.tasks.generate.grammar_profile is None
+ assert config.resolve_profile("fast").grammar_profile == "no-spec"
+
+ def test_unknown_profile_scoped_grammar_profile_rejected(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["fast"] = ProfileConfig(
+ extends="default",
+ grammar_profile="missing",
+ kv_budget_tokens=1024,
+ )
+ with pytest.raises(ValidationError, match="Profile 'fast' grammar_profile 'missing' is not defined"):
+ ModelConfig.model_validate(config.model_dump())
+
+ def test_profile_scoped_grammar_profile_preserves_thinking_mode(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["fast"] = ProfileConfig(
+ extends="default",
+ grammar_profile="no-spec",
+ kv_budget_tokens=1024,
+ chat_template_kwargs={"enable_thinking": True},
+ )
+ with pytest.raises(ValidationError, match="tokenizer mode"):
+ ModelConfig.model_validate(config.model_dump())
+
+ def test_default_profile_scoped_grammar_profile_rejected(self) -> None:
+ config = self._config("no-spec")
+ config.profiles["default"].grammar_profile = "no-spec"
+ with pytest.raises(ValidationError, match=r"Profile 'default' must use tasks\.generate\.grammar_profile"):
+ ModelConfig.model_validate(config.model_dump())
+
+ @pytest.mark.parametrize("target", ["default", "fast"])
+ def test_profile_scoped_grammar_profile_rejects_default_or_self(self, target: str) -> None:
+ config = self._config("no-spec")
+ config.profiles["fast"] = ProfileConfig(
+ extends="default",
+ grammar_profile=target,
+ kv_budget_tokens=1024,
+ )
+ with pytest.raises(ValidationError, match="must name a non-default sibling"):
+ ModelConfig.model_validate(config.model_dump())
+
class TestLoraRevisionPins:
"""The pinned-LoRA spelling on loadtime.lora_paths dict values (#2113)."""
@@ -1203,3 +1286,36 @@ class TestLoraRevisionPins:
}
)
assert config.lora_revisions() == {"acme/l": self.SHA_A}
+
+
+class TestSpeculativeDraftRevisionPins:
+ SHA_A = "a" * 40
+ SHA_B = "b" * 40
+
+ @staticmethod
+ def _profile(draft_model: str, revision: str | None) -> ProfileConfig:
+ speculative = {"enabled": True, "algorithm": "nextn", "draft_model": draft_model}
+ if revision is not None:
+ speculative["draft_model_revision"] = revision
+ return ProfileConfig(
+ adapter_path="mod:Cls",
+ max_batch_tokens=8192,
+ adapter_options=AdapterOptions(loadtime={"speculative": speculative}),
+ )
+
+ def test_pinned_draft_is_accepted_and_surfaced(self) -> None:
+ config = _make_config(profiles={"default": self._profile("acme/draft", self.SHA_A)})
+ assert config.speculative_draft_revisions() == {"acme/draft": self.SHA_A}
+
+ def test_moving_draft_revision_is_rejected(self) -> None:
+ with pytest.raises(ValidationError, match="40-char commit SHA"):
+ self._profile("acme/draft", "main")
+
+ def test_conflicting_draft_pins_are_rejected(self) -> None:
+ with pytest.raises(ValidationError, match="two different revisions"):
+ _make_config(
+ profiles={
+ "default": self._profile("acme/draft", self.SHA_A),
+ "other": self._profile("acme/draft", self.SHA_B),
+ }
+ )
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 f289a2aa9..f81f47571 100644
--- a/packages/sie_server/tests/config/test_generation_mode_profiles.py
+++ b/packages/sie_server/tests/config/test_generation_mode_profiles.py
@@ -40,9 +40,14 @@ _LONG_CONTEXT_THINKING_MODELS = (
_LONG_CONTEXT_THINKING_IDS = {model_id for _, model_id in _LONG_CONTEXT_THINKING_MODELS}
_HARDWARE_THINKING_PROFILES = {
- "Qwen/Qwen3.6-27B": ("h100-256k-thinking",),
+ "Qwen/Qwen3.6-27B": ("h100-256k-thinking", "long-context-thinking-no-spec"),
"Qwen/Qwen3.6-35B-A3B": ("h100-256k-thinking",),
- "google/gemma-4-31B-it": ("h100-96k-thinking", "h200-256k-thinking"),
+ "google/gemma-4-31B-it": (
+ "h100-96k-thinking",
+ "h200-256k-thinking",
+ "long-context-thinking-no-spec",
+ "h100-96k-thinking-no-spec",
+ ),
}
@@ -94,7 +99,7 @@ def test_long_context_profile_promotes_request_and_adapter_limits(
@pytest.mark.parametrize(("model_file", "model_id"), _LONG_CONTEXT_THINKING_MODELS)
-def test_long_context_thinking_profile_reuses_256k_launch_shape(
+def test_long_context_thinking_profile_preserves_256k_contract(
model_file: str,
model_id: str,
) -> None:
@@ -111,7 +116,14 @@ def test_long_context_thinking_profile_reuses_256k_launch_shape(
assert non_thinking.tasks.generate.max_output_tokens == expected_non_thinking_cap
assert thinking.tasks.generate.max_output_tokens == expected_thinking_cap
assert non_thinking.max_sequence_length == thinking.max_sequence_length == 262144
- assert non_thinking.resolve_profile("default").loadtime == thinking.resolve_profile("default").loadtime
+ if model_id in {"Qwen/Qwen3.6-27B", "google/gemma-4-31B-it"}:
+ # The first optimized release is intentionally non-thinking only. Keep
+ # the existing conservative thinking launch until its separate gate.
+ assert non_thinking.resolve_profile("default").loadtime["speculative"]["enabled"] is True
+ assert thinking.resolve_profile("default").loadtime["speculative"] == {"enabled": False}
+ assert thinking.resolve_profile("default").loadtime["disable_cuda_graph"] is True
+ else:
+ assert non_thinking.resolve_profile("default").loadtime == thinking.resolve_profile("default").loadtime
assert non_thinking.resolve_profile("default").kv_budget_tokens == 262144
assert thinking.resolve_profile("default").kv_budget_tokens == 262144
assert non_thinking.tasks.generate.chat_template_kwargs == {"enable_thinking": False}
@@ -157,6 +169,50 @@ def test_gemma_31b_large_context_profiles_use_measured_kv_precision() -> None:
]
+def test_gemma_31b_profiles_use_measured_mtp_shape_with_grammar_fallback() -> None:
+ config = load_model_config(MODELS_DIR / "google__gemma-4-31B-it.yaml")
+ assert config.tasks.generate is not None
+ assert config.tasks.generate.grammar_profile == "no-spec"
+ assert config.resolve_profile("no-spec").loadtime["speculative"] == {"enabled": False}
+
+ expected = {
+ "enabled": True,
+ "algorithm": "nextn",
+ "num_steps": 3,
+ "eagle_topk": 1,
+ "num_draft_tokens": 4,
+ "draft_model": "google/gemma-4-31B-it-assistant",
+ "draft_model_revision": "627c5ec1458b9086b841a91e0512fd31fd2fbbf1",
+ }
+ for profile_name in ("default", "h100-96k", "long-context"):
+ loadtime = config.resolve_profile(profile_name).loadtime
+ assert loadtime["speculative"] == expected
+ assert loadtime["speculative_needs_extra_buffer"] is False
+ assert "disable_cuda_graph" not in loadtime
+
+ for source_name, fallback_name, thinking in (
+ ("long-context", "long-context-no-spec", False),
+ ("h200-256k", "long-context-no-spec", False),
+ ("long-context-thinking", "long-context-thinking-no-spec", True),
+ ("h200-256k-thinking", "long-context-thinking-no-spec", True),
+ ("h100-96k", "h100-96k-no-spec", False),
+ ("h100-96k-thinking", "h100-96k-thinking-no-spec", True),
+ ("thinking", "h100-96k-thinking-no-spec", True),
+ ):
+ source = config.resolve_profile(source_name)
+ fallback = config.resolve_profile(fallback_name)
+ assert source.grammar_profile == fallback_name
+ assert fallback.grammar_profile is None
+ assert source.adapter_path == fallback.adapter_path
+ assert source.compute_precision == fallback.compute_precision
+ assert source.max_batch_tokens == fallback.max_batch_tokens
+ assert source.loadtime | {"speculative": None} == fallback.loadtime | {"speculative": None}
+ assert fallback.loadtime["speculative"] == {"enabled": False}
+ assert source.chat_template_kwargs == fallback.chat_template_kwargs
+ effective_mode = source.chat_template_kwargs or config.tasks.generate.chat_template_kwargs
+ assert effective_mode == {"enable_thinking": thinking}
+
+
@pytest.mark.parametrize(
("model_file", "model_id"),
[
diff --git a/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py b/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py
index 52f6a4a75..c5e008b8d 100644
--- a/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py
+++ b/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py
@@ -10,13 +10,25 @@ MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
@pytest.mark.parametrize(
- ("model_file", "model_id", "adapter_path", "grammar_backend", "extra_launch_args"),
+ (
+ "model_file",
+ "model_id",
+ "adapter_path",
+ "grammar_backend",
+ "grammar_profile",
+ "disable_cuda_graph",
+ "speculative",
+ "extra_launch_args",
+ ),
[
(
"Qwen__Qwen3.6-35B-A3B.yaml",
"Qwen/Qwen3.6-35B-A3B",
"sie_server.adapters.sglang.generation:SGLangGenerationAdapter",
"xgrammar",
+ None,
+ True,
+ {"enabled": False},
[
"--mm-process-config",
'{"image":{"min_pixels":65536,"max_pixels":1003520}}',
@@ -29,6 +41,17 @@ MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
"google/gemma-4-31B-it",
"sie_server.adapters.sglang.gemma:SGLangGemmaAdapter",
"xgrammar",
+ "no-spec",
+ None,
+ {
+ "enabled": True,
+ "algorithm": "nextn",
+ "num_steps": 3,
+ "eagle_topk": 1,
+ "num_draft_tokens": 4,
+ "draft_model": "google/gemma-4-31B-it-assistant",
+ "draft_model_revision": "627c5ec1458b9086b841a91e0512fd31fd2fbbf1",
+ },
["--quantization", "fp8"],
),
],
@@ -38,6 +61,9 @@ def test_new_generation_models_resolve_h100_fp8_alias(
model_id: str,
adapter_path: str,
grammar_backend: str,
+ grammar_profile: str | None,
+ disable_cuda_graph: bool | None,
+ speculative: dict[str, object],
extra_launch_args: list[str],
) -> None:
config = ModelConfig.model_validate(yaml.safe_load((MODELS_DIR / model_file).read_text()))
@@ -49,14 +75,14 @@ def test_new_generation_models_resolve_h100_fp8_alias(
assert config.tasks.generate is not None
assert config.tasks.generate.context_length == 8192
assert config.tasks.generate.max_output_tokens == 4096
- assert config.tasks.generate.grammar_profile is None
+ assert config.tasks.generate.grammar_profile == grammar_profile
assert h100_fp8 == default
assert default.adapter_path == adapter_path
assert default.compute_precision == "bfloat16"
assert default.kv_budget_tokens == 8192
assert default.loadtime["served_model_name"] == model_id
- assert default.loadtime["disable_cuda_graph"] is True
+ assert default.loadtime.get("disable_cuda_graph") is disable_cuda_graph
assert default.loadtime["grammar_backend"] == grammar_backend
- assert default.loadtime["speculative"] == {"enabled": False}
+ assert default.loadtime["speculative"] == speculative
assert default.loadtime["extra_launch_args"] == extra_launch_args
diff --git a/packages/sie_server/tests/config/test_qwen_generation_profiles.py b/packages/sie_server/tests/config/test_qwen_generation_profiles.py
index 7f05688f1..ad588d9e1 100644
--- a/packages/sie_server/tests/config/test_qwen_generation_profiles.py
+++ b/packages/sie_server/tests/config/test_qwen_generation_profiles.py
@@ -10,6 +10,7 @@ from transformers import Qwen2VLImageProcessorFast
_QWEN35_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.5-4B.yaml"
_ADAPTER = "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"
+_CUDA13_ADAPTER = "sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter"
_STRICT_THINKING_ADAPTER = "sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter"
_MLX_REPO = "mlx-community/Qwen3.5-4B-4bit"
_QWEN36_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.6-27B.yaml"
@@ -196,7 +197,7 @@ def test_all_qwen_vlm_profiles_pair_pinned_image_bounds() -> None:
assert config.inputs.image is True
for profile_name in config.profiles:
profile = config.resolve_profile(profile_name)
- if profile.adapter_path not in {_ADAPTER, _STRICT_THINKING_ADAPTER}:
+ if profile.adapter_path not in {_ADAPTER, _CUDA13_ADAPTER, _STRICT_THINKING_ADAPTER}:
continue
args = profile.loadtime["extra_launch_args"]
assert args.count("--mm-process-config") == 1, (model_path.name, profile_name, args)
@@ -211,6 +212,57 @@ def test_all_qwen_vlm_profiles_pair_pinned_image_bounds() -> None:
}
+def test_qwen36_native_window_uses_measured_cuda13_eagle_shape() -> None:
+ config = ModelConfig.model_validate(yaml.safe_load(_QWEN36_MODEL_PATH.read_text()))
+ profile = config.resolve_profile("long-context")
+
+ assert profile.adapter_path == _CUDA13_ADAPTER
+ assert profile.loadtime["max_seq_length"] == 262144
+ assert profile.loadtime["mem_fraction_static"] == 0.90
+ assert "disable_cuda_graph" not in profile.loadtime
+ assert profile.loadtime["speculative"] == {
+ "enabled": True,
+ "algorithm": "eagle",
+ "num_steps": 3,
+ "eagle_topk": 1,
+ "num_draft_tokens": 4,
+ }
+ assert profile.loadtime["extra_launch_args"] == [
+ *_MM_PROCESS_CONFIG_ARGS,
+ "--quantization",
+ "fp8",
+ "--mamba-scheduler-strategy",
+ "extra_buffer",
+ "--page-size",
+ "64",
+ ]
+
+
+def test_qwen36_native_window_grammar_twins_preserve_launch_shape_and_mode() -> None:
+ config = ModelConfig.model_validate(yaml.safe_load(_QWEN36_MODEL_PATH.read_text()))
+
+ for source_name, fallback_name, thinking in (
+ ("long-context", "long-context-no-spec", False),
+ ("h100-256k", "long-context-no-spec", False),
+ ("long-context-thinking", "long-context-thinking-no-spec", True),
+ ("h100-256k-thinking", "long-context-thinking-no-spec", True),
+ ("thinking", "long-context-thinking-no-spec", True),
+ ):
+ source = config.resolve_profile(source_name)
+ fallback = config.resolve_profile(fallback_name)
+ assert source.grammar_profile == fallback_name
+ assert fallback.grammar_profile is None
+ assert source.adapter_path == fallback.adapter_path
+ assert source.compute_precision == fallback.compute_precision
+ assert source.max_batch_tokens == fallback.max_batch_tokens
+ assert source.loadtime | {"speculative": None} == fallback.loadtime | {"speculative": None}
+ assert source.loadtime["speculative"]["enabled"] is (not thinking)
+ assert fallback.loadtime["speculative"] == {"enabled": False}
+ assert source.chat_template_kwargs == fallback.chat_template_kwargs
+ effective_mode = source.chat_template_kwargs or config.tasks.generate.chat_template_kwargs
+ assert effective_mode == {"enable_thinking": thinking}
+
+
def test_qwen_fast_processor_applies_paired_image_bounds() -> None:
processor = Qwen2VLImageProcessorFast(
size={"shortest_edge": _QWEN_IMAGE_MIN_PIXELS, "longest_edge": 16777216},
diff --git a/packages/sie_server/tests/core/test_model_loader_cache.py b/packages/sie_server/tests/core/test_model_loader_cache.py
new file mode 100644
index 000000000..a83843ff5
--- /dev/null
+++ b/packages/sie_server/tests/core/test_model_loader_cache.py
@@ -0,0 +1,72 @@
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+from sie_server.config.model import AdapterOptions, ModelConfig, ProfileConfig, Tasks
+from sie_server.core.model_loader import ModelLoader
+from sie_server.core.postprocessor_registry import PostprocessorRegistry
+from sie_server.core.preprocessor_registry import PreprocessorRegistry
+
+
+ ("base_source", "expected_refs"),
+ [
+ pytest.param(
+ {"hf_id": "acme/base", "hf_revision": "a" * 40},
+ [("acme/base", "a" * 40), ("acme/draft", "b" * 40)],
+ id="hf-base",
+ ),
+ pytest.param(
+ {"weights_path": Path("/models/base")},
+ [("acme/draft", "b" * 40)],
+ id="local-base",
+ ),
+ ],
+)
+def test_ensure_weights_cached_stages_pinned_speculative_draft(
+ base_source: dict[str, object],
+ expected_refs: list[tuple[str, str]],
+) -> None:
+ draft_revision = "b" * 40
+ config = ModelConfig(
+ sie_id="acme/base",
+ **base_source,
+ tasks=Tasks(),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="mod:Cls",
+ max_batch_tokens=8192,
+ adapter_options=AdapterOptions(
+ loadtime={
+ "speculative": {
+ "enabled": True,
+ "algorithm": "nextn",
+ "draft_model": "acme/draft",
+ "draft_model_revision": draft_revision,
+ }
+ }
+ ),
+ )
+ },
+ )
+ cpu_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cpu")
+ loader = ModelLoader(
+ preprocessor_registry=PreprocessorRegistry(),
+ postprocessor_registry=PostprocessorRegistry(cpu_pool),
+ all_configs={},
+ )
+ cache_config = MagicMock()
+
+ try:
+ with (
+ patch("sie_sdk.cache.get_cache_config", return_value=cache_config),
+ patch("sie_sdk.cache.ensure_model_cached", return_value=Path("/cache/model")) as ensure,
+ ):
+ loader.ensure_weights_cached(config)
+
+ assert [(entry.args[0], entry.kwargs["revision"]) for entry in ensure.call_args_list] == expected_refs
+ assert all(entry.args[1] is cache_config for entry in ensure.call_args_list)
+ finally:
+ loader._load_executor.shutdown(wait=True)
+ cpu_pool.shutdown(wait=True)
diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.toml
index 92e225d35..9426195bc 100644
--- a/packages/sie_server_sidecar/Cargo.toml
+++ b/packages/sie_server_sidecar/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-server-sidecar"
-version = "0.6.27"
+version = "0.6.28"
edition = "2021"
publish = false
description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index c0f4afccc..9ab1e1e25 100644
--- a/packages/sie_ts_sdk/package.json
+++ b/packages/sie_ts_sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-sdk",
- "version": "0.6.27",
+ "version": "0.6.28",
"description": "Official TypeScript SDK for SIE (Search Inference Engine)",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.ts
index c31563183..8ac3b8a64 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.6.27"; // x-release-please-version
+export const SDK_VERSION = "0.6.28"; // x-release-please-version
diff --git a/uv.lock b/uv.lock
index 457cfaaf5..a684c36f0 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4373,12 +4373,12 @@ dev = [
[[package]]
name = "sie-audio-prep"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "packages/sie_audio_prep" }
[[package]]
name = "sie-chroma"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -4458,7 +4458,7 @@ dev = [
[[package]]
name = "sie-crewai"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -4483,7 +4483,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -4508,7 +4508,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -4535,7 +4535,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -4562,7 +4562,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -4589,7 +4589,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -4655,7 +4655,7 @@ dev = [
[[package]]
name = "sie-qdrant"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -4678,7 +4678,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -4731,7 +4731,7 @@ requires-dist = [
[[package]]
name = "sie-server"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "packages/sie_server" }
dependencies = [
{ name = "blake3" },
@@ -4854,7 +4854,7 @@ dev = []
[[package]]
name = "sie-weaviate"
-version = "0.6.27"
+version = "0.6.28"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },