Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -814,17 +814,24 @@ constraint. Violations return HTTP 400.
Responses, and Messages. It caps generated reasoning tokens from the start of
this request's output. At the cap, if reasoning is unambiguously open, output
capacity remains, and any grammar allows it, Flare emits the prepared reasoning
close token and continues with the remaining output limit. The forced close
counts as a generated token within that limit; forced tokens are omitted from
logprobs. No transition text is inserted.
close token and continues with the remaining output limit. For all reasoning
formats, any incomplete multi-byte UTF-8 tail tokens at a forced cut boundary are
trimmed from the re-prefilled continuation context before the close token is
appended. For TMLv0 content-header reasoning (`ContentHeaders`), when no tools or
grammar are active and output capacity remains beyond the frame opener, Flare also
emits the silent `<|message_model|><|content_text|>` control tokens after
`<|end_message|>` so continuation enters a text frame directly; when tools or a
grammar are active, only `<|end_message|>` is emitted. Forced close tokens count
as generated tokens within the output limit and are omitted from logprobs. No
transition text is inserted.
If reasoning closed earlier, a tool opener is still undecided, or the grammar
disallows the close, generation continues without an injected token.
EOS, user stops, and errors terminate normally without continuation.

The budget requires prepared reasoning syntax with a single-token close delimiter
when output starts in reasoning. Unsupported formats and raw Completions
return HTTP 400 naming `thinking_token_budget`. When output starts in content,
the budget is accepted without a cut.
when output starts in reasoning or a content-header frame. Unsupported formats and
raw Completions return HTTP 400 naming `thinking_token_budget`. When output starts
in content, the budget is accepted without a cut.

`[server] thinking_token_budget = N` sets a default for Chat Completions, Responses,
and Messages requests that omit a budget, including when the request field is null.
Expand Down
17 changes: 17 additions & 0 deletions helios/src/output/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@ pub struct OutputConfig {
pub control_tokens: Vec<(u32, String)>,
}

impl OutputConfig {
/// Follow-on control tokens that open a model text frame after a forced
/// reasoning close, when the output format requires them and no tools are active.
pub(crate) fn reasoning_close_tail(&self) -> Vec<u32> {
if self.syntax.reasoning.as_ref().map(|r| r.kind)
== Some(ReasoningParserKind::ContentHeaders)
&& self.content.tools.is_empty()
{
super::tml::text_frame_opener(&self.control_tokens)
.map(|tokens| tokens.to_vec())
.unwrap_or_default()
} else {
Vec::new()
}
}
}

pub enum OutputPipeline {
FunctionTags(TaggedOutput<super::chatml::FunctionTags<true>>),
CompactFunctionTags(TaggedOutput<super::chatml::FunctionTags<false>>),
Expand Down
13 changes: 13 additions & 0 deletions helios/src/output/tml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ pub(crate) const CONTROL_MARKERS: [&str; 14] = [
TURN_END, BEGIN,
];

/// Returns `[<|message_model|>, <|content_text|>]` from validated single-token control markers.
pub(crate) fn text_frame_opener(control_tokens: &[(u32, String)]) -> Option<[u32; 2]> {
let model = control_tokens
.iter()
.find(|(_, marker)| marker == MODEL)
.map(|(id, _)| *id)?;
let text = control_tokens
.iter()
.find(|(_, marker)| marker == TEXT)
.map(|(id, _)| *id)?;
Some([model, text])
}

#[derive(Clone, Copy, PartialEq)]
enum Body {
Text,
Expand Down
36 changes: 35 additions & 1 deletion helios/src/server/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl Bootstrap {
)?;
let declared = crate::model::declared_control_tokens(&frontend, &model.contract.frontend)?;
let frontend = frontend.with_controls(declared);
if model.max_top_logprobs != 0 { frontend.prepare_token_bytes()?; }
frontend.prepare_token_bytes()?;
if frontend_settings
.image
.as_ref()
Expand Down Expand Up @@ -660,6 +660,40 @@ mod tests {
);
}
}
{
let mut tml_tokenizer = tokenizer.clone();
tml_tokenizer
.add_special_tokens(
crate::output::tml::CONTROL_MARKERS
.iter()
.map(|&s| tokenizers::AddedToken::from(s, true)),
)
.unwrap();
let mut configured = config.clone();
configured["frontend"]["prompt_encoder"] = json!(3);
configured["thinking_token_budget"] = json!(16);
configured["assets"]["tokenizer"] = asset(
"tml-budget-tokenizer.json",
tml_tokenizer.to_string(false).unwrap().as_bytes(),
);
configured["model_contract"]["frontend"]["assistant_marker"] = json!("<|message_model|>");
configured["model_contract"]["frontend"]["reasoning"] =
json!(crate::model::contract::ReasoningParser {
kind: crate::model::contract::ReasoningParserKind::ContentHeaders,
open: "<|content_thinking|>".into(),
close: "<|end_message|>".into(),
wrapping_newlines: 0,
terminal_markers: vec![],
});
configured["model_contract"]["frontend"]["tools"] =
json!(crate::model::contract::ToolParser {
kind: crate::model::contract::ToolParserKind::TmlJson,
wrapping_newlines: 0,
tag_separator: String::new(),
});
let loaded = Bootstrap::load(&configured.to_string(), &manifest).unwrap();
assert_eq!(loaded.server.thinking_token_budget, Some(16));
}
for (selector, expected) in [
(1, PromptEncoder::DeepseekV4),
(2, PromptEncoder::DeepseekV41),
Expand Down
166 changes: 165 additions & 1 deletion helios/src/server/protocol/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1837,7 +1837,7 @@ mod native_prompt_tests {
(budget < 32).then_some(16)
);
if let Some(cut) = prepared.prompt.reasoning_cut {
assert_eq!(frontend.encode("</think>", false).unwrap(), vec![cut.close]);
assert_eq!(frontend.encode("</think>", false).unwrap(), cut.close);
}
}
}
Expand Down Expand Up @@ -2028,4 +2028,168 @@ mod native_prompt_tests {
);
}
}

#[test]
fn tml_content_headers_thinking_budget_prepares_close_and_optional_text_frame_tail() {
let mut alphabet: Vec<_> = tokenizers::pre_tokenizers::byte_level::ByteLevel::alphabet()
.into_iter()
.collect();
alphabet.sort_unstable();
let vocabulary = alphabet
.into_iter()
.enumerate()
.map(|(id, c)| (c.to_string(), id as u32))
.collect::<tokenizers::models::bpe::Vocab>();
let model = tokenizers::models::bpe::BPE::builder()
.vocab_and_merges(vocabulary, vec![])
.build()
.unwrap();
let mut tokenizer = Tokenizer::new(model);
tokenizer.with_pre_tokenizer(Some(
tokenizers::pre_tokenizers::byte_level::ByteLevel::new(false, true, false),
));
tokenizer.with_decoder(Some(tokenizers::decoders::byte_level::ByteLevel::default()));
tokenizer
.add_special_tokens(
crate::output::tml::CONTROL_MARKERS
.iter()
.map(|&s| AddedToken::from(s, true)),
)
.unwrap();
let eos = tokenizer
.token_to_id("<|content_model_end_sampling|>")
.unwrap();
let end_message = tokenizer.token_to_id("<|end_message|>").unwrap();
let model_tok = tokenizer.token_to_id("<|message_model|>").unwrap();
let text_tok = tokenizer.token_to_id("<|content_text|>").unwrap();
let bytes = tokenizer.to_string(false).unwrap();
let path = std::env::temp_dir().join(format!(
"flare-tml-budget-{}-{:?}.json",
std::process::id(),
std::thread::current().id()
));
std::fs::write(&path, &bytes).unwrap();
let settings: FrontendSettings = serde_json::from_value(json!({
"tokenizer": {},
"eos_token_ids": [eos],
"prompt_encoder": i32::from(PromptEncoder::TmlV0),
}))
.unwrap();
let frontend = Frontend::load_with_settings(
FrontendAssets {
tokenizer: Asset {
path: path.clone(),
sha256: format!("{:x}", Sha256::digest(bytes.as_bytes())),
range: None,
},
tokens: TokenizerSettings::default(),
chat_template: None,
},
Default::default(),
&settings,
)
.unwrap();
std::fs::remove_file(path).unwrap();
let mut config =
crate::frontend::test_support::model_config(crate::model::testing::metadata());
config.contract.vocabulary = frontend.tokenizer().get_vocab_size(true);
config.contract.input_vocabulary = config.contract.vocabulary;
let contracts_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/support/contracts/inkling2_frontend.json");
let contracts: Value =
serde_json::from_slice(&std::fs::read(contracts_path).unwrap()).unwrap();
config.contract.frontend = serde_json::from_value(contracts["text"].clone()).unwrap();
config.eos_token_ids = vec![eos];
let compiler = GrammarCompiler::new(
frontend.tokenizer(),
config.contract.vocabulary,
&config.eos_token_ids,
&crate::model::reasoning_delimiter_tokens(&frontend, &config.contract.frontend)
.unwrap(),
)
.unwrap();
let prepare = |protocol: Protocol, body: Value| {
let decoded = decode(protocol, body, false).unwrap();
crate::server::request::prepare_inference(
&frontend,
None,
&compiler,
&config,
&decoded.request,
0,
false,
)
.unwrap()
};

// Omitting thinking_token_budget (including effort=none / enable_thinking=false) leaves output uncapped.
for body in [
json!({"max_tokens": 32, "messages": [{"role": "user", "content": "Hi"}]}),
json!({"max_tokens": 32, "reasoning_effort": "none", "messages": [{"role": "user", "content": "Hi"}]}),
json!({"max_tokens": 32, "chat_template_kwargs": {"enable_thinking": false}, "messages": [{"role": "user", "content": "Hi"}]}),
] {
let prepared = prepare(Protocol::Chat, body);
assert!(prepared.prompt.reasoning_cut.is_none());
assert_eq!(prepared.prompt.max_new_tokens, 32);
}

// Plain Chat request with after >= 4 attaches close=[<|end_message|>, <|message_model|>, <|content_text|>].
let prepared = prepare(
Protocol::Chat,
json!({"max_tokens": 32, "thinking_token_budget": 16, "messages": [{"role": "user", "content": "Hi"}]}),
);
let cut = prepared.prompt.reasoning_cut.as_ref().unwrap();
assert_eq!(prepared.prompt.max_new_tokens, 16);
assert_eq!(cut.close, vec![end_message, model_tok, text_tok]);
assert_eq!(cut.after, 16);

// Tight remaining capacity (after <= 3) emits only <|end_message|> so a partial frame header is never injected.
for budget in [29u32, 30, 31] {
let prepared = prepare(
Protocol::Chat,
json!({"max_tokens": 32, "thinking_token_budget": budget, "messages": [{"role": "user", "content": "Hi"}]}),
);
let cut = prepared.prompt.reasoning_cut.as_ref().unwrap();
assert_eq!(cut.close, vec![end_message], "budget={budget}");
assert_eq!(cut.after, 32 - budget);
}

// Active tools emit only <|end_message|> so tool frames stay valid; tool_choice=none restores the text frame opener.
let tools = json!([{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}]);
let with_tools = prepare(
Protocol::Chat,
json!({"max_tokens": 32, "thinking_token_budget": 16, "tools": tools, "messages": [{"role": "user", "content": "Hi"}]}),
);
let cut = with_tools.prompt.reasoning_cut.as_ref().unwrap();
assert_eq!(cut.close, vec![end_message]);

let tools_disabled = prepare(
Protocol::Chat,
json!({"max_tokens": 32, "thinking_token_budget": 16, "tools": tools, "tool_choice": "none", "messages": [{"role": "user", "content": "Hi"}]}),
);
assert_eq!(
tools_disabled.prompt.reasoning_cut.as_ref().unwrap().close,
vec![end_message, model_tok, text_tok]
);

// Structured output grammar emits only <|end_message|>.
let with_grammar = prepare(
Protocol::Chat,
json!({"max_tokens": 32, "thinking_token_budget": 16, "response_format": {"type": "json_object"}, "messages": [{"role": "user", "content": "Hi"}]}),
);
assert!(with_grammar.prompt.grammar.is_some());
assert_eq!(
with_grammar.prompt.reasoning_cut.as_ref().unwrap().close,
vec![end_message]
);

// Messages thinking.budget_tokens arms the same ContentHeaders cut.
let messages = prepare(
Protocol::Messages,
json!({"max_tokens": 32, "thinking": {"type": "enabled", "budget_tokens": 16}, "messages": [{"role": "user", "content": "Hi"}]}),
);
let cut = messages.prompt.reasoning_cut.as_ref().unwrap();
assert_eq!(cut.close, vec![end_message, model_tok, text_tok]);
assert_eq!(cut.after, 16);
}
}
19 changes: 15 additions & 4 deletions helios/src/server/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,9 +381,16 @@ pub(super) fn prepare_validated_inference(
(budget.tokens() < u64::from(max_new_tokens)).then(|| {
let budget = budget.tokens() as u32;
let after = max_new_tokens - budget;
let mut tokens = vec![close];
if grammar.is_none() {
let tail = output.reasoning_close_tail();
if !tail.is_empty() && tokens.len() + tail.len() < after as usize {
tokens.extend(tail);
}
}
max_new_tokens = budget;
ReasoningCut {
close,
close: tokens,
after,
output: Some(output.clone()),
}
Expand Down Expand Up @@ -534,13 +541,17 @@ pub(super) fn thinking_budget_close(
config: &ModelConfig,
start: crate::output::tagged::OutputStart,
) -> Result<Option<u32>> {
use crate::model::contract::ReasoningParserKind;
use crate::output::tagged::OutputStart;
if !matches!(start, OutputStart::Reasoning | OutputStart::Content) {
return Ok(None);
}
let Some(syntax) = &config.contract.frontend.reasoning else {
return Ok(None);
};
let supported_start = matches!(start, OutputStart::Reasoning | OutputStart::Content)
|| (matches!(start, OutputStart::RecipientFrame | OutputStart::RecipientHeader)
&& syntax.kind == ReasoningParserKind::ContentHeaders);
if !supported_start {
return Ok(None);
}
let close = frontend.encode(&syntax.close, false)?;
Ok(match close.as_slice() {
[close] => Some(*close),
Expand Down
Loading
Loading