diff --git a/docs/TODO.txt b/docs/TODO.txt index 591053d75..d041df340 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -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. diff --git a/docs/model-preparation.md b/docs/model-preparation.md index e948c9a2d..cb7c930d0 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -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 @@ -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 diff --git a/helios/model-contract.md b/helios/model-contract.md index 7e8be881b..3c1d7e10a 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -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 diff --git a/helios/proto/runtime_package.proto b/helios/proto/runtime_package.proto index 1830bb146..48b6d3098 100644 --- a/helios/proto/runtime_package.proto +++ b/helios/proto/runtime_package.proto @@ -341,6 +341,7 @@ enum ToolParserKind { MINIMAX_XML = 5; GEMMA_CALL = 6; ATEM = 7; + TML_JSON = 8; } enum ReasoningParserKind { REASONING_PARSER_UNSPECIFIED = 0; @@ -349,6 +350,7 @@ enum ReasoningParserKind { MM_THINK = 3; CHANNEL_THOUGHT = 4; RECIPIENT_HEADERS = 5; + CONTENT_HEADERS = 6; } enum ImagePreparationKind { IMAGE_PREPARATION_UNSPECIFIED = 0; diff --git a/helios/src/frontend/jinja/tests.rs b/helios/src/frontend/jinja/tests.rs index c851daa19..9e2d137a6 100644 --- a/helios/src/frontend/jinja/tests.rs +++ b/helios/src/frontend/jinja/tests.rs @@ -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()", @@ -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 [ diff --git a/helios/src/frontend/jinja/vm.rs b/helios/src/frontend/jinja/vm.rs index d7cd440d6..cdde906ff 100644 --- a/helios/src/frontend/jinja/vm.rs +++ b/helios/src/frontend/jinja/vm.rs @@ -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::().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 { diff --git a/helios/src/grammar.rs b/helios/src/grammar.rs index a3805598f..422b8f5d3 100644 --- a/helios/src/grammar.rs +++ b/helios/src/grammar.rs @@ -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, } @@ -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() @@ -354,6 +359,42 @@ impl GrammarCompiler { self.compile(grammar) } + fn compile_content_headers(&self, mut grammar: TopLevelGrammar, envelope: &RecipientEnvelope) -> Result { + 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() @@ -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| 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}"#; diff --git a/helios/src/model/contract.rs b/helios/src/model/contract.rs index a88aa2734..157ddd86b 100644 --- a/helios/src/model/contract.rs +++ b/helios/src/model/contract.rs @@ -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 }); @@ -634,6 +634,11 @@ 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 => ("", ""), @@ -641,6 +646,7 @@ impl FrontendContract { ReasoningParserKind::MmThink => ("", ""), ReasoningParserKind::ChannelThought => ("<|channel>thought", ""), 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(""), @@ -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 @@ -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()); @@ -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 = "".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}; diff --git a/helios/src/model/prompt.rs b/helios/src/model/prompt.rs index 468ea22df..6e552d57e 100644 --- a/helios/src/model/prompt.rs +++ b/helios/src/model/prompt.rs @@ -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::>>()? - } 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::>>()?; 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, @@ -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| { diff --git a/helios/src/output.rs b/helios/src/output.rs index 7be268d06..ac99e6f18 100644 --- a/helios/src/output.rs +++ b/helios/src/output.rs @@ -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; diff --git a/helios/src/output/pipeline.rs b/helios/src/output/pipeline.rs index 18198cc55..2846e13ed 100644 --- a/helios/src/output/pipeline.rs +++ b/helios/src/output/pipeline.rs @@ -31,6 +31,7 @@ pub enum OutputPipeline { SpacedDsml(super::dsml::DsmlOutput), Xtml(super::xtml::XtmlOutput), Recipient(super::recipient::RecipientOutput), + Tml(super::tml::TmlOutput), MiniMaxXml(TaggedOutput), GemmaCall(TaggedOutput), Text(TaggedOutput), @@ -57,6 +58,7 @@ macro_rules! dispatch { OutputPipeline::SpacedDsml($parser) => $body, OutputPipeline::Xtml($parser) => $body, OutputPipeline::Recipient($parser) => $body, + OutputPipeline::Tml($parser) => $body, OutputPipeline::MiniMaxXml($parser) => $body, OutputPipeline::GemmaCall($parser) => $body, OutputPipeline::Text($parser) => $body, @@ -73,6 +75,7 @@ impl OutputPipeline { .as_ref() .map(|t| (t.kind, t.wrapping_newlines, t.tag_separator.as_str())) { + Some((ToolParserKind::TmlJson, _, _)) => Self::Tml(super::tml::TmlOutput::new(config.content, config.control_tokens)), Some((ToolParserKind::Atem, _, _)) => Self::Recipient(super::recipient::RecipientOutput::new(config.content, config.control_tokens)), Some((ToolParserKind::QwenCoder, 0, _)) => Self::CompactFunctionTags( TaggedOutput::new(config.content).with_reasoning(reasoning, &config.control_tokens), @@ -106,10 +109,10 @@ impl OutputPipeline { } /// Whether the parser `new` selects gates reasoning delimiters by token identity. - /// XTML and recipient-header framing carry their own control tokens. + /// XTML, recipient-header, and content-header framing carry their own control tokens. pub fn gates_reasoning_tokens(syntax: &FrontendContract) -> bool { match syntax.tools.as_ref().map(|t| t.kind) { - Some(ToolParserKind::Xtml | ToolParserKind::Atem) => false, + Some(ToolParserKind::Xtml | ToolParserKind::Atem | ToolParserKind::TmlJson) => false, Some( ToolParserKind::Dsml | ToolParserKind::QwenCoder @@ -128,8 +131,9 @@ impl OutputPipeline { .as_ref() .map(|t| (t.kind, t.wrapping_newlines, t.tag_separator.as_str())) { - Some((ToolParserKind::Atem, _, _)) => Some(crate::grammar::OutputEnvelope { + Some((kind @ (ToolParserKind::Atem | ToolParserKind::TmlJson), _, _)) => Some(crate::grammar::OutputEnvelope { recipient: Some(crate::grammar::RecipientEnvelope { + syntax: kind, start: config.content.start, tools: config.content.tools.iter().filter_map(|t| t["function"]["name"].as_str().map(str::to_owned)).collect(), }), reasoning_end: None, tool: None, function: None, diff --git a/helios/src/output/tml.rs b/helios/src/output/tml.rs new file mode 100644 index 000000000..ac454724a --- /dev/null +++ b/helios/src/output/tml.rs @@ -0,0 +1,476 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Token-delimited content headers with named JSON tool invocations. + +use super::{ + Event, Input, Termination, + tagged::{OutputConfig, OutputStart}, +}; +use crate::Result; +use serde_json::Value; +use std::collections::VecDeque; + +const START: &str = "<|message_model|>"; +const TEXT: &str = "<|content_text|>"; +const THINK: &str = "<|content_thinking|>"; +const TOOL: &str = "<|content_invoke_tool_json|>"; +const END: &str = "<|end_message|>"; +const TURN_END: &str = "<|content_model_end_sampling|>"; + +#[derive(Clone, Copy, PartialEq)] +enum State { + Frame, + Header, + Content, + Reasoning, + Tool, + Closed, +} + +pub struct TmlOutput { + state: State, + buffer: String, + recipient: Option<String>, + tools: Vec<Value>, + calls: usize, + received: usize, + spans: Vec<Option<std::ops::Range<usize>>>, + control_tokens: Vec<(u32, String)>, + pending_controls: VecDeque<String>, + pending_text: String, +} + +fn escape(text: &str) -> String { + text.replace('&', "&amp;").replace('<', "&lt;") +} +fn unescape(text: &str) -> String { + text.replace("&lt;", "<").replace("&amp;", "&") +} +fn partial(text: &str, marker: &str) -> usize { + (1..marker.len()) + .rev() + .find(|&n| text.ends_with(&marker[..n])) + .unwrap_or(0) +} + +impl TmlOutput { + pub fn new(config: OutputConfig, control_tokens: Vec<(u32, String)>) -> Self { + Self { + state: match config.start { + OutputStart::RecipientHeader => State::Header, + OutputStart::RecipientFrame => State::Frame, + OutputStart::Content => State::Content, + OutputStart::Reasoning => State::Reasoning, + OutputStart::ToolBody => State::Tool, + }, + buffer: String::new(), + recipient: None, + tools: config.tools, + calls: 0, + received: 0, + spans: vec![], + control_tokens, + pending_controls: VecDeque::new(), + pending_text: String::new(), + } + } + + pub fn reasoning_open(&self) -> bool { + self.state == State::Reasoning + } + pub fn content_spans(&self) -> Vec<Option<std::ops::Range<usize>>> { + self.spans.clone() + } + pub fn consumed_bytes(&self) -> usize { + self.received + .saturating_sub(unescape(&self.buffer).len() + self.pending_text.len()) + } + + pub fn push(&mut self, input: Input<'_>) -> Result<Vec<Event>> { + self.spans.clear(); + let text = match input { + Input::Token(id) => { + if let Some((_, marker)) = + self.control_tokens.iter().find(|(token, _)| *token == id) + { + self.pending_controls.push_back(marker.clone()); + } + return Ok(vec![]); + } + Input::Text(text) => text, + }; + self.received += text.len(); + self.pending_text.push_str(text); + while let Some(marker) = self.pending_controls.front() { + if let Some(at) = self.pending_text.find(marker) { + self.buffer.push_str(&escape(&self.pending_text[..at])); + self.buffer.push_str(marker); + self.pending_text.drain(..at + marker.len()); + self.pending_controls.pop_front(); + } else { + let n = self.pending_text.len() - partial(&self.pending_text, marker); + self.buffer.push_str(&escape(&self.pending_text[..n])); + self.pending_text.drain(..n); + break; + } + } + if self.pending_controls.is_empty() { + self.buffer + .push_str(&escape(&std::mem::take(&mut self.pending_text))); + } + self.drain(false) + } + + fn drain(&mut self, finishing: bool) -> Result<Vec<Event>> { + let mut events = vec![]; + loop { + match self.state { + State::Frame => { + if self.buffer.starts_with(TURN_END) { + self.buffer.drain(..TURN_END.len()); + self.state = State::Closed; + } else if self.buffer.starts_with(START) { + self.buffer.drain(..START.len()); + self.state = State::Header; + } else if self.buffer.is_empty() + || (!finishing + && [START, TURN_END] + .iter() + .any(|m| m.starts_with(&self.buffer))) + { + break; + } else { + return Err("TML output requires a model message header".into()); + } + } + State::Header => { + let boundary = [TEXT, THINK, TOOL] + .into_iter() + .filter_map(|m| self.buffer.find(m).map(|at| (at, m))) + .min_by_key(|(at, _)| *at); + let Some((at, marker)) = boundary else { break }; + let recipient = unescape(&self.buffer[..at]); + self.recipient = None; + self.state = if marker == TOOL { + if recipient.is_empty() + || !self + .tools + .iter() + .any(|tool| tool["function"]["name"] == recipient) + { + return Err("TML header names an unavailable tool".into()); + } + self.recipient = Some(recipient); + State::Tool + } else { + if !recipient.is_empty() { + return Err("TML text and thinking headers cannot name a tool".into()); + } + if marker == THINK { + State::Reasoning + } else { + State::Content + } + }; + self.buffer.drain(..at + marker.len()); + } + State::Content | State::Reasoning | State::Tool => { + let boundary = [END, TURN_END] + .into_iter() + .filter_map(|m| self.buffer.find(m).map(|at| (at, m))) + .min_by_key(|(at, _)| *at); + if self.state == State::Tool { + if self.buffer.len() > 1 << 20 { + return Err("TML tool call exceeds the 1 MiB parser bound".into()); + } + let Some((at, marker)) = boundary else { break }; + events.extend(self.call(&unescape(&self.buffer[..at]))?); + self.buffer.drain(..at + marker.len()); + self.state = if marker == END { + State::Frame + } else { + State::Closed + }; + continue; + } + let visible = boundary.map(|(at, _)| at).unwrap_or_else(|| { + self.buffer.len() + - if finishing { + 0 + } else { + [END, TURN_END] + .iter() + .map(|m| partial(&self.buffer, m)) + .max() + .unwrap_or(0) + } + }); + if visible > 0 { + let start = self.consumed_bytes(); + let text = unescape(&self.buffer[..visible]); + self.buffer.drain(..visible); + if self.state == State::Reasoning { + events.push(Event::Reasoning(text)); + } else { + self.spans.push(Some(start..start + text.len())); + events.push(Event::Content(text)); + } + } + if let Some((_, marker)) = boundary { + self.buffer.drain(..marker.len()); + self.state = if marker == END { + State::Frame + } else { + State::Closed + }; + } else { + break; + } + } + State::Closed => { + if !self.buffer.is_empty() { + return Err("content after TML end of turn".into()); + } + break; + } + } + } + Ok(events) + } + + fn call(&mut self, body: &str) -> Result<Vec<Event>> { + let value: Value = serde_json::from_str(body) + .map_err(|error| format!("invalid TML tool JSON: {error}"))?; + let object = value + .as_object() + .ok_or("TML tool call must be a JSON object")?; + let name = object + .get("name") + .and_then(Value::as_str) + .ok_or("TML tool call requires a name")?; + let args = object + .get("args") + .filter(|v| v.is_object()) + .ok_or("TML tool args must be an object")?; + if object.len() != 2 + || !self + .tools + .iter() + .any(|tool| tool["function"]["name"] == name) + || self + .recipient + .as_ref() + .is_some_and(|recipient| recipient != name) + { + return Err("TML tool call does not match its registered header".into()); + } + let index = self.calls; + self.calls += 1; + Ok(vec![ + Event::ToolBegin { + index, + name: name.to_owned(), + id: None, + }, + Event::ToolArguments { + index, + text: args.to_string(), + }, + Event::ToolEnd { index }, + ]) + } + + pub fn finish(&mut self, cause: Termination) -> Result<Vec<Event>> { + self.spans.clear(); + if matches!(cause, Termination::Cancelled | Termination::ExecutionError) + || (cause != Termination::Eos + && matches!(self.state, State::Frame | State::Header | State::Tool)) + { + self.buffer.clear(); + self.pending_text.clear(); + self.pending_controls.clear(); + return Ok(vec![]); + } + self.buffer + .push_str(&escape(&std::mem::take(&mut self.pending_text))); + self.pending_controls.clear(); + let mut events = self.drain(true)?; + if self.state == State::Tool && cause == Termination::Eos { + events.extend(self.call(&unescape(&self.buffer))?); + self.buffer.clear(); + } else if self.state == State::Header && cause == Termination::Eos { + return Err("unterminated TML content header".into()); + } + Ok(events) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn parser(start: OutputStart) -> TmlOutput { + TmlOutput::new( + OutputConfig { + structured: false, + start, + tools: vec![json!({"type":"function","function":{"name":"lookup"}})], + }, + [START, TEXT, THINK, TOOL, END, TURN_END] + .iter() + .enumerate() + .map(|(i, s)| (i as u32 + 1, (*s).to_owned())) + .collect(), + ) + } + + fn feed(p: &mut TmlOutput, marker: &str, fragmented: bool) -> Result<Vec<Event>> { + let id = p + .control_tokens + .iter() + .find(|(_, m)| m == marker) + .unwrap() + .0; + let mut events = p.push(Input::Token(id))?; + if fragmented { + for c in marker.chars() { + events.extend(p.push(Input::Text(&c.to_string()))?); + } + } else { + events.extend(p.push(Input::Text(marker))?); + } + Ok(events) + } + + #[test] + fn content_headers_stream_reasoning_content_and_parallel_tools() { + for fragmented in [false, true] { + let mut p = parser(OutputStart::RecipientHeader); + assert!(feed(&mut p, THINK, fragmented).unwrap().is_empty()); + assert!(p.reasoning_open()); + assert_eq!( + p.push(Input::Text("Plan 世界")).unwrap(), + vec![Event::Reasoning("Plan 世界".into())] + ); + feed(&mut p, END, fragmented).unwrap(); + for index in 0..2 { + feed(&mut p, START, fragmented).unwrap(); + p.push(Input::Text("lookup")).unwrap(); + feed(&mut p, TOOL, fragmented).unwrap(); + p.push(Input::Text( + r#"{"name":"lookup","args":{"q":"世界 <|end_message|>","n":3}}"#, + )) + .unwrap(); + assert_eq!( + feed(&mut p, END, fragmented).unwrap(), + vec![ + Event::ToolBegin { + index, + name: "lookup".into(), + id: None + }, + Event::ToolArguments { + index, + text: r#"{"q":"世界 <|end_message|>","n":3}"#.into() + }, + Event::ToolEnd { index }, + ] + ); + } + feed(&mut p, START, fragmented).unwrap(); + feed(&mut p, TEXT, fragmented).unwrap(); + let before = p.received; + assert_eq!( + p.push(Input::Text("Answer & café")).unwrap(), + vec![Event::Content("Answer & café".into())] + ); + assert_eq!( + p.content_spans(), + vec![Some(before..before + "Answer & café".len())] + ); + feed(&mut p, END, fragmented).unwrap(); + assert!(p.finish(Termination::Eos).unwrap().is_empty()); + } + } + + #[test] + fn ordinary_delimiter_spellings_remain_content() { + let mut p = parser(OutputStart::Content); + let text = "literal <|end_message|><|message_model|><|content_thinking|> &lt;|"; + let mut result = String::new(); + for c in text.chars() { + for event in p.push(Input::Text(&c.to_string())).unwrap() { + let Event::Content(value) = event else { + panic!("ordinary text changed framing") + }; + result.push_str(&value); + } + } + assert_eq!(result, text); + assert!(p.finish(Termination::OutputLimit).unwrap().is_empty()); + } + + #[test] + fn malformed_calls_and_headers_fail_without_leaking_tool_content() { + for body in [ + r#"{"name":"other","args":{}}"#, + r#"{"name":"lookup","args":[]}"#, + r#"{"name":"lookup","args":{},"extra":1}"#, + "incomplete", + ] { + let mut p = parser(OutputStart::ToolBody); + assert!(p.push(Input::Text(body)).unwrap().is_empty()); + assert!(p.finish(Termination::Eos).is_err()); + } + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut p = parser(OutputStart::ToolBody); + p.push(Input::Text("incomplete")).unwrap(); + assert!(p.finish(cause).unwrap().is_empty()); + let mut p = parser(OutputStart::RecipientFrame); + p.push(Input::Token(1)).unwrap(); + p.push(Input::Text("<|mess")).unwrap(); + assert!(p.finish(cause).unwrap().is_empty()); + } + let mut p = parser(OutputStart::RecipientHeader); + p.push(Input::Text("other")).unwrap(); + assert!(feed(&mut p, TOOL, false).is_err()); + let mut p = parser(OutputStart::RecipientFrame); + assert!(feed(&mut p, TEXT, false).is_err()); + } + + #[test] + fn suppressed_turn_eos_completes_json_but_rejects_an_incomplete_header() { + let mut p = parser(OutputStart::RecipientHeader); + p.push(Input::Text("lookup")).unwrap(); + feed(&mut p, TOOL, false).unwrap(); + p.push(Input::Text(r#"{"name":"lookup","args":{"ok":true}}"#)) + .unwrap(); + assert_eq!( + p.finish(Termination::Eos).unwrap(), + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: None + }, + Event::ToolArguments { + index: 0, + text: r#"{"ok":true}"#.into() + }, + Event::ToolEnd { index: 0 }, + ] + ); + let mut p = parser(OutputStart::RecipientHeader); + p.push(Input::Text("lookup")).unwrap(); + assert!(p.finish(Termination::Eos).is_err()); + } +} diff --git a/helios/src/server/output.rs b/helios/src/server/output.rs index 7f351d1bc..d513e1454 100644 --- a/helios/src/server/output.rs +++ b/helios/src/server/output.rs @@ -561,6 +561,41 @@ pub(crate) mod tests { result } + #[test] + fn content_header_streams_reconstruct_the_collected_message() { + use crate::model::contract::{ReasoningParser, ReasoningParserKind, ToolParser, ToolParserKind}; + use crate::output::{OutputPipeline, tagged::OutputStart}; + let pieces = ["<|content_thinking|>", "Plan 世界", "<|end_message|>", + "<|message_model|>", "lookup", "<|content_invoke_tool_json|>", + r#"{"name":"lookup","args":{"q":"café","n":1}}"#, + r#"{"name":"lookup","args":{"q":"世界","n":2}}"#, + "<|content_text|>", "Answer & café"]; + let frontend = frontend(&pieces); + let mut syntax = crate::model::testing::metadata().frontend; + syntax.tools = Some(ToolParser { kind: ToolParserKind::TmlJson, + wrapping_newlines: 0, tag_separator: String::new() }); + syntax.reasoning = Some(ReasoningParser { kind: ReasoningParserKind::ContentHeaders, + open: pieces[0].into(), close: pieces[2].into(), wrapping_newlines: 0, terminal_markers: vec![] }); + let config = crate::output::OutputConfig { syntax, + control_tokens: [0,2,3,5,8].map(|id| (id, pieces[id as usize].into())).to_vec(), + content: OutputConfig { start: OutputStart::RecipientHeader, structured: false, + tools: vec![json!({"function":{"name":"lookup"}})] }, + }; + let mut streamed = Presentation::<OutputPipeline>::new(&frontend, &[99], config.clone(), "tml".into()); + let mut collected = Presentation::<OutputPipeline>::new(&frontend, &[99], config, "tml".into()); + let mut deltas = vec![]; + for token in [0,1,2,3,4,5,6,2,3,4,5,7,2,3,8,9,2,99] { + deltas.extend(streamed.push(token).unwrap()); + collected.push(token).unwrap(); + } + deltas.extend(streamed.finish(Termination::Eos).unwrap()); + collected.finish(Termination::Eos).unwrap(); + assert_eq!(reconstruct(&deltas), collected.message()); + assert_eq!(streamed.message()["reasoning_content"], "Plan 世界"); + assert_eq!(streamed.message()["content"], "Answer & café"); + assert_eq!(streamed.message()["tool_calls"].as_array().unwrap().len(), 2); + } + #[test] fn json_and_stream_reconstruction_share_incremental_reasoning_and_multiple_calls() { let pieces = [ diff --git a/helios/src/server/request.rs b/helios/src/server/request.rs index e08a2941f..7ca1480bb 100644 --- a/helios/src/server/request.rs +++ b/helios/src/server/request.rs @@ -982,3 +982,7 @@ fn describe_images( #[cfg(test)] #[path = "request/recipient_tests.rs"] mod recipient_tests; + +#[cfg(test)] +#[path = "request/tml_tests.rs"] +mod tml_tests; diff --git a/helios/src/server/request/tml_tests.rs b/helios/src/server/request/tml_tests.rs new file mode 100644 index 000000000..ca8978642 --- /dev/null +++ b/helios/src/server/request/tml_tests.rs @@ -0,0 +1,194 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +//! CPU request preparation with the canonical content-header checkpoint frontend. + +use super::*; +use crate::frontend::{Asset, FrontendAssets}; +use crate::output::tagged::OutputStart; +use crate::server::protocol::{Protocol, decode}; +use serde_json::json; +use sha2::{Digest, Sha256}; + +#[path = "../../../tests/support/frontend.rs"] +mod support; + +#[test] +#[ignore = "requires FLARE_INKLING_SNAPSHOT and FLARE_TEST_TEMPLATE_DIR checkpoint assets"] +fn content_headers_preserve_requests_tools_and_constrained_answers() { + let snapshot = std::path::PathBuf::from(std::env::var_os("FLARE_INKLING_SNAPSHOT").unwrap()); + let asset = |path: std::path::PathBuf| Asset { + sha256: format!("{:x}", Sha256::digest(std::fs::read(&path).unwrap())), + path, + range: None, + }; + let frontend = Frontend::load( + FrontendAssets { + tokenizer: asset(snapshot.join("tokenizer.json")), + tokens: crate::frontend::test_support::tokens(&asset( + snapshot.join("tokenizer_config.json"), + )) + .unwrap(), + chat_template: Some(asset(crate::template_fixtures::path( + "inkling", + "chat_template", + ))), + }, + json!({"add_generation_prompt":true}) + .as_object() + .unwrap() + .clone(), + ) + .unwrap(); + let mut config = support::model_config(crate::model::testing::metadata()); + config.contract.vocabulary = frontend.tokenizer().get_vocab_size(true); + config.contract.input_vocabulary = config.contract.vocabulary; + config.contract.vision.max_images = 0; + config.contract.frontend = serde_json::from_value(json!({ + "tools":{"kind":8,"wrapping_newlines":0,"tag_separator":""}, + "reasoning":{"kind":6,"open":"<|content_thinking|>","close":"<|end_message|>","wrapping_newlines":0,"terminal_markers":[]}, + "assistant_marker":"<|message_model|>","message_end_markers":["<|end_message|>","<|content_model_end_sampling|>"], + "rejected_tokens":[200005,200020,200023,200053,200054],"position_dimensions":0 + })).unwrap(); + config.eos_token_ids = vec![200006]; + let compiler = crate::grammar::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, mut body: Value| { + body["model"] = json!(config.model_id); + let decoded = decode(protocol, body, false)?; + prepare_inference( + &frontend, + None, + &compiler, + &config, + &decoded.request, + 0, + false, + ) + }; + for (protocol, body) in [ + ( + Protocol::Chat, + json!({"messages":[{"role":"user","content":"Hello 世界"}]}), + ), + ( + Protocol::Messages, + json!({"max_tokens":32,"messages":[{"role":"user","content":"Hello 世界"}]}), + ), + (Protocol::Responses, json!({"input":"Hello 世界"})), + ] { + let request = prepare(protocol, body).unwrap(); + assert!(request.rendered_prompt.ends_with("<|message_model|>")); + assert!( + request + .rendered_prompt + .contains("Thinking effort level: 0.9") + ); + assert_eq!( + request.output.unwrap().content.start, + OutputStart::RecipientHeader + ); + } + let tools = json!([{"type":"function","function":{"name":"lookup","parameters":{"type":"object","properties":{"query":{"type":"string"}}}}}]); + let history = json!([{"role":"user","content":"Find it"}, + {"role":"assistant","tool_calls":[{"id":"a","type":"function","function":{"name":"lookup","arguments":"{\"query\":\"世界\"}"}}]}, + {"role":"tool","tool_call_id":"a","content":"Found"},{"role":"user","content":"Explain"}]); + let request = prepare(Protocol::Chat, json!({"messages":history,"tools":tools})).unwrap(); + assert!(request.rendered_prompt.contains( + "lookup<|content_invoke_tool_json|>{\"name\":\"lookup\",\"args\":{\"query\":\"世界\"}}" + )); + assert!( + request + .rendered_prompt + .contains("<|message_tool|>lookup<|content_text|>Found<|end_message|>") + ); + assert!(request.prompt.message_boundaries.len() >= 4); + for (message, field, start) in [ + ( + json!({"role":"assistant","content":"Partial café"}), + json!(true), + OutputStart::Content, + ), + ( + json!({"role":"assistant","content":"","reasoning_content":"Plan café"}), + json!("reasoning_content"), + OutputStart::Reasoning, + ), + ] { + let request = prepare( + Protocol::Chat, + json!({"messages":[{"role":"user","content":"Hello"},message], + "chat_template_kwargs":{"continue_final_message":field,"add_generation_prompt":false}}), + ) + .unwrap(); + assert_eq!(request.output.unwrap().content.start, start); + } + let closed = prepare( + Protocol::Chat, + json!({"messages":[{"role":"user","content":"Hello"}], + "chat_template_kwargs":{"add_generation_prompt":false}}), + ) + .unwrap(); + assert_eq!( + closed.output.unwrap().content.start, + OutputStart::RecipientFrame + ); + assert!( + prepare( + Protocol::Chat, + json!({"messages":[{"role":"user","content":"<|content_image|>"}]}) + ) + .is_err() + ); + for choice in [ + json!("none"), + json!("auto"), + json!("required"), + json!({"type":"function","function":{"name":"lookup"}}), + ] { + let request = prepare(Protocol::Chat, json!({"messages":[{"role":"user","content":"Find"}],"tools":tools,"tool_choice":choice, + "response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"const":{"ok":true}}}}})).unwrap(); + assert!(request.prompt.grammar.is_some()); + assert_eq!( + request.output.unwrap().content.tools.is_empty(), + choice == "none" + ); + } + let answer = "<|content_text|>{\"ok\":true}<|end_message|>"; + let thinking = "<|content_thinking|>Plan 世界<|end_message|><|message_model|>"; + let call = "lookup<|content_invoke_tool_json|>{\"name\":\"lookup\",\"args\":{\"query\":\"café\"}}<|end_message|>"; + for (text, valid) in [ + (answer.to_owned(), true), + (format!("{thinking}{answer}"), true), + (call.to_owned(), true), + (format!("{call}<|message_model|>{thinking}{call}"), true), + (answer.replace("true", "false"), false), + (call.replace("lookup", "other"), false), + ( + call.replace("\"name\":\"lookup\"", "\"name\":\"other\""), + false, + ), + ( + call.replace("\"args\":{\"query\":\"café\"}", "\"args\":[]"), + false, + ), + ] { + let mut request = prepare(Protocol::Chat, json!({"messages":[{"role":"user","content":"Find"}],"tools":tools, + "response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"const":{"ok":true}}}}})).unwrap(); + let grammar = request.prompt.grammar.as_mut().unwrap(); + let accepted = frontend + .encode(&text, false) + .unwrap() + .into_iter() + .all(|id| grammar.advance(id).is_ok()) + && grammar.advance(200006).is_ok(); + assert_eq!(accepted, valid, "{text}"); + } +} diff --git a/helios/tests/inkling_operator_package_fixture.py b/helios/tests/inkling_operator_package_fixture.py new file mode 100644 index 000000000..b69cf4f13 --- /dev/null +++ b/helios/tests/inkling_operator_package_fixture.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Export relative attention and residual convolution for native replay.""" + +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + + +class OperatorForward: + def __init__(self, attention, convolution, history, result): + self.attention, self.convolution, self.history, self.result = attention, convolution, history, result + + def __call__(self): + attention = self.attention() + convolution = self.convolution() + end = attention.numel() + convolution.numel() + self.result[:attention.numel()].copy_(attention.flatten()) + self.result[attention.numel():end].copy_(convolution.flatten()) + self.result[end:].copy_(self.history.flatten()) + + +def prepare(directory): + import torch + from ignition.components.paged_batch import Metadata + from ignition.components.relative_paged_attention import PreparedRelativePagedAttention + from ignition.components.residual_short_conv import PreparedResidualShortConvolution + from ignition.preparation.capture import capture_forwards + from ignition.preparation.execution import GraphSignature, PreparedExecution + from ignition.preparation.module_images import ModuleImages + from ignition.preparation.package_storage import PackageStorage + from ignition.preparation.package_file import combine + from ignition.preparation.runtime_package import export_model + from ignition.preparation.tuning import RecordedPreparationSession + from fixed_package_fixture import allocation_reference + from fixture_frontend import server_config + from signing import publisher + + torch.cuda.set_device(0) + torch.manual_seed(838) + device = torch.device("cuda", 0) + with ModuleImages() as images, PackageStorage() as storage: + with RecordedPreparationSession(device=device, checkpoint="inkling-operator-export", + workload_schema="relative-attention-residual-convolution", numerical_policy="bf16-fp32-history", + compile_workers=1, benchmark_storage=storage) as session: + query = torch.randn((17, 2, 128), device=device, dtype=torch.bfloat16) + key = torch.randn((2, 128, 1, 128), device=device, dtype=torch.bfloat16) + value = torch.randn_like(key) + pages = torch.tensor([[1, 0]], device=device, dtype=torch.int32) + lengths = torch.tensor([145], device=device, dtype=torch.int32) + cu = torch.tensor([0, 13], device=device, dtype=torch.int32) + bias = (torch.randn((17, 2, 1024), device=device) * .2).bfloat16() + attention_output = torch.empty_like(query) + attention = PreparedRelativePagedAttention(query, key, value, pages, lengths, cu, bias, attention_output, + softmax_scale=1 / 128, session=session, name="relative-attention") + source = torch.randn((17, 67), device=device, dtype=torch.bfloat16) + weight = torch.randn((67, 4), device=device) * .1 + history = torch.zeros((3, 67, 3), device=device) + metadata = Metadata.allocate(17, 1, 2, device) + metadata.state_rows.fill_(1) + metadata.starts.zero_() + metadata.lengths.fill_(13) + metadata.query_start_loc.copy_(cu) + convolution_output = torch.empty_like(source) + convolution = PreparedResidualShortConvolution(source, weight, history, metadata, convolution_output, + session=session, name="residual-convolution") + result = torch.empty(query.numel() + source.numel() + history.numel(), device=device) + run = OperatorForward(attention, convolution, history, result) + session.tune(show_progress=False) + signatures = {"decode": GraphSignature("decode", 1, 1)} + stream = torch.cuda.Stream(device=device) + graphs, compiled = capture_forwards({"decode": run}, signatures, session=session, device=device, + stream=stream, pool=storage.graph_pool.id, retain_graphs=True) + session.freeze() + graphs["decode"].replay() + torch.cuda.synchronize(device) + expected = result.view(torch.uint8).cpu().numpy().tobytes() + assert torch.count_nonzero(attention_output[13:]) == 0 + assert torch.count_nonzero(convolution_output[13:]) == 0 + torch.testing.assert_close(history[1], source[10:13].float().T, atol=0, rtol=0) + result.zero_() + buffers = { + "frame_index": torch.zeros(1, device=device, dtype=torch.int32), + "submission_sequence": torch.zeros(1, device=device, dtype=torch.int64), + "completion_records": torch.zeros((2, 1, 24), device=device, dtype=torch.int64), + "result": result, + } + records = buffers["completion_records"] + records[..., 4] = -1 + records[..., 12:14] = -1 + records[..., 15] = 1 + records[..., 16:] = -1 + prepared = PreparedExecution(device=0, graphs=graphs, buffers=buffers, signatures=signatures, + max_active=1, resources=(storage, attention, convolution, result, stream, session, compiled), + export_zero_ranges=((result.data_ptr(), result.nbytes),)) + prepared.server_config = server_config(directory) + prepared.package_data = None + package = export_model(prepared, images, storage, directory / "rank.json", options={}, sources=True) + combine(directory / "package", [directory / "rank.json"], [], publisher=publisher()) + reference = allocation_reference(package.allocations, result) + (directory / "expected.json").write_text(json.dumps({ + "reference": reference, "bytes": list(expected), + "addresses": {allocation.name: allocation.address for allocation in package.allocations}, + "zero_reference": reference, "zero_bytes": result.nbytes, + })) + assert package.export_counts["modules"] >= 3 + for graph in graphs.values(): + graph.reset() + print("exported prepared relative attention and residual convolution", flush=True) + + +if __name__ == "__main__": + # Compiler workers import the fixture type by its stable module name. + from inkling_operator_package_fixture import prepare + + destination = Path(sys.argv[1]) + destination.mkdir(parents=True, exist_ok=True) + prepare(destination) diff --git a/ignition/components/bf16_experts.py b/ignition/components/bf16_experts.py index 9294c02e3..6ffaf9f5d 100644 --- a/ignition/components/bf16_experts.py +++ b/ignition/components/bf16_experts.py @@ -118,6 +118,7 @@ def _moe_bf16_stage1_kernel( TILE_N: tl.constexpr, TILE_K: tl.constexpr, SILU: tl.constexpr = False, + ROUND_SILU: tl.constexpr = True, ): tile_id = tl.program_id(0) n_id = tl.program_id(1) @@ -158,7 +159,9 @@ def _moe_bf16_stage1_kernel( gate = gate_acc.to(tl.bfloat16).to(tl.float32) if SILU: - gate_val = (gate * tl.sigmoid(gate)).to(tl.bfloat16).to(tl.float32) + gate_val = gate * tl.sigmoid(gate) + if ROUND_SILU: + gate_val = gate_val.to(tl.bfloat16).to(tl.float32) else: gate_val = _gelu_tanh(gate).to(tl.bfloat16).to(tl.float32) up_val = up_acc.to(tl.bfloat16).to(tl.float32) @@ -258,7 +261,8 @@ def rows(self, tokens, top_k): class PreparedBF16Experts: """Execute intermediate-sharded BF16 experts into unweighted route rows.""" - def __init__(self, source, gate_up, down, ids, weights, output, valid_tokens, *, buffers=None, scratch=None): + def __init__(self, source, gate_up, down, ids, weights, output, valid_tokens, *, + buffers=None, scratch=None, round_silu=True): tokens, hidden = source.shape count, twice_inter, width = gate_up.shape inter = twice_inter // 2 @@ -269,7 +273,7 @@ def __init__(self, source, gate_up, down, ids, weights, output, valid_tokens, *, or output.shape != (tokens, top_k, hidden) or output.dtype != source.dtype or ids.dtype != torch.int32 or weights.dtype != torch.float32 or valid_tokens.dtype != torch.int32 or valid_tokens.numel() != 1 - or count <= 0 or count & (count - 1) or twice_inter % 2 + or count <= 0 or count & (count - 1) or twice_inter % 2 or type(round_silu) is not bool or any(t.device != source.device or not t.is_contiguous() for t in (source, gate_up, down, ids, weights, output, valid_tokens))): raise ValueError("BF16 experts require matched source, weights, routes, and raw output geometry") @@ -295,7 +299,7 @@ def __init__(self, source, gate_up, down, ids, weights, output, valid_tokens, *, ) self.first = prepare_triton(_moe_bf16_stage1_kernel, (source, gate_up, sorted_ids, tile_experts, self.intermediate, - top_k, hidden, inter, tile_m, tile_n, tile_k, True), + top_k, hidden, inter, tile_m, tile_n, tile_k, True, round_silu), (tiles, triton.cdiv(inter, tile_n), 1), num_warps=4) self.second = prepare_triton(_moe_bf16_stage2_kernel, (self.intermediate, down, weights, sorted_ids, tile_experts, output, diff --git a/ignition/components/moe_sm103.py b/ignition/components/moe_sm103.py index a1fec231c..00690d4d9 100644 --- a/ignition/components/moe_sm103.py +++ b/ignition/components/moe_sm103.py @@ -13,6 +13,8 @@ checkpoint scale, quantizing separate routed rows when scales differ. FC2 inputs are quantized per expert in trtllm-gen's FC1 epilogue with each expert's FC2 input scale. * W4A16 NVFP4 experts use FlashInfer's CuTe-DSL NVFP4xBF16 grouped GEMMs. +* NVFP4 experts with NVFP4 activations and a BF16 SwiGLU intermediate use + CuTe-DSL block-scaled grouped GEMMs and write unweighted per-route rows. Weights are re-laid out once, in place. Routing remains b12x's portable ``route_topk``. Native kernels allocate their graph-local intermediates from @@ -31,6 +33,7 @@ from b12x._lib.compile_plan import _NATIVE_JITS, load_programs from b12x._lib.compile_pool import CompileJob from b12x._lib.program_cache import program_cache +from b12x._lib.scratch import scratch_buffer_spec from b12x.preparation import PreparedCall from b12x.preparation.types import plan_from_handle, require_prepared @@ -134,6 +137,15 @@ class CuteW4A16Experts(Sm103Experts): kind = "cute_w4a16" +@dataclass(frozen=True, eq=False, kw_only=True) +class CuteNvfp4Experts(CuteW4A16Experts): + """NVFP4 x NVFP4 experts with a BF16 SwiGLU intermediate; ``*_alpha`` include the activation global scales.""" + + input_global_scale: torch.Tensor + intermediate_global_scale: torch.Tensor + kind = "cute_nvfp4" + + def _check_packed(w13, s13, w2, s2): if w13.dtype != torch.uint8 or w2.dtype != torch.uint8 or w13.ndim != 3 or w2.ndim != 3: raise ValueError("packed NVFP4 experts must be rank-three uint8 tensors") @@ -249,6 +261,24 @@ def prepare_cute_w4a16_experts(w13, s13, w2, s2, w13_global, w2_global, *, swigl swiglu_limit=None if swiglu_limit is None else float(swiglu_limit)) +def prepare_cute_nvfp4_experts(w13, s13, w2, s2, scale_vectors) -> CuteNvfp4Experts: + """Re-lay out packed NVFP4 experts for NVFP4-activation CuTe-DSL GEMMs, in place.""" + count, hidden, intermediate = _check_packed(w13, s13, w2, s2) + if len(scale_vectors) != 4: + raise ValueError("NVFP4 A4 experts require weight and activation global scales") + if hidden % 128 or intermediate % 64: + raise ValueError("CuTe NVFP4 experts require 128-aligned hidden and 64-aligned intermediate dimensions") + globals_ = tuple(_vector(v, count, w13.device, "NVFP4 global scales") for v in scale_vectors) + if any(not bool((v == v[0]).all()) for v in globals_[2:]): + raise ValueError("CuTe BF16-intermediate NVFP4 requires shared activation calibration per projection") + e = prepare_cute_w4a16_experts(w13, s13, w2, s2, *globals_[:2]) + a1, a2 = (v[:1].to(device=w13.device, dtype=torch.float32) for v in globals_[2:]) + return CuteNvfp4Experts( + w13=e.w13, w13_scale=e.w13_scale, w13_alpha=e.w13_alpha / a1, + w2=e.w2, w2_scale=e.w2_scale, w2_alpha=e.w2_alpha / a2, + scale_storage=e.scale_storage, input_global_scale=a1, intermediate_global_scale=a2) + + @dataclass(frozen=True) class RoutedExpertsQuery: """Exact routed-expert invocation; tactics depend only on these values.""" @@ -297,6 +327,31 @@ def implementable(m, k, slots, tactic): return tuple(tactics) +@cache +def _cute_nvfp4_tactics(query: RoutedExpertsQuery): + import cutlass + from flashinfer.fused_moe.cute_dsl.blackwell.blockscaled_contiguous_gather_grouped_gemm_act_fusion import ( + BlockScaledContiguousGatherGroupedGemmKernel as FC1, + ) + from flashinfer.fused_moe.cute_dsl.blackwell.blockscaled_contiguous_grouped_gemm_finalize_fusion import ( + Sm100BlockScaledContiguousGroupedGemmFinalizeFusionKernel as FC2, + ) + from flashinfer.fused_moe.cute_dsl.moe_utils import get_max_num_permuted_tokens + from flashinfer.fused_moe.cute_dsl.tuner import get_blackwell_moe_valid_tactics + + tactics = [] + for tile, fc1, fc2 in get_blackwell_moe_valid_tactics(): + rows = get_max_num_permuted_tokens(query.num_tokens, query.top_k, query.num_experts, tile) + types = (cutlass.Float4E2M1FN, cutlass.Float4E2M1FN, cutlass.Float8E4M3FN, 16, cutlass.BFloat16) + if (FC1.can_implement(*types, fc1[0], fc1[1], rows, 2 * query.intermediate_size, + query.hidden_size, query.num_experts, "k", "k", "n") + and FC2.can_implement(*types, cutlass.Float32, fc2[0], fc2[1], rows, + query.hidden_size, query.intermediate_size, + query.num_experts, "k", "k", "n")): + tactics.append((tile, fc1, fc2)) + return tuple(tactics) + + TRTLLM_CONTRACT = native_contract(component_id="flare.moe.sm103_trtllm_nvfp4", query_type=RoutedExpertsQuery, tactics=_trtllm_tactics, semantic_version=3) @@ -305,6 +360,9 @@ def implementable(m, k, slots, tactic): W4A16_CONTRACT = native_contract(component_id="flare.moe.sm103_cute_w4a16", query_type=RoutedExpertsQuery, tactics=_w4a16_tactics, semantic_version=3) +CUTE_NVFP4_CONTRACT = native_contract(component_id="flare.moe.sm103_cute_nvfp4_routes", + query_type=RoutedExpertsQuery, tactics=_cute_nvfp4_tactics, + semantic_version=2) def _aligned(nbytes): @@ -319,6 +377,36 @@ def _scratch_bytes(query): return _aligned(tokens * hidden // 2) + _aligned((tokens + 15) // 16 * 16 * hidden // 16) +def _cute_nvfp4_scratch(query, tactic, storage=None): + """One planned arena for routing, packed activations, and BF16 SwiGLU rows.""" + from math import prod + from flashinfer.fused_moe.cute_dsl.moe_utils import get_max_num_tiles + + q, tile = query, tactic[0] + tiles = get_max_num_tiles(q.num_tokens, q.top_k, q.num_experts, tile) + rows = tiles * tile + shapes = ( + ("values", (q.num_tokens, q.hidden_size // 2), torch.uint8), + ("scales", ((q.num_tokens + 15) // 16 * 16 * q.hidden_size // 16,), torch.uint8), + ("activated", (rows, q.intermediate_size), torch.bfloat16), + ("intermediate", (rows, q.intermediate_size // 2), torch.uint8), + ("intermediate_scales", (rows * q.intermediate_size // 16,), torch.uint8), + ("out_tile_idx_to_expert_idx", (tiles,), torch.int32), + ("out_tile_idx_to_mn_limit", (tiles,), torch.int32), + ("out_expanded_idx_to_permuted_idx", (q.num_tokens, q.top_k), torch.int32), + ("out_permuted_idx_to_expanded_idx", (rows,), torch.int32), + ("out_total_num_padded_tokens", (1,), torch.int32), + ("out_num_non_exiting_tiles", (1,), torch.int32), + ) + offset, views = 0, {} + for name, shape, dtype in shapes: + size = prod(shape) * dtype.itemsize + if storage is not None: + views[name] = storage[offset:offset + size].view(dtype).view(shape) + offset += _aligned(size) + return offset if storage is None else views + + _REDUCE_BLOCK = 512 @@ -523,9 +611,67 @@ def run(self, a, topk_ids, topk_weights, output, scratch): use_fused_finalize=False, enable_pdl=True, tactic=self.tactic, **clamp) +class _CuteNvfp4State: + """CuTe-DSL NVFP4 GEMMs: FC1 to BF16 SwiGLU rows, requantized for FC2, written as unweighted per-route rows.""" + + implementation = "cute_nvfp4_routes" + + def __init__(self, experts: CuteNvfp4Experts, query: RoutedExpertsQuery, tactic): + from flashinfer.cute_dsl.utils import convert_sf_to_mma_layout + from flashinfer.fused_moe.cute_dsl.moe_utils import moe_sort + from flashinfer.fused_moe.cute_dsl.blockscaled_contiguous_gather_grouped_gemm_act_fusion import ( + blockscaled_contiguous_gather_grouped_gemm_act_fusion, + ) + from flashinfer.fused_moe.cute_dsl.blockscaled_contiguous_grouped_gemm_finalize_fusion import ( + blockscaled_contiguous_grouped_gemm_finalize_fusion, + ) + + self.experts, self.query, self.tactic = experts, query, tactic + self.quantize = _fp4_quantizer().fp4_quantize + self.scale_view, self.sort = convert_sf_to_mma_layout, moe_sort + self.fc1 = blockscaled_contiguous_gather_grouped_gemm_act_fusion + self.fc2 = blockscaled_contiguous_grouped_gemm_finalize_fusion + + def scratch_bytes(self): + return _cute_nvfp4_scratch(self.query, self.tactic) + + def run(self, a, topk_ids, topk_weights, output, scratch): + e, q = self.experts, self.query + tile, fc1, fc2 = self.tactic + s = _cute_nvfp4_scratch(q, self.tactic, scratch) + metadata = self.sort(topk_ids, topk_weights, q.num_experts, q.top_k, + num_local_experts=q.num_experts, tile_tokens_dim=tile, enable_pdl=True, + **{name: value for name, value in s.items() if name.startswith("out_")}) + expert_tiles, limits, _, mapping, _, active_tiles = metadata + self.quantize(a, e.input_global_scale, s["values"], s["scales"], + 16, False, False, False, False, True, 0) + # Gather GEMM1 reads source scales in row-major order; its weight scales + # and GEMM2's contiguous activation scales use the 128x4 MMA layout. + scales = s["scales"][:q.num_tokens * q.hidden_size // 16].view(q.num_tokens, q.hidden_size // 16) + self.fc1(s["values"], e.w13, scales, e.w13_scale, e.w13_alpha, + expert_tiles, limits, mapping, active_tiles, out=s["activated"], + topk=q.top_k, c_dtype="bfloat16", quantize_output=False, + mma_tiler_mn=fc1[0], cluster_shape_mn=fc1[1], raster_along_m=fc1[2], enable_pdl=True) + self.quantize(s["activated"], e.intermediate_global_scale, + s["intermediate"], s["intermediate_scales"], + 16, False, True, False, False, True, 0) + scales = self.scale_view(s["intermediate_scales"], m=s["activated"].shape[0], + k=q.intermediate_size, num_groups=1, sf_vec_size=16) + # Non-local/negative routes have no FC2 store. Clear their caller-owned rows each replay. + output.zero_() + self.fc2(s["intermediate"], e.w2, scales, e.w2_scale, e.w2_alpha, + expert_tiles, active_tiles, limits, mapping, topk_weights, + out=output.view(q.num_tokens * q.top_k, q.hidden_size), + a_dtype="float4_e2m1fn", b_dtype="float4_e2m1fn", + mma_tiler_mn=fc2[0], cluster_shape_mn=fc2[1], raster_along_m=fc2[2], + enable_pdl=True, use_fused_finalize=False) + + def _state_type(experts): if isinstance(experts, TrtllmNvfp4Experts): return TRTLLM_CONTRACT, _TrtllmNvfp4State + if isinstance(experts, CuteNvfp4Experts): + return CUTE_NVFP4_CONTRACT, _CuteNvfp4State if isinstance(experts, CuteW4A16Experts): return W4A16_CONTRACT, _CuteW4A16State raise TypeError("SM103 routed experts require FlashInfer-prepared expert storage") @@ -547,7 +693,8 @@ def plan_routed_experts(experts: Sm103Experts, *, tokens: int, top_k: int): CompileJob.create("ignition.components.moe_sm103:compile_route_quantization", query.num_tokens, query.hidden_size, query.top_k, detected.ordinal)) return native_plan(contract=contract, query=query, device=experts.device, - scratch_bytes=lambda tactic: _scratch_bytes(query), + scratch_bytes=(lambda tactic: _cute_nvfp4_scratch(query, tactic)) + if state_type is _CuteNvfp4State else (lambda tactic: _scratch_bytes(query)), materialize=lambda tactic: state_type(experts, query, tactic), compile_jobs=jobs) @@ -648,8 +795,9 @@ def _bind(plan, state, a, topk_ids, topk_weights, output, scratch): for tensor, dtype in ((topk_ids, torch.int32), (topk_weights, torch.float32)): if tensor.dtype != dtype or tensor.shape != (tokens, query.top_k) or not tensor.is_contiguous(): raise ValueError("SM103 routes require contiguous int32 IDs and FP32 weights per token") - if output.dtype != torch.bfloat16 or output.shape != a.shape or not output.is_contiguous(): - raise ValueError("SM103 routed output must be contiguous BF16 matching the source") + output_shape = ((tokens, query.top_k, hidden) if query.kind == "cute_nvfp4" else (tokens, hidden)) + if output.dtype != torch.bfloat16 or output.shape != output_shape or not output.is_contiguous(): + raise ValueError(f"SM103 routed output must be contiguous BF16 with shape {output_shape}") if scratch.dtype != torch.uint8 or scratch.ndim != 1 or scratch.numel() < state.scratch_bytes(): raise ValueError("SM103 routed-expert scratch is smaller than its plan") if any(t.device != a.device for t in (topk_ids, topk_weights, output, scratch)): @@ -657,14 +805,21 @@ def _bind(plan, state, a, topk_ids, topk_weights, output, scratch): return Sm103Binding(plan, state, a, topk_ids, topk_weights, output, scratch, state.implementation) +def _state_scratch(plan, state, workspace): + # During tuning the plan has no installed selection. Its default tactic can + # require less storage than the candidate whose call is being bound. + specs = (scratch_buffer_spec(plan.component_id, nbytes=state.scratch_bytes(), device=state.experts.device),) + return planned_scratch(specs, workspace) + + def _benchmark_call(state, *, plan, source, experts, top_k, session, name, workspace, - allocate_router, router_plan): + allocate_router, router_plan, output_template): from ignition.preparation.fixtures.fused_moe import ExpertBenchmarkInputs operands = benchmark_resource(session, ("moe_inputs", name), lambda: ExpertBenchmarkInputs(source, experts=experts.num_experts, top_k=top_k, - allocate_router=allocate_router, router_plan=router_plan)) - scratch = planned_scratch(plan.memory_requirements().scratch, workspace) + allocate_router=allocate_router, router_plan=router_plan, output_template=output_template)) + scratch = _state_scratch(plan, state, workspace) binding = _bind(plan, state, operands.source, operands.router.ids, operands.router.weights, operands.output, scratch) return PreparedCall(run=binding.run, output=operands.output, produce=operands.producers[0], @@ -691,7 +846,7 @@ def __init__(self, source, experts: Sm103Experts, ids, weights, output, *, sessi raise ValueError("SM103 routed experts require [tokens, hidden] source and [tokens, top_k] routes") for field in ("w13", "w13_scale", "w2", "w2_scale", "w13_alpha", "w2_alpha", "input_global_scale", "output1_scale", "output1_gate_scale", "output2_scale", - "gate_alpha", "gate_beta", "clamp_limit"): + "intermediate_global_scale", "gate_alpha", "gate_beta", "clamp_limit"): tensor = getattr(experts, field, None) if tensor is not None: record_numeric_tensor(tensor) @@ -702,7 +857,7 @@ def __init__(self, source, experts: Sm103Experts, ids, weights, output, *, sessi plan = self.plan def prepare_call(state): - scratch = planned_scratch(plan.memory_requirements().scratch, workspace) + scratch = _state_scratch(plan, state, workspace) self.scratch = scratch binding = _bind(plan, state, source, ids, weights, output, scratch) return PreparedCall(run=binding.run, owners=prime_owners(workspace, scratch, binding)) @@ -710,7 +865,7 @@ def prepare_call(state): declare(session, (plan.request(name=name, prepare_call=prepare_call, benchmark_call=partial(_benchmark_call, plan=plan, source=source, experts=experts, top_k=ids.shape[1], session=session, name=name, workspace=workspace, - allocate_router=RouterScratch.allocate, router_plan=router_plan)),)) + allocate_router=RouterScratch.allocate, router_plan=router_plan, output_template=output)),)) def finalize(): self.scratch = planned_scratch(plan.scratch_specs(), workspace) diff --git a/ignition/components/native_operator.py b/ignition/components/native_operator.py index 4bc65b88e..c4a0fc3d7 100644 --- a/ignition/components/native_operator.py +++ b/ignition/components/native_operator.py @@ -10,9 +10,19 @@ import torch from b12x._lib.scratch import scratch_buffer_spec +from b12x._lib.compile_plan import launch_triton +from b12x._lib.program_cache import register_program_cache from b12x.preparation import Knob, MemoryRequirements, Plan, TuningContract +def compile_triton(kernel, grid, *args, **kwargs): + """Register local Triton executable caches for reclamation during b12x preparation.""" + program = launch_triton(kernel, grid, *args, **kwargs) + for executable_cache, *_ in kernel.device_caches.values(): + register_program_cache(executable_cache) + return program + + def _tactic(value): """Restore tuple tactics after a JSON round trip through the selection cache.""" if isinstance(value, (list, tuple)): diff --git a/ignition/components/relative_paged_attention.py b/ignition/components/relative_paged_attention.py new file mode 100644 index 000000000..6b8f96760 --- /dev/null +++ b/ignition/components/relative_paged_attention.py @@ -0,0 +1,209 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Paged causal attention with a finite learned bias for each backward distance.""" + +from dataclasses import dataclass, replace +import math + +import torch +import triton +import triton.language as tl +from b12x._lib.compile_plan import attach_programs, compile_only_launches, load_programs +from b12x._lib.compile_pool import CompileJob +from b12x._lib.program_cache import program_cache +from b12x.preparation import PreparedCall +from b12x.preparation.types import plan_from_handle, require_prepared + +from ignition.preparation.tuning import benchmark_resource, declare +from .native_operator import compile_triton, native_contract, native_plan +from .selected_attention import metadata_tensor, tensor_facts + + +@triton.jit +def _relative_attention(Q, K, V, Pages, Lengths, Cu, Bias, Out, + QT: tl.constexpr, QH: tl.constexpr, KP: tl.constexpr, KT: tl.constexpr, + KH: tl.constexpr, VP: tl.constexpr, VT: tl.constexpr, VH: tl.constexpr, + PT: tl.constexpr, BT: tl.constexpr, BH: tl.constexpr, + OT: tl.constexpr, OH: tl.constexpr, HEADS: tl.constexpr, + KV_HEADS: tl.constexpr, DIM: tl.constexpr, PAGE: tl.constexpr, + EXTENT: tl.constexpr, WINDOW: tl.constexpr, SCALE: tl.constexpr, + BM: tl.constexpr, BN: tl.constexpr): + tile, head, batch = tl.program_id(0), tl.program_id(1), tl.program_id(2) + begin, end = tl.load(Cu + batch), tl.load(Cu + batch + 1) + length = tl.load(Lengths + batch) + if tile * BM < end - begin: + rows = tile * BM + tl.arange(0, BM) + columns = tl.arange(0, BN) + d = tl.arange(0, DIM) + positions = length - (end - begin) + rows + live = rows < end - begin + q = tl.load(Q + (begin + rows[:, None]) * QT + head * QH + d[None, :], live[:, None], 0) + kv_head = head // (HEADS // KV_HEADS) + first = 0 + if WINDOW >= 0: + first = tl.maximum(0, length - (end - begin) + tile * BM - WINDOW) + stop = tl.minimum(length, length - (end - begin) + (tile + 1) * BM) + maximum = tl.full((BM,), -1.0e30, tl.float32) + denominator = tl.full((BM,), 0, tl.float32) + # Pass one finds each row's max and denominator; pass two rounds normalized probabilities to BF16 before the V product. + for start in range(first, stop, BN): + keys = start + columns + page = tl.load(Pages + batch * PT + keys // PAGE, keys < length, 0) + k = tl.load(K + page[None, :] * KP + (keys[None, :] % PAGE) * KT + + kv_head * KH + d[:, None], keys[None, :] < length, 0) + score = tl.dot(q, k).to(tl.bfloat16).to(tl.float32) + score = (score * SCALE).to(tl.bfloat16).to(tl.float32) + distance = positions[:, None] - keys[None, :] + bias = tl.load(Bias + (begin + rows[:, None]) * BT + head * BH + distance, + live[:, None] & (distance >= 0) & (distance < EXTENT), 0).to(tl.float32) + score = (score + bias).to(tl.bfloat16).to(tl.float32) + valid = live[:, None] & (keys[None, :] < length) & (distance >= 0) + if WINDOW >= 0: + valid = valid & (distance <= WINDOW) + score = tl.where(valid, score, float("-inf")) + next_max = tl.maximum(maximum, tl.max(score, 1)) + denominator = denominator * tl.exp(maximum - next_max) + tl.sum(tl.exp(score - next_max[:, None]), 1) + maximum = next_max + accumulator = tl.full((BM, DIM), 0, tl.float32) + for start in range(first, stop, BN): + keys = start + columns + page = tl.load(Pages + batch * PT + keys // PAGE, keys < length, 0) + k = tl.load(K + page[None, :] * KP + (keys[None, :] % PAGE) * KT + + kv_head * KH + d[:, None], keys[None, :] < length, 0) + score = tl.dot(q, k).to(tl.bfloat16).to(tl.float32) + score = (score * SCALE).to(tl.bfloat16).to(tl.float32) + distance = positions[:, None] - keys[None, :] + bias = tl.load(Bias + (begin + rows[:, None]) * BT + head * BH + distance, + live[:, None] & (distance >= 0) & (distance < EXTENT), 0).to(tl.float32) + score = (score + bias).to(tl.bfloat16).to(tl.float32) + valid = live[:, None] & (keys[None, :] < length) & (distance >= 0) + if WINDOW >= 0: + valid = valid & (distance <= WINDOW) + probability = tl.where(valid, tl.exp(score - maximum[:, None]) / denominator[:, None], 0).to(tl.bfloat16) + value = tl.load(V + page[:, None] * VP + (keys[:, None] % PAGE) * VT + + kv_head * VH + d[None, :], keys[:, None] < length, 0) + accumulator = tl.dot(probability, value, accumulator) + tl.store(Out + (begin + rows[:, None]) * OT + head * OH + d[None, :], accumulator, live[:, None]) + + +@dataclass(frozen=True) +class Query: + operands: tuple + window: int + scale: float + + +CONTRACT = native_contract(component_id="flare.relative_paged_attention", query_type=Query, + tactics=lambda q: ((16, 32, 4), (16, 64, 4), (32, 64, 4), (16, 64, 8))) + + +def _arguments(tensors, query, tactic): + q, k, v, pages, lengths, cu, bias, out = tensors + bm, bn, _ = tactic + return (*tensors, *q.stride()[:2], *k.stride()[:3], *v.stride()[:3], pages.stride(0), + *bias.stride()[:2], *out.stride()[:2], q.shape[1], k.shape[2], q.shape[2], + k.shape[1], bias.shape[2], query.window, query.scale, bm, bn) + + +@program_cache(scope="preparation") +def compile_attention(payload, tactic, ordinal): + query = Query(**dict(payload)) + tensors = tuple(map(metadata_tensor, query.operands)) + q, _, _, pages, *_ = tensors + bm, _, warps = tactic + with torch.cuda.device(ordinal), compile_only_launches(): + return compile_triton(_relative_attention, (triton.cdiv(q.shape[0], bm), q.shape[1], pages.shape[0]), + *_arguments(tensors, query, tactic), num_warps=warps, enable_fp_fusion=False) + + +@dataclass(frozen=True) +class State: + query: Query + tactic: tuple + program: object + + def run(self, tensors): + q, _, _, pages, _, _, _, out = tensors + out.zero_() + self.program[(triton.cdiv(q.shape[0], self.tactic[0]), q.shape[1], pages.shape[0])]( + *_arguments(tensors, self.query, self.tactic)) + + +@torch.library.custom_op("flare::relative_paged_attention", mutates_args=("output",)) +def _execute(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, + pages: torch.Tensor, lengths: torch.Tensor, cu: torch.Tensor, + bias: torch.Tensor, output: torch.Tensor, handle: int) -> None: + plan = plan_from_handle(handle) + require_prepared(plan, plan.component_id, query.device).run((query, key, value, pages, lengths, cu, bias, output)) + + +@_execute.register_fake +def _fake(query, key, value, pages, lengths, cu, bias, output, handle): + pass + + +class PreparedRelativePagedAttention: + """Read BF16 pages and caller-projected relative logits without expanding KV.""" + + def __init__(self, query, key_cache, value_cache, page_table, lengths, cu, relative_logits, output, + *, window=-1, softmax_scale, session, name): + self.arguments = query, key_cache, value_cache, page_table, lengths, cu, relative_logits, output + q, k, v, pages, lengths, cu, bias, out = self.arguments + if (q.ndim != 3 or min(q.shape) < 1 or q.shape[2] not in (32, 64, 128, 256) + or k.ndim != 4 or k.shape != v.shape or min(k.shape) < 1 or k.shape[3] != q.shape[2] + or q.shape[1] % k.shape[2] or out.shape != q.shape + or bias.ndim != 3 or bias.shape[:2] != q.shape[:2] or bias.shape[2] < 1 + or any(t.dtype != torch.bfloat16 or t.stride(-1) != 1 for t in (q, k, v, bias, out)) + or any(t.stride(1) != t.shape[2] or t.stride(0) < t.shape[1] * t.shape[2] + for t in (q, bias, out)) + or any(t.stride()[1:] != (t.shape[2] * t.shape[3], t.shape[3], 1) + or t.stride(0) < t.shape[1] * t.shape[2] * t.shape[3] for t in (k, v)) + or pages.ndim != 2 or min(pages.shape) < 1 or pages.dtype != torch.int32 + or lengths.shape != (pages.shape[0],) or lengths.dtype != torch.int32 + or cu.shape != (pages.shape[0] + 1,) or cu.dtype != torch.int32 + or any(not t.is_contiguous() for t in (pages, lengths, cu)) + or type(window) is not int or window < -1 or not math.isfinite(softmax_scale) or softmax_scale <= 0 + or any(t.device != q.device for t in self.arguments) or q.device.type != "cuda"): + raise ValueError("relative paged attention requires matching BF16 GQA pages, per-query biases and packed int32 metadata") + from .window_staging import _overlap + + if any(_overlap(output, t) for t in self.arguments[:-1]): + raise ValueError("relative attention output must not overlap its inputs") + geometry = Query(tuple(tensor_facts(t) for t in self.arguments), window, float(softmax_scale)) + payload = CONTRACT.encode_query(geometry) + + def materialize(tactic): + program = compile_attention(payload, tactic, q.device.index) + load_programs(program) + return attach_programs(State(geometry, tactic, program), program) + + self.plan = native_plan(contract=CONTRACT, query=geometry, device=q.device, + scratch_bytes=lambda t: 0, materialize=materialize, + compile_jobs=lambda t, d: (CompileJob.create( + "ignition.components.relative_paged_attention:compile_attention", payload, t, d.ordinal),)) + + def benchmark(state): + def inputs(): + values = [] + for index, tensor in enumerate(self.arguments): + shape = (1, *tensor.shape[1:]) if index in (1, 2) else tensor.shape + values.append(torch.empty_strided(shape, tensor.stride(), dtype=tensor.dtype, device=tensor.device)) + a, k, v, p, n, c, b, y = values + for tensor in (a, k, v, b): + tensor.normal_(std=.2) + p.zero_() + n.zero_() + n[0] = a.shape[0] + c.fill_(a.shape[0]) + c[0] = 0 + return tuple(values), a.clone() + values, seed = benchmark_resource(session, ("relative_paged_attention", name), inputs) + return PreparedCall(run=lambda: state.run(values), output=values[-1], + produce=lambda: values[0].copy_(seed), owners=(values, seed)) + declare(session, (self.plan.request(name=name, + prepare_call=lambda state: replace(benchmark(state), owners=()), benchmark_call=benchmark),)) + + def __call__(self): + _execute(*self.arguments, self.plan.handle) + return self.arguments[-1] diff --git a/ignition/components/residual_short_conv.py b/ignition/components/residual_short_conv.py new file mode 100644 index 000000000..d6bfef6ee --- /dev/null +++ b/ignition/components/residual_short_conv.py @@ -0,0 +1,192 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepared FP32 causal depthwise convolution with a raw-input residual.""" + +from dataclasses import dataclass, replace + +import torch +import triton +import triton.language as tl +from b12x._lib.compile_plan import attach_programs, compile_only_launches, load_programs +from b12x._lib.compile_pool import CompileJob +from b12x._lib.program_cache import program_cache +from b12x.preparation import PreparedCall +from b12x.preparation.types import plan_from_handle, require_prepared + +from ignition.preparation.tuning import benchmark_resource, declare +from .native_operator import compile_triton, native_contract, native_plan +from .selected_attention import metadata_tensor, tensor_facts + + +@triton.jit +def _convolve(X, W, H, States, Starts, Lengths, Cu, Y, + XS: tl.constexpr, WS: tl.constexpr, HS: tl.constexpr, HC: tl.constexpr, + YS: tl.constexpr, C: tl.constexpr, K: tl.constexpr, T: tl.constexpr, + BLOCK: tl.constexpr): + token, batch, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) + n = tl.load(Lengths + batch) + state = tl.load(States + batch) + if token < n and state > 0: + c = tile * BLOCK + tl.arange(0, BLOCK) + begin, start = tl.load(Cu + batch), tl.load(Starts + batch) + raw = tl.load(X + (begin + token) * XS + c, c < C, 0).to(tl.float32) + result = tl.full((BLOCK,), 0, tl.float32) + for i in tl.static_range(K): + offset = token + i - (K - 1) + current = tl.load(X + (begin + offset) * XS + c, + (c < C) & (offset >= 0), 0).to(tl.float32) + previous = tl.load(H + state * HS + c * HC + offset + K - 1, + (c < C) & (offset < 0) & (start + offset >= 0), 0) + value = tl.where(offset >= 0, current, previous) + weight = tl.load(W + c * WS + i, c < C, 0) + result = result + value * weight + tl.store(Y + (begin + token) * YS + c, result + raw, c < C) + + +@triton.jit +def _commit(X, W, H, States, Starts, Lengths, Cu, Y, + XS: tl.constexpr, WS: tl.constexpr, HS: tl.constexpr, HC: tl.constexpr, + YS: tl.constexpr, C: tl.constexpr, K: tl.constexpr, T: tl.constexpr, + BLOCK: tl.constexpr): + batch, tile = tl.program_id(0), tl.program_id(1) + n, state = tl.load(Lengths + batch), tl.load(States + batch) + if n > 0 and state > 0: + c = tile * BLOCK + tl.arange(0, BLOCK) + history = tl.arange(0, triton.next_power_of_2(K - 1)) + offset = n - (K - 1) + history + begin, start = tl.load(Cu + batch), tl.load(Starts + batch) + current = tl.load(X + (begin + offset[None, :]) * XS + c[:, None], + (c[:, None] < C) & (history[None, :] < K - 1) & (offset[None, :] >= 0), 0).to(tl.float32) + previous = tl.load(H + state * HS + c[:, None] * HC + offset[None, :] + K - 1, + (c[:, None] < C) & (history[None, :] < K - 1) + & (offset[None, :] < 0) & (start + offset[None, :] >= 0), 0) + value = tl.where(offset[None, :] >= 0, current, previous) + tl.store(H + state * HS + c[:, None] * HC + history[None, :], value, + (c[:, None] < C) & (history[None, :] < K - 1)) + + +@dataclass(frozen=True) +class Query: + operands: tuple + + +CONTRACT = native_contract(component_id="flare.residual_short_conv", query_type=Query, + tactics=lambda q: ((128, 4), (256, 4), (128, 8))) + + +def _arguments(tensors, block): + x, w, h, states, starts, lengths, cu, y = tensors + return (*tensors, x.stride(0), w.stride(0), h.stride(0), h.stride(1), y.stride(0), + x.shape[1], w.shape[1], x.shape[0], block) + + +@program_cache(scope="preparation") +def compile_convolution(payload, tactic, ordinal): + q = Query(**dict(payload)) + tensors = tuple(map(metadata_tensor, q.operands)) + block, warps = tactic + x, _, _, states, *_ = tensors + with torch.cuda.device(ordinal), compile_only_launches(): + args = _arguments(tensors, block) + return dict( + convolve=compile_triton(_convolve, (x.shape[0], states.numel(), triton.cdiv(x.shape[1], block)), + *args, num_warps=warps, enable_fp_fusion=False), + commit=compile_triton(_commit, (states.numel(), triton.cdiv(x.shape[1], block)), + *args, num_warps=warps, enable_fp_fusion=False)) + + +@dataclass(frozen=True) +class State: + tactic: tuple + programs: dict + + def run(self, tensors): + x, _, _, states, *_, y = tensors + block, _ = self.tactic + y.zero_() + args = _arguments(tensors, block) + self.programs["convolve"][(x.shape[0], states.numel(), triton.cdiv(x.shape[1], block))](*args) + self.programs["commit"][(states.numel(), triton.cdiv(x.shape[1], block), 1)](*args) + + +@torch.library.custom_op("flare::residual_short_conv", mutates_args=("history", "output")) +def _execute(source: torch.Tensor, weight: torch.Tensor, history: torch.Tensor, + states: torch.Tensor, starts: torch.Tensor, lengths: torch.Tensor, + cu: torch.Tensor, output: torch.Tensor, handle: int) -> None: + plan = plan_from_handle(handle) + require_prepared(plan, plan.component_id, source.device).run( + (source, weight, history, states, starts, lengths, cu, output)) + + +@_execute.register_fake +def _fake(source, weight, history, states, starts, lengths, cu, output, handle): + pass + + +class PreparedResidualShortConvolution: + """Commit chronological raw FP32 history after all packed outputs are computed.""" + + def __init__(self, source, weight, history, metadata, output, *, session, name): + m = metadata + self.arguments = source, weight, history, m.state_rows, m.starts, m.lengths, m.query_start_loc, output + if (source.ndim != 2 or source.dtype != torch.bfloat16 or source.stride(-1) != 1 + or min(source.shape) < 1 or weight.ndim != 2 or weight.shape[0] != source.shape[1] + or not 2 <= weight.shape[1] <= 8 or weight.dtype != torch.float32 or weight.stride(-1) != 1 + or weight.stride(0) < weight.shape[1] + or history.ndim != 3 or history.shape[1:] != (source.shape[1], weight.shape[1] - 1) + or history.shape[0] < 2 or history.dtype != torch.float32 or history.stride(-1) != 1 + or history.stride(1) < history.shape[2] + or history.stride(0) < (history.shape[1] - 1) * history.stride(1) + history.shape[2] + or output.shape != source.shape or output.dtype != source.dtype or output.stride(-1) != 1 + or source.stride(0) < source.shape[1] or output.stride(0) < output.shape[1] + or any(t.device != source.device for t in self.arguments) or source.device.type != "cuda"): + raise ValueError("residual convolution requires BF16 matrices, FP32 depthwise weights and FP32 chronological history") + from .window_staging import _overlap + + if any(_overlap(output, t) for t in self.arguments[:-1]) or _overlap(source, history): + raise ValueError("residual convolution output, source and history must not overlap") + rows = m.state_rows.numel() + for tensor, dtype, count in ((m.state_rows, torch.int64, rows), (m.starts, torch.int64, rows), + (m.lengths, torch.int32, rows), (m.query_start_loc, torch.int32, rows + 1)): + if tensor.dtype != dtype or tensor.shape != (count,) or not tensor.is_contiguous(): + raise ValueError("residual convolution has incompatible packed metadata") + q = Query(tuple(tensor_facts(t) for t in self.arguments)) + payload = CONTRACT.encode_query(q) + + def materialize(tactic): + programs = compile_convolution(payload, tactic, source.device.index) + load_programs(programs) + return attach_programs(State(tactic, programs), *programs.values()) + + self.plan = native_plan(contract=CONTRACT, query=q, device=source.device, + scratch_bytes=lambda t: 0, materialize=materialize, + compile_jobs=lambda t, d: (CompileJob.create( + "ignition.components.residual_short_conv:compile_convolution", payload, t, d.ordinal),)) + + def benchmark(state): + def inputs(): + values = tuple(torch.empty_strided((2, *t.shape[1:]) if index == 2 else t.shape, + t.stride(), dtype=t.dtype, device=t.device) + if index != 1 else t for index, t in enumerate(self.arguments)) + x, _, h, states, starts, lengths, cu, _ = values + x.normal_(std=.2) + h.normal_(std=.2) + states.zero_() + states[0] = 1 + starts.fill_(weight.shape[1]) + lengths.zero_() + lengths[0] = source.shape[0] + cu.fill_(source.shape[0]) + cu[0] = 0 + return values, h.clone(), x.clone() + values, history_seed, source_seed = benchmark_resource(session, ("residual_short_conv", name), inputs) + return PreparedCall(run=lambda: state.run(values), output=values[-1], + produce=lambda: values[0].copy_(source_seed), + reset=lambda: values[2].copy_(history_seed), owners=(values, history_seed, source_seed)) + declare(session, (self.plan.request(name=name, + prepare_call=lambda state: replace(benchmark(state), owners=()), benchmark_call=benchmark),)) + + def __call__(self): + _execute(*self.arguments, self.plan.handle) + return self.arguments[-1] diff --git a/ignition/preparation/runtime_package_pb2.py b/ignition/preparation/runtime_package_pb2.py index c111819b4..0f2bc89f6 100644 --- a/ignition/preparation/runtime_package_pb2.py +++ b/ignition/preparation/runtime_package_pb2.py @@ -24,7 +24,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15runtime_package.proto\x12\rflare.runtime\"\x9c\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\npackage_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\xcf\x03\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12/\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestJ\x04\x08\x04\x10\x05\"\xff\x05\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x14\n\x0cjoint_tuning\x18\x17 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x19\n\x11\x63ollective_tuning\x18\x19 \x01(\t\x12\x1e\n\x16\x63ollective_ladder_json\x18\x1a \x01(\t\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x42\x1b\n\x19_expert_scale_compression\"\xaa\x03\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\tB\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budget\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\x8b\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\x86\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xb1\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"k\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xcf\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\x80\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\"E\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xc3\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"v\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xfc\x01\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xfa\x06\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(*|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\xf5\x01\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\x93\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07*\x91\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05*\xd1\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t*\x98\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t*D\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*(\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15runtime_package.proto\x12\rflare.runtime\"\x9c\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\npackage_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\xcf\x03\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12/\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestJ\x04\x08\x04\x10\x05\"\xff\x05\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x14\n\x0cjoint_tuning\x18\x17 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x19\n\x11\x63ollective_tuning\x18\x19 \x01(\t\x12\x1e\n\x16\x63ollective_ladder_json\x18\x1a \x01(\t\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x42\x1b\n\x19_expert_scale_compression\"\xaa\x03\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\tB\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budget\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\x8b\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\x86\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xb1\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"k\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xcf\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\x80\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\"E\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xc3\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"v\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xfc\x01\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xfa\x06\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(*|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\xf5\x01\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\xa1\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07\x12\x0c\n\x08TML_JSON\x10\x08*\xa6\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05\x12\x13\n\x0f\x43ONTENT_HEADERS\x10\x06*\xd1\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t*\x98\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t*D\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*(\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -44,25 +44,25 @@ _globals['_GRAPHOPERATION']._serialized_start=15737 _globals['_GRAPHOPERATION']._serialized_end=15982 _globals['_TOOLPARSERKIND']._serialized_start=15985 - _globals['_TOOLPARSERKIND']._serialized_end=16132 - _globals['_REASONINGPARSERKIND']._serialized_start=16135 - _globals['_REASONINGPARSERKIND']._serialized_end=16280 - _globals['_IMAGEPREPARATIONKIND']._serialized_start=16283 - _globals['_IMAGEPREPARATIONKIND']._serialized_end=16620 - _globals['_IMAGELAYOUTKIND']._serialized_start=16623 - _globals['_IMAGELAYOUTKIND']._serialized_end=16903 - _globals['_PROMPTENCODER']._serialized_start=16905 - _globals['_PROMPTENCODER']._serialized_end=16973 - _globals['_TEMPLATEENCODING']._serialized_start=16975 - _globals['_TEMPLATEENCODING']._serialized_end=17041 - _globals['_MEMORY']._serialized_start=17043 - _globals['_MEMORY']._serialized_end=17090 - _globals['_CAPACITY']._serialized_start=17092 - _globals['_CAPACITY']._serialized_end=17132 - _globals['_RELOCATIONKIND']._serialized_start=17134 - _globals['_RELOCATIONKIND']._serialized_end=17179 - _globals['_DRAFTSOURCE']._serialized_start=17181 - _globals['_DRAFTSOURCE']._serialized_end=17233 + _globals['_TOOLPARSERKIND']._serialized_end=16146 + _globals['_REASONINGPARSERKIND']._serialized_start=16149 + _globals['_REASONINGPARSERKIND']._serialized_end=16315 + _globals['_IMAGEPREPARATIONKIND']._serialized_start=16318 + _globals['_IMAGEPREPARATIONKIND']._serialized_end=16655 + _globals['_IMAGELAYOUTKIND']._serialized_start=16658 + _globals['_IMAGELAYOUTKIND']._serialized_end=16938 + _globals['_PROMPTENCODER']._serialized_start=16940 + _globals['_PROMPTENCODER']._serialized_end=17008 + _globals['_TEMPLATEENCODING']._serialized_start=17010 + _globals['_TEMPLATEENCODING']._serialized_end=17076 + _globals['_MEMORY']._serialized_start=17078 + _globals['_MEMORY']._serialized_end=17125 + _globals['_CAPACITY']._serialized_start=17127 + _globals['_CAPACITY']._serialized_end=17167 + _globals['_RELOCATIONKIND']._serialized_start=17169 + _globals['_RELOCATIONKIND']._serialized_end=17214 + _globals['_DRAFTSOURCE']._serialized_start=17216 + _globals['_DRAFTSOURCE']._serialized_end=17268 _globals['_PROTECTEDINDEX']._serialized_start=41 _globals['_PROTECTEDINDEX']._serialized_end=197 _globals['_SIGNEDGROUP']._serialized_start=199 diff --git a/ignition/recipes/__init__.py b/ignition/recipes/__init__.py index 1364eae62..0c4400bc7 100644 --- a/ignition/recipes/__init__.py +++ b/ignition/recipes/__init__.py @@ -33,8 +33,9 @@ def recipes() -> tuple[Recipe, ...]: from .nemotron_h.recipe import RECIPE as nemotron_h from .minimax_m3.recipe import RECIPE as minimax_m3 from .muse_spark.recipe import RECIPE as muse_spark + from .inkling.recipe import RECIPE as inkling - return qwen38, qwen38_dense, glm53, deepseek41, deepseek4, mimo_v2, kimi3, step5, nemotron_h, minimax_m3, gemma4, muse_spark + return qwen38, qwen38_dense, glm53, deepseek41, deepseek4, mimo_v2, kimi3, step5, nemotron_h, minimax_m3, gemma4, muse_spark, inkling def snapshot_directory(hub_cache: Path, checkpoint: Checkpoint) -> Path: diff --git a/ignition/recipes/inkling/__init__.py b/ignition/recipes/inkling/__init__.py new file mode 100644 index 000000000..3622a63c6 --- /dev/null +++ b/ignition/recipes/inkling/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling-Small NVFP4 text preparation.""" diff --git a/ignition/recipes/inkling/assets/chat_template.patch.json b/ignition/recipes/inkling/assets/chat_template.patch.json new file mode 100644 index 000000000..f2eeae035 --- /dev/null +++ b/ignition/recipes/inkling/assets/chat_template.patch.json @@ -0,0 +1,15 @@ +{ + "source": { + "repository": "thinkingmachines/Inkling-Small-NVFP4", + "revision": "b6a99534467840620d411e4cd4ad5819b2610d9c", + "filename": "chat_template.jinja" + }, + "source_sha256": "0aa1aa0c729d90176dcaa00c440c8faffca2957ffb2cc4b79456ee6d02bcf43b", + "result_sha256": "15794c8e135ef68c22a1428c1b4d56791070fdf0b7cc32eb0a6ad56afbdb9661", + "insertions": [ + 1827, + 2156, + 6113, + 6200 + ] +} diff --git a/ignition/recipes/inkling/attention.py b/ignition/recipes/inkling/attention.py new file mode 100644 index 000000000..fdfd11d15 --- /dev/null +++ b/ignition/recipes/inkling/attention.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Paged attention with learned relative bias and residual K/V convolutions.""" + +from dataclasses import dataclass + +import torch + +from ignition.components.collectives import PreparedChunkedAllReduce +from ignition.components.linear import UnquantizedProjection +from ignition.components.paged_attention import PreparedPagedKVWriter +from ignition.components.relative_paged_attention import PreparedRelativePagedAttention +from ignition.components.residual_short_conv import PreparedResidualShortConvolution +from ignition.components.window_attention import stage_windows, commit_window +from .model import norm +from .pool import PAGE_TOKENS + + +@dataclass(frozen=True) +class AttentionScratch: + projected: torch.Tensor + query: torch.Tensor + key_source: torch.Tensor + value_source: torch.Tensor + key: torch.Tensor + value: torch.Tensor + relative_source: torch.Tensor + relative: torch.Tensor + attended: torch.Tensor + partial: torch.Tensor + output: torch.Tensor + window_key: torch.Tensor + window_value: torch.Tensor + + @classmethod + def allocate(cls, config, shard, tokens, *, requests, buffers): + geometries = [config.attention(i) for i in range(config.layers)] + if len({(a.heads, a.kv_heads, a.key_dim) for a in geometries}) != 1: + raise ValueError("Inkling scratch requires matching global and sliding head geometry") + a = geometries[0] + heads, kv = a.local(shard) + drel = config.text["d_rel"] + window, extent = max(a.window for a in geometries), max(a.relative_extent for a in geometries) + pages = requests * -(-(window + (tokens + requests - 1) // requests) // PAGE_TOKENS) + def zeros(*shape): + return buffers.zeros(shape, torch.bfloat16) + return cls(zeros(tokens, (heads + 2 * kv) * a.key_dim + heads * drel), + zeros(tokens, heads, a.key_dim), zeros(tokens, kv * a.key_dim), zeros(tokens, kv * a.key_dim), + zeros(tokens, kv, a.key_dim), zeros(tokens, kv, a.key_dim), + zeros(tokens, heads, drel), zeros(tokens, heads, extent), zeros(tokens, heads, a.key_dim), + zeros(tokens, config.hidden), zeros(tokens, config.hidden), + zeros(pages, PAGE_TOKENS, kv, a.key_dim), zeros(pages, PAGE_TOKENS, kv, a.key_dim)) + + def rows(self, tokens): + return type(self)(*(getattr(self, name) if name.startswith("window_") else getattr(self, name)[:tokens] + for name in self.__dataclass_fields__)) + + +class PreparedAttention(torch.nn.Module): + def __init__(self, layer, weights, config, source, scratch, metadata, pool, *, mode, + runtime, coordinator, session, name, buffers, cache_metadata): + super().__init__() + self.source = source + if mode not in ("prefill", "decode"): + raise ValueError("Inkling supports ordinary prefill and decode") + self.geometry, self.scratch, self.metadata, self.mode = config.attention(layer), scratch, metadata, mode + c, a, s = config.text, self.geometry, scratch + self.projection = UnquantizedProjection(source, weights.qkv_relative, s.projected, + session=session, name=name + ".qkv_relative") + self.query_norm, self.key_norm = norm(weights.query_norm, c["rms_norm_eps"]), norm(weights.key_norm, c["rms_norm_eps"]) + self.key_conv = PreparedResidualShortConvolution(s.key_source, weights.key_conv, + pool.convolution(layer, "key"), metadata, s.key.flatten(1), session=session, name=name + ".key_conv") + self.value_conv = PreparedResidualShortConvolution(s.value_source, weights.value_conv, + pool.convolution(layer, "value"), metadata, s.value.flatten(1), session=session, name=name + ".value_conv") + self.relative = s.relative.flatten()[:s.query.shape[0] * s.query.shape[1] * a.relative_extent].view( + s.query.shape[0], s.query.shape[1], a.relative_extent) + self.relative_projection = UnquantizedProjection(s.relative_source.flatten(0, 1), weights.relative, + self.relative.flatten(0, 1), session=session, name=name + ".relative") + self.log_floor, self.log_alpha = c["log_scaling_n_floor"], c["log_scaling_alpha"] + self.output_projection = UnquantizedProjection(s.attended.flatten(1), weights.output, s.partial, + session=session, name=name + ".output") + self.reduction = PreparedChunkedAllReduce(s.partial, s.output, runtime=runtime, + coordinator=coordinator, session=session, name=name + ".reduce") + self.key_cache, self.value_cache = pool.cache(layer, "key"), pool.cache(layer, "value") + if a.window > 0: + self.lengths = buffers.zeros(metadata.lengths.shape, torch.int32) + self.slots = buffers.zeros(metadata.positions.shape, torch.int64).fill_(-1) + count = metadata.lengths.numel() * -(-(a.window + metadata.max_query_tokens) // PAGE_TOKENS) + self.staged_key, self.staged_value = s.window_key[:count], s.window_value[:count] + self.pages = torch.arange(count, dtype=torch.int32, device=source.device).view(metadata.lengths.numel(), -1) + key, value = self.staged_key, self.staged_value + self.window_stride = pool.window_page_stride(layer) + self.writer = PreparedPagedKVWriter(s.key, s.value, pool.window_pages(layer, "key"), + pool.window_pages(layer, "value"), self.slots, session=session, name=name + ".ring_write") if mode == "decode" else None + else: + self.slots, self.lengths = cache_metadata.slots, cache_metadata.lengths + key, value, self.pages = self.key_cache, self.value_cache, metadata.page_table + self.writer = PreparedPagedKVWriter(s.key, s.value, key, value, self.slots, + session=session, name=name + ".cache_write") + self.attention = PreparedRelativePagedAttention(s.query, key, value, self.pages, self.lengths, + metadata.query_start_loc, self.relative, s.attended, window=a.window - 1 if a.window > 0 else -1, + softmax_scale=1. / a.key_dim, session=session, name=name + ".attention") + + def forward(self, hidden_states, **kwargs): + hidden = self.source.copy_(hidden_states.reshape_as(self.source)) + s, m, a = self.scratch, self.metadata, self.geometry + heads, kv, dim = s.query.shape[1], s.key.shape[1], a.key_dim + q, k, v, r = self.projection(hidden).split((heads * dim, kv * dim, kv * dim, + s.relative_source.shape[1] * s.relative_source.shape[2]), -1) + s.query.copy_(self.query_norm(q.view_as(s.query))) + s.key_source.copy_(k) + s.value_source.copy_(v) + self.key_conv() + self.value_conv() + s.key.copy_(self.key_norm(s.key)) + s.relative_source.copy_(r.view_as(s.relative_source)) + self.relative_projection(s.relative_source.flatten(0, 1)) + if a.window < 0: + if self.log_floor is not None: + tau = 1. + self.log_alpha * torch.log(((m.positions.clamp_min(0) + 1).float() / self.log_floor).clamp_min(1.)) + s.query.copy_(s.query.float() * tau[:, None, None]) + self.relative.copy_(self.relative.float() * tau[:, None, None]) + self.writer() + else: + stage_windows(self.key_cache, s.key, self.staged_key, m) + stage_windows(self.value_cache, s.value, self.staged_value, m) + self.lengths.copy_(m.starts.clamp(max=a.window).int() + m.lengths) + self.attention() + if a.window > 0: + if self.mode == "prefill": + commit_window(self.key_cache, s.key, m.state_rows[0], m.starts[0], m.lengths[0]) + commit_window(self.value_cache, s.value, m.state_rows[0], m.starts[0], m.lengths[0]) + else: + self.slots.copy_(torch.where(m.positions >= 0, + m.state_rows[m.requests] * self.window_stride * PAGE_TOKENS + m.positions.remainder(a.window), -1)) + self.writer() + return self.reduction(self.output_projection(s.attended.flatten(1))).view_as(hidden_states), None + + def scratch_tensors(self): + return (self.lengths, self.slots) if self.geometry.window > 0 else () diff --git a/ignition/recipes/inkling/bootstrap.py b/ignition/recipes/inkling/bootstrap.py new file mode 100644 index 000000000..649389755 --- /dev/null +++ b/ignition/recipes/inkling/bootstrap.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepare Inkling text graphs and complete continuation storage for native serving.""" + +import contextlib +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import torch + +from ignition.components.capacity import batch_capacities, prefill_capacities, request_capacity +from ignition.components.completion import CompletionOutputs, VECTOR_TOKENS_FIELD +from ignition.components.paged_batch import BatchInputs, Metadata, PreparedBatch +from ignition.components.paged_generation import PreparedGeneration +from ignition.components.paged_maintenance import PreparedMaintenance +from ignition.components.paged_resume import PreparedResume +from ignition.components.parallel import TensorParallelShard +from ignition.components.prompt_logprobs import PreparedScoredPrefill, PromptScoring, prefill_modes +from ignition.components.sampling import AdmissionBuffers, DeviceRequestState +from ignition.components.sm103 import is_sm103 +from ignition.components.state_transfer import StateCommands +from ignition.preparation.capture import capture_forwards +from ignition.preparation.checkpoint import inspect_indexed_checkpoint +from ignition.preparation.disposable import storage_ranges +from ignition.preparation.execution import GraphSignature +from ignition.preparation.host_memory import release_unused +from ignition.preparation.model import PreparedModel +from ignition.preparation.rebuild_manifest import declare_weights +from ignition.preparation.scratch import GraphBufferPool, ScratchArena +from ignition.preparation.tuning import RecordedPreparationSession, with_autotune_effort +from ignition.preparation.tuning_replicas import TuningReplica +from ignition.progress import phase + +from .contract import prepare as prepare_contract +from .decoder import PreparedDecoder, Scratch +from .frontend import prepare_frontend, runtime_assets +from .pool import PAGE_TOKENS, ContinuationPool, continuation_layout, page_bytes +from .weights import ModelWeights + + +@dataclass(frozen=True) +class PreparationConfig: + collective_tuning: str = "static" + collective_ladder: dict | None = None + prompt_logprobs: bool = False + compile_workers: int | None = None + native_dense_activations: bool = False + lock_gpu_clocks: bool = False + autotune_effort: str = "default" + tuning_replica: TuningReplica | None = None + device: int = 0 + context: int = 262144 + prefill_chunk_size: int = 4096 + max_active: int = 4 + snapshot_budget_bytes: int = 4 << 30 + headroom_bytes: int = 4 << 30 + compile_decoder: bool = True + retain_graphs: bool = False + kernel_cache: Path | None = None + stream_overlap: bool = True + + def __post_init__(self): + request_capacity(self.max_active) + if not PAGE_TOKENS <= self.context <= 262144 or self.context % PAGE_TOKENS: + raise ValueError("Inkling context must be 128-aligned in [128,262144]") + if not 64 <= self.prefill_chunk_size <= self.context or self.prefill_chunk_size % 64: + raise ValueError("Inkling prefill chunk must be 64-aligned and fit the context") + if self.snapshot_budget_bytes <= 0 or self.headroom_bytes < 0: + raise ValueError("snapshot budget must be positive and headroom nonnegative") + + +@torch.no_grad() +@with_autotune_effort +def prepare(snapshot, config, *, progress=None, package_storage): + from .recipe import RECIPE + + snapshot = Path(snapshot).resolve() + shard = TensorParallelShard(0, 1) + device = torch.device("cuda", config.device) + torch.cuda.set_device(device) + if not is_sm103(device): + raise ValueError("Inkling preparation requires an SM103 GPU") + with phase(progress, "Inspect checkpoint"): + manifest = inspect_indexed_checkpoint(snapshot) + headers = [s.header_sha256 for s in manifest.shards] + weights = ModelWeights.load(manifest, device, shard=shard, progress=progress, package_storage=package_storage) + del manifest + release_unused() + transient = contextlib.ExitStack() + transient.enter_context(package_storage.transient()) + layout = continuation_layout(weights.config, shard) + snapshots = layout.snapshot_capacity(config.snapshot_budget_bytes) + if snapshots < 1: + raise ValueError("snapshot budget must hold one complete Inkling continuation") + slots, blocks = request_capacity(config.max_active), config.context // PAGE_TOKENS + tokens = max(config.prefill_chunk_size, slots) + state_rows, pages = slots + snapshots, (config.prefill_chunk_size + PAGE_TOKENS - 1) // PAGE_TOKENS + 2 * slots + total_memory = torch.cuda.mem_get_info(device)[1] + with phase(progress, "Allocate model state"): + pool = ContinuationPool.allocate(weights.config, shard, state_rows + 1, pages, device, + storage=package_storage, maximum_pages=total_memory // page_bytes(weights.config, shard), + maximum_rows=total_memory // layout.row_bytes, backed_slots=min(state_rows + 1, 1 + 2 * slots)) + vocabulary = weights.config.vocabulary + requests = DeviceRequestState.allocate(device, vocab_size=vocabulary, capacity=slots) + inputs = BatchInputs.allocate(tokens, blocks, device, capacity=slots) + admission = AdmissionBuffers.allocate(device, vocab_size=vocabulary, capacity=slots) + commands = StateCommands.allocate(device, capacity=slots) + frame = torch.zeros(1, dtype=torch.int32, device=device) + sequence = torch.zeros(1, dtype=torch.int64, device=device) + completion = CompletionOutputs.allocate((2, slots, VECTOR_TOKENS_FIELD + 1), device=device) + coordinator = None + identity = hashlib.sha256(json.dumps(dict(config=weights.config.text, quantization=weights.config.quantization, + headers=headers, + kv_dtype="bfloat16", world_size=shard.world_size, contract="inkling.text.v1"), sort_keys=True).encode()).hexdigest() + session = RecordedPreparationSession(compile_workers=config.compile_workers, + collective_tuning=config.collective_tuning, collective_ladder=config.collective_ladder, autotune_effort=config.autotune_effort, + tuning_replica=config.tuning_replica, native_dense_activations=config.native_dense_activations, + lock_gpu_clocks=config.lock_gpu_clocks, device=device, checkpoint=identity, + workload_schema="inkling", numerical_policy="default", coordinator=coordinator, + headroom_bytes=config.headroom_bytes, benchmark_storage=package_storage) + session.__enter__() + arena = ScratchArena(device, overlap=config.stream_overlap) + session.register_scratch(arena) + graph_buffers, private_buffers = (GraphBufferPool(device, chunk_bytes=2 << 20) for _ in range(2)) + with package_storage.scratch_pool() as scratch_pool: + prefill_storage = Scratch.allocate(weights.config, shard, config.prefill_chunk_size, 1, device, + buffers=graph_buffers.cursor()) + decode_storage = Scratch.allocate(weights.config, shard, slots, slots, device, buffers=graph_buffers.cursor()) + buffers = dict(inputs.buffers(), **commands.buffers(), + **{name: getattr(admission, name) for name in admission.__dataclass_fields__}, + state_pool=pool.backing, memory_capacity=pool.memory_capacity, request_pending_token=requests.pending_token, + sampling_grammar_mask=requests.grammar_mask, frame_index=frame, submission_sequence=sequence, + **completion.buffers()) + scoring = PromptScoring.allocate(config, device, buffers, frame=frame) + forwards, signatures, metadata = {}, {}, {} + prefills, batches = prefill_capacities(config.prefill_chunk_size), batch_capacities(config.max_active) + with phase(progress, "Construct graph catalog"): + def add(name, forward, kind, rows, tokens, fields): + if kind == "scored_prefill": + forward = PreparedScoredPrefill(forward, requests, inputs) + fields = (*fields, "prompt_target_tokens") + forwards[name] = forward + signatures[name] = GraphSignature(kind, rows, tokens, tuple(fields)) + + forward_inputs = (*inputs.buffers(), "sampling_grammar_mask") + for kind, mode, sizes in prefill_modes(prefills, reversed(batches), scoring): + for capacity in sizes: + rows = 1 if mode == "prefill" else capacity + name = f"{kind}{capacity}" + private = private_buffers.cursor() + m = metadata[name] = Metadata.allocate(capacity, rows, blocks, device, buffers=private) + scratch = (prefill_storage if mode == "prefill" else decode_storage).rows(capacity, rows) + decoder = PreparedDecoder(weights, scratch, m, pool, mode=mode, runtime=None, + embedding_runtime=None, vocabulary_runtime=None, coordinator=coordinator, + session=session, name=name, workspace=arena, + buffers=private, scoring=scoring if kind == "scored_prefill" else None) + batch = PreparedBatch(inputs, requests, m, mode=mode, shard=shard, pool=pool, buffers=private) + forward = PreparedGeneration(decoder, batch, completion, frame, sequence, + runtime=None, coordinator=coordinator, session=session, + name=name + ".generation", workspace=arena, buffers=private) + add(name, forward, kind, rows, capacity if mode == "prefill" else 1, forward_inputs) + row_inputs = ("request_state_rows", "row_slot_ids", "row_generations", "live_rows") + for capacity in reversed(batches): + name = f"resume{capacity}" + forward = PreparedResume(weights, requests, pool, inputs, completion, frame, sequence, rows=capacity, + runtime=None, vocabulary_runtime=None, coordinator=coordinator, + session=session, name=name, buffers=private_buffers.cursor()) + add(name, forward, "resume", capacity, 1, (*row_inputs, "sampling_grammar_mask")) + for mode in ("init", "restore", "snapshot"): + name = f"{mode}{capacity}" + forward = PreparedMaintenance(mode, requests, pool, commands, inputs, completion, frame, sequence, + runtime=None, coordinator=coordinator, session=session, name=name, capacity=capacity, + admission_buffers=admission, draft_state=False, buffers=private_buffers.cursor()) + fields = row_inputs if mode == "snapshot" else ("request_state_rows", *admission.__dataclass_fields__) + add(name, forward, mode, capacity, 1, (*fields, "page_tables", *commands.buffers())) + with phase(progress, "Prepare and tune kernels") as stage, transient: + tuning = session.tune(show_progress=progress is not None, console=stage.console) + stream, graph_pool = torch.cuda.Stream(device=device), package_storage.graph_pool.id + if config.compile_decoder: + scratch_pool.release_backing() + + def materialize(): + scratch_pool.materialize() + pool.clear_for_preparation() + + try: + graphs, compiled = capture_forwards(forwards, signatures, session=session, device=device, stream=stream, + pool=graph_pool, collective=None, coordinator=coordinator, compile_decoder=config.compile_decoder, + progress=progress, cache_root=config.kernel_cache, retain_graphs=config.retain_graphs, + materialize=materialize, warmup_storage=package_storage, + compile_kinds=("prefill", "scored_prefill", "decode", "resume")) + finally: + scratch_pool.materialize() + session.freeze() + pool.clear_for_preparation() + torch.cuda.synchronize(device) + release_unused() + assets = runtime_assets(snapshot) + frontend = prepare_frontend(snapshot, eos_token_ids=weights.config.text["eos_token_id"]) + server_config = dict(identity=identity, model_id=snapshot.name, max_sequence_tokens=config.context, + prefill_chunk_size=config.prefill_chunk_size, pages=pages, state_rows=state_rows, snapshots=snapshots, + page_tokens=PAGE_TOKENS, frontend=frontend, sampling_defaults=RECIPE.sampling_defaults.as_dict(), assets=assets, + model_contract=prepare_contract(signatures, buffers, pool, vocabulary=vocabulary)) + free, total = torch.cuda.mem_get_info(device) + memory = dict(rank=0, world_size=1, device=config.device, weights_bytes=weights.allocated_bytes, + mapped_host_bytes=0, offloaded_bytes=0, continuation_bytes=pool.backing.nbytes, state_rows=state_rows, + preparation_state_rows=int(pool.memory_capacity[0].item()), + preparation_state_bytes=int(pool.memory_capacity[0].item()) * layout.row_bytes, + pages=pages, page_bytes=page_bytes(weights.config, shard), page_tokens=PAGE_TOKENS, + kv_bytes=pages * page_bytes(weights.config, shard), kv_dtype="bfloat16", completion_output_bytes=completion.nbytes, + operator_scratch_bytes=arena.nbytes, graphs=len(graphs), graph_buffer_bytes=graph_buffers.nbytes, + private_buffer_bytes=private_buffers.nbytes, prefill_capacities=prefills, free_device_bytes=free, + total_device_bytes=total, headroom_bytes=config.headroom_bytes, tuning=tuning, compiled_decoder=config.compile_decoder) + if scoring is not None: + memory.update(scoring.memory_report()) + disposable = [prefill_storage, decode_storage, arena.tensor, metadata, graph_buffers.chunks, private_buffers.chunks] + for forward in forwards.values(): + if isinstance(forward, PreparedScoredPrefill): + forward = forward.forward + if hasattr(forward, "scratch_tensors"): + disposable.append(forward.scratch_tensors()) + if hasattr(forward, "completion") and hasattr(forward.completion, "scratch_tensors"): + disposable.append(forward.completion.scratch_tensors) + if hasattr(forward, "decoder"): + disposable.append(forward.decoder.scratch_tensors()) + return PreparedModel(rebuild_weights=declare_weights(weights, components=("embedding", "embedding_norm", "norm", "head")), + device=config.device, graphs=graphs, buffers=buffers, signatures=signatures, max_active=config.max_active, + session=session, server_config=server_config, memory_report=memory, + export_zero_ranges=(*(() if scoring is None else scoring.zero_ranges()), *storage_ranges(disposable), *completion.zero_ranges()), + resources=(scoring, weights, pool, requests, inputs, admission, commands, arena, forwards, prefill_storage, + decode_storage, metadata, compiled, stream, graph_pool, session, coordinator, + scratch_pool, graph_buffers, private_buffers), + close_resources=(() if scoring is None else (scoring,))) diff --git a/ignition/recipes/inkling/config.py b/ignition/recipes/inkling/config.py new file mode 100644 index 000000000..88cc52d49 --- /dev/null +++ b/ignition/recipes/inkling/config.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling text geometry, normalized with the checkpoint's canonical config.""" + +from dataclasses import dataclass +import json +from pathlib import Path + + +@dataclass(frozen=True) +class AttentionGeometry: + heads: int + kv_heads: int + key_dim: int + window: int + relative_extent: int + + @property + def value_dim(self): + return self.key_dim + + def local(self, shard): + shard.partition(self.heads) + first, last = shard.replicated_partition(self.kv_heads) + return self.heads // shard.world_size, last - first + + +@dataclass(frozen=True) +class ModelConfig: + text: dict + quantization: dict + + @classmethod + def load(cls, snapshot): + snapshot = Path(snapshot) + return cls.from_dict(json.loads((snapshot / "config.json").read_text()), + json.loads((snapshot / "hf_quant_config.json").read_text()).get("quantization")) + + @classmethod + def from_dict(cls, config, quantization): + from transformers.models.inkling.configuration_inkling import InklingTextConfig + + if (config.get("model_type") != "inkling_mm_model" + or config.get("architectures") != ["InklingForConditionalGeneration"]): + raise ValueError("Inkling requires InklingForConditionalGeneration") + if config.get("quantization_config"): + raise ValueError("Inkling NVFP4 quantization must be declared in hf_quant_config.json") + c = InklingTextConfig.from_dict(config["text_config"]).to_dict() + if (c.get("dtype") != "bfloat16" or c["hidden_act"] != "silu" or c["q_bias"] or c["o_bias"] + or not c["use_sconv"] or not c["use_embed_norm"] or not c["shared_expert_sink"] + or c["gate_activation"] != "sigmoid" or not c["norm_after_topk"] + or not c["use_gate_bias"] or not c["use_global_scale"] + or c["final_logit_softcapping"] is not None or c.get("tie_word_embeddings", False)): + raise ValueError("unsupported Inkling normalization, convolution, or routing arithmetic") + if (len(c["layer_types"]) != c["num_hidden_layers"] + or len(c["mlp_layer_types"]) != c["num_hidden_layers"] + or any(t not in ("hybrid", "hybrid_sliding") for t in c["layer_types"]) + or any(t not in ("dense", "sparse") for t in c["mlp_layer_types"]) + or c["conv_kernel_size"] != 4 or c["head_dim"] != 128 + or c["swa_head_dim"] != 128 or c["sliding_window_size"] % 128 + or c["n_shared_experts"] <= 0 or c["n_routed_experts"] & (c["n_routed_experts"] - 1)): + raise ValueError("unsupported Inkling layer or cache geometry") + c["eos_token_id"] = config["eos_token_id"] + if (not isinstance(quantization, dict) or quantization.get("quant_algo") != "NVFP4" + or quantization.get("kv_cache_quant_algo") != "none" or quantization.get("group_size") != 16): + raise ValueError("Inkling requires declared NVFP4 weights and activations with unquantized KV") + modelopt = quantization.get("modelopt_quant_config", {}) + quantizers = modelopt.get("quant_cfg", {}) + expected = dict(num_bits=[2, 1], block_sizes={"-1": 16, "type": "dynamic", "scale_bits": [4, 3]}, + axis=None, enable=True) + if (modelopt.get("algorithm") != "max" + or any(quantizers.get(name) != expected for name in ("*weight_quantizer", "*input_quantizer"))): + raise ValueError("Inkling requires calibrated NVFP4 weight and input quantizers") + if any(value not in ({"enable": False}, {"*": {"enable": False}}) + for name, value in quantizers.items() if name not in ("*weight_quantizer", "*input_quantizer")): + raise ValueError("unsupported Inkling quantizer override") + exclusions = quantization.get("exclude_modules") + if not isinstance(exclusions, list) or any(not isinstance(name, str) or not name for name in exclusions): + raise ValueError("Inkling requires an explicit quantization exclusion list") + result = cls(c, quantization) + ordinary = ["model.llm." + name for name in ("embed", "embed_norm", "norm", "unembed")] + for layer, kind in enumerate(c["mlp_layer_types"]): + prefix = f"model.llm.layers.{layer}." + ordinary.extend(prefix + name for name in ("attn", "attn_norm", "attn_sconv", "mlp_norm", "mlp_sconv")) + ordinary.extend(prefix + name for name in + (("mlp.w13_dn", "mlp.w2_md", "mlp.global_scale") if kind == "dense" + else ("mlp.gate", "mlp.shared_experts"))) + if not all(result.excluded(name) for name in ordinary): + raise ValueError("Inkling requires unquantized attention, dense/shared experts, routers and norms") + if not result.quantized_routed_layers: + raise ValueError("Inkling NVFP4 requires quantized routed experts") + return result + + def excluded(self, name): + return any(name == prefix or name.startswith(prefix + ".") + for prefix in self.quantization["exclude_modules"]) + + @property + def quantized_routed_layers(self): + return tuple(layer for layer, kind in enumerate(self.text["mlp_layer_types"]) + if kind == "sparse" and not self.excluded(f"model.llm.layers.{layer}.mlp.experts")) + + @property + def layers(self): + return self.text["num_hidden_layers"] + + @property + def hidden(self): + return self.text["hidden_size"] + + @property + def vocabulary(self): + return self.text["unpadded_vocab_size"] + + def attention(self, layer): + c = self.text + local = c["layer_types"][layer] == "hybrid_sliding" + return AttentionGeometry(c["swa_num_attention_heads"] if local else c["num_attention_heads"], + c["swa_num_key_value_heads"] if local else c["num_key_value_heads"], + c["swa_head_dim"] if local else c["head_dim"], c["sliding_window_size"] if local else -1, + c["sliding_window_size"] if local else c["rel_extent"]) + + def validate_shard(self, shard): + for layer in range(self.layers): + self.attention(layer).local(shard) + for extent in (self.hidden, self.text["intermediate_size"], self.text["moe_intermediate_size"]): + shard.partition(extent, alignment=64) + + def vocabulary_partition(self, shard): + width = -(-self.vocabulary // (shard.world_size * 64)) * 64 + return shard.rank * width, min((shard.rank + 1) * width, self.vocabulary), width diff --git a/ignition/recipes/inkling/contract.py b/ignition/recipes/inkling/contract.py new file mode 100644 index 000000000..ef6bce7b4 --- /dev/null +++ b/ignition/recipes/inkling/contract.py @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Text graph bindings, complete continuation rows, and paged attention histories.""" + +from ignition.preparation import contract as c +from ignition.preparation import runtime_package_pb2 as p + +from .frontend import FRONTEND +from .pool import PAGE_TOKENS + + +def prepare(signatures, buffers, pool, *, vocabulary): + inputs = {kind: c.text_inputs(kind) for kind in {s.kind for s in signatures.values()}} + continuation = c.state_view("state_pool", pool.layout.row_bytes) + regions = [c.history_region(buffers, f"cache.{name}", tensor, p.PAGED_KEY_VALUE) + for name, tensor in pool.pages.items()] + return c.model_contract(vocabulary=vocabulary, page_tokens=PAGE_TOKENS, + page_tables=[dict(buffer="page_tables", page_offset=0)], + regions=[dict(kind=p.CONTINUATION_STATE, storage=continuation, + tokens_per_record=1, window_tokens=0), *regions], + graphs=c.graph_contracts(signatures, inputs, continuation=continuation, + pending=c.state_view("request_pending_token", 8)), frontend=FRONTEND) diff --git a/ignition/recipes/inkling/decoder.py b/ignition/recipes/inkling/decoder.py new file mode 100644 index 000000000..666710e68 --- /dev/null +++ b/ignition/recipes/inkling/decoder.py @@ -0,0 +1,193 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepared Inkling text layers, shared-expert sinks, and vocabulary projection.""" + +from dataclasses import dataclass + +import torch + +from ignition.components.bf16_experts import BF16ExpertScratch, PreparedBF16Experts +from ignition.components.collectives import PreparedChunkedAllReduce +from ignition.components.embedding import PreparedShardedEmbedding +from ignition.components.linear import UnquantizedProjection +from ignition.components.mlp import MLPScratch, PreparedMLP +from ignition.components.moe import PreparedRoutedExperts +from ignition.components.paged_attention import PagedAttentionMetadata +from ignition.components.residual_short_conv import PreparedResidualShortConvolution +from ignition.components.vocabulary import PreparedVocabularyProjection +from .attention import AttentionScratch, PreparedAttention +from .model import decoder_layer, mix_routes, norm, route +from .pool import PAGE_TOKENS +from .weights import Experts + + +@dataclass(frozen=True) +class Scratch: + embedding: torch.Tensor + local_embedding: torch.Tensor + normalized: torch.Tensor + attention: AttentionScratch + convolved: torch.Tensor + router_logits: torch.Tensor + route_ids: torch.Tensor + route_weights: torch.Tensor + gammas: torch.Tensor + routes: torch.Tensor + reduced_routes: torch.Tensor + bf16: BF16ExpertScratch + dense: MLPScratch + shared: MLPScratch + partial: torch.Tensor + reduced: torch.Tensor + output: torch.Tensor + hidden: torch.Tensor + local_logits: torch.Tensor + logits: torch.Tensor + + @classmethod + def allocate(cls, config, shard, tokens, samples, device, *, buffers): + c = config.text + def zeros(shape, dtype=torch.bfloat16): + return buffers.zeros(shape, dtype) + embedding = zeros((tokens, config.hidden)) + local_embedding = zeros((tokens, config.hidden // shard.world_size)) + normalized = zeros((tokens, config.hidden)) + attention = AttentionScratch.allocate(config, shard, tokens, requests=samples, buffers=buffers) + convolved = zeros((tokens, config.hidden)) + logits = zeros((tokens, c["n_routed_experts"] + c["n_shared_experts"]), torch.float32) + ids = zeros((tokens, c["num_experts_per_tok"]), torch.int32) + weights = zeros(ids.shape, torch.float32) + gammas = zeros((tokens, c["n_shared_experts"]), torch.float32) + shape = (tokens, c["num_experts_per_tok"], config.hidden) + routes, reduced_routes = zeros(shape), zeros(shape) + bf16 = BF16ExpertScratch.allocate(tokens, c["num_experts_per_tok"], c["n_routed_experts"], + c["moe_intermediate_size"] // shard.world_size, buffers=buffers) + dense = MLPScratch.allocate(tokens, config.hidden, c["intermediate_size"] // shard.world_size, device, buffers=buffers) + shared = MLPScratch.allocate(tokens, config.hidden, c["moe_intermediate_size"] // shard.world_size, device, buffers=buffers) + return cls(embedding, local_embedding, normalized, attention, convolved, logits, ids, weights, gammas, + routes, reduced_routes, bf16, dense, shared, zeros((tokens, config.hidden)), + zeros((tokens, config.hidden)), zeros((tokens, config.hidden)), zeros((samples, config.hidden)), + zeros((samples, config.vocabulary_partition(shard)[2])), zeros((samples, config.vocabulary))) + + def rows(self, tokens, samples): + return type(self)(*(getattr(self, field).rows(tokens, self.route_ids.shape[1]) if field == "bf16" + else getattr(self, field).rows(tokens) if field in ("attention", "dense", "shared") + else getattr(self, field)[:samples if field in ("hidden", "local_logits", "logits") else tokens] + for field in self.__dataclass_fields__)) + + +class PreparedFeedForward(torch.nn.Module): + def __init__(self, weights, config, scratch, metadata, *, runtime, coordinator, session, name, workspace): + super().__init__() + self.scratch, self.metadata, self.config, self.weights = scratch, metadata, config, weights + s = scratch + self.dense = None if weights.dense is None else PreparedMLP(s.normalized, weights.dense, s.dense.gate_up, + s.dense.intermediate, s.dense.output, session=session, name=name + ".dense", workspace=workspace, round_silu=False) + self.reduce = PreparedChunkedAllReduce(s.partial, s.reduced, runtime=runtime, + coordinator=coordinator, session=session, name=name + ".reduce") + if self.dense is None: + self.router = UnquantizedProjection(s.normalized, weights.router, s.router_logits, + session=session, name=name + ".router") + if isinstance(weights.experts, Experts): + self.experts = PreparedBF16Experts(s.normalized, weights.experts.gate_up, weights.experts.down, + s.route_ids, s.route_weights, s.routes, metadata.live_counts[:1], scratch=s.bf16, round_silu=False) + else: + self.experts = PreparedRoutedExperts(s.normalized, weights.experts, s.route_ids, + s.route_weights, s.routes, session=session, name=name + ".experts", workspace=workspace) + self.reduce_routes = PreparedChunkedAllReduce(s.routes.flatten(1), s.reduced_routes.flatten(1), + runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduce_routes") + self.shared = tuple(( + UnquantizedProjection(s.normalized, w.gate_up, s.shared.gate_up, session=session, name=f"{name}.shared{index}.gate_up"), + UnquantizedProjection(s.shared.intermediate, w.down, s.shared.output, session=session, name=f"{name}.shared{index}.down")) + for index, w in enumerate(weights.shared)) + + def forward(self, hidden_states): + s, c = self.scratch, self.config.text + s.normalized.copy_(hidden_states.reshape_as(s.normalized)) + if self.dense is not None: + s.partial.copy_(self.dense(s.normalized)) + s.output.copy_(self.reduce(s.partial) * self.weights.scale) + return s.output.view_as(hidden_states) + ids, weights, gammas = route(self.router(s.normalized), self.weights.correction, self.weights.scale, + top_k=c["num_experts_per_tok"], shared_experts=c["n_shared_experts"], route_scale=c["route_scale"]) + valid = torch.arange(s.normalized.shape[0], device=s.normalized.device)[:, None] < self.metadata.live_counts[0] + s.route_ids.copy_(torch.where(valid, ids, -1).int()) + s.route_weights.copy_(torch.where(valid, weights, 0.)) + s.gammas.copy_(torch.where(valid, gammas, 0.)) + self.experts() + s.routes.copy_(torch.where(s.route_ids[..., None] >= 0, s.routes, 0.)) + self.reduce_routes(s.routes.flatten(1)) + routed = mix_routes(s.reduced_routes, weights, ids) + shared = torch.zeros_like(s.output, dtype=torch.float32) + for index, (gate_up, down) in enumerate(self.shared): + gate_up(s.normalized) + gate, up = s.shared.gate_up.float().chunk(2, dim=-1) + s.shared.intermediate.copy_(torch.nn.functional.silu(gate) * up * s.gammas[:, index, None]) + s.partial.copy_(down(s.shared.intermediate)) + shared = shared + self.reduce(s.partial).float() + s.output.copy_(routed + shared.to(s.output.dtype)) + return s.output.view_as(hidden_states) + + +class PreparedConvolution(torch.nn.Module): + def __init__(self, source, weight, history, metadata, output, **kwargs): + super().__init__() + self.source, self.output = source, output + self.operation = PreparedResidualShortConvolution(source, weight, history, metadata, output, **kwargs) + + def forward(self, hidden_states, **kwargs): + self.source.copy_(hidden_states.reshape_as(self.source)) + self.operation() + return self.output.view_as(hidden_states) + + +class PreparedDecoder: + def __init__(self, weights, scratch, metadata, pool, *, mode, runtime, embedding_runtime, + vocabulary_runtime, coordinator, session, name, workspace, buffers, scoring=None): + self.weights, self.scratch, self.metadata, self.pool = weights, scratch, metadata, pool + c, s = weights.config.text, scratch + self.embedding = PreparedShardedEmbedding(weights.embedding, metadata.token_ids, s.local_embedding, + s.embedding, runtime=embedding_runtime, coordinator=coordinator, session=session, + name=name + ".embedding", num_rows=metadata.live_counts[:1]) + self.embedding_norm = norm(weights.embedding_norm, c["rms_norm_eps"]) + self.cache_metadata = PagedAttentionMetadata(metadata, page_tokens=PAGE_TOKENS, buffers=buffers) + self.layers = [] + for index, w in enumerate(weights.layers): + prefix = f"{name}.layer{index}" + attention = PreparedAttention(index, w, weights.config, s.normalized, + s.attention, metadata, pool, mode=mode, runtime=runtime, coordinator=coordinator, + session=session, name=prefix + ".attention", buffers=buffers, cache_metadata=self.cache_metadata) + feedforward = PreparedFeedForward(w, weights.config, s, metadata, runtime=runtime, + coordinator=coordinator, session=session, name=prefix + ".mlp", workspace=workspace) + def convolution(kind, source, weight): + return PreparedConvolution(source, weight, pool.convolution(index, kind), metadata, + s.convolved, session=session, name=prefix + "." + kind + "_conv") + self.layers.append(decoder_layer(weights.config, w, attention, feedforward, + convolution("attention", s.attention.output, w.attention_conv), + convolution("mlp", s.output, w.mlp_conv))) + self.norm = norm(weights.norm, c["rms_norm_eps"]) + self.multiplier = c["logits_mup_width_multiplier"] + self.scoring = None if scoring is None else scoring.prepare(s.embedding, weights.head, + vocabulary=weights.config.vocabulary, session=session, coordinator=coordinator, + name=name + ".prompt", copy_source=True) + self.head = PreparedVocabularyProjection(s.hidden, weights.head, s.local_logits, s.logits, + runtime=vocabulary_runtime, coordinator=coordinator, session=session, name=name + ".head", buffers=buffers) + + def __call__(self): + self.cache_metadata() + s = self.scratch + hidden = self.embedding_norm(self.embedding()) + for layer in self.layers: + hidden = layer(hidden) + if self.scoring is not None: + self.scoring.source.copy_(self.norm(hidden) / self.multiplier) + self.scoring() + s.hidden.copy_(self.scoring.source[self.metadata.sample_indices]) + else: + s.hidden.copy_(self.norm(hidden[self.metadata.sample_indices]) / self.multiplier) + self.head(s.hidden) + + def scratch_tensors(self): + return (self.head.gathered, self.cache_metadata.slots, self.cache_metadata.lengths, + *(layer.self_attn.scratch_tensors() for layer in self.layers)) diff --git a/ignition/recipes/inkling/frontend.py b/ignition/recipes/inkling/frontend.py new file mode 100644 index 000000000..ab9f73612 --- /dev/null +++ b/ignition/recipes/inkling/frontend.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Content-header messages and JSON tool invocations for Inkling text graphs.""" + +from pathlib import Path + +from tokenizers import Tokenizer + +from ignition.preparation import contract as c +from ignition.preparation import runtime_package_pb2 as p +from ignition.preparation.frontend import annotated_template_asset, prepare_frontend as _prepare_frontend + + +FRONTEND = c.frontend(tools=p.TML_JSON, assistant_marker="<|message_model|>", + message_end_markers=["<|end_message|>", "<|content_model_end_sampling|>"], prefix_boundary=None, + rejected_tokens=[200005, 200020, 200023, 200053, 200054]) +FRONTEND["reasoning"] = dict(kind=p.CONTENT_HEADERS, open="<|content_thinking|>", + close="<|end_message|>", wrapping_newlines=0, terminal_markers=[]) + + +def prepare_frontend(snapshot, *, eos_token_ids): + snapshot = Path(snapshot) + tokenizer = Tokenizer.from_file(str(snapshot / "tokenizer.json")) + for marker, expected in {"<|message_model|>": 200001, "<|content_text|>": 200004, + "<|content_model_end_sampling|>": 200006, "<|content_thinking|>": 200008, + "<|end_message|>": 200010, "<|content_invoke_tool_json|>": 200049}.items(): + if tokenizer.token_to_id(marker) != expected: + raise ValueError(f"Inkling requires {marker} token ID {expected}") + eos = [eos_token_ids] if type(eos_token_ids) is int else list(eos_token_ids) + if eos != [200006]: + raise ValueError("Inkling requires the model-end-sampling token as its sole EOS") + return _prepare_frontend(snapshot, eos_token_ids=eos) + + +def runtime_assets(snapshot): + snapshot = Path(snapshot) + return {"tokenizer": {"path": str(snapshot / "tokenizer.json")}, + "chat_template": annotated_template_asset((snapshot / "chat_template.jinja").read_bytes(), + Path(__file__).with_name("assets") / "chat_template.patch.json")} diff --git a/ignition/recipes/inkling/model.py b/ignition/recipes/inkling/model.py new file mode 100644 index 000000000..9ca6b8464 --- /dev/null +++ b/ignition/recipes/inkling/model.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling normalization, FP32 sink routing, route mixing and decoder composition.""" + +import torch + + +def norm(weight, eps): + from transformers.models.inkling.modeling_inkling import InklingRMSNorm + + with torch.device("meta"): + module = InklingRMSNorm(weight.numel(), eps=eps) + module.weight = torch.nn.Parameter(weight, requires_grad=False) + return module.eval() + + +def route(logits, correction, scale, *, top_k, shared_experts, route_scale): + """Select top-k routed experts and normalize their FP32 weights jointly with the shared-expert sinks.""" + routed = logits[..., :-shared_experts] + ids = torch.topk(routed.sigmoid() + correction, top_k, dim=-1, sorted=False).indices + selected = torch.cat((routed.gather(-1, ids), logits[..., -shared_experts:]), dim=-1) + log_probabilities = torch.nn.functional.logsigmoid(selected) + weights = torch.exp(log_probabilities - torch.logsumexp(log_probabilities, dim=-1, keepdim=True)) + weights = weights * route_scale * scale + return ids, weights[..., :top_k], weights[..., top_k:] + + +def mix_routes(routes, weights, ids): + """Accumulate weighted BF16 expert outputs in canonical ascending expert order.""" + order = ids.argsort(dim=-1) + weighted = (routes * weights[..., None]).to(routes.dtype) + ordered = weighted.gather(1, order[..., None].expand_as(weighted)) + result = torch.zeros_like(ordered[:, 0]) + for index in range(ordered.shape[1]): + result = result + ordered[:, index] + return result + + +def decoder_layer(config, weights, attention, mlp, attention_conv, mlp_conv): + from transformers.models.inkling.configuration_inkling import InklingTextConfig + from transformers.models.inkling.modeling_inkling import InklingDecoderLayer + + layer = InklingDecoderLayer.__new__(InklingDecoderLayer) + torch.nn.Module.__init__(layer) + layer.config = InklingTextConfig.from_dict(config.text) + layer.hidden_size = config.hidden + layer.self_attn, layer.mlp = attention, mlp + layer.attn_sconv, layer.mlp_sconv = attention_conv, mlp_conv + layer.input_layernorm = norm(weights.input_norm, config.text["rms_norm_eps"]) + layer.post_attention_layernorm = norm(weights.post_attention_norm, config.text["rms_norm_eps"]) + return layer.eval() diff --git a/ignition/recipes/inkling/pool.py b/ignition/recipes/inkling/pool.py new file mode 100644 index 000000000..3f8038d6c --- /dev/null +++ b/ignition/recipes/inkling/pool.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""BF16 paged KV, local rings, and all four FP32 convolution histories per layer.""" + +from dataclasses import dataclass +import math + +import torch + +from ignition.components.paged_state import PagedStateStorage +from ignition.components.state import StateLayout + +PAGE_TOKENS = 128 +KV_DTYPE = torch.bfloat16 + + +def page_specs(config, shard): + for layer in range(config.layers): + geometry = config.attention(layer) + if geometry.window < 0: + _, heads = geometry.local(shard) + for kind, dim in (("key", geometry.key_dim), ("value", geometry.value_dim)): + yield f"layer{layer}.{kind}", (PAGE_TOKENS * heads * dim * KV_DTYPE.itemsize,) + + +def page_bytes(config, shard): + return sum(shape[0] for _, shape in page_specs(config, shard)) + + +def continuation_layout(config, shard): + regions = [] + for layer in range(config.layers): + geometry = config.attention(layer) + if geometry.window > 0: + _, heads = geometry.local(shard) + for kind, dim in (("key", geometry.key_dim), ("value", geometry.value_dim)): + regions.append((f"layer{layer}.{kind}", (geometry.window, heads, dim), KV_DTYPE)) + regions.extend((name, shape, torch.uint8) for name, shape in page_specs(config, shard)) + for layer in range(config.layers): + geometry = config.attention(layer) + _, heads = geometry.local(shard) + for kind, channels in (("key_conv", heads * geometry.key_dim), + ("value_conv", heads * geometry.value_dim), + ("attention_conv", config.hidden), ("mlp_conv", config.hidden)): + regions.append((f"layer{layer}.{kind}", (channels, config.text["conv_kernel_size"] - 1), torch.float32)) + regions.extend((("last_hidden", (config.hidden,), torch.bfloat16), + ("consumed_tokens", (1,), torch.int64))) + layout = StateLayout.from_specs(regions) + # Rows align to whole KV pages so window_pages can view rings across adjacent rows. + alignment = math.lcm(256, *(math.prod(shape) * dtype.itemsize + for name, shape, dtype in regions if name.startswith("layer") and dtype == KV_DTYPE)) + return StateLayout(layout.regions, (layout.row_bytes + alignment - 1) // alignment * alignment) + + +@dataclass(frozen=True) +class ContinuationPool(PagedStateStorage): + config: object + shard: object + + @classmethod + def allocate(cls, config, shard, slots, pages, device, *, storage=None, maximum_pages=None, maximum_rows=None, + backed_slots=None): + layout = continuation_layout(config, shard) + backing = PagedStateStorage.allocate(layout, page_specs(config, shard), slots, pages, device, + storage=storage, maximum_pages=maximum_pages, maximum_rows=maximum_rows, backed_slots=backed_slots) + return cls(backing.backing, backing.layout, backing.memory_capacity, + backing.pages, backing.reserved_backing, config, shard) + + def cache(self, layer, kind): + geometry = self.config.attention(layer) + name = f"layer{layer}.{kind}" + if geometry.window > 0: + return self.reserved_region(name) + _, heads = geometry.local(self.shard) + dim = geometry.key_dim if kind == "key" else geometry.value_dim + return self.pages[name].view(KV_DTYPE).view(-1, PAGE_TOKENS, heads, dim) + + def window_page_stride(self, layer): + geometry = self.config.attention(layer) + _, heads = geometry.local(self.shard) + record = PAGE_TOKENS * heads * geometry.key_dim * KV_DTYPE.itemsize + if self.layout.row_bytes % record: + raise ValueError("circular continuation rows must align to physical KV pages") + return self.layout.row_bytes // record + + def window_pages(self, layer, kind): + """Expose circular regions as pages with the continuation row stride intact.""" + geometry = self.config.attention(layer) + _, heads = geometry.local(self.shard) + dim = geometry.key_dim if kind == "key" else geometry.value_dim + region = self.layout.region(f"layer{layer}.{kind}") + row_pages = self.window_page_stride(layer) + pages = (self.reserved_backing.shape[0] - 1) * row_pages + geometry.window // PAGE_TOKENS + return self.reserved_backing.view(KV_DTYPE).as_strided( + (pages, PAGE_TOKENS, heads, dim), (PAGE_TOKENS * heads * dim, heads * dim, dim, 1), + storage_offset=region.offset // KV_DTYPE.itemsize) + + def convolution(self, layer, kind): + return self.reserved_region(f"layer{layer}.{kind}_conv") diff --git a/ignition/recipes/inkling/recipe.py b/ignition/recipes/inkling/recipe.py new file mode 100644 index 000000000..9b0210d2b --- /dev/null +++ b/ignition/recipes/inkling/recipe.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling-Small NVFP4 text preparation on one SM103 GPU.""" + +from types import MappingProxyType + +from ignition.recipes.declaration import Checkpoint, RankCosts, RankUsage, Recipe, SamplingDefaults + + +def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_graphs=False, + package_storage=None, ranks=None): + from .bootstrap import PreparationConfig, prepare as prepare_model + + if plan.world_size != 1 or ranks is not None: + raise ValueError("Inkling preparation requires one local GPU") + config = PreparationConfig(collective_tuning=plan.collective_tuning, collective_ladder=plan.collective_ladder, + prompt_logprobs=plan.prompt_logprobs, compile_workers=plan.compile_workers, + autotune_effort=plan.autotune_effort, tuning_replica=plan.tuning_replica, + native_dense_activations=plan.native_dense_activations, + lock_gpu_clocks=plan.lock_gpu_clocks and plan.autotune_effort != "off", + context=plan.context, max_active=plan.concurrency, + prefill_chunk_size=plan.prefill_chunk, snapshot_budget_bytes=plan.snapshots * plan.costs.state_row_bytes, + headroom_bytes=plan.headroom_bytes + plan.reserve_bytes, compile_decoder=compile_forwards, + retain_graphs=retain_graphs, kernel_cache=kernel_cache, stream_overlap=plan.stream_overlap) + return prepare_model(snapshot, config, progress=progress, package_storage=package_storage) + + +def usage(prepared): + return (RankUsage(prepared.memory_report["pages"], prepared.memory_report["free_device_bytes"]),) + + +RECIPE = Recipe(name="inkling", served_model_name="Inkling-Small-NVFP4", + # Recommended sampling: https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md. + sampling_defaults=SamplingDefaults(temperature=1., top_p=1., top_k=-1), prepare=prepare, usage=usage, + checkpoints=(Checkpoint(alias="inkling-small-nvfp4", repository="thinkingmachines/Inkling-Small-NVFP4", + revision="b6a99534467840620d411e4cd4ad5819b2610d9c", architecture="InklingForConditionalGeneration", + # Upper bound: includes the unused multimodal and MTP tensors. + stored_bytes=170_733_074_592, device_bytes=170_733_074_592, expansion_bytes=1 << 30),), + context=262144, page_tokens=128, concurrency=4, max_concurrency=4, max_draft_tokens=0, prefill_chunk=4096, + ranks=MappingProxyType({1: RankCosts(82_837_504, 3_670_016, 8 << 30)})) diff --git a/ignition/recipes/inkling/weights.py b/ignition/recipes/inkling/weights.py new file mode 100644 index 000000000..04dbb532b --- /dev/null +++ b/ignition/recipes/inkling/weights.py @@ -0,0 +1,215 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct loading of Inkling's interleaved NVFP4 and unquantized checkpoint tensors.""" + +from contextlib import nullcontext +from dataclasses import dataclass +from functools import cached_property + +import torch + +from ignition.components.weights import DirectWeightLoader, MLPWeights +from .config import ModelConfig + +PREFIX = "model.llm" + + +@dataclass(frozen=True) +class Experts: + gate_up: torch.Tensor + down: torch.Tensor + + +@dataclass(frozen=True) +class LayerWeights: + qkv_relative: torch.Tensor + output: torch.Tensor + relative: torch.Tensor + query_norm: torch.Tensor + key_norm: torch.Tensor + input_norm: torch.Tensor + post_attention_norm: torch.Tensor + key_conv: torch.Tensor + value_conv: torch.Tensor + attention_conv: torch.Tensor + mlp_conv: torch.Tensor + scale: torch.Tensor + dense: MLPWeights | None + router: torch.Tensor | None + correction: torch.Tensor | None + experts: object | None + shared: tuple[MLPWeights, ...] + + +@dataclass(frozen=True) +class ModelWeights: + config: ModelConfig + shard: object + embedding: torch.Tensor + embedding_norm: torch.Tensor + norm: torch.Tensor + head: torch.Tensor + layers: tuple[LayerWeights, ...] + allocated_bytes: int + draft: object | None = None + + @classmethod + def load(cls, manifest, device, *, shard, progress=None, package_storage=None): + before = torch.cuda.memory_allocated(device) + loading = nullcontext if package_storage is None else package_storage.transient + with loading(), InklingWeightLoader(manifest, device, shard=shard, progress=progress) as loader: + config = loader.config + first, last = shard.partition(config.hidden) + embedding = loader.load_tensor(PREFIX + ".embed.weight", extent=(slice(None), slice(first, last))) + embed_norm = loader.load_tensor(PREFIX + ".embed_norm.weight") + norm = loader.load_tensor(PREFIX + ".norm.weight") + first, last, width = config.vocabulary_partition(shard) + head = torch.zeros((width, config.hidden), dtype=torch.bfloat16, device=device) + loader._copy(head[:last-first], loader._sources[PREFIX + ".unembed.weight"][first:last]) + loader._session.flush() + layers = tuple(loader.load_layer(i) for i in range(config.layers)) + return cls(config, shard, embedding, embed_norm, norm, head, layers, + torch.cuda.memory_allocated(device) - before) + + +class InklingWeightLoader(DirectWeightLoader): + def __init__(self, manifest, device, *, shard, progress=None): + super().__init__(manifest, device, progress=progress) + self.config, self.shard = ModelConfig.load(manifest.snapshot), shard + self.config.validate_shard(shard) + + @cached_property + def quantization(self): + return {} + + def _selected_names(self): + return {n for n in super()._selected_names() if n.startswith(PREFIX + ".")} + + def _interleaved(self, name, down_name, inter, *, expert=None, destination=None): + first, last = self.shard.partition(inter, alignment=64) + source, down = self._sources[name], self._sources[down_name] + if expert is not None: + source, down = source[expert], down[expert] + if (source.dtype != torch.bfloat16 or down.dtype != torch.bfloat16 + or source.shape != (2 * inter, self.config.hidden) + or down.shape != (self.config.hidden, inter)): + raise ValueError(f"{name}: expected interleaved BF16 gate/up and BF16 down weights") + if destination is None: + destination = MLPWeights( + torch.empty((2 * (last-first), self.config.hidden), dtype=torch.bfloat16, device=self.device), + torch.empty((self.config.hidden, last-first), dtype=torch.bfloat16, device=self.device)) + target, output = destination.gate_up, destination.down + self._copy(target[:last-first], source[2*first:2*last:2]) + self._copy(target[last-first:], source[2*first+1:2*last:2]) + self._copy(output, down[:, first:last]) + self._session.flush() + return MLPWeights(target, output) + + def _nvfp4_experts(self, prefix, inter): + from b12x._lib.intrinsics.reference import swizzle_block_scale + from b12x.moe import fused_moe as moe + from ignition.components.sm103 import is_sm103 + from ignition.preparation.tensor_metadata import record_numeric_tensor + + sm103 = is_sm103(self.device) + first, last = self.shard.partition(inter, alignment=64) + local, count, hidden = last - first, self.config.text["n_routed_experts"], self.config.hidden + packed, blocks, globals_, inputs = [], [], [], [] + for projection, rows, columns in (("w13_weight", 2 * inter, hidden), ("w2_weight", hidden, inter)): + name = prefix + "." + projection + if any(name + suffix not in self._sources for suffix in ("", ".scale", ".scale2", ".input_amax", ".original_shape")): + raise ValueError(f"{name}: incomplete NVFP4 checkpoint tensors") + source, scale = self._sources[name], self._sources[name + ".scale"] + shape = self._session.materialize(self._sources[name + ".original_shape"]) + global_scale = self.load_tensor(name + ".scale2") + amax = self._session.materialize(self._sources[name + ".input_amax"]) + if (source.dtype != torch.uint8 or source.shape != (count, rows, columns // 2) + or scale.dtype != torch.float8_e4m3fn or scale.shape != (count, rows, columns // 16) + or shape.dtype != torch.int64 or shape.shape != (3,) or shape.tolist() != [count, rows, columns]): + raise ValueError(f"{name}: invalid packed NVFP4 weight or block-scale geometry") + if (global_scale.dtype != torch.float32 or global_scale.shape != (count,) + or not bool((torch.isfinite(global_scale) & (global_scale > 0)).all()) + or amax.dtype != torch.bfloat16 or amax.shape != (1,) + or not bool((torch.isfinite(amax) & (amax > 0)).all())): + raise ValueError(f"{name}: expected positive FP32 per-expert scale2 and BF16 input_amax") + down = projection == "w2_weight" + output_shape = (count, hidden, local // 2) if down else (count, 2 * local, hidden // 2) + scale_shape = (count, hidden, local // 16) if down else (count, 2 * local, hidden // 16) + values = torch.empty(output_shape, dtype=torch.uint8, device=self.device) + scales = torch.empty(scale_shape, dtype=torch.float8_e4m3fn, device=self.device) + for expert in range(count): + if down: + self._copy(values[expert], source[expert, :, first // 2:last // 2]) + self._copy(scales[expert], scale[expert, :, first // 16:last // 16]) + else: + for offset in (0, 1): + half = 1 - offset if sm103 else offset + target = slice(half * local, (half + 1) * local) + self._copy(values[expert, target], source[expert, 2 * first + offset:2 * last:2]) + self._copy(scales[expert, target], scale[expert, 2 * first + offset:2 * last:2]) + globals_.append(global_scale) + # Preserve ModelOpt's FP32 amax/(448*6) boundary before b12x's reciprocal. + activation_scale = (amax.float() / 2688.).reciprocal().to(self.device).expand(count).clone() + record_numeric_tensor(activation_scale) + inputs.append(activation_scale) + self._session.flush() + packed.append(values) + blocks.append(scales if sm103 else swizzle_block_scale(scales)) + del scales + if sm103: + from ignition.components.moe_sm103 import prepare_cute_nvfp4_experts + + return prepare_cute_nvfp4_experts(packed[0], blocks[0], packed[1], blocks[1], + (*globals_, *inputs)) + plan = moe.plan_weights(source=moe.PackedSource(format="modelopt_nvfp4", w13_layout="w31"), + activation=moe.ActivationSpec(mode="a4", nonlinearity="silu", io_dtype=torch.bfloat16), + geometry=moe.MoEGeometry(num_experts=count, hidden_size=hidden, intermediate_size=local)) + return moe.prepare_weights(plan=plan, weights=moe.PackedWeights( + w13=packed[0], w2=packed[1], w13_block_scales=blocks[0], w2_block_scales=blocks[1], + w13_global_scales=globals_[0], w2_global_scales=globals_[1], + input_scale=inputs[0], intermediate_scale=inputs[1], immutable_input_scales=True)) + + def load_layer(self, layer): + c, shard = self.config.text, self.shard + prefix = f"{PREFIX}.layers.{layer}" + a = self.config.attention(layer) + q0, q1 = shard.partition(a.heads * a.key_dim, alignment=a.key_dim) + r0, r1 = shard.partition(a.heads * c["d_rel"], alignment=c["d_rel"]) + k0, k1 = shard.replicated_partition(a.kv_heads) + kv = (k0 * a.key_dim, k1 * a.key_dim) + attn = prefix + ".attn" + qkv = self.load_linear_group(tuple(attn + "." + name for name in ("wq_du", "wk_dv", "wv_dv", "wr_du")), + row_ranges=((q0, q1), kv, kv, (r0, r1))) + def tensor(name, **kwargs): + return self.load_tensor(prefix + "." + name, **kwargs) + def conv(name, extent=None): + value = tensor(name + ".weight", dtype=torch.float32, + extent=None if extent is None else (slice(*extent), slice(None), slice(None))) + return value.reshape(value.shape[0], c["conv_kernel_size"]) + dense, router, correction, experts, shared = None, None, None, None, () + mlp = prefix + ".mlp" + if c["mlp_layer_types"][layer] == "dense": + dense = self._interleaved(mlp + ".w13_dn.weight", mlp + ".w2_md.weight", c["intermediate_size"]) + scale = tensor("mlp.global_scale") + else: + router, correction, scale = (tensor("mlp.gate." + n) for n in ("weight", "bias", "global_scale")) + if layer in self.config.quantized_routed_layers: + experts = self._nvfp4_experts(mlp + ".experts", c["moe_intermediate_size"]) + else: + count, local = c["n_routed_experts"], c["moe_intermediate_size"] // shard.world_size + experts = Experts( + torch.empty((count, 2 * local, self.config.hidden), dtype=torch.bfloat16, device=self.device), + torch.empty((count, self.config.hidden, local), dtype=torch.bfloat16, device=self.device)) + for expert in range(count): + self._interleaved(mlp + ".experts.w13_weight", mlp + ".experts.w2_weight", + c["moe_intermediate_size"], expert=expert, + destination=MLPWeights(experts.gate_up[expert], experts.down[expert])) + shared = tuple(self._interleaved(mlp + ".shared_experts.shared_w13_weight", + mlp + ".shared_experts.shared_w2_weight", c["moe_intermediate_size"], expert=i) + for i in range(c["n_shared_experts"])) + return LayerWeights(qkv, self.load_linear(attn + ".wo_ud", columns=(q0, q1)), + tensor("attn.rel_logits_proj.proj").T.contiguous(), tensor("attn.q_norm.weight"), + tensor("attn.k_norm.weight"), tensor("attn_norm.weight"), tensor("mlp_norm.weight"), + conv("attn.k_sconv", kv), conv("attn.v_sconv", kv), conv("attn_sconv"), conv("mlp_sconv"), + scale, dense, router, correction, experts, shared) diff --git a/pyproject.toml b/pyproject.toml index 2f61b3f50..d06179244 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,6 +61,7 @@ include = ["ignition*"] "ignition.recipes.qwen38" = ["assets/*"] "ignition.recipes.step5" = ["assets/*"] "ignition.recipes.muse_spark" = ["assets/*"] +"ignition.recipes.inkling" = ["assets/*"] "ignition.recipes.minimax_m3" = ["assets/*"] [tool.pytest.ini_options] diff --git a/tests/cli/test_models.py b/tests/cli/test_models.py index bf38254ba..0fa45eeca 100644 --- a/tests/cli/test_models.py +++ b/tests/cli/test_models.py @@ -21,7 +21,7 @@ def test_declarations_import_without_model_dependencies(): result = subprocess.run( [sys.executable, "-c", "import sys; from ignition.recipes import aliases; from ignition import planning;" - " import ignition.cli.preparation; assert aliases() == ('qwen3.8-flash', 'qwen3.8-27b', 'glm-5.3-flash', 'deepseek-v4.1-flash', 'deepseek-v4-flash', 'mimo-v2.6-pro-mopd', 'kimi-k3-mxfp4-csf', 'kimi-k3', 'kimi-k3-dspark', 'step5-preview-nvfp4', 'nemotron-bolt-24gb', 'minimax-m3-1-flash', 'gemma-4-e2b', 'gemma-4-e4b', 'gemma-4-12b', 'gemma-4-26b-a4b', 'gemma-4-31b', 'gemma-4-e4b-nvfp4', 'gemma-4-12b-nvfp4', 'gemma-4-26b-a4b-nvfp4', 'gemma-4-31b-nvfp4', 'muse-spark-open-nvfp4');" + " import ignition.cli.preparation; assert aliases() == ('qwen3.8-flash', 'qwen3.8-27b', 'glm-5.3-flash', 'deepseek-v4.1-flash', 'deepseek-v4-flash', 'mimo-v2.6-pro-mopd', 'kimi-k3-mxfp4-csf', 'kimi-k3', 'kimi-k3-dspark', 'step5-preview-nvfp4', 'nemotron-bolt-24gb', 'minimax-m3-1-flash', 'gemma-4-e2b', 'gemma-4-e4b', 'gemma-4-12b', 'gemma-4-26b-a4b', 'gemma-4-31b', 'gemma-4-e4b-nvfp4', 'gemma-4-12b-nvfp4', 'gemma-4-26b-a4b-nvfp4', 'gemma-4-31b-nvfp4', 'muse-spark-open-nvfp4', 'inkling-small-nvfp4');" " assert not {'torch', 'transformers', 'flare_heliopause'} & set(sys.modules)"], cwd=ROOT, check=False, capture_output=True, text=True) assert result.returncode == 0, result.stderr diff --git a/tests/components/inkling_nvfp4_helpers.py b/tests/components/inkling_nvfp4_helpers.py new file mode 100644 index 000000000..7422c0089 --- /dev/null +++ b/tests/components/inkling_nvfp4_helpers.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""NVFP4 reference arithmetic for Inkling's unweighted routed-expert outputs.""" + +import torch +import triton +import triton.language as tl + +from ignition.reference.qwen38_quant import decode_nvfp4, round_e2m1 + + +@triton.jit +def _reciprocal_approximate_kernel(source, output, count: tl.constexpr, BLOCK: tl.constexpr): + index = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + value = tl.load(source + index, index < count, other=1.) + result = tl.inline_asm_elementwise("rcp.approx.ftz.f32 $0, $1;", constraints="=f,f", + args=[value], dtype=tl.float32, is_pure=True, pack=1) + tl.store(output + index, result, index < count) + + +def _reciprocal_approximate(value): + value = value.contiguous() + output = torch.empty_like(value) + _reciprocal_approximate_kernel[(triton.cdiv(value.numel(), 256),)](value, output, value.numel(), 256) + return output + + +@triton.jit +def _exp2_approximate_kernel(source, output, count: tl.constexpr, BLOCK: tl.constexpr): + index = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + value = tl.load(source + index, index < count, other=0.) + result = tl.inline_asm_elementwise("ex2.approx.ftz.f32 $0, $1;", constraints="=f,f", + args=[value], dtype=tl.float32, is_pure=True, pack=1) + tl.store(output + index, result, index < count) + + +def _exp2_approximate(value): + value = value.contiguous() + output = torch.empty_like(value) + _exp2_approximate_kernel[(triton.cdiv(value.numel(), 256),)](value, output, value.numel(), 256) + return output + + +def quantize_activation(value, amax, *, quant_scale_math="b12x"): + """Return E2M1 values times E4M3 block scales, and separate FP32 calibration.""" + value = value.float() + blocks = value.reshape(*value.shape[:-1], -1, 16) + # Round amax/2688 before reciprocating, as the publisher does. + dequant = torch.tensor(float(amax.item()) / 2688., dtype=torch.float32, device=value.device) + encode = dequant.reciprocal() + sixth = (_reciprocal_approximate(torch.full_like(encode, 6.)) + if quant_scale_math == "flashinfer" else torch.full_like(encode, 1. / 6.)) + scales = ((blocks.abs().amax(-1, keepdim=True) * sixth) * encode).clamp(max=448.) + scales = scales.to(torch.float8_e4m3fn).float() + if quant_scale_math == "b12x": + inverse = scales.reciprocal() * encode + elif quant_scale_math == "flashinfer": + # Preserve rcp.approx.ftz ordering from quantization_utils.cuh; reassociation + # or correctly-rounded reciprocal changes E2M1 ties, including amax=187. + inverse = _reciprocal_approximate(scales * _reciprocal_approximate(encode)) + else: + raise ValueError(f"unknown NVFP4 quantizer arithmetic: {quant_scale_math}") + inverse = torch.where(scales != 0, inverse, 0.) + return (round_e2m1(blocks * inverse) * scales).reshape_as(value), encode + + +def nvfp4_routes(source, ids, tensors, prefix, *, quant_scale_math="b12x"): + """Unweighted routes: FP32 FC1/SwiGLU -> BF16 -> NVFP4 -> FP32 FC2 -> BF16.""" + first = prefix + ".w13_weight" + second = prefix + ".w2_weight" + tensors = {name: value.to(source.device) for name, value in tensors.items() if name.startswith(prefix + ".")} + source_quantized, input_scale = quantize_activation( + source, tensors[first + ".input_amax"], quant_scale_math=quant_scale_math) + result = torch.zeros((*ids.shape, source.shape[-1]), dtype=torch.bfloat16, device=source.device) + one = torch.ones((), device=source.device) + for expert in range(tensors[first].shape[0]): + tokens, routes = torch.where(ids == expert) + if tokens.numel() == 0: + continue + # Scaled FP4 MMA applies the outer multiplier after the dot product. + up_gate = decode_nvfp4(tensors[first][expert], tensors[first + ".scale"][expert], one) + projected = (source_quantized[tokens] @ up_gate.T) * (tensors[first + ".scale2"][expert] / input_scale) + gate, up = projected[:, ::2], projected[:, 1::2] + if quant_scale_math == "flashinfer": + # CuTe's FP32 SwiGLU epilogue uses exp2.approx and rcp.approx. + # Their rounding can cross a BF16 midpoint before FC2 quantization. + sigmoid = _reciprocal_approximate(1. + _exp2_approximate(gate * -1.4426950408889634)) + activated = ((sigmoid * gate) * up).bfloat16() + else: + activated = (torch.nn.functional.silu(gate) * up).bfloat16() + activated, intermediate_scale = quantize_activation( + activated, tensors[second + ".input_amax"], quant_scale_math=quant_scale_math) + down = decode_nvfp4(tensors[second][expert], tensors[second + ".scale"][expert], one) + result[tokens, routes] = ((activated @ down.T) + * (tensors[second + ".scale2"][expert] / intermediate_scale)).bfloat16() + return result diff --git a/tests/components/test_inkling_nvfp4_sm103_cuda.py b/tests/components/test_inkling_nvfp4_sm103_cuda.py new file mode 100644 index 000000000..cc0515546 --- /dev/null +++ b/tests/components/test_inkling_nvfp4_sm103_cuda.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Original Inkling W4A4 weights through SM103 grouped GEMMs and captured raw routes.""" + +import os +from pathlib import Path + +import pytest +import torch +from safetensors import safe_open + +from ignition.components.moe import PreparedRoutedExperts +from ignition.components.moe_sm103 import CuteNvfp4Experts, _fp4_quantizer +from ignition.components.parallel import TensorParallelShard +from ignition.preparation.checkpoint import inspect_indexed_checkpoint +from ignition.preparation.compilation import compile_forward +from ignition.preparation.scratch import ScratchArena +from ignition.preparation.tuning import RecordedPreparationSession +from ignition.recipes.inkling.model import mix_routes +from ignition.recipes.inkling.weights import InklingWeightLoader +from ignition.reference.qwen38_quant import decode_nvfp4 +from tests.recipes.inkling_helpers import checkpoint +from .inkling_nvfp4_helpers import nvfp4_routes, quantize_activation + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an assigned SM103 GPU") + + +@pytest.mark.parametrize("amax", [1.8359375, 187., 4.]) +def test_sm103_activation_calibration_and_fp4_ties(amax): + if torch.cuda.get_device_capability() != (10, 3): + pytest.skip("SM103 NVFP4 quantizer") + generator = torch.Generator(device="cuda").manual_seed(103) + source = torch.randn((4, 256), generator=generator, device="cuda", dtype=torch.bfloat16) + source[0].fill_(1.6875) + source[0, 0] = 1. + source[1].zero_() + amax = torch.tensor([amax], device="cuda", dtype=torch.bfloat16) + reference, scale = quantize_activation(source, amax, quant_scale_math="flashinfer") + values = torch.empty((4, 128), device="cuda", dtype=torch.uint8) + scales = torch.empty(16 * 16, device="cuda", dtype=torch.uint8) + _fp4_quantizer().fp4_quantize(source, scale.reshape(1), values, scales, + 16, False, False, False, False, True, 0) + actual = decode_nvfp4(values, scales[:64].view(torch.float8_e4m3fn).reshape(4, 16), torch.ones((), device="cuda")) + torch.testing.assert_close(actual, reference, atol=0, rtol=0) + + +class RawRoutes: + def __init__(self, source, experts, ids, weights, live, session, workspace): + self.source, self.ids, self.weights, self.live = source, ids, weights, live + self.active_ids = torch.empty_like(ids) + self.routes = torch.empty((*ids.shape, source.shape[1]), dtype=source.dtype, device=source.device) + self.output = torch.empty_like(source) + self.experts = PreparedRoutedExperts(source, experts, self.active_ids, weights, self.routes, + session=session, workspace=workspace, name="nvfp4") + + def __call__(self): + live = torch.arange(self.ids.shape[0], device=self.ids.device)[:, None] < self.live[0] + self.active_ids.copy_(torch.where(live, self.ids, -1)) + self.experts() + self.output.copy_(mix_routes(self.routes, self.weights, self.active_ids)) + + +@pytest.mark.parametrize("tokens", [1, 129, 4096]) +@torch.no_grad() +def test_sm103_calibrated_raw_routes_compiled_replay(tmp_path, tokens): + if torch.cuda.get_device_capability() != (10, 3): + pytest.skip("SM103 grouped NVFP4 execution") + config, tensors = checkpoint(tmp_path, moe_intermediate=256, routed_experts=8, top_k=6) + prefix = "model.llm.layers.2.mlp.experts" + manifest = inspect_indexed_checkpoint(tmp_path) + with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(0, 1)) as loader: + experts = loader.load_layer(2).experts + assert isinstance(experts, CuteNvfp4Experts) + for name, calibration, alpha in ( + ("w13_weight", experts.input_global_scale, experts.w13_alpha), + ("w2_weight", experts.intermediate_global_scale, experts.w2_alpha), + ): + amax = float(tensors[prefix + "." + name + ".input_amax"].item()) + scale = torch.tensor([amax / 2688.], dtype=torch.float32).reciprocal() + assert torch.equal(calibration.cpu(), scale) + assert torch.equal(alpha.cpu(), tensors[prefix + "." + name + ".scale2"] / scale) + + torch.manual_seed(4517 + tokens) + device = torch.device("cuda:0") + source = torch.randn((tokens, config.hidden), device=device, dtype=torch.bfloat16) + ids = ((torch.arange(tokens, device=device)[:, None] + torch.arange(6, device=device)) % 8).int() + weights = torch.rand((tokens, 6), device=device) * 1.1387381553649902 + live = torch.tensor([tokens], dtype=torch.int32, device=device) + with RecordedPreparationSession(device=device, checkpoint="inkling-nvfp4-sm103", + workload_schema="inkling", numerical_policy="default", compile_workers=1) as session: + arena = ScratchArena(device) + session.register_scratch(arena) + forward = RawRoutes(source, experts, ids, weights, live, session, arena) + session.tune() + run = compile_forward(forward) + run() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + run() + session.freeze() + for count, factor in ((tokens, 1.), (max(1, tokens // 2), .3125), (0, 1.), (tokens, -1.5)): + live.fill_(count) + source.mul_(factor) + ids[0, 1] = -1 + active = torch.where(torch.arange(tokens, device=device)[:, None] < count, ids, -1) + expected = nvfp4_routes(source, active, tensors, prefix, quant_scale_math="flashinfer") + forward.routes.fill_(float("nan")) + allocations = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations + torch.testing.assert_close(forward.routes, expected, atol=0, rtol=0) + before = forward.routes.clone() + weights.mul_(.375) + graph.replay() + torch.cuda.synchronize() + assert torch.equal(forward.routes, before) + result = torch.zeros_like(source) + for expert in range(8): + route = ((forward.routes.float() * weights[..., None]) + * (active == expert)[..., None]).sum(1).bfloat16() + result += route + assert torch.equal(forward.output, result) + assert not forward.routes[active < 0].count_nonzero() + graph.reset() + + +@pytest.mark.skipif(not os.environ.get("FLARE_INKLING_SNAPSHOT"), reason="requires the official NVFP4 checkpoint") +@torch.no_grad() +def test_original_checkpoint_sm103_production_geometry(): + if torch.cuda.get_device_capability() != (10, 3): + pytest.skip("SM103 grouped NVFP4 execution") + manifest = inspect_indexed_checkpoint(Path(os.environ["FLARE_INKLING_SNAPSHOT"])) + with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(0, 1)) as loader: + layer = loader.config.quantized_routed_layers[0] + prefix = f"model.llm.layers.{layer}.mlp.experts" + experts = loader._nvfp4_experts(prefix, loader.config.text["moe_intermediate_size"]) + assert (experts.num_experts, experts.hidden_size, experts.intermediate_size) == (256, 4096, 2048) + selected = [255, 7, 33, 100, 127, 0] + original = {} + for projection in ("w13_weight", "w2_weight"): + for suffix in ("", ".scale", ".scale2", ".input_amax"): + name = prefix + "." + projection + suffix + with safe_open(manifest.snapshot / manifest.tensors[name].shard, framework="pt", device="cpu") as reader: + if suffix in ("", ".scale"): + original[name] = torch.stack([reader.get_slice(name)[expert] for expert in selected]) + elif suffix == ".scale2": + original[name] = reader.get_tensor(name)[selected] + else: + original[name] = reader.get_tensor(name) + + device = torch.device("cuda:0") + generator = torch.Generator(device=device).manual_seed(103276) + source = torch.randn((1, 4096), generator=generator, device=device, dtype=torch.bfloat16) + ids = torch.tensor([selected], dtype=torch.int32, device=device) + weights = torch.tensor([[.7, .1, .6, .9, .3, .5]], dtype=torch.float32, device=device) + live = torch.ones(1, dtype=torch.int32, device=device) + reference_ids = torch.arange(6, device=device, dtype=torch.int32)[None] + with RecordedPreparationSession(device=device, checkpoint="inkling-nvfp4-sm103-production-geometry", + workload_schema="inkling", numerical_policy="default", compile_workers=1) as session: + arena = ScratchArena(device) + session.register_scratch(arena) + forward = RawRoutes(source, experts, ids, weights, live, session, arena) + session.tune() + run = compile_forward(forward) + run() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + run() + session.freeze() + reference = nvfp4_routes(source, reference_ids, original, prefix, quant_scale_math="flashinfer") + assert reference.count_nonzero() + allocations = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations + torch.testing.assert_close(forward.routes, reference, atol=0, rtol=0) + live.zero_() + graph.replay() + torch.cuda.synchronize() + assert not forward.routes.count_nonzero() + graph.reset() diff --git a/tests/components/test_inkling_operators_cuda.py b/tests/components/test_inkling_operators_cuda.py new file mode 100644 index 000000000..2baae99fc --- /dev/null +++ b/tests/components/test_inkling_operators_cuda.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Learned relative attention and residual convolution preserve packed histories.""" + +import os +from types import SimpleNamespace + +import pytest +import torch + +from ignition.components.paged_batch import Metadata +from ignition.components.relative_paged_attention import PreparedRelativePagedAttention +from ignition.components.residual_short_conv import PreparedResidualShortConvolution +from ignition.preparation.compilation import compile_forward +from ignition.preparation.tuning import RecordedPreparationSession + + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an assigned CUDA GPU") + + +@pytest.mark.parametrize("window,counts,starts,capacity", [ + (-1, (1, 0), (1024, 0), 1), + (-1, (129, 0, 3), (127, 0, 1030), 144), + (511, (129, 0, 1), (510, 0, 1024), 144), + (-1, (4096,), (3,), 4096), +]) +@torch.no_grad() +def test_relative_attention_canonical_paged_capture(window, counts, starts, capacity): + from transformers.models.inkling.modeling_inkling import eager_attention_forward + + torch.manual_seed(835) + device = torch.device("cuda", 0) + heads, groups, dim, extent = 4, 1 if capacity == 1 else 2, 128, 1024 if window < 0 else 512 + batches = len(counts) + blocks = (max(start + count for start, count in zip(starts, counts)) + 127) // 128 + pages = torch.randperm(batches * blocks, device=device).int().reshape(batches, blocks) + # Noncontiguous page strides exercise the runtime's interleaved layer storage. + key = torch.randn((batches * blocks, 2, 128, groups, dim), device=device).bfloat16()[:, 0] + value = torch.randn_like(key) + query = torch.randn((capacity, heads, dim), device=device).bfloat16() + relative = (torch.randn((capacity, heads, 16), device=device).bfloat16() + @ torch.randn((16, extent), device=device).bfloat16()) * .125 + output = torch.empty_like(query) + lengths = torch.tensor([s + n for s, n in zip(starts, counts)], dtype=torch.int32, device=device) + cu = torch.tensor([0, *torch.tensor(counts).cumsum(0).tolist()], dtype=torch.int32, device=device) + with RecordedPreparationSession(device=device, checkpoint="relative-paged-test", workload_schema="relative-paged", + numerical_policy="default", compile_workers=1) as session: + operation = PreparedRelativePagedAttention(query, key, value, pages, lengths, cu, relative, output, + window=window, softmax_scale=1 / dim, session=session, name="attention") + saved = tuple(t.clone() for t in (pages, lengths, cu)) + for tensor in (pages, lengths, cu): + tensor.fill_(1 << 29) + session.tune() + for tensor, original in zip((pages, lengths, cu), saved): + tensor.copy_(original) + run = compile_forward(operation) + run() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + run() + session.freeze() + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + reference = torch.zeros_like(output) + for batch, (count, start) in enumerate(zip(counts, starts)): + if count == 0: + continue + begin = int(cu[batch]) + positions = torch.arange(start, start + count, device=device) + offsets = torch.arange(start + count, device=device) + k = key[pages[batch, offsets // 128], offsets % 128] + v = value[pages[batch, offsets // 128], offsets % 128] + distance = positions[:, None] - offsets[None, :] + bias = relative[begin:begin + count].transpose(0, 1).gather( + -1, distance.clamp(0, extent - 1)[None].expand(heads, -1, -1)) + bias.masked_fill_((distance < 0)[None] | (distance >= extent)[None], 0) + valid = distance >= 0 + if window >= 0: + valid &= distance <= window + mask = torch.where(valid, 0., float("-inf")).bfloat16()[None, None] + expected, _ = eager_attention_forward(SimpleNamespace(num_key_value_groups=heads // groups, training=False), + query[begin:begin + count].transpose(0, 1)[None], k.transpose(0, 1)[None], + v.transpose(0, 1)[None], mask, scaling=1 / dim, position_bias=bias[None]) + reference[begin:begin + count] = expected[0] + # BF16-rounded matmul/softmax with a different FP32 reduction tree. + torch.testing.assert_close(output, reference, atol=.001, rtol=.008) + assert (output.float() - reference.float()).norm() / reference.float().norm() < .0002 + first = output.clone() + graph.replay() + torch.cuda.synchronize() + assert torch.equal(first, output) + assert torch.count_nonzero(output[sum(counts):]) == 0 + # Changing the live request set after capture cannot read its stale pages. + lengths.zero_() + cu.zero_() + pages.fill_(-1) + graph.replay() + torch.cuda.synchronize() + assert torch.count_nonzero(output) == 0 + graph.reset() + + +@pytest.mark.parametrize("capacity,channels", [(1, 67), (129, 257), (4096, 67)]) +@torch.no_grad() +def test_residual_convolution_canonical_chunking_and_state(capacity, channels): + from transformers.models.inkling.modeling_inkling import InklingShortConvolution + + torch.manual_seed(836) + device = torch.device("cuda", 0) + rows = 1 if capacity == 4096 else 3 + source = torch.randn((capacity, channels + 16), device=device).bfloat16()[:, :channels] + output = torch.empty_like(source) + weights = torch.randn((channels, 4), device=device) * .1 + backing = torch.zeros((rows + 2, channels * 3 + 32), device=device) + history = backing[:, :channels * 3].view(rows + 2, channels, 3) + m = Metadata.allocate(capacity, rows, 1, device) + with RecordedPreparationSession(device=device, checkpoint="residual-short-conv-test", workload_schema="residual-conv", + numerical_policy="default", compile_workers=1) as session: + operation = PreparedResidualShortConvolution(source, weights, history, m, output, + session=session, name="convolution") + for tensor in (m.state_rows, m.starts, m.lengths, m.query_start_loc): + tensor.fill_(1 << 29) + session.tune() + m.state_rows.zero_() + m.lengths.zero_() + m.query_start_loc.zero_() + run = compile_forward(operation) + run() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + run() + session.freeze() + backing.zero_() + all_inputs = [torch.empty((0, channels), device=device, dtype=torch.bfloat16) for _ in range(rows)] + canonical = InklingShortConvolution(channels, 4, 0, 0).to(device) + canonical.conv1d.weight.copy_(weights[:, None]) + patterns = ([1, 1, 0, 1] if capacity == 1 else [capacity - 3, 1, 3, 0, capacity - 2]) + for count in patterns: + source.normal_() + lengths = [count] if rows == 1 else [max(0, count - 1), 0, min(count, 1)] + starts = [len(x) for x in all_inputs] + m.lengths.copy_(torch.tensor(lengths, device=device, dtype=torch.int32)) + m.starts.copy_(torch.tensor(starts, device=device)) + m.state_rows.copy_(torch.arange(1, rows + 1, device=device)) + m.query_start_loc[0] = 0 + m.query_start_loc[1:].copy_(m.lengths.cumsum(0)) + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + begin = 0 + for row, n in enumerate(lengths): + if n: + all_inputs[row] = torch.cat((all_inputs[row], source[begin:begin + n])) + expected = canonical(all_inputs[row][None])[0, -n:] + torch.testing.assert_close(output[begin:begin + n], expected, atol=1e-7, rtol=.008) + assert (output[begin:begin + n].float() - expected.float()).norm() / expected.float().norm() < .0001 + recent = all_inputs[row][-3:].float().T + expected_history = torch.nn.functional.pad(recent, (3 - recent.shape[1], 0)) + torch.testing.assert_close(history[row + 1], expected_history, atol=0, rtol=0) + begin += n + assert torch.count_nonzero(output[begin:]) == 0 + assert torch.count_nonzero(history[0]) == 0 + assert torch.count_nonzero(history[-1]) == 0 + if rows > 1: + assert torch.count_nonzero(history[2]) == 0 + # A reused physical row at position zero must ignore the previous request. + stale = history.clone() + m.starts.zero_() + m.lengths.zero_() + m.lengths[0] = 1 + m.query_start_loc.fill_(1) + m.query_start_loc[0] = 0 + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(output[:1], canonical(source[:1][None])[0], atol=1e-7, rtol=.008) + torch.testing.assert_close(history[1, :, :2], torch.zeros_like(history[1, :, :2]), atol=0, rtol=0) + torch.testing.assert_close(history[1, :, 2], source[0].float(), atol=0, rtol=0) + torch.testing.assert_close(history[2:], stale[2:], atol=0, rtol=0) + graph.reset() diff --git a/tests/components/test_inkling_package_cuda.py b/tests/components/test_inkling_package_cuda.py new file mode 100644 index 000000000..9239a4182 --- /dev/null +++ b/tests/components/test_inkling_package_cuda.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Custom prepared operators survive Python exit and native package replay.""" + +import os +from pathlib import Path +import subprocess +import sys + +import pytest + + +@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="requires an assigned CUDA GPU") +def test_inkling_operator_package_native_replay(tmp_path): + root = Path(__file__).resolve().parents[2] + target = Path(os.environ.get("CARGO_TARGET_DIR", root / "helios/target")) + subprocess.run(["cargo", "build", "-j", "4", "--manifest-path", str(root / "helios/Cargo.toml"), + "--no-default-features", "--features", "runtime-package,test-tools", "--bin", "test_fixed_runtime_package"], + cwd=root, check=True, timeout=600) + exported = subprocess.run([sys.executable, str(root / "helios/tests/inkling_operator_package_fixture.py"), str(tmp_path)], + cwd=root, text=True, capture_output=True, timeout=600) + assert exported.returncode == 0, exported.stdout + exported.stderr + assert "exported prepared relative attention and residual convolution" in exported.stdout + replay = subprocess.run([str(target / "debug/test_fixed_runtime_package"), str(tmp_path)], + cwd=root, text=True, capture_output=True, timeout=180) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "native fixed-address replay passed" in replay.stdout diff --git a/tests/components/test_weight_metadata.py b/tests/components/test_weight_metadata.py index 8967936db..c5d2ba52b 100644 --- a/tests/components/test_weight_metadata.py +++ b/tests/components/test_weight_metadata.py @@ -185,7 +185,7 @@ def bytes(): assert_numeric(numeric, expected, opaque=(opaque,)) -@pytest.mark.parametrize("kind", ["trtllm", "cute"]) +@pytest.mark.parametrize("kind", ["trtllm", "cute", "cute_nvfp4"]) def test_sm103_expert_storage_uses_the_same_numeric_contract(monkeypatch, kind): from ignition.components import moe, moe_sm103 @@ -195,11 +195,17 @@ def test_sm103_expert_storage_uses_the_same_numeric_contract(monkeypatch, kind): one = torch.ones(2) if kind == "trtllm": experts = moe_sm103.TrtllmNvfp4Experts(w13, s13, w2, s2, one, one, one, one, one, one, one) - else: + elif kind == "cute": experts = moe_sm103.CuteW4A16Experts(w13, s13, one, w2, s2, one, (s13, s2)) + else: + experts = moe_sm103.CuteNvfp4Experts( + w13=w13, w13_scale=s13, w13_alpha=one, w2=w2, w2_scale=s2, w2_alpha=one, + scale_storage=(s13, s2), input_global_scale=torch.ones(1), + intermediate_global_scale=torch.full((1,), 2.)) source = torch.zeros((1, 16), dtype=torch.bfloat16) + output = torch.empty((1, 1, 16), dtype=torch.bfloat16) if kind == "cute_nvfp4" else torch.empty_like(source) with NumericStorage() as numeric: operation = moe.PreparedRoutedExperts(source, experts, torch.zeros((1, 1), dtype=torch.int32), - torch.ones((1, 1)), torch.empty_like(source), session=None, name="experts") + torch.ones((1, 1)), output, session=None, name="experts") assert isinstance(operation, moe_sm103.Sm103RoutedExperts) assert_numeric(numeric, (value for value in vars(experts).values() if isinstance(value, torch.Tensor))) diff --git a/tests/frontend/test_inkling.py b/tests/frontend/test_inkling.py new file mode 100644 index 000000000..0c8ad61e2 --- /dev/null +++ b/tests/frontend/test_inkling.py @@ -0,0 +1,116 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Native TML rendering against the pinned checkpoint template and tokenizer.""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SNAPSHOT = Path(os.environ.get("FLARE_INKLING_SNAPSHOT", "/data/models/Inkling-Small-NVFP4")) + + +def test_native_inkling_matches_checkpoint(tmp_path): + from tokenizers import Tokenizer + from transformers import PreTrainedTokenizerFast + from transformers.utils.chat_template_utils import _compile_jinja_template + from ignition.recipes.inkling.frontend import prepare_frontend, runtime_assets + + if not (SNAPSHOT / "tokenizer.json").is_file(): + pytest.skip("requires pinned Inkling-Small-NVFP4 frontend assets") + assets = runtime_assets(SNAPSHOT) + settings = prepare_frontend(SNAPSHOT, eos_token_ids=[200006]) + tokenizer = Tokenizer.from_file(str(SNAPSHOT / "tokenizer.json")) + hf = PreTrainedTokenizerFast.from_pretrained(SNAPSHOT) + source = (SNAPSHOT / "chat_template.jinja").read_text() + annotated = assets["chat_template"]["text"] + assert annotated.replace("{%- mark -%}", "") == source + reference = _compile_jinja_template(source) + marked = _compile_jinja_template(annotated.replace("{%- mark -%}", "{{- message_position() -}}")) + cases = [] + + def add(name, messages, **options): + options = dict(dict(add_generation_prompt=True), **options) + rendered = reference.render(messages=messages, **settings["tokenizer"], **options) + marker = "\0message-position\0" + chunks = marked.render(messages=messages, **settings["tokenizer"], **options, + message_position=lambda: marker).split(marker) + assert "".join(chunks) == rendered + if options.get("continue_final_message"): + rendered = hf.apply_chat_template(messages, tokenize=False, chat_template=source, **options) + positions, end = [], 0 + for chunk in chunks[:-1]: + end += len(chunk) + positions.append(end) + encoding = tokenizer.encode(rendered, add_special_tokens=False) + preceding = [0] + for _, end in encoding.offsets: + preceding.append(max(preceding[-1], end)) + following = [len(rendered)] * (len(encoding.ids) + 1) + for index in range(len(encoding.ids) - 1, -1, -1): + following[index] = min(following[index + 1], encoding.offsets[index][0]) + boundaries = sorted({index for position in positions for index in range(1, len(encoding.ids)) + if preceding[index] <= position <= following[index]}) + cases.append(dict(name=name, messages=messages, options=options, rendered=rendered, + token_ids=encoding.ids, message_boundaries=boundaries)) + + user = dict(role="user", content="Hello 世界 café á 👨‍👩‍👧‍👦") + add("default", [user]) + add("empty", [dict(role="user", content="")]) + add("system", [dict(role="system", content="Be precise."), user]) + add("system_only", [dict(role="system", content="Be precise.")]) + add("closed_header", [user], add_generation_prompt=False) + for effort in ["none", "minimal", "low", "medium", "high", "max", 0.0, 0.5, 0.99]: + add(f"effort_{effort}", [user], reasoning_effort=effort) + for text in ["Partial café", " repeated repeated "]: + add("continuation_" + text, [user, dict(role="assistant", content=text)], + continue_final_message=True, add_generation_prompt=False) + add("reasoning", [user, dict(role="assistant", content="Answer", reasoning_content="Plan 世界"), user]) + add("blocks", [dict(role="user", content=[dict(type="text", text="Repeated"), + dict(type="text", text="Repeated"), dict(type="text", text=" café ")])]) + tools = [dict(type="function", function=dict(name="lookup", description="Find things", + parameters=dict(type="object", properties=dict(query=dict(type="string")))))] + calls = [dict(id=str(i), type="function", function=dict(name="lookup", arguments=dict( + query="世界 & \"quoted\"", n=i, yes=True, absent=None))) for i in range(2)] + add("tools", [user], tools=tools) + add("tool_history", [user, dict(role="assistant", content="", tool_calls=calls), + dict(role="tool", tool_call_id="1", content="Second"), + dict(role="tool", tool_call_id="0", content="First"), user], tools=tools) + for effort, error in [("unknown", "Unknown reasoning_effort: unknown"), (1.0, "reasoning_effort must be in [0.0, 0.99]")]: + cases.append(dict(name=f"invalid_{effort}", messages=[user], options=dict(reasoning_effort=effort), error=error)) + with pytest.raises(ValueError, match="sole EOS"): + prepare_frontend(SNAPSHOT, eos_token_ids=[200010]) + + manifest = str(ROOT / "helios/Cargo.toml") + subprocess.run(["cargo", "build", "--locked", "--quiet", "--manifest-path", manifest, + "--features", "frontend,test-tools", "--bin", "test_frontend"], check=True) + target = json.loads(subprocess.check_output(["cargo", "metadata", "--format-version", "1", "--no-deps", + "--manifest-path", manifest], text=True))["target_directory"] + runtime = tmp_path / "runtime" + runtime.mkdir() + for name in ["tokenizer.json", "tokenizer_config.json"]: + (runtime / name).symlink_to(SNAPSHOT / name) + (runtime / "chat_template.jinja").write_text(annotated) + fingerprints = {name: hashlib.sha256((runtime / name).read_bytes()).hexdigest() + for name in ["tokenizer.json", "tokenizer_config.json", "chat_template.jinja"]} + fixture = tmp_path / "chat.json" + encode_cases, decode_cases = [], [] + for text in [user["content"], "<|message_model|><|content_text|> café <|end_message|>", "", " repeated repeated "]: + for special in [False, True]: + ids = hf.encode(text, add_special_tokens=special) + encode_cases.append(dict(name=f"encode_{text}_{special}", text=text, + add_special_tokens=special, token_ids=ids)) + decode_cases.append(dict(name=f"decode_{text}_{special}", token_ids=ids, + skip_special_tokens=special, text=hf.decode(ids, skip_special_tokens=special))) + fixture.write_text(json.dumps(dict(assets=fingerprints, cases=cases, + template_defaults=dict(add_generation_prompt=True), + default_overrides=[["default", {}], ["closed_header", dict(add_generation_prompt=False)]], + encode_cases=encode_cases, decode_cases=decode_cases))) + result = subprocess.run([str(Path(target) / "debug/test_frontend"), str(runtime), str(fixture)], + capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/preparation/test_frontend_metadata.py b/tests/preparation/test_frontend_metadata.py index eba2048f9..bbbac23ee 100644 --- a/tests/preparation/test_frontend_metadata.py +++ b/tests/preparation/test_frontend_metadata.py @@ -21,7 +21,7 @@ @pytest.mark.parametrize("recipe", recipes(), ids=lambda recipe: recipe.name) def test_default_mode_uses_manually_declared_model_card_sampling(recipe): qwen = recipe.name in ("qwen38", "qwen38_dense") - expected = dict(seed=0, temperature=1., top_p=1. if recipe.name in ("deepseek41", "kimi3") else .95, + expected = dict(seed=0, temperature=1., top_p=1. if recipe.name in ("deepseek41", "kimi3", "inkling") else .95, top_k=20 if qwen else 64 if recipe.name == "gemma4" else -1, min_p=0., repetition_penalty=1., presence_penalty=0., frequency_penalty=0.) if qwen: expected["ranges"] = {"temperature": {"min": .7, "max": 1.}, "top_p": {"min": .8, "max": .95}, diff --git a/tests/recipes/inkling_helpers.py b/tests/recipes/inkling_helpers.py new file mode 100644 index 000000000..11782107a --- /dev/null +++ b/tests/recipes/inkling_helpers.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Small checkpoints with the publisher's original tensor names and mixed precision.""" + +import json + +import torch +from safetensors.torch import save_file + +from ignition.recipes.inkling.config import ModelConfig + + +def configuration(): + return dict(architectures=["InklingForConditionalGeneration"], model_type="inkling_mm_model", eos_token_id=200006, + text_config=dict(hidden_size=256, num_hidden_layers=3, vocab_size=256, unpadded_vocab_size=250, + num_attention_heads=2, num_key_value_heads=1, head_dim=128, swa_head_dim=128, + swa_num_attention_heads=2, swa_num_key_value_heads=1, sliding_window_size=128, + d_rel=16, rel_extent=256, local_layer_ids=[0], dense_mlp_idx=1, + dense_intermediate_size=256, intermediate_size=128, n_routed_experts=4, + num_experts_per_tok=2, n_shared_experts=2, shared_expert_sink=True, + q_bias=False, o_bias=False, use_sconv=True, use_embed_norm=True, + sconv_kernel_size=4, hidden_act="silu", route_scale=8., use_gate_bias=True, + gate_activation="sigmoid", norm_after_topk=True, use_global_scale=True, + logits_mup_width_multiplier=16., final_logit_softcapping=None, + log_scaling_n_floor=128, log_scaling_alpha=.1, rms_norm_eps=1e-6, torch_dtype="bfloat16")) + + +def quantization(): + excluded = ["model.llm." + name for name in ("embed", "embed_norm", "norm", "unembed")] + for layer in range(3): + prefix = f"model.llm.layers.{layer}." + excluded.extend(prefix + name for name in ("attn", "attn_norm", "attn_sconv", "mlp_norm", "mlp_sconv")) + excluded.extend(prefix + name for name in + (("mlp.w13_dn", "mlp.w2_md", "mlp.global_scale") if layer == 0 + else ("mlp.gate", "mlp.shared_experts"))) + excluded.append("model.llm.layers.1.mlp.experts") + quantizer = dict(num_bits=[2, 1], block_sizes={"-1": 16, "type": "dynamic", "scale_bits": [4, 3]}, + axis=None, enable=True) + return dict(quant_algo="NVFP4", kv_cache_quant_algo="none", group_size=16, exclude_modules=excluded, + modelopt_quant_config=dict(algorithm="max", quant_cfg={"*weight_quantizer": quantizer, + "*input_quantizer": quantizer.copy(), "default": {"enable": False}})) + + +def checkpoint(path, *, moe_intermediate=128, routed_experts=4, top_k=2, vocabulary=None): + torch.manual_seed(7821) + raw = configuration() + raw["text_config"]["intermediate_size"] = moe_intermediate + raw["text_config"]["n_routed_experts"] = routed_experts + raw["text_config"]["num_experts_per_tok"] = top_k + if vocabulary is not None: + raw["text_config"].update(vocab_size=vocabulary[0], unpadded_vocab_size=vocabulary[1]) + quant = quantization() + config = ModelConfig.from_dict(raw, quant) + c, h = config.text, config.hidden + tensors = {} + def rand(name, shape, scale=.025, dtype=torch.bfloat16): + tensors[name] = (torch.randn(shape) * scale).to(dtype) + def ones(name, shape): + tensors[name] = torch.ones(shape, dtype=torch.bfloat16) + prefix = "model.llm" + rand(prefix + ".embed.weight", (c["vocab_size"], h), .1) + rand(prefix + ".unembed.weight", (c["vocab_size"], h), .1) + for name in ("embed_norm", "norm"): + ones(prefix + "." + name + ".weight", (h,)) + for i in range(config.layers): + p = prefix + f".layers.{i}" + a = config.attention(i) + for name, rows in (("wq_du", a.heads * a.key_dim), ("wk_dv", a.kv_heads * a.key_dim), + ("wv_dv", a.kv_heads * a.key_dim), ("wr_du", a.heads * c["d_rel"])): + rand(p + ".attn." + name + ".weight", (rows, h)) + rand(p + ".attn.wo_ud.weight", (h, a.heads * a.key_dim)) + rand(p + ".attn.rel_logits_proj.proj", (c["d_rel"], a.relative_extent)) + for name in ("q_norm", "k_norm"): + ones(p + ".attn." + name + ".weight", (a.key_dim,)) + for name in ("attn_norm", "mlp_norm"): + ones(p + "." + name + ".weight", (h,)) + for name, channels in (("attn.k_sconv", a.kv_heads * a.key_dim), ("attn.v_sconv", a.kv_heads * a.key_dim), + ("attn_sconv", h), ("mlp_sconv", h)): + rand(p + "." + name + ".weight", (channels, 1, 4), .05) + if c["mlp_layer_types"][i] == "dense": + inter = c["intermediate_size"] + rand(p + ".mlp.w13_dn.weight", (2 * inter, h)) + rand(p + ".mlp.w2_md.weight", (h, inter)) + tensors[p + ".mlp.global_scale"] = torch.tensor([1.125], dtype=torch.bfloat16) + else: + inter = c["moe_intermediate_size"] + for name, count in (("experts", c["n_routed_experts"]), ("shared_experts", c["n_shared_experts"])): + stem = "shared_" if name == "shared_experts" else "" + rand(p + f".mlp.{name}.{stem}w13_weight", (count, 2 * inter, h)) + rand(p + f".mlp.{name}.{stem}w2_weight", (count, h, inter)) + rand(p + ".mlp.gate.weight", (c["n_routed_experts"] + c["n_shared_experts"], h)) + rand(p + ".mlp.gate.bias", (c["n_routed_experts"],), .01, torch.float32) + tensors[p + ".mlp.gate.global_scale"] = torch.tensor([.14234226942062378], dtype=torch.float32) + if i in config.quantized_routed_layers: + for projection in ("w13_weight", "w2_weight"): + name = p + ".mlp.experts." + projection + original = tensors[name] + count, rows, columns = original.shape + # Random E2M1 codes, distinct block scales and per-expert gains expose row/column packing errors. + codes = torch.randint(0, 16, original.shape, dtype=torch.uint8) + tensors[name] = codes[..., ::2] | (codes[..., 1::2] << 4) + tensors[name + ".scale"] = (torch.rand(count, rows, columns // 16) * 2 + 1).to(torch.float8_e4m3fn) + tensors[name + ".scale2"] = torch.linspace(.001, .0025, count, dtype=torch.float32) + tensors[name + ".input_amax"] = torch.tensor([1.8359375 if projection == "w13_weight" else 187.], dtype=torch.bfloat16) + tensors[name + ".original_shape"] = torch.tensor(original.shape, dtype=torch.int64) + (path / "config.json").write_text(json.dumps(raw)) + (path / "hf_quant_config.json").write_text(json.dumps(dict(quantization=quant))) + save_file(tensors, path / "model.safetensors") + return config, tensors diff --git a/tests/recipes/muse_spark/test_experts_cuda.py b/tests/recipes/muse_spark/test_experts_cuda.py index 64f48d2e8..da6987023 100644 --- a/tests/recipes/muse_spark/test_experts_cuda.py +++ b/tests/recipes/muse_spark/test_experts_cuda.py @@ -56,7 +56,8 @@ def test_route_finalizer_canonical_rounding(tokens, valid): torch.testing.assert_close(output, expected, rtol=.016, atol=.015625) -def test_bf16_experts_raw_silu(): +@pytest.mark.parametrize("round_silu", [True, False]) +def test_bf16_experts_raw_silu(round_silu): from ignition.components.bf16_experts import PreparedBF16Experts from ignition.preparation.scratch import GraphBufferPool @@ -70,15 +71,21 @@ def test_bf16_experts_raw_silu(): valid = torch.tensor([13], device="cuda", dtype=torch.int32) output = torch.empty((17, 2, 128), device="cuda", dtype=torch.bfloat16) prepared = PreparedBF16Experts(source, gate_up, down, ids, weights, output, valid, - buffers=GraphBufferPool("cuda").cursor()) + buffers=GraphBufferPool("cuda").cursor(), round_silu=round_silu) expected = torch.zeros_like(output) + intermediate = torch.empty((13, 2, 64), dtype=torch.bfloat16, device="cuda") for token in range(13): for route in range(2): expert = ids[token, route].item() gate, up = torch.nn.functional.linear(source[token], gate_up[expert]).chunk(2) - expected[token, route] = torch.nn.functional.linear(torch.nn.functional.silu(gate) * up, down[expert]) + activated = (torch.nn.functional.silu(gate) * up if round_silu else + (torch.nn.functional.silu(gate.float()) * up.float()).bfloat16()) + intermediate[token, route] = activated + expected[token, route] = torch.nn.functional.linear(activated, down[expert]) prepared() - torch.testing.assert_close(output, expected, rtol=.025, atol=.002) + tolerance = dict(rtol=.025, atol=.002) if round_silu else dict(rtol=.008, atol=2e-4) + torch.testing.assert_close(prepared.intermediate[:26], intermediate.flatten(0, 1), rtol=.008, atol=2e-5) + torch.testing.assert_close(output, expected, **tolerance) assert torch.count_nonzero(output[13:]) == 0 from ignition.preparation.compilation import compile_forward run = compile_forward(prepared) @@ -86,5 +93,14 @@ def test_bf16_experts_raw_silu(): graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): run() + before = torch.cuda.memory_stats()["allocation.all.allocated"] graph.replay() - torch.testing.assert_close(output, expected, rtol=.025, atol=.002) + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + torch.testing.assert_close(output, expected, **tolerance) + assert torch.count_nonzero(output[13:]) == 0 + valid.zero_() + graph.replay() + torch.cuda.synchronize() + assert torch.count_nonzero(output) == 0 + graph.reset() diff --git a/tests/recipes/test_inkling.py b/tests/recipes/test_inkling.py new file mode 100644 index 000000000..44e280b7f --- /dev/null +++ b/tests/recipes/test_inkling.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling architecture, checkpoint-precision arithmetic, and complete cache contract.""" + +import json + +import pytest +import torch +from google.protobuf.json_format import ParseDict + +from ignition.components.paged_batch import BatchInputs +from ignition.components.parallel import TensorParallelShard +from ignition.preparation import contract as c, runtime_package_pb2 as p +from ignition.preparation.execution import GraphSignature +from ignition.recipes.inkling.config import ModelConfig +from ignition.recipes.inkling.contract import prepare +from ignition.recipes.inkling.model import route, mix_routes +from ignition.recipes.inkling.pool import ContinuationPool, page_bytes +from ignition.recipes.inkling.recipe import RECIPE +from .inkling_helpers import configuration, quantization + + +def test_canonical_geometry(): + model = ModelConfig.from_dict(configuration(), quantization()) + assert model.text["mlp_layer_types"] == ["dense", "sparse", "sparse"] + assert model.text["intermediate_size"] == 256 + assert model.text["moe_intermediate_size"] == 128 + assert [model.attention(i).window for i in range(3)] == [128, -1, -1] + assert model.quantized_routed_layers == (2,) + assert model.vocabulary == 250 + assert RECIPE.speculation is None and RECIPE.max_draft_tokens == 0 + + +@pytest.mark.parametrize("change", [ + {"q_bias": True}, {"use_sconv": False}, {"gate_activation": "softmax"}, + {"sconv_kernel_size": 3}, {"final_logit_softcapping": 30.}, +]) +def test_rejects_changed_arithmetic(change): + raw = configuration() + raw["text_config"].update(change) + with pytest.raises(ValueError): + ModelConfig.from_dict(raw, quantization()) + + +def test_checkpoint_quantization_requires_both_calibration_and_exclusions(tmp_path): + raw, quant = configuration(), quantization() + (tmp_path / "config.json").write_text(json.dumps(raw)) + with pytest.raises(FileNotFoundError, match="hf_quant_config"): + ModelConfig.load(tmp_path) + misplaced = dict(raw, quantization_config={"quant_method": "modelopt", "quant_algo": "NVFP4"}) + with pytest.raises(ValueError, match="hf_quant_config"): + ModelConfig.from_dict(misplaced, quant) + for key, value in (("group_size", 32), ("quant_algo", "W4A16_NVFP4"), ("kv_cache_quant_algo", "FP8")): + with pytest.raises(ValueError): + ModelConfig.from_dict(raw, dict(quant, **{key: value})) + quant["modelopt_quant_config"]["quant_cfg"]["*input_quantizer"]["enable"] = False + with pytest.raises(ValueError, match="weight and input"): + ModelConfig.from_dict(raw, quant) + quant = quantization() + quant["exclude_modules"].remove("model.llm.layers.1.mlp.shared_experts") + with pytest.raises(ValueError, match="shared experts"): + ModelConfig.from_dict(raw, quant) + quant = quantization() + quant["exclude_modules"].remove("model.llm.layers.1.mlp.experts") + assert ModelConfig.from_dict(raw, quant).quantized_routed_layers == (1, 2) + + +def test_fp32_router_keeps_shared_sinks_and_unrounded_checkpoint_scale(): + torch.manual_seed(718) + logits = torch.randn(13, 6, dtype=torch.float32) + bias = torch.randn(4) * .01 + scale = torch.tensor([.14234226942062378]) + ids, weights, gammas = route(logits, bias, scale, top_k=2, shared_experts=2, route_scale=8.) + expected_ids = torch.topk(logits[:, :4].sigmoid() + bias, 2, sorted=False).indices + selected = torch.cat((logits[:, :4].gather(1, expected_ids), logits[:, 4:]), -1) + expected = selected.sigmoid() + expected = expected / expected.sum(-1, keepdim=True) * 8. * scale + assert torch.equal(ids, expected_ids) + torch.testing.assert_close(torch.cat((weights, gammas), -1), expected) + torch.testing.assert_close(weights.sum(-1) + gammas.sum(-1), (8. * scale).expand(13)) + assert not torch.equal(scale, scale.bfloat16().float()) + assert weights.dtype == gammas.dtype == torch.float32 + + +def test_routed_sum_uses_checkpoint_expert_order_and_bf16_boundaries(): + ids = torch.tensor([[3, 0, 2], [2, 1, 0]]) + outputs = torch.tensor([[[1., 2.], [256., 256.], [-256., -256.]], + [[.5, .25], [128., 128.], [-128., -128.]]], dtype=torch.bfloat16) + weights = torch.ones((2, 3), dtype=torch.float32) + expected = torch.zeros((2, 2), dtype=torch.bfloat16) + for expert in range(4): + for row in range(2): + selected = (ids[row] == expert).nonzero() + if selected.numel(): + expected[row] += outputs[row, selected[0, 0]] + assert torch.equal(mix_routes(outputs, weights, ids), expected) + + +def test_contract_snapshots_every_history_and_retains_bf16_pages(): + config, shard = ModelConfig.from_dict(configuration(), quantization()), TensorParallelShard(0, 1) + pool = ContinuationPool.allocate(config, shard, 4, 3, "cpu") + assert page_bytes(config, shard) == 4 * 128 * 128 * 2 + for layer in range(config.layers): + for kind, channels in (("key", 128), ("value", 128), ("attention", 256), ("mlp", 256)): + view = pool.convolution(layer, kind) + assert view.shape == (4, channels, 3) and view.dtype == torch.float32 + assert view.stride(0) * 4 == pool.layout.row_bytes + buffers = BatchInputs.allocate(128, 2, "cpu", capacity=4).buffers() + signatures = {kind: GraphSignature(kind, 1 if "prefill" in kind else 4, + 128 if "prefill" in kind else 1, tuple(c.text_inputs(kind))) + for kind in ("init", "restore", "snapshot", "prefill", "scored_prefill", "decode", "resume")} + contract = ParseDict(prepare(signatures, buffers, pool, vocabulary=250), p.ModelContract()) + assert contract.frontend.tools.kind == p.TML_JSON + assert contract.frontend.reasoning.kind == p.CONTENT_HEADERS + histories = [r for r in contract.cache.regions if r.kind == p.PAGED_KEY_VALUE] + assert len(histories) == 4 and all(r.storage.stride == 32768 for r in histories) + assert all(any(state.view.nbytes == pool.layout.row_bytes for state in graph.state) for graph in contract.graphs) + assert all(not graph.HasField("draft_cursor") for graph in contract.graphs) diff --git a/tests/recipes/test_inkling_cuda.py b/tests/recipes/test_inkling_cuda.py new file mode 100644 index 000000000..035ff8dc9 --- /dev/null +++ b/tests/recipes/test_inkling_cuda.py @@ -0,0 +1,273 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Real prepared Inkling decoder replay across prefill, decode, and restored state.""" + +import contextlib +import json +import os + +import pytest +import torch +import torch.nn.functional as F + +from ignition.components.paged_batch import Metadata +from ignition.components.parallel import TensorParallelShard +from ignition.preparation.checkpoint import inspect_indexed_checkpoint +from ignition.preparation.compilation import compile_forward +from ignition.preparation.scratch import GraphBufferPool, ScratchArena +from ignition.preparation.tuning import RecordedPreparationSession +from ignition.recipes.inkling.decoder import PreparedDecoder, Scratch +from ignition.recipes.inkling.model import norm +from ignition.recipes.inkling.pool import ContinuationPool +from ignition.recipes.inkling.weights import InklingWeightLoader, ModelWeights +from tests.components.inkling_nvfp4_helpers import nvfp4_routes +from .inkling_helpers import checkpoint + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="requires an assigned CUDA GPU") + + +def convolution(x, weight): + y = F.conv1d(x.float().T[None], weight[:, None], padding=weight.shape[1]-1, groups=x.shape[1]) + return (y[0, :, :x.shape[0]].T + x.float()).to(x.dtype) + + +def assert_decoder_close(actual, expected): + # Tiled and dense FP32 softmax reductions can straddle a BF16 probability + # rounding boundary. Residuals and later KV history propagate that difference; + # normalize error by the vector scale so cancellation near zero stays meaningful. + epsilon = torch.finfo(torch.bfloat16).eps + reference = expected.float() + torch.testing.assert_close(actual, expected, atol=epsilon * reference.abs().max().item(), rtol=0) + assert (actual.float() - reference).norm().item() <= (epsilon / 2) * reference.norm().item() + + +def reference(weights, tokens, original): + from transformers.models.inkling.configuration_inkling import InklingTextConfig + from transformers.models.inkling.modeling_inkling import InklingAttention + + c = weights.config.text + config = InklingTextConfig.from_dict(c) + config._attn_implementation = "eager" + x = norm(weights.embedding_norm, c["rms_norm_eps"])(F.embedding(tokens, weights.embedding)) + for index, w in enumerate(weights.layers): + a = weights.config.attention(index) + attention = InklingAttention(config, index).to(device=tokens.device, dtype=torch.bfloat16).eval() + sizes = a.heads * a.key_dim, a.kv_heads * a.key_dim, a.kv_heads * a.key_dim, a.heads * c["d_rel"] + for name, value in zip(("q_proj", "k_proj", "v_proj", "r_proj"), w.qkv_relative.split(sizes)): + getattr(attention, name).weight = torch.nn.Parameter(value, requires_grad=False) + attention.o_proj.weight = torch.nn.Parameter(w.output, requires_grad=False) + attention.q_norm.weight = torch.nn.Parameter(w.query_norm, requires_grad=False) + attention.k_norm.weight = torch.nn.Parameter(w.key_norm, requires_grad=False) + attention.rel_logits_proj.proj = torch.nn.Parameter(w.relative.T, requires_grad=False) + attention.k_sconv.conv1d.weight = torch.nn.Parameter(w.key_conv[:, None], requires_grad=False) + attention.v_sconv.conv1d.weight = torch.nn.Parameter(w.value_conv[:, None], requires_grad=False) + positions = torch.arange(tokens.numel(), device=tokens.device) + distance = positions[:, None] - positions[None] + allowed = distance >= 0 + if a.window > 0: + allowed &= distance < a.window + mask = torch.where(allowed, 0., float("-inf")).bfloat16()[None, None] + attended = attention(norm(w.input_norm, c["rms_norm_eps"])(x)[None], attention_mask=mask)[0][0] + x = x + convolution(attended, w.attention_conv) + source = norm(w.post_attention_norm, c["rms_norm_eps"])(x) + def mlp(gate_up, down, gamma=None): + gate, up = F.linear(source, gate_up).float().chunk(2, dim=-1) + activated = F.silu(gate) * up + if gamma is not None: + activated *= gamma[:, None] + return F.linear(activated.bfloat16(), down) + if w.dense is not None: + out = mlp(w.dense.gate_up, w.dense.down) * w.scale + else: + # SGLang InklingGate retains FP32 logits, correction and global scale. + logits = source.float() @ w.router.float().T + ids = torch.topk(logits[:, :-c["n_shared_experts"]].sigmoid() + w.correction, + c["num_experts_per_tok"], sorted=False).indices + selected = torch.cat((logits[:, :-c["n_shared_experts"]].gather(1, ids), logits[:, -c["n_shared_experts"]:]), -1) + logp = F.logsigmoid(selected) + probabilities = (logp - logp.logsumexp(-1, keepdim=True)).exp() * c["route_scale"] * w.scale + routed = torch.zeros_like(source) + quantized = index in weights.config.quantized_routed_layers + if quantized: + # Native SM103 and b12x use different FP32 reciprocal evaluation + # orders at the same calibrated NVFP4 quantization boundary. + quant_scale_math = "flashinfer" if torch.cuda.get_device_capability(tokens.device) == (10, 3) else "b12x" + routes = nvfp4_routes(source, ids, original, f"model.llm.layers.{index}.mlp.experts", + quant_scale_math=quant_scale_math) + for expert in range(c["n_routed_experts"]): + selection = ids == expert + if quantized: + for slot in range(ids.shape[1]): + weight = probabilities[:, slot] * selection[:, slot] + routed += (routes[:, slot] * weight[:, None]).bfloat16() + else: + expert_out = mlp(w.experts.gate_up[expert], w.experts.down[expert]) + weight = (probabilities[:, :c["num_experts_per_tok"]] * selection).sum(-1) + routed += (expert_out * weight[:, None]).bfloat16() + shared = torch.stack([mlp(expert.gate_up, expert.down, + probabilities[:, c["num_experts_per_tok"] + i]) for i, expert in enumerate(w.shared)]) + out = routed + shared.float().sum(0).bfloat16() + x = x + convolution(out, w.mlp_conv) + hidden = norm(weights.norm, c["rms_norm_eps"])(x) / c["logits_mup_width_multiplier"] + return F.linear(hidden, weights.head)[:, :weights.config.vocabulary], hidden + + +@contextlib.contextmanager +def captured_decoders(tmp_path, rows, pages, shapes): + _, original = checkpoint(tmp_path) + device, shard = torch.device("cuda", 0), TensorParallelShard(0, 1) + weights = ModelWeights.load(inspect_indexed_checkpoint(tmp_path), device, shard=shard) + pool = ContinuationPool.allocate(weights.config, shard, rows, pages, device) + buffers = GraphBufferPool(device, chunk_bytes=2 << 20) + prepared, catalog, keep = {}, {}, [] + with RecordedPreparationSession(device=device, checkpoint="inkling-decoder-test", workload_schema="inkling", + numerical_policy="default", compile_workers=1) as session: + arena = ScratchArena(device) + session.register_scratch(arena) + for mode, capacity, batch in shapes: + cursor = buffers.cursor() + metadata = Metadata.allocate(capacity, batch, 5, device, buffers=cursor) + scratch = Scratch.allocate(weights.config, shard, capacity, batch, device, buffers=cursor) + decoder = PreparedDecoder(weights, scratch, metadata, pool, mode=mode, runtime=None, + embedding_runtime=None, vocabulary_runtime=None, coordinator=None, session=session, + name=mode, workspace=arena, buffers=cursor) + prepared[mode] = metadata, scratch, decoder + session.tune() + for mode, (metadata, scratch, decoder) in prepared.items(): + # Bare decoder tests must initialize metadata that PreparedBatch owns in serving. + for field in metadata.__dataclass_fields__: + value = getattr(metadata, field) + if isinstance(value, torch.Tensor): + value.fill_(-1 if field in ("positions", "page_table", "token_page_table") else 0) + compiled = compile_forward(decoder) + compiled() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + compiled() + catalog[mode] = metadata, scratch, graph + keep.append((decoder, compiled)) + session.freeze() + pool.clear_for_preparation() + try: + yield original, weights, pool, catalog + finally: + for _, _, graph in catalog.values(): + graph.reset() + + +@torch.no_grad() +def test_original_checkpoint_loader_deinterleaves_rows_without_losing_precision(tmp_path): + config, original = checkpoint(tmp_path) + manifest = inspect_indexed_checkpoint(tmp_path) + with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(0, 1)) as loader: + layer = loader.load_layer(1) + raw = original["model.llm.layers.1.mlp.experts.w13_weight"] + assert torch.equal(layer.experts.gate_up.cpu(), torch.cat((raw[:, 0::2], raw[:, 1::2]), dim=1)) + assert torch.equal(layer.correction.cpu(), original["model.llm.layers.1.mlp.gate.bias"]) + assert torch.equal(layer.scale.cpu(), original["model.llm.layers.1.mlp.gate.global_scale"]) + assert layer.correction.dtype == layer.scale.dtype == layer.key_conv.dtype == torch.float32 + assert torch.equal(layer.key_conv.cpu(), original["model.llm.layers.1.attn.k_sconv.weight"].float().flatten(1)) + + +@pytest.mark.parametrize("layer,excluded,error", [(1, False, "incomplete NVFP4"), (2, True, "interleaved BF16")]) +@torch.no_grad() +def test_loader_rejects_checkpoint_precision_disagreeing_with_exclusions(tmp_path, layer, excluded, error): + checkpoint(tmp_path) + path = tmp_path / "hf_quant_config.json" + metadata = json.loads(path.read_text()) + prefix = f"model.llm.layers.{layer}.mlp.experts" + exclusions = metadata["quantization"]["exclude_modules"] + if excluded: + exclusions.append(prefix) + exclusions.remove("model.llm.layers.1.mlp.experts") + else: + exclusions.remove(prefix) + path.write_text(json.dumps(metadata)) + with InklingWeightLoader(inspect_indexed_checkpoint(tmp_path), "cuda:0", shard=TensorParallelShard(0, 1)) as loader: + with pytest.raises(ValueError, match=error): + loader.load_layer(layer) + + +@torch.no_grad() +def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): + device = torch.device("cuda", 0) + with captured_decoders(tmp_path, 4, 5, (("prefill", 64, 1), ("decode", 1, 1))) as (original, weights, pool, catalog): + tokens = (torch.arange(259, device=device) * 17 % weights.config.vocabulary).long() + expected, expected_hidden = reference(weights, tokens, original) + start = 0 + for mode, count in (("prefill", 63), ("decode", 1), ("decode", 1), ("prefill", 62), + ("decode", 1), ("decode", 1), ("prefill", 64), ("prefill", 64), ("decode", 1), ("decode", 1)): + metadata, scratch, graph = catalog[mode] + values = torch.zeros((1, metadata.token_ids.numel()), dtype=torch.int64, device=device) + values[0, :count] = tokens[start:start+count] + metadata.set(torch.tensor([start], device=device), torch.tensor([count], device=device, dtype=torch.int32), + torch.tensor([1], device=device), torch.arange(5, device=device, dtype=torch.int32)[None], + values, torch.ones(1, device=device, dtype=torch.int32)) + metadata.sample_indices.fill_(count - 1) + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + start += count + assert_decoder_close(scratch.logits[0], expected[start - 1]) + assert_decoder_close(scratch.hidden[0], expected_hidden[start - 1]) + assert start == tokens.numel() + saved = pool.backing.clone() + pages = {name: value.clone() for name, value in pool.pages.items()} + metadata, scratch, graph = catalog["decode"] + metadata.starts.fill_(start) + metadata.positions.fill_(start) + metadata.token_ids.fill_(13) + graph.replay() + torch.cuda.synchronize() + branch = scratch.logits.clone() + pool.backing.copy_(saved) + for name, value in pages.items(): + pool.pages[name].copy_(value) + graph.replay() + torch.cuda.synchronize() + assert torch.equal(branch, scratch.logits) + saved = pool.backing.clone() + metadata.lengths.zero_() + metadata.query_start_loc.zero_() + metadata.live_counts.zero_() + metadata.positions.fill_(-1) + metadata.state_rows.zero_() + graph.replay() + torch.cuda.synchronize() + assert torch.equal(saved, pool.backing) + + +@torch.no_grad() +def test_decoder_batched_decode_with_inactive_rows_after_window_wrap(tmp_path): + device = torch.device("cuda", 0) + with captured_decoders(tmp_path, 5, 10, (("prefill", 192, 1), ("decode", 4, 4))) as (original, weights, pool, catalog): + sequences = [(torch.arange(length + 1, device=device) * (17 + row) % weights.config.vocabulary).long() + for row, length in enumerate((129, 131))] + for row, sequence in enumerate(sequences): + m, s, graph = catalog["prefill"] + values = torch.zeros((1, 192), dtype=torch.int64, device=device) + values[0, :sequence.numel()-1] = sequence[:-1] + m.set(torch.zeros(1, device=device, dtype=torch.int64), + torch.tensor([sequence.numel()-1], device=device, dtype=torch.int32), + torch.tensor([row+1], device=device), (torch.arange(5, device=device, dtype=torch.int32) + row*5)[None], + values, torch.ones(1, device=device, dtype=torch.int32)) + m.sample_indices.fill_(sequence.numel()-2) + graph.replay() + untouched = pool.backing[[0, 3, 4]].clone() + m, s, graph = catalog["decode"] + m.set(torch.tensor([129, 0, 131, 0], device=device), torch.tensor([1, 0, 1, 0], device=device, dtype=torch.int32), + torch.tensor([1, 3, 2, 4], device=device), + torch.tensor([[0, 1, 2, 3, 4], [-1]*5, [5, 6, 7, 8, 9], [-1]*5], dtype=torch.int32, device=device), + torch.stack((sequences[0][-1:], torch.zeros(1, dtype=torch.int64, device=device), + sequences[1][-1:], torch.zeros(1, dtype=torch.int64, device=device))), + torch.tensor([4], device=device, dtype=torch.int32)) + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + assert torch.equal(untouched, pool.backing[[0, 3, 4]]) + for row, sequence in zip((0, 2), sequences): + expected, _ = reference(weights, sequence, original) + assert_decoder_close(s.logits[row], expected[-1]) diff --git a/tests/recipes/test_inkling_preparation_cuda.py b/tests/recipes/test_inkling_preparation_cuda.py new file mode 100644 index 000000000..555ccda32 --- /dev/null +++ b/tests/recipes/test_inkling_preparation_cuda.py @@ -0,0 +1,151 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Single-rank preparation and replay of the complete Inkling graph catalog.""" + +import os +from pathlib import Path + +import pytest +import torch + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an explicitly assigned CUDA device") + + +@torch.no_grad() +def test_single_rank_mixed_checkpoint_prepares_and_replays_catalog(tmp_path): + from ignition.components.parallel import TensorParallelShard + from ignition.components.sampling import AdmissionBuffers, DeviceRequestState, RequestAdmission + from ignition.preparation.package_storage import PackageStorage + from ignition.recipes.inkling.bootstrap import PreparationConfig, prepare + from ignition.recipes.inkling.config import ModelConfig + from ignition.recipes.inkling.pool import ContinuationPool, continuation_layout + from .inkling_helpers import checkpoint + + if torch.cuda.get_device_capability() != (10, 3): + pytest.skip("Inkling preparation requires an SM103 GPU") + snapshot = Path(os.environ.get("FLARE_INKLING_SNAPSHOT", "")) + if not (snapshot / "tokenizer.json").is_file(): + pytest.skip("requires pinned Inkling frontend assets") + # Keep the publisher's frontend and special-token IDs while reducing layer geometry. + publisher = ModelConfig.load(snapshot) + checkpoint(tmp_path, vocabulary=(publisher.text["vocab_size"], publisher.vocabulary)) + for name in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja"): + (tmp_path / name).symlink_to(snapshot / name) + config = ModelConfig.load(tmp_path) + preparation = PreparationConfig(device=0, context=256, prefill_chunk_size=128, max_active=1, + snapshot_budget_bytes=continuation_layout(config, TensorParallelShard(0, 1)).row_bytes, + compile_workers=1, autotune_effort="off", headroom_bytes=1 << 30, prompt_logprobs=True) + with PackageStorage(device=0) as storage: + with prepare(tmp_path, preparation, package_storage=storage) as model: + assert {signature.kind for signature in model.signatures.values()} == { + "init", "restore", "snapshot", "prefill", "scored_prefill", "decode", "resume"} + assert model.memory_report["compiled_decoder"] + assert model.server_config["frontend"]["eos_token_ids"] == [200006] + pool = next(resource for resource in model.resources if isinstance(resource, ContinuationPool)) + requests = next(resource for resource in model.resources if isinstance(resource, DeviceRequestState)) + buffers = model.buffers + buffers["live_rows"].zero_() + buffers["admission_count"].zero_() + buffers["state_num_ops"].zero_() + before = pool.backing.clone() + physical_pages = int(pool.memory_capacity[1].item()) + pages_before = {name: page[:physical_pages].clone() for name, page in pool.pages.items()} + allocations = torch.cuda.memory_stats()["allocation.all.allocated"] + for graph in model.graphs.values(): + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations + assert torch.equal(pool.backing, before) + assert all(torch.equal(page[:physical_pages], pages_before[name]) for name, page in pool.pages.items()) + buffers["request_state_rows"][0, 0] = 1 + buffers["row_slot_ids"][0] = 0 + buffers["live_rows"].fill_(1) + buffers["page_tables"][0].copy_(torch.tensor([0, 1], device="cuda")) + prompt = list(range(127)) + + def replay(name): + allocations = torch.cuda.memory_stats()["allocation.all.allocated"] + model.graphs[name].replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations + assert requests.error_code[0].item() == 0 + + def state_command(*, source, destination, operation, consumed): + for name, value in dict(request_slots=0, source_slots=source, destination_slots=destination, + operation=operation, expected_consumed=consumed, num_ops=1).items(): + buffers["state_" + name].fill_(value) + + def admit(generation, *, restore=False): + admission = AdmissionBuffers.allocate("cpu", vocab_size=config.vocabulary, capacity=1) + admission.stage(0, 0, RequestAdmission(generation, 13, max_new_tokens=8, top_k=1), prompt) + admission.admission_count.fill_(1) + for name in admission.__dataclass_fields__: + buffers[name].copy_(getattr(admission, name)) + buffers["row_generations"][0] = generation + state_command(source=2 if restore else -1, destination=1, + operation=0 if restore else 1, consumed=127 if restore else 0) + replay("restore1" if restore else "init1") + buffers["state_num_ops"].zero_() + buffers["admission_count"].zero_() + + def prefill(*, scored=False): + buffers["query_lengths"][0] = len(prompt) + buffers["token_ids"][:len(prompt)].copy_(torch.tensor(prompt, device="cuda")) + buffers["sample_enabled"][0] = 0 + replay("scored_prefill128" if scored else "prefill128") + assert requests.consumed_tokens[0].item() == 127 + + def continuation(): + replay("resume1") + tokens = [requests.pending_token[0].item()] + buffers["query_lengths"][0] = buffers["sample_enabled"][0] = 1 + for _ in range(2): + replay("decode1") + tokens.append(requests.pending_token[0].item()) + assert requests.consumed_tokens[0].item() == 129 + # Live histories exclude the embedded partial-page snapshot copies; + # compare their active external KV pages instead. + state = {region.name: pool.region(region.name)[1].clone() + for region in pool.layout.regions + if region.name not in pool.pages and region.name != "consumed_tokens"} + state.update({f"pages.{layer}.{kind}": pool.cache(layer, kind).flatten(0, 1)[:129].clone() + for layer in range(config.layers) if config.attention(layer).window < 0 + for kind in ("key", "value")}) + return tokens, state + + admit(7) + prefill() + hidden = pool.last_hidden[1].clone() + state_command(source=1, destination=2, operation=0, consumed=127) + replay("snapshot1") + buffers["state_num_ops"].zero_() + snapshot_row = pool.backing[2].clone() + expected_tokens, expected_state = continuation() + + admit(8, restore=True) + assert requests.consumed_tokens[0].item() == 127 + assert torch.equal(pool.last_hidden[1], hidden) + tokens, state = continuation() + assert tokens == expected_tokens + torch.testing.assert_close(state, expected_state, atol=0, rtol=0) + assert torch.equal(pool.backing[2], snapshot_row) + + admit(9) + buffers["prompt_target_tokens"].fill_(-1) + buffers["prompt_target_tokens"][:126].copy_(torch.tensor(prompt[1:], device="cuda")) + prefill(scored=True) + assert torch.equal(pool.last_hidden[1], hidden) + scores = buffers["prompt_logprobs"][int(buffers["frame_index"].item())].cpu() + logprobs = scores[:, 1].contiguous().view(torch.float32) + assert scores[:126, 0].tolist() == prompt[1:] + assert torch.isfinite(logprobs[:126]).all() + assert (logprobs[:126] <= 0).all() + assert ((scores[:126, 2] >= 1) & (scores[:126, 2] <= config.vocabulary)).all() + assert (scores[126:, 0] == -1).all() + assert torch.isnan(logprobs[126:]).all() + tokens, state = continuation() + assert tokens == expected_tokens + torch.testing.assert_close(state, expected_state, atol=0, rtol=0) + assert torch.equal(pool.backing[2], snapshot_row) diff --git a/tests/recipes/test_inkling_topology.py b/tests/recipes/test_inkling_topology.py new file mode 100644 index 000000000..ab88f65fa --- /dev/null +++ b/tests/recipes/test_inkling_topology.py @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling NVFP4 preparation limits and memory planning through the shared planner.""" + +import os +from pathlib import Path + +import pytest +from huggingface_hub.constants import HF_HUB_CACHE + +from ignition import planning +from ignition.components.parallel import TensorParallelShard +from ignition.recipes import resolve +from ignition.recipes.inkling import bootstrap +from ignition.recipes.inkling.config import ModelConfig +from ignition.recipes.inkling.pool import continuation_layout, page_bytes +from ignition.recipes.inkling.recipe import RECIPE + + +def test_minimum_prefill_chunk_is_accepted(): + assert bootstrap.PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 + + +@pytest.mark.parametrize('values,match', [ + (dict(context=100), '128-aligned'), (dict(prefill_chunk_size=96), '64-aligned'), +]) +def test_invalid_preparation_config_rejects_before_loading(values, match): + with pytest.raises(ValueError, match=match): + bootstrap.PreparationConfig(**values) + + +def test_unsupported_gpu_is_rejected_before_checkpoint_loading(monkeypatch, tmp_path): + monkeypatch.setattr(bootstrap.torch.cuda, 'set_device', lambda device: None) + monkeypatch.setattr(bootstrap.torch.cuda, 'get_device_capability', lambda device: (12, 1)) + with pytest.raises(ValueError, match='requires an SM103'): + bootstrap.prepare(tmp_path / 'not-downloaded', bootstrap.PreparationConfig(), package_storage=None) + + +def test_nvfp4_plan_fits_one_station(): + model = resolve('inkling-small-nvfp4') + assert model.recipe is RECIPE and model.checkpoint.repository == 'thinkingmachines/Inkling-Small-NVFP4' + station = planning.Gpu(0, 'NVIDIA GB300', 'GPU-0', 256 << 30, 240 << 30, (10, 3)) + plan = planning.plan(RECIPE, model.checkpoint, (station,), selected=None, + concurrency=4, reserve_bytes=4 << 30, speculation=None) + assert plan.world_size == 1 and plan.fits + assert plan.context == plan.guaranteed_tokens == 262144 + + +def test_declared_costs_match_publisher_cache_geometry(): + snapshot = Path(os.environ.get('FLARE_INKLING_SNAPSHOT') or resolve('inkling-small-nvfp4').snapshot(Path(HF_HUB_CACHE))) + if not (snapshot / 'hf_quant_config.json').is_file(): + pytest.skip('Inkling checkpoint metadata is unavailable') + config, shard = ModelConfig.load(snapshot), TensorParallelShard(0, 1) + costs = RECIPE.costs(1, None) + assert costs.state_row_bytes == continuation_layout(config, shard).row_bytes + assert costs.page_bytes == page_bytes(config, shard) diff --git a/tests/server/test_inkling.py b/tests/server/test_inkling.py new file mode 100644 index 000000000..e4bdfad58 --- /dev/null +++ b/tests/server/test_inkling.py @@ -0,0 +1,168 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Acceptance for an Inkling NVFP4 package exported with prompt logprobs and served by Flare. + +Set FLARE_RUN_CUDA_TESTS=1, FLARE_INKLING_TEST_URL and FLARE_INKLING_SNAPSHOT. +The package uses the default 262144-token context and concurrency four. +""" + +from concurrent.futures import ThreadPoolExecutor +import json +import math +import os +from pathlib import Path +import urllib.error +import urllib.request + +import pytest + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1" + or not os.environ.get("FLARE_INKLING_TEST_URL"), reason="requires an exported Inkling package served by flare run") + + +LONG_INPUTS = (4097, 8193, 16385, 32769, 65537, 262080) +CASES = ([("text", i) for i in range(32)] + [("tool", i) for i in range(12)] + + [("long", i) for i in range(6)]) + + +@pytest.fixture(scope="module") +def checkpoint_frontend(): + from transformers import PreTrainedTokenizerFast + + root = Path(os.environ["FLARE_INKLING_SNAPSHOT"]) + return PreTrainedTokenizerFast.from_pretrained(root), (root / "chat_template.jinja").read_text() + + +@pytest.fixture(scope="module") +def service(checkpoint_frontend): + tokenizer, template = checkpoint_frontend + url = os.environ["FLARE_INKLING_TEST_URL"].rstrip("/") + def request(path, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url + path, data, {"Content-Type": "application/json", + "Authorization": "Bearer " + os.environ.get("FLARE_API_TEST_KEY", "local")}) + with urllib.request.urlopen(req, timeout=1800) as response: + return json.load(response) + card, = request("/v1/models")["data"] + assert "inkling" in card["id"].lower() + assert card["max_model_len"] == 262144 + assert card["flare"]["max_concurrency"] == 4 + assert card["flare"]["input_modalities"] == ["text"] + assert card["flare"]["sampling_defaults"]["temperature"] == 1. + def ask(messages, **options): + body = dict(model=card["id"], messages=messages, seed=58123, max_tokens=128, + return_token_ids=True, chat_template_kwargs=dict(reasoning_effort="none")) + body.update(options) + result = request("/v1/chat/completions", body) + expected_messages = messages + if options.get("tool_choice") == "required": + expected_messages = [dict(role="system", content="You must call at least one of the provided tools in your next response. Choose the appropriate tool and arguments."), *messages] + expected = tokenizer.apply_chat_template(expected_messages, chat_template=template, tokenize=True, + return_dict=False, add_generation_prompt=True, tools=options.get("tools"), **body["chat_template_kwargs"]) + assert result["prompt_token_ids"] == expected + assert result["usage"]["completion_tokens"] == len(result["choices"][0]["token_ids"]) + return result + return ask + + +def text(result): + return (result["choices"][0]["message"].get("content") or "").strip() + + +@pytest.mark.parametrize("effort", ["minimal", "low", "medium", "high", "max"]) +def test_reasoning_headers(service, effort): + result = service([dict(role="user", content="A store has 7 boxes of 13 bolts, sells 19 bolts and receives two more boxes. How many bolts remain? Put only the integer in the final answer.")], + max_tokens=2048, chat_template_kwargs=dict(reasoning_effort=effort)) + assert text(result) == "98" + assert result["choices"][0]["message"]["reasoning_content"] + + +def test_prefix_branches_preserve_convolution_histories(service): + prefix = "Preserve this context before answering the final question. " * 1600 + history = [dict(role="user", content=prefix), dict(role="assistant", content="I have read the context.")] + def ask(index): + return service([*history, dict(role="user", content=f"Reply with only INKLING-BRANCH-{index}.")]) + first, second = ask(0), ask(0) + assert first["choices"][0]["token_ids"] == second["choices"][0]["token_ids"] + assert second["usage"]["prompt_tokens_details"]["cached_tokens"] > 4096 + with ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(ask, range(4))) + assert [text(result) for result in results] == [f"INKLING-BRANCH-{i}" for i in range(4)] + + +def test_prompt_scores(service): + result = service([dict(role="user", content="A cache preserves context. café 世界.")], max_tokens=1, prompt_logprobs=2) + assert len(result["prompt_logprobs"]) == len(result["prompt_token_ids"]) + assert result["prompt_logprobs"][0] is None + for token, scores in zip(result["prompt_token_ids"][1:], result["prompt_logprobs"][1:]): + assert str(token) in scores + assert all(math.isfinite(value["logprob"]) and value["logprob"] <= 0 for value in scores.values()) + + +@pytest.mark.parametrize("content", [ + [dict(type="image_url", image_url=dict(url="data:image/png;base64,AA=="))], + [dict(type="input_audio", input_audio=dict(data="AA==", format="wav"))], +], ids=["image", "audio"]) +def test_unsupported_media_is_rejected(service, content): + with pytest.raises(urllib.error.HTTPError) as rejected: + service([dict(role="user", content=content)]) + assert rejected.value.code == 400 + + +def long_prompt(frontend, target): + tokenizer, template = frontend + head = "The secret code is INKLING-84127. Remember it while reading the filler.\n" + tail = "\nWhat is the secret code? Reply with only the code." + + def length(prompt): + return len(tokenizer.apply_chat_template([dict(role="user", content=prompt)], + chat_template=template, tokenize=True, return_dict=False, + add_generation_prompt=True, reasoning_effort="none")) + + # Each additional filler contributes one token in the pinned checkpoint tokenizer. + count = target - length(head + " filler" + tail) + 1 + prompt = head + " filler" * count + tail + assert length(prompt) == target + return prompt + + +@pytest.mark.parametrize("kind,index", CASES, ids=[f"{kind}-{i}" for kind, i in CASES]) +def test_fifty_generation_cases(service, checkpoint_frontend, kind, index): + options = dict(max_tokens=64) + if kind == "text": + if index < 20: + a, b = 31 + index, 47 - index + prompt = f"What is {a} times {b}? Reply with only the integer." + expected = str(a * b) + else: + expected = ["INKLING-64283", "café noir", "世界和平", "naïve", "á", "Δοκιμή", + "مرحبا", "日本語", "Straße", "한국어", "mañana", "résumé"][index - 20] + prompt = "Repeat exactly this text, without quotation marks or explanation: " + expected + elif kind == "tool": + expected = dict(value=index + 11, label=f"café 世界 {index}") + function = dict(name="record_value", description="Record the supplied value exactly.", + parameters=dict(type="object", properties=dict(value=dict(type="integer"), label=dict(type="string")), + required=["value", "label"], additionalProperties=False)) + options["tools"] = [dict(type="function", function=function)] + options["tool_choice"] = ("required" if index % 2 else + dict(type="function", function=dict(name="record_value"))) + prompt = "Call record_value once with exactly these arguments:\n" + json.dumps(expected) + else: + prompt = long_prompt(checkpoint_frontend, LONG_INPUTS[index]) + expected = "INKLING-84127" + + result = service([dict(role="user", content=prompt)], **options) + choice = result["choices"][0] + assert 0 < result["usage"]["completion_tokens"] <= 64 + assert result["usage"]["prompt_tokens"] == len(result["prompt_token_ids"]) + if kind == "tool": + call, = choice["message"]["tool_calls"] + assert call["function"]["name"] == "record_value" + assert json.loads(call["function"]["arguments"]) == expected + assert choice["finish_reason"] == "tool_calls" + else: + assert text(result) == expected + assert choice["finish_reason"] == "stop" + if kind == "long": + assert result["usage"]["prompt_tokens"] == LONG_INPUTS[index]