Skip to content
Draft
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
9 changes: 9 additions & 0 deletions docs/TODO.txt
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,12 @@
MoE, GLM KDA/MLA, and other attention consumers with their checkpoints.
Qwen3.8 dense layer1 output exposed BF16 atomic replay errors beyond the
shared operator bounds. Checkpoint coverage for these other consumers remains pending.

[ ] Remove the SM120/SM121 b12x expert branch from InklingWeightLoader._nvfp4_experts.
Inkling preparation accepts only one SM103 GPU, so only the decoder tests in
tests/recipes/test_inkling_cuda.py reach that branch; restrict them to SM103
when the branch is removed.

[ ] Support Inkling-Small NVFP4 on two GPUs (two local GPUs or two DGX Sparks over
RoCE) and on SM120/SM121. Close when a full-checkpoint export on those
platforms serves tests/server/test_inkling.py through flare run.
35 changes: 35 additions & 0 deletions docs/model-preparation.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Flare loads the package files without Python. Helios is a Rust library;

Recipes default to FP8 E4M3 KV storage, including learned draft-model caches. Qwen Flash retains BF16 selector keys;
GLM and DeepSeek retain their packed latent formats, including scale metadata and any BF16 rotary fields.
Inkling retains BF16 KV pages and local histories.
Recurrent state, compressor accumulators, and hidden activations retain their
model-specific precision. Cache writers and attention readers use matching
scales where required, and memory planning includes each cache's declared page
Expand Down Expand Up @@ -1013,6 +1014,40 @@ weight budget for this encoding; loading reports its actual allocation.
flare/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.safetensors --gpus 0,1,2,3
```

## Inkling-Small NVFP4

The `inkling-small-nvfp4` alias selects
[`thinkingmachines/Inkling-Small-NVFP4`](https://huggingface.co/thinkingmachines/Inkling-Small-NVFP4)
at revision `b6a99534467840620d411e4cd4ad5819b2610d9c`. It targets one
GB300 DGX Station (SM103). Defaults are a 262144-token context, concurrency four,
and 4096-token prefill chunks. The prepared context is capped below the
checkpoint's 1048576-token limit. Image, audio, video and MTP are not prepared;
only `model.llm` weights are loaded from the indexed checkpoint.

Quantization follows `hf_quant_config.json`: excluded projections retain BF16;
routed NVFP4 experts retain their packed weights, block/global scales and
calibrated activations. Router biases/scales, logits and normalization stay FP32,
as do residual-convolution history and arithmetic.

Continuation rows preserve all 35 local 512-token BF16 KV rings, seven global
paged histories, four convolution histories per layer, partial pages, consumed
cursor and resume hidden state. Each continuation row occupies 82,837,504 bytes
and each 128-token global KV page occupies 3,670,016 bytes.

Sampling follows the publisher
[guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md):
temperature 1.0, top-p 1.0, and top-k disabled.

Ignition applies `ignition/recipes/inkling/assets/chat_template.patch.json`
to the downloaded checkpoint template. `<|content_thinking|>` messages route to
reasoning, `<|content_invoke_tool_json|>` messages become JSON tool calls, and
`<|content_model_end_sampling|>` ends generation.

```sh
.venv/bin/ignition export inkling-small-nvfp4 --gpus 0 --prompt-logprobs
flare/target/release/flare run CACHE_ENTRY --gpus 0
```

## Muse Spark Open

The `muse-spark-open-nvfp4` alias selects
Expand Down
10 changes: 10 additions & 0 deletions helios/model-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,16 @@ continuation starts inside the prepared reasoning, content, or tool body.
Structured-output grammars preserve recipient frames and constrain the user
answer while allowing the registered tool recipients.

Content-header reasoning pairs with TML JSON tool syntax. A model message begins
with `<|message_model|>`, followed by `<|content_text|>` for visible text,
`<|content_thinking|>` for reasoning, or a registered tool name followed by
`<|content_invoke_tool_json|>`. Tool bodies contain exactly `name` and object-valued
`args` fields; the name must match the header. `<|end_message|>` closes a frame
without ending generation, and `<|content_model_end_sampling|>` ends the turn.
Consecutive frames can carry parallel tool calls. Delimiters affect parsing only
when generated as their control tokens; ordinary text spellings remain content.
Structured-output grammars constrain the answer document within these frames.

`OutputPipeline` selects reusable parsers. The shared presentation layer emits
JSON or SSE while preserving streamed tool IDs and argument fragments. The same
reasoning/tool envelope constrains structured output through llguidance; literal
Expand Down
2 changes: 2 additions & 0 deletions helios/proto/runtime_package.proto
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ enum ToolParserKind {
MINIMAX_XML = 5;
GEMMA_CALL = 6;
ATEM = 7;
TML_JSON = 8;
}
enum ReasoningParserKind {
REASONING_PARSER_UNSPECIFIED = 0;
Expand All @@ -349,6 +350,7 @@ enum ReasoningParserKind {
MM_THINK = 3;
CHANNEL_THOUGHT = 4;
RECIPIENT_HEADERS = 5;
CONTENT_HEADERS = 6;
}
enum ImagePreparationKind {
IMAGE_PREPARATION_UNSPECIFIED = 0;
Expand Down
14 changes: 14 additions & 0 deletions helios/src/frontend/jinja/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ fn expressions_and_python_methods_match_minijinja() {
"1 if true else 2",
"1 if false else 2 if true else 3",
"s|trim",
"0.9|float",
"3|float",
"true|float",
"s.strip()",
"s.lstrip()",
"s.rstrip()",
Expand Down Expand Up @@ -129,6 +132,17 @@ fn float_text_conversions_use_python_spelling() {
);
}

#[test]
fn float_filter_matches_jinja_conversion_and_failure_defaults() {
// Python Jinja's do_float accepts whitespace and returns the supplied
// default on conversion failure; MiniJinja instead errors on these inputs.
let template = CompiledTemplate::compile(
"{{ ' 0.7 '|float }}|{{ 'invalid'|float }}|{{ none|float(default=0.99) }}|{{ []|float(7) }}"
).unwrap();
assert_eq!(template.render(json!({}).as_object().unwrap(), &[]).unwrap().text,
"0.7|0.0|0.99|7");
}

#[test]
fn scopes_macros_captures_and_control_flow_match_minijinja() {
for source in [
Expand Down
11 changes: 11 additions & 0 deletions helios/src/frontend/jinja/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,17 @@ fn filter<'a>(
},
),
"length" | "count" => Ok(Value::Int(v.len() as i64)),
"float" => {
let number = v.number().or_else(|| match &v {
Value::Bool(value) => Some(if *value { 1.0 } else { 0.0 }),
_ => v.as_str().and_then(|s| s.trim().parse::<f64>().ok()),
});
Ok(number.map(Value::Float).unwrap_or_else(|| {
kw.iter().find(|(name, _)| *name == "default")
.map(|(_, value)| value.clone())
.or_else(|| args.first().cloned()).unwrap_or(Value::Float(0.0))
}))
}
"string" => Ok(if v.as_str().is_some() {
v
} else {
Expand Down
45 changes: 43 additions & 2 deletions helios/src/grammar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const MAX_SCHEMA_DEPTH: usize = 64;

/// Assistant recipient framing and the registered tool recipient names.
pub struct RecipientEnvelope {
pub syntax: crate::model::contract::ToolParserKind,
pub start: crate::output::tagged::OutputStart,
pub tools: Vec<String>,
}
Expand Down Expand Up @@ -233,7 +234,11 @@ impl GrammarCompiler {
return self.compile(grammar);
};
if let Some(recipient) = &envelope.recipient {
return self.compile_recipient(grammar, recipient);
return if recipient.syntax == crate::model::contract::ToolParserKind::TmlJson {
self.compile_content_headers(grammar, recipient)
} else {
self.compile_recipient(grammar, recipient)
};
}
if envelope.reasoning_end.is_none()
&& envelope.tool.is_none()
Expand Down Expand Up @@ -354,6 +359,42 @@ impl GrammarCompiler {
self.compile(grammar)
}

fn compile_content_headers(&self, mut grammar: TopLevelGrammar, envelope: &RecipientEnvelope) -> Result<RequestGrammar> {
use crate::output::tagged::OutputStart;
let restart = self.marker("<|message_model|>");
let end = self.marker("<|end_message|>");
let mut rules = self.region("thinking_body", "<|end_message|>");
rules.push_str(&format!("thinking: {} thinking_body {restart}\nanswer: {} @answer {end}\n",
self.marker("<|content_thinking|>"), self.marker("<|content_text|>")));
grammar.grammars[0].name = Some("answer".into());
let mut tools = vec![];
for (index, name) in envelope.tools.iter().enumerate() {
let mut payload = TopLevelGrammar::from_json_schema(serde_json::json!({
"type":"object", "properties":{"name":{"const":name},"args":{"type":"object"}},
"required":["name","args"], "additionalProperties":false,
})).grammars.remove(0);
payload.name = Some(format!("payload_{index}"));
grammar.grammars.push(payload);
rules.push_str(&format!("tool_{index}: {} {} @payload_{index} {end}\n",
self.marker(name), self.marker("<|content_invoke_tool_json|>")));
tools.push(format!("tool_{index}"));
}
let ending = if tools.is_empty() { "answer" } else {
rules.push_str(&format!("tool: {}\ntools: tool ({restart} thinking* tool)* ({restart} thinking* answer)?\n", tools.join(" | ")));
"(answer | tools)"
};
rules.push_str(&format!("tail: thinking* {ending}\n"));
match envelope.start {
OutputStart::RecipientHeader => rules.push_str("start: tail\n"),
OutputStart::RecipientFrame => rules.push_str(&format!("start: {restart} tail\n")),
OutputStart::Reasoning => rules.push_str(&format!("start: thinking_body {restart} tail\n")),
OutputStart::Content => rules.push_str(&format!("start: @answer {end}\n")),
OutputStart::ToolBody => return Err("structured output cannot continue a TML tool body".into()),
}
grammar.grammars.insert(0, GrammarWithLexer::from_lark(rules));
self.compile(grammar)
}

fn marker(&self, text: &str) -> String {
if text.is_empty() {
String::new()
Expand Down Expand Up @@ -1751,7 +1792,7 @@ mod recipient_tests {
let controls=["<|start|>","<|message|>","<|eom|>","<|eot|>"].map(|s|(tokenizer.token_to_id(s).unwrap(),s.to_owned()));
let compiler=GrammarCompiler::new(&tokenizer,tokenizer.get_vocab_size(true),&[200001,200008],&controls).unwrap();
let envelope=|start,tools:Vec<String>| OutputEnvelope {
recipient:Some(RecipientEnvelope{start,tools}),reasoning_end:None,tool:None,function:None,
recipient:Some(RecipientEnvelope{syntax:crate::model::contract::ToolParserKind::Atem,start,tools}),reasoning_end:None,tool:None,function:None,
tool_ends_reasoning:false,tool_body_start:false,response:None,
};
let answer=r#"{"ok":true}"#;
Expand Down
35 changes: 30 additions & 5 deletions helios/src/model/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ contract_enum!(ValueSource {
});
contract_enum!(InputIndexing { Scalar = 1, SubmissionRow = 2, RequestRow = 3, PackedToken = 4, ActiveRow = 5 });
contract_enum!(StateAccessKind { Read = 1, Write = 2, ReadWrite = 3 });
contract_enum!(ToolParserKind { QwenCoder = 1, GlmArgumentTags = 2, Dsml = 3, Xtml = 4, MiniMaxXml = 5, GemmaCall = 6, Atem = 7 });
contract_enum!(ReasoningParserKind { ThinkTags = 1, XtmlThink = 2, MmThink = 3, ChannelThought = 4, RecipientHeaders = 5 });
contract_enum!(ToolParserKind { QwenCoder = 1, GlmArgumentTags = 2, Dsml = 3, Xtml = 4, MiniMaxXml = 5, GemmaCall = 6, Atem = 7, TmlJson = 8 });
contract_enum!(ReasoningParserKind { ThinkTags = 1, XtmlThink = 2, MmThink = 3, ChannelThought = 4, RecipientHeaders = 5, ContentHeaders = 6 });
contract_enum!(ImagePreparationKind { Qwen = 1, Mimo = 2, Deepseek = 3, Moonvit = 4, Step = 5, Radio = 6, DeepseekRowMajor = 7, Glm = 8, PatchMerge = 9 });
contract_enum!(ImageLayoutKind { Qwen = 1, Mimo = 2, Deepseek = 3, Moonvit = 4, Step = 5, Radio = 6, DeepseekRowMajor = 7, Glm = 8, Bracketed = 9 });
contract_enum!(GraphOperation { Init = 1, Restore = 2, Snapshot = 3, Prefill = 4, Decode = 5, Resume = 6, Vision = 7, Speculative = 8, Mixed = 9, ScoredPrefill = 12 });
Expand Down Expand Up @@ -634,13 +634,19 @@ impl FrontendContract {
{
return Err("ATEM recipient framing requires recipient-header reasoning syntax".into());
}
if self.tools.as_ref().is_some_and(|t| t.kind == ToolParserKind::TmlJson)
!= self.reasoning.as_ref().is_some_and(|r| r.kind == ReasoningParserKind::ContentHeaders)
{
return Err("TML JSON framing requires content-header reasoning syntax".into());
}
if let Some(reasoning) = &self.reasoning {
let (open, close) = match reasoning.kind {
ReasoningParserKind::ThinkTags => ("<think>", "</think>"),
ReasoningParserKind::XtmlThink => ("<|open|>think<|sep|>", "<|close|>think<|sep|>"),
ReasoningParserKind::MmThink => ("<mm:think>", "</mm:think>"),
ReasoningParserKind::ChannelThought => ("<|channel>thought", "<channel|>"),
ReasoningParserKind::RecipientHeaders => ("<|start|>assistant to=self<|message|>", "<|eom|>"),
ReasoningParserKind::ContentHeaders => ("<|content_thinking|>", "<|end_message|>"),
};
let tool_open = self.tools.as_ref().and_then(|tool| match tool.kind {
ToolParserKind::QwenCoder | ToolParserKind::GlmArgumentTags => Some("<tool_call>"),
Expand All @@ -656,7 +662,7 @@ impl FrontendContract {
.tools
.as_ref()
.is_none_or(|tool| tool.kind != ToolParserKind::Xtml)))
|| (reasoning.kind == ReasoningParserKind::RecipientHeaders
|| (matches!(reasoning.kind, ReasoningParserKind::RecipientHeaders | ReasoningParserKind::ContentHeaders)
&& (reasoning.wrapping_newlines != 0 || !reasoning.terminal_markers.is_empty()))
|| reasoning.wrapping_newlines > 1
|| reasoning
Expand Down Expand Up @@ -761,8 +767,8 @@ mod tests {
fn recipient_syntax_requires_matching_typed_parsers_and_known_identifiers() {
assert_eq!(ToolParserKind::try_from(7).unwrap(), ToolParserKind::Atem);
assert_eq!(ReasoningParserKind::try_from(5).unwrap(), ReasoningParserKind::RecipientHeaders);
for value in [0, 8, 999] { assert!(ToolParserKind::try_from(value).is_err()); }
for value in [0, 6, 999] { assert!(ReasoningParserKind::try_from(value).is_err()); }
for value in [0, 9, 999] { assert!(ToolParserKind::try_from(value).is_err()); }
for value in [0, 7, 999] { assert!(ReasoningParserKind::try_from(value).is_err()); }
let mut syntax = crate::model::testing::metadata().frontend;
syntax.tools = Some(ToolParser {kind: ToolParserKind::Atem, wrapping_newlines: 0, tag_separator: String::new()});
assert!(syntax.validate().is_err());
Expand All @@ -777,6 +783,25 @@ mod tests {
assert!(syntax.validate().is_ok());
}

#[test]
fn content_header_syntax_requires_matching_json_tools_and_delimiters() {
assert_eq!(ToolParserKind::try_from(8).unwrap(), ToolParserKind::TmlJson);
assert_eq!(ReasoningParserKind::try_from(6).unwrap(), ReasoningParserKind::ContentHeaders);
let mut syntax = crate::model::testing::metadata().frontend;
syntax.tools = Some(ToolParser { kind: ToolParserKind::TmlJson,
wrapping_newlines: 0, tag_separator: String::new() });
assert!(syntax.validate().is_err());
syntax.reasoning = Some(ReasoningParser { kind: ReasoningParserKind::ContentHeaders,
open: "<|content_thinking|>".into(), close: "<|end_message|>".into(),
wrapping_newlines: 0, terminal_markers: vec![] });
assert!(syntax.validate().is_ok());
syntax.reasoning.as_mut().unwrap().close = "</think>".into();
assert!(syntax.validate().is_err());
syntax.reasoning.as_mut().unwrap().close = "<|end_message|>".into();
syntax.tools = None;
assert!(syntax.validate().is_err());
}

#[test]
fn startup_tuning_bindings_match_transport_and_exclude_request_state() {
use crate::execution::{BufferDescriptor, Dtype, TuningGraphDescriptor};
Expand Down
42 changes: 22 additions & 20 deletions helios/src/model/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,26 +276,23 @@ pub fn prepare_output(
if !tools.is_empty() && syntax.tools.is_none() {
return Err("tool parsing is not prepared".into());
}
let mut control_tokens = if syntax
.tools
.as_ref()
.is_some_and(|tool| matches!(tool.kind, super::contract::ToolParserKind::Xtml | super::contract::ToolParserKind::Atem))
{
let markers = if syntax.tools.as_ref().unwrap().kind == super::contract::ToolParserKind::Atem {
vec!["<|start|>", "<|message|>", "<|eom|>", "<|eot|>"]
} else { vec!["<|open|>", "<|close|>", "<|sep|>"] };
markers.into_iter()
.map(|marker| {
let ids = frontend.encode(marker, false)?;
if ids.len() != 1 {
return Err("output envelope delimiters must each occupy one tokenizer token".into());
}
Ok((ids[0], marker.to_owned()))
})
.collect::<Result<Vec<_>>>()?
} else {
vec![]
let markers: &[&str] = match syntax.tools.as_ref().map(|tool| tool.kind) {
Some(super::contract::ToolParserKind::Xtml) => &["<|open|>", "<|close|>", "<|sep|>"],
Some(super::contract::ToolParserKind::Atem) => &["<|start|>", "<|message|>", "<|eom|>", "<|eot|>"],
Some(super::contract::ToolParserKind::TmlJson) => &["<|message_model|>", "<|content_text|>", "<|content_thinking|>",
"<|content_invoke_tool_json|>", "<|end_message|>", "<|content_model_end_sampling|>"],
_ => &[],
};
let mut control_tokens = markers
.iter()
.map(|&marker| {
let ids = frontend.encode(marker, false)?;
if ids.len() != 1 {
return Err("output envelope delimiters must each occupy one tokenizer token".into());
}
Ok((ids[0], marker.to_owned()))
})
.collect::<Result<Vec<_>>>()?;
if syntax.tools.as_ref().is_some_and(|tool| tool.kind == super::contract::ToolParserKind::Dsml) {
let tokenizer = frontend.tokenizer();
for token in [deepseek_recipe_core::special_tokens::SpecialToken::ThinkingEnd,
Expand All @@ -313,8 +310,13 @@ pub fn prepare_output(
if recipient {
reasoning = prefix.is_some_and(|p| p.starts_with(" to=self<|message|>"));
}
let start = if recipient && !open_assistant {
let content_headers = syntax.tools.as_ref().is_some_and(|t| t.kind == super::contract::ToolParserKind::TmlJson);
let start = if (recipient || content_headers) && !open_assistant {
crate::output::tagged::OutputStart::RecipientFrame
} else if content_headers && prefix.is_some_and(|p| !["<|content_text|>", "<|content_thinking|>", "<|content_invoke_tool_json|>"].iter().any(|m| p.contains(m))) {
crate::output::tagged::OutputStart::RecipientHeader
} else if content_headers && prefix.is_some_and(|p| p.contains("<|content_invoke_tool_json|>")) {
crate::output::tagged::OutputStart::ToolBody
} else if recipient && prefix.is_some_and(|p| !p.contains("<|message|>")) {
crate::output::tagged::OutputStart::RecipientHeader
} else if recipient && prefix.is_some_and(|p| {
Expand Down
2 changes: 2 additions & 0 deletions helios/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub mod chatml;
mod pipeline;
#[cfg(feature = "server")]
mod recipient;
#[cfg(feature = "server")]
mod tml;
pub mod tagged;
#[cfg(feature = "server")]
mod xtml;
Expand Down
Loading
Loading