Skip to content

Commit f54857e

Browse files
authored
feat(rust): serve /v1/decisions and /v1/systemone in the Rust frontend (#1812)
* feat(rust): serve /v1/decisions and /v1/systemone in the Rust frontend Port the generative read strategies (next-token, Liquid and DiffusionGemma canvas and joint reads) with the Python request validation, prompts, label reads and answers. Models that read through a classification head answer 501 and name the Python frontend. The frontend now reads --logprobs-mode and --diffusion-config and forwards them to a managed engine. Signed-off-by: AlpinDale <alpindale@gmail.com> * feat(rust): read D3 and Clef decisions with pooling requests Serve the pooling strategies of /v1/systemone in the Rust frontend: D3Strategy, ClefFlashStrategy and JointSchemaStrategy (Clef-Omni), with Python's prompts, request validation, messages and answers. D3 and Clef-Flash also read images. Like Python, /v1/decisions stays 501 on these models. The engine-core client now types PoolingParams and decodes pooling_output tensors, inline or in auxiliary frames, checked against fixtures from Python's serializer. sonar-llm gains Llm::encode for pooling requests. The text backend names the decision architecture of a checkpoint that ships a decision_config.json or joint_head_config.json, as Python's architecture convertors do, so Clef-Flash is no longer served as Qwen3.5. Videos to D3 and Clef-Flash and all media to Clef-Omni answer 501 with the reason: their Python sampling and processor options have no per-request counterpart in the Rust multimodal pipeline. Signed-off-by: AlpinDale <alpindale@gmail.com> --------- Signed-off-by: AlpinDale <alpindale@gmail.com>
1 parent 461e453 commit f54857e

37 files changed

Lines changed: 6874 additions & 20 deletions

File tree

‎docs/src/content/docs/deployment/rust-frontend.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,19 @@ The current Rust router provides these public routes:
8282
| `/v1/models` | Served model list |
8383
| `/v1/completions` | OpenAI-compatible completions |
8484
| `/v1/chat/completions` | OpenAI-compatible chat completions |
85+
| `/v1/decisions` and `/v1/systemone` | Structured decisions |
8586
| `/tokenize` and `/detokenize` | Tokenizer operations |
8687
| `/inference/v1/generate` | Token-input and token-output generation |
8788

89+
The decision routes serve the models that read labels by generation: Qwen3,
90+
Qwen3.5, Gemma 4, LFM2-VL and DiffusionGemma. They read the engine's
91+
`--logprobs-mode` and `--diffusion-config` like the Python frontend. The
92+
models that score options with a pooling head (D3, Clef-Flash and Clef-Omni)
93+
answer on `/v1/systemone` only, as in the Python frontend; D3 and Clef-Flash
94+
also read images. These inputs return 501: videos to D3 and Clef-Flash, any
95+
media to Clef-Omni, images to LFM2-VL, and images for models without a Rust
96+
image processor. Use the Python frontend for them.
97+
8898
Runtime LoRA routes are available when
8999
`SONAR_ALLOW_RUNTIME_LORA_UPDATING` is enabled. Development and profiling
90100
routes require their corresponding server settings.

‎rust/src/chat/src/lib.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,22 @@ impl ChatRequestProcessor {
273273
Ok(text_request)
274274
}
275275

276+
/// Render one request's chat template without preparing its media, whose
277+
/// placeholders stay as the template writes them.
278+
pub async fn render_prompt(&self, mut request: ChatRequest) -> Result<Prompt> {
279+
request.validate()?;
280+
self.map_reasoning_effort(&mut request);
281+
let renderer = self.backend.chat_renderer();
282+
if request.chat_options.chat_template.is_some() && !renderer.renders_request_chat_template()
283+
{
284+
return Err(Error::UnsupportedRequestChatTemplate);
285+
}
286+
let rendered = tokio::task::spawn_blocking(move || renderer.render(&request))
287+
.await
288+
.map_err(|e| Error::ChatTemplate(format!("render task join error: {e}")))??;
289+
Ok(rendered.prompt)
290+
}
291+
276292
/// Prepare one chat request without submitting it to an engine.
277293
///
278294
/// The returned text request is already tokenized: the output processors

‎rust/src/cmd/src/cli.rs‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ use sonar_server::{
3838
AccessLogConfig, ApiServerOptions, ChatTemplateContentFormatOption, Config, CoordinatorMode,
3939
CorsConfig, CustomHistogramBuckets, DEFAULT_KEEP_ALIVE_TIMEOUT, DEFAULT_LOG_STATS_INTERVAL,
4040
DEFAULT_MAX_N_SEQUENCES, DEFAULT_REQUEST_BODY_LIMIT_BYTES, FingerprintMode, HttpListenerMode,
41-
LoraModulePath, OutputLogConfig, OutputLogging, ParserSelection, ReasoningEffort, RenderConfig,
42-
RendererSelection,
41+
LogprobsMode, LoraModulePath, OutputLogConfig, OutputLogging, ParserSelection, ReasoningEffort,
42+
RenderConfig, RendererSelection,
4343
};
4444
use sonar_text::backend::hf::{HfOverrides, ModelFileSources};
4545
use sonar_tracing::{LogFormatter, LogLevel};
@@ -442,6 +442,17 @@ pub struct SharedRuntimeArgs {
442442
#[arg(long, value_parser = clap::value_parser!(i32).range(-1..), allow_negative_numbers = true)]
443443
#[serde(default)]
444444
pub max_logprobs: Option<i32>,
445+
/// What the engine returns as logprobs: `raw_logprobs` (default),
446+
/// `processed_logprobs`, `raw_logits` or `processed_logits`. Forwarded to
447+
/// the engine; decisions need log probabilities.
448+
#[arg(long, default_value_t)]
449+
#[serde(default)]
450+
pub logprobs_mode: LogprobsMode,
451+
/// Configuration of discrete diffusion models as a JSON object. The Rust
452+
/// frontend reads `canvas_length`; the engine reads every field.
453+
#[arg(long, value_parser = parse_json::<DiffusionConfig>, value_name = "JSON")]
454+
#[serde(default)]
455+
pub diffusion_config: Option<DiffusionConfig>,
445456
/// The interval (or buffer size) for streaming in terms of token length.
446457
/// A smaller value (1) makes streaming smoother by sending each token
447458
/// immediately, while a larger value (e.g., 10) reduces host overhead and
@@ -1158,6 +1169,11 @@ impl SharedRuntimeArgs {
11581169
lora_modules: self.lora_modules,
11591170
chat_template_content_format: self.chat_template_content_format,
11601171
max_logprobs: self.max_logprobs,
1172+
logprobs_mode: self.logprobs_mode,
1173+
diffusion_canvas_length: self
1174+
.diffusion_config
1175+
.as_ref()
1176+
.and_then(|config| config.canvas_length),
11611177
stream_interval: self.stream_interval,
11621178
api_server_options,
11631179
fingerprint_mode,
@@ -1252,6 +1268,11 @@ impl SharedRuntimeArgs {
12521268
lora_modules: self.lora_modules,
12531269
chat_template_content_format: self.chat_template_content_format,
12541270
max_logprobs: self.max_logprobs,
1271+
logprobs_mode: self.logprobs_mode,
1272+
diffusion_canvas_length: self
1273+
.diffusion_config
1274+
.as_ref()
1275+
.and_then(|config| config.canvas_length),
12551276
stream_interval: self.stream_interval,
12561277
api_server_options,
12571278
fingerprint_mode,
@@ -1406,6 +1427,20 @@ pub struct StructuredOutputsConfig {
14061427
pub extra: serde_json::Map<String, Value>,
14071428
}
14081429

1430+
/// Diffusion model configuration parsed from `--diffusion-config`.
1431+
///
1432+
/// Only `canvas_length` is read by the Rust frontend. All other fields are
1433+
/// accepted but ignored; they are consumed by the Python engine layer.
1434+
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1435+
pub struct DiffusionConfig {
1436+
/// Length of the denoising canvas.
1437+
#[serde(default, skip_serializing_if = "Option::is_none")]
1438+
pub canvas_length: Option<u32>,
1439+
/// Additional Python diffusion config fields consumed by the engine layer.
1440+
#[serde(flatten)]
1441+
pub extra: serde_json::Map<String, Value>,
1442+
}
1443+
14091444
/// Keys are API effort names, so unknown efforts fail at startup.
14101445
type ReasoningEffortMap = HashMap<ReasoningEffort, String>;
14111446

@@ -1659,6 +1694,19 @@ impl ServeArgs {
16591694
.python_args
16601695
.extend(["--logging-config".to_string(), logging_config]);
16611696
}
1697+
// The engine owns these; the frontend reads them to serve decisions.
1698+
if self.runtime.logprobs_mode != LogprobsMode::default() {
1699+
managed_engine.python_args.extend([
1700+
"--logprobs-mode".to_string(),
1701+
self.runtime.logprobs_mode.to_string(),
1702+
]);
1703+
}
1704+
if let Some(diffusion_config) = &self.runtime.diffusion_config {
1705+
managed_engine.python_args.extend([
1706+
"--diffusion-config".to_string(),
1707+
serde_json::to_string(diffusion_config).expect("JSON object serializes"),
1708+
]);
1709+
}
16621710
managed_engine.into_config(
16631711
self.runtime.model.id.clone(),
16641712
self.runtime.max_logprobs,

‎rust/src/cmd/src/cli/tests.rs‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use sonar_engine_core_client::protocol::dtype::ModelDtype;
1010
use sonar_engine_core_client::protocol::structured_outputs::StructuredOutputBackend;
1111
use sonar_engine_core_client::{CoordinatorMode as EngineCoreCoordinatorMode, TransportMode};
1212
use sonar_server::{
13-
Config, FingerprintMode, GenerationConfigMode, HttpListenerMode, LoraModulePath,
13+
Config, FingerprintMode, GenerationConfigMode, HttpListenerMode, LogprobsMode, LoraModulePath,
1414
OutputLogConfig, OutputLogging, ParserSelection, ReasoningEffort, RendererSelection,
1515
};
1616
use sonar_text::backend::hf::ModelSource;
@@ -278,6 +278,8 @@ fn serve_args_forward_python_flags_with_separator() {
278278
renderer: Auto,
279279
language_model_only: false,
280280
max_logprobs: None,
281+
logprobs_mode: RawLogprobs,
282+
diffusion_config: None,
281283
stream_interval: 1,
282284
shutdown_timeout: 0,
283285
http_timeout_keep_alive: None,
@@ -995,6 +997,63 @@ fn frontend_args_json_reads_python_structured_outputs_config() {
995997
}
996998
}
997999

1000+
#[test]
1001+
fn serve_args_read_and_forward_decision_engine_settings() {
1002+
let cli = Cli::try_parse_from([
1003+
"sonar-rs",
1004+
"serve",
1005+
"Qwen/Qwen3-0.6B",
1006+
"--logprobs-mode",
1007+
"processed_logprobs",
1008+
"--diffusion-config",
1009+
r#"{"canvas_length":64,"max_denoising_steps":8}"#,
1010+
])
1011+
.unwrap();
1012+
let Command::Serve(args) = cli.command else {
1013+
panic!("expected serve args");
1014+
};
1015+
let frontend = args.to_frontend_config("tcp://127.0.0.1:0".into(), &topology(&args));
1016+
assert_eq!(frontend.logprobs_mode, LogprobsMode::ProcessedLogprobs);
1017+
assert_eq!(frontend.diffusion_canvas_length, Some(64));
1018+
let python_args = args.to_managed_engine_config(5555, &topology(&args), None).python_args;
1019+
let value = |flag: &str| {
1020+
let index = python_args.iter().position(|arg| arg == flag).expect(flag);
1021+
python_args[index + 1].clone()
1022+
};
1023+
assert_eq!(value("--logprobs-mode"), "processed_logprobs");
1024+
let forwarded: serde_json::Value = serde_json::from_str(&value("--diffusion-config")).unwrap();
1025+
assert_eq!(
1026+
forwarded,
1027+
serde_json::json!({"canvas_length": 64, "max_denoising_steps": 8})
1028+
);
1029+
1030+
// The Python supervisor passes them in the bootstrap JSON.
1031+
let args_json = serde_json::json!({
1032+
"model_tag": "Qwen/Qwen3-0.6B",
1033+
"logprobs_mode": "raw_logits",
1034+
"diffusion_config": {"canvas_length": 32},
1035+
});
1036+
let cli = Cli::try_parse_from([
1037+
"sonar-rs",
1038+
"frontend",
1039+
"--listen-fd",
1040+
"3",
1041+
"--input-listener-fd",
1042+
"999999",
1043+
"--output-listener-fd",
1044+
"999998",
1045+
"--args-json",
1046+
&args_json.to_string(),
1047+
])
1048+
.unwrap();
1049+
let Command::Frontend(args) = cli.command else {
1050+
panic!("expected frontend args");
1051+
};
1052+
let config = args.into_config();
1053+
assert_eq!(config.logprobs_mode, LogprobsMode::RawLogits);
1054+
assert_eq!(config.diffusion_canvas_length, Some(32));
1055+
}
1056+
9981057
#[test]
9991058
fn serve_args_tool_strict_level_requires_xgrammar() {
10001059
let validate = |strict_level: &str, backend: &str| {
@@ -2290,6 +2349,8 @@ fn frontend_args_accept_json() {
22902349
renderer: Auto,
22912350
language_model_only: false,
22922351
max_logprobs: None,
2352+
logprobs_mode: RawLogprobs,
2353+
diffusion_config: None,
22932354
stream_interval: 1,
22942355
shutdown_timeout: 0,
22952356
http_timeout_keep_alive: None,
@@ -3340,6 +3401,8 @@ fn serve_args_accept_handshake_aliases() {
33403401
renderer: Auto,
33413402
language_model_only: false,
33423403
max_logprobs: None,
3404+
logprobs_mode: RawLogprobs,
3405+
diffusion_config: None,
33433406
stream_interval: 1,
33443407
shutdown_timeout: 0,
33453408
http_timeout_keep_alive: None,
@@ -3663,6 +3726,8 @@ fn serve_frontend_config_uses_dp_address_as_advertised_host() {
36633726
lora_modules: [],
36643727
chat_template_content_format: Auto,
36653728
max_logprobs: None,
3729+
logprobs_mode: RawLogprobs,
3730+
diffusion_canvas_length: None,
36663731
stream_interval: 1,
36673732
api_server_options: ApiServerOptions {
36683733
enable_log_requests: false,
@@ -3801,6 +3866,8 @@ fn serve_frontend_config_keeps_tcp_transport_for_non_local_only_topology() {
38013866
lora_modules: [],
38023867
chat_template_content_format: Auto,
38033868
max_logprobs: None,
3869+
logprobs_mode: RawLogprobs,
3870+
diffusion_canvas_length: None,
38043871
stream_interval: 1,
38053872
api_server_options: ApiServerOptions {
38063873
enable_log_requests: false,
@@ -4058,6 +4125,8 @@ fn frontend_config_uses_external_coordinator_when_coordinator_address_is_present
40584125
lora_modules: [],
40594126
chat_template_content_format: Auto,
40604127
max_logprobs: None,
4128+
logprobs_mode: RawLogprobs,
4129+
diffusion_canvas_length: None,
40614130
stream_interval: 1,
40624131
api_server_options: ApiServerOptions {
40634132
enable_log_requests: false,

‎rust/src/engine-core-client/src/protocol/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ pub mod logprobs;
2929
pub mod lora;
3030
pub mod multimodal;
3131
pub mod output;
32+
pub mod pooling;
3233
pub mod request;
3334
pub mod sampling;
3435
pub mod sampling_mask;

‎rust/src/engine-core-client/src/protocol/output.rs‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,9 @@ pub struct EngineCoreOutput {
9999
/// output.
100100
#[serde(default)]
101101
pub new_prompt_logprobs_tensors: Option<MaybeWireLogprobs>,
102+
/// The pooler's output of a finished pooling request.
102103
#[serde(default)]
103-
pub pooling_output: Option<Box<OpaqueValue>>,
104+
pub pooling_output: Option<Box<WireNdArray>>,
104105
#[serde(default)]
105106
pub finish_reason: Option<EngineCoreFinishReason>,
106107
#[serde(default)]
@@ -238,6 +239,11 @@ impl EngineCoreOutput {
238239
.resolve_aux_frame(frames)
239240
.map_err(|message| ext_value_decode!("routed_experts: {message}"))?;
240241
}
242+
if let Some(value) = self.pooling_output.as_mut() {
243+
value
244+
.resolve_aux_frame(frames)
245+
.map_err(|message| ext_value_decode!("pooling_output: {message}"))?;
246+
}
241247
Ok(())
242248
}
243249
}
@@ -685,4 +691,33 @@ mod tests {
685691
]]
686692
.assert_eq(&error.to_string());
687693
}
694+
695+
/// Python's `MsgpackEncoder().encode(EngineCoreOutputs(...))` of a
696+
/// finished pooling output `torch.tensor([1.5, -0.25, 3.0])`, inline and
697+
/// (with `size_threshold=0`) in an auxiliary frame.
698+
const PYTHON_INLINE_POOLING: &str = "990091dc0014ac6465636973696f6e2d312d3090c0c093a7666c6f617433329103c70c030000c03f000080be0000404000c0c0c0c0c0c0c000c0c0c0c0c0c0c0cb4128c8d35833fc5cc0c0c0c0c0";
699+
const PYTHON_AUX_POOLING: [&str; 2] = [
700+
"990091dc0014ac6465636973696f6e2d312d3090c0c093a7666c6f6174333291030100c0c0c0c0c0c0c000c0\
701+
c0c0c0c0c0c0cb4128c8d35833fc5cc0c0c0c0c0",
702+
"0000c03f000080be00004040",
703+
];
704+
705+
#[test]
706+
fn engine_core_outputs_decode_python_pooling_output() {
707+
for frames in [&[PYTHON_INLINE_POOLING][..], &PYTHON_AUX_POOLING[..]] {
708+
let frames: Vec<Bytes> =
709+
frames.iter().map(|frame| Bytes::from(hex::decode(frame).unwrap())).collect();
710+
let EngineCoreOutputs::RequestBatch(batch) =
711+
decode_engine_core_outputs(&frames).unwrap()
712+
else {
713+
panic!("expected a request batch");
714+
};
715+
let output = &batch.outputs[0];
716+
assert_eq!(output.finish_reason, Some(EngineCoreFinishReason::Stop));
717+
assert!(output.new_token_ids.is_empty());
718+
let pooled = output.pooling_output.as_ref().expect("a pooling output");
719+
assert_eq!(pooled.shape, [3]);
720+
assert_eq!(pooled.to_f64_vec(), Some(vec![1.5, -0.25, 3.0]));
721+
}
722+
}
688723
}

0 commit comments

Comments
 (0)