From 81044d149bbdb71977e00265e52fe1f6c616bf5d Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 3 Nov 2026 16:12:07 -0800 Subject: [PATCH 1/5] Add Inkling-Small BF16 text recipe Prepare the pinned thinkingmachines/Inkling-Small text checkpoint on eight local GPUs. Preserve canonical decoder composition, FP32 router and convolution state, learned relative attention, complete cache snapshots, and original BF16 checkpoint weights. Add native content-header reasoning, JSON tools, template parity, and request grammar integration using existing graph operation contracts. Validation: 22 focused recipe/component/sampling checks passed on SM120 with both the declared and lockfile FlashInfer revisions. Checkpoint frontend parity and native output (79), Jinja (15), grammar (20), contract (6), and request (1) checks passed. Broader Python checks: 72 passed, 13 skipped, and two unchanged sampling-expectation failures reproduced on the base commit. Full-checkpoint TP8 export/serving, long-context behavior, and SM103/SM121 remain unqualified. The available GPU has 8 GB. Reduced operator export reaches kernel serialization but the existing package hardware validator rejects its laptop PCI ID; native exported-package replay is unvalidated. Image/audio preparation and MTP are outside this text recipe. Design-Signed-Off-By: Codex (GPT-6); design-review=a38f Signed-off-by: Arthur --- docs/model-preparation.md | 59 +++ helios/model-contract.md | 10 + helios/proto/runtime_package.proto | 2 + helios/src/frontend/jinja/tests.rs | 14 + helios/src/frontend/jinja/vm.rs | 11 + helios/src/grammar.rs | 42 +- helios/src/model/contract.rs | 39 +- helios/src/model/prompt.rs | 12 +- helios/src/output.rs | 2 + helios/src/output/pipeline.rs | 8 +- helios/src/output/tml.rs | 469 ++++++++++++++++++ helios/src/server/output.rs | 35 ++ helios/src/server/request.rs | 4 + helios/src/server/request/tml_tests.rs | 192 +++++++ .../tests/inkling_operator_package_fixture.py | 125 +++++ ignition/components/bf16_experts.py | 12 +- ignition/components/native_operator.py | 15 + .../components/relative_paged_attention.py | 210 ++++++++ ignition/components/residual_short_conv.py | 193 +++++++ ignition/preparation/runtime_package_pb2.py | 40 +- ignition/recipes/__init__.py | 3 +- ignition/recipes/inkling/__init__.py | 4 + .../inkling/assets/chat_template.patch.json | 15 + ignition/recipes/inkling/attention.py | 144 ++++++ ignition/recipes/inkling/bootstrap.py | 250 ++++++++++ ignition/recipes/inkling/config.py | 92 ++++ ignition/recipes/inkling/contract.py | 26 + ignition/recipes/inkling/decoder.py | 188 +++++++ ignition/recipes/inkling/frontend.py | 40 ++ ignition/recipes/inkling/model.py | 52 ++ ignition/recipes/inkling/pool.py | 100 ++++ ignition/recipes/inkling/recipe.py | 43 ++ ignition/recipes/inkling/weights.py | 148 ++++++ pyproject.toml | 1 + .../components/test_inkling_operators_cuda.py | 240 +++++++++ tests/components/test_inkling_package_cuda.py | 28 ++ tests/frontend/test_inkling.py | 116 +++++ tests/preparation/test_frontend_metadata.py | 2 +- tests/recipes/inkling_helpers.py | 75 +++ tests/recipes/test_inkling.py | 108 ++++ tests/recipes/test_inkling_cuda.py | 253 ++++++++++ tests/server/test_inkling.py | 124 +++++ 42 files changed, 3510 insertions(+), 36 deletions(-) create mode 100644 helios/src/output/tml.rs create mode 100644 helios/src/server/request/tml_tests.rs create mode 100644 helios/tests/inkling_operator_package_fixture.py create mode 100644 ignition/components/relative_paged_attention.py create mode 100644 ignition/components/residual_short_conv.py create mode 100644 ignition/recipes/inkling/__init__.py create mode 100644 ignition/recipes/inkling/assets/chat_template.patch.json create mode 100644 ignition/recipes/inkling/attention.py create mode 100644 ignition/recipes/inkling/bootstrap.py create mode 100644 ignition/recipes/inkling/config.py create mode 100644 ignition/recipes/inkling/contract.py create mode 100644 ignition/recipes/inkling/decoder.py create mode 100644 ignition/recipes/inkling/frontend.py create mode 100644 ignition/recipes/inkling/model.py create mode 100644 ignition/recipes/inkling/pool.py create mode 100644 ignition/recipes/inkling/recipe.py create mode 100644 ignition/recipes/inkling/weights.py create mode 100644 tests/components/test_inkling_operators_cuda.py create mode 100644 tests/components/test_inkling_package_cuda.py create mode 100644 tests/frontend/test_inkling.py create mode 100644 tests/recipes/inkling_helpers.py create mode 100644 tests/recipes/test_inkling.py create mode 100644 tests/recipes/test_inkling_cuda.py create mode 100644 tests/server/test_inkling.py diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 321470744..45ca6c003 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 @@ -982,6 +983,64 @@ 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 + +The `inkling-small` alias selects the BF16 +[`thinkingmachines/Inkling-Small`](https://huggingface.co/thinkingmachines/Inkling-Small) +checkpoint at revision `8cc5877b44d343f88b92086aa1fb72897950f06a`. +This text recipe prepares eight GPUs on one host, a default 262144-token context, +four concurrent requests, and 4096-token prefill chunks. This initial recipe caps +prepared context at 262144 tokens of the checkpoint's 1048576-token limit. Image, audio, video, and +MTP graphs are not prepared. The indexed download includes the publisher's MTP +weights; only `model.llm` tensors become serving weights. + +The 42-layer decoder retains 35 local 512-token KV rings and seven global paged +histories in BF16. Query-dependent relative logits, head RMS normalization, +`1 / head_dim` attention scaling, and global logarithmic position scaling follow +the checkpoint. Four residual short convolutions per layer retain FP32 history +and arithmetic. Every continuation row includes those histories, local rings, +partial global pages, the consumed cursor, and the normalized and scaled hidden +vector used by resume. + +The BF16 checkpoint stores router correction biases and global scales in FP32. +They remain FP32, as do router logits and route normalization. Dense and expert +SwiGLU arithmetic uses FP32 before rounding the final intermediate to BF16; +shared sink weights apply before the down projection. These precision boundaries +follow the publisher-supported SGLang +[router](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/moe.py) +and [MLP implementation](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/dense_mlp.py). +Transformers supplies the reference attention, normalization, and checkpoint +layout; loading it with a blanket BF16 dtype also narrows the FP32 router +parameters, so that load mode is not the precision reference for routing. + +At tensor parallelism eight, resident text weights occupy 65,993,544,868 bytes +per rank, including replicated parameters and FP32 convolution weights. Each +continuation row occupies 14,024,704 bytes; each 128-token global KV page occupies +458,752 bytes per rank. The planner reserves additional space for preparation, +graphs, and caches. The complete indexed source tensors occupy 531,912,898,740 +bytes on disk. This BF16 recipe therefore requires GPUs with substantially more +memory than the 8 GB device used for the reduced model tests. + +The publisher's [Inkling sampling guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) +recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, +`top_k=-1`, `min_p=0`) and penalties are neutral. The pinned checkpoint template +owns the thinking-effort system message and content-header/tool syntax. + +```sh +.venv/bin/ignition export inkling-small --gpus 0-7 --prompt-logprobs +.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-tp8.safetensors +flare/target/release/flare run /data/flare-runtime/inkling-small-tp8.safetensors --gpus 0,1,2,3,4,5,6,7 +``` + +Reduced model validation covers original-format weight loading, learned relative +attention, FP32 residual convolution, complete compiled decoder replay across +prefill/decode and page/window boundaries, state restoration, inactive rows, and +allocation stability on SM120. Full-checkpoint TP8 export and native serving, +long-context behavior, and SM103/SM121 execution remain unqualified. Run +`tests/server/test_inkling.py` against the exported package with +`FLARE_RUN_CUDA_TESTS=1`, `FLARE_INKLING_TEST_URL`, and +`FLARE_INKLING_SNAPSHOT` set before promoting this draft recipe. + ## Muse Spark Open The `muse-spark-open-nvfp4` alias selects diff --git a/helios/model-contract.md b/helios/model-contract.md index ee3cfd609..8ab4bcdfa 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -256,6 +256,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 0c341e08e..378f36ec0 100644 --- a/helios/proto/runtime_package.proto +++ b/helios/proto/runtime_package.proto @@ -337,6 +337,7 @@ enum ToolParserKind { MINIMAX_XML = 5; GEMMA_CALL = 6; ATEM = 7; + TML_JSON = 8; } enum ReasoningParserKind { REASONING_PARSER_UNSPECIFIED = 0; @@ -345,6 +346,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..b9b5db788 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, } @@ -307,6 +308,9 @@ impl GrammarCompiler { } fn compile_recipient(&self, mut grammar: TopLevelGrammar, envelope: &RecipientEnvelope) -> Result { + if envelope.syntax == crate::model::contract::ToolParserKind::TmlJson { + return self.compile_content_headers(grammar, envelope); + } use crate::output::tagged::OutputStart; let mut rules = String::new(); let marker = |text: &str| self.marker(text); @@ -354,6 +358,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 +1791,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 acc6cdafd..6c307b2b6 100644 --- a/helios/src/model/contract.rs +++ b/helios/src/model/contract.rs @@ -60,8 +60,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 }); @@ -628,6 +628,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 => ("", ""), @@ -635,6 +640,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(""), @@ -650,7 +656,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 @@ -680,8 +686,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()); @@ -696,6 +702,29 @@ 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()); + let encoded = serde_json::to_value(&syntax).unwrap(); + assert_eq!(encoded["tools"]["kind"], 8); + assert_eq!(encoded["reasoning"]["kind"], 6); + assert!(serde_json::from_value::(encoded).unwrap().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..5cee84ac9 100644 --- a/helios/src/model/prompt.rs +++ b/helios/src/model/prompt.rs @@ -279,10 +279,13 @@ pub fn prepare_output( let mut control_tokens = if syntax .tools .as_ref() - .is_some_and(|tool| matches!(tool.kind, super::contract::ToolParserKind::Xtml | super::contract::ToolParserKind::Atem)) + .is_some_and(|tool| matches!(tool.kind, super::contract::ToolParserKind::Xtml | super::contract::ToolParserKind::Atem | super::contract::ToolParserKind::TmlJson)) { let markers = if syntax.tools.as_ref().unwrap().kind == super::contract::ToolParserKind::Atem { vec!["<|start|>", "<|message|>", "<|eom|>", "<|eot|>"] + } else if syntax.tools.as_ref().unwrap().kind == super::contract::ToolParserKind::TmlJson { + vec!["<|message_model|>", "<|content_text|>", "<|content_thinking|>", + "<|content_invoke_tool_json|>", "<|end_message|>", "<|content_model_end_sampling|>"] } else { vec!["<|open|>", "<|close|>", "<|sep|>"] }; markers.into_iter() .map(|marker| { @@ -313,8 +316,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..7f324e0df 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), @@ -109,7 +112,7 @@ impl OutputPipeline { /// XTML and recipient-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..f841a8ed4 --- /dev/null +++ b/helios/src/output/tml.rs @@ -0,0 +1,469 @@ +/* + * 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; + +pub const START: &str = "<|message_model|>"; +pub const TEXT: &str = "<|content_text|>"; +pub const THINK: &str = "<|content_thinking|>"; +pub const TOOL: &str = "<|content_invoke_tool_json|>"; +pub const END: &str = "<|end_message|>"; +pub 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>>>, + controls: 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, controls: 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![], + controls, + 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.controls.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.controls.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..40d4141b1 --- /dev/null +++ b/helios/src/server/request/tml_tests.rs @@ -0,0 +1,192 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +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, + &[], + ) + .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..e4767ed95 --- /dev/null +++ b/helios/tests/inkling_operator_package_fixture.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Export relative attention and residual convolution for independent 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, result): + self.attention, self.convolution, self.result = attention, convolution, result + + def __call__(self): + attention = self.attention() + convolution = self.convolution() + history = self.convolution.arguments[2] + end = attention.numel() + convolution.numel() + self.result[:attention.numel()].copy_(attention.flatten()) + self.result[attention.numel():end].copy_(convolution.flatten()) + self.result[end:].copy_(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.scratch import ScratchArena + 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: + arena = ScratchArena(device) + session.register_scratch(arena) + 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, workspace=arena, 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, workspace=arena, name="residual-convolution") + result = torch.empty(query.numel() + source.numel() + history.numel(), device=device) + run = OperatorForward(attention, convolution, 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/native_operator.py b/ignition/components/native_operator.py index 4bc65b88e..46884045f 100644 --- a/ignition/components/native_operator.py +++ b/ignition/components/native_operator.py @@ -10,9 +10,24 @@ 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): + """Make an Ignition Triton factory's executable cache reclaimable by b12x. + + b12x discovers its own JIT functions automatically. Its mapping registration + also covers local functions, so deferred planning entries and losing tactics + are reclaimed at the same preparation boundaries. + """ + 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..524bd2c9e --- /dev/null +++ b/ignition/components/relative_paged_attention.py @@ -0,0 +1,210 @@ +# 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) + # Two bounded scans preserve canonical BF16 softmax-probability rounding. + # A materialized [queries, context] score or probability tensor is unnecessary. + 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, workspace, 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..b7d1efc06 --- /dev/null +++ b/ignition/components/residual_short_conv.py @@ -0,0 +1,193 @@ +# 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: + query: Query + tactic: tuple + programs: dict + + def run(self, tensors): + x, _, _, states, _, _, cu, 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, workspace, 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(q, 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 3675ec196..031b2adb4 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\"\xe1\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(\tB\x1b\n\x19_expert_scale_compression\"\x9a\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\x42\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\"\xe1\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(\tB\x1b\n\x19_expert_scale_compression\"\x9a\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\x42\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=15691 _globals['_GRAPHOPERATION']._serialized_end=15936 _globals['_TOOLPARSERKIND']._serialized_start=15939 - _globals['_TOOLPARSERKIND']._serialized_end=16086 - _globals['_REASONINGPARSERKIND']._serialized_start=16089 - _globals['_REASONINGPARSERKIND']._serialized_end=16234 - _globals['_IMAGEPREPARATIONKIND']._serialized_start=16237 - _globals['_IMAGEPREPARATIONKIND']._serialized_end=16574 - _globals['_IMAGELAYOUTKIND']._serialized_start=16577 - _globals['_IMAGELAYOUTKIND']._serialized_end=16857 - _globals['_PROMPTENCODER']._serialized_start=16859 - _globals['_PROMPTENCODER']._serialized_end=16927 - _globals['_TEMPLATEENCODING']._serialized_start=16929 - _globals['_TEMPLATEENCODING']._serialized_end=16995 - _globals['_MEMORY']._serialized_start=16997 - _globals['_MEMORY']._serialized_end=17044 - _globals['_CAPACITY']._serialized_start=17046 - _globals['_CAPACITY']._serialized_end=17086 - _globals['_RELOCATIONKIND']._serialized_start=17088 - _globals['_RELOCATIONKIND']._serialized_end=17133 - _globals['_DRAFTSOURCE']._serialized_start=17135 - _globals['_DRAFTSOURCE']._serialized_end=17187 + _globals['_TOOLPARSERKIND']._serialized_end=16100 + _globals['_REASONINGPARSERKIND']._serialized_start=16103 + _globals['_REASONINGPARSERKIND']._serialized_end=16269 + _globals['_IMAGEPREPARATIONKIND']._serialized_start=16272 + _globals['_IMAGEPREPARATIONKIND']._serialized_end=16609 + _globals['_IMAGELAYOUTKIND']._serialized_start=16612 + _globals['_IMAGELAYOUTKIND']._serialized_end=16892 + _globals['_PROMPTENCODER']._serialized_start=16894 + _globals['_PROMPTENCODER']._serialized_end=16962 + _globals['_TEMPLATEENCODING']._serialized_start=16964 + _globals['_TEMPLATEENCODING']._serialized_end=17030 + _globals['_MEMORY']._serialized_start=17032 + _globals['_MEMORY']._serialized_end=17079 + _globals['_CAPACITY']._serialized_start=17081 + _globals['_CAPACITY']._serialized_end=17121 + _globals['_RELOCATIONKIND']._serialized_start=17123 + _globals['_RELOCATIONKIND']._serialized_end=17168 + _globals['_DRAFTSOURCE']._serialized_start=17170 + _globals['_DRAFTSOURCE']._serialized_end=17222 _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..75078c828 --- /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 BF16 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..42cada405 --- /dev/null +++ b/ignition/recipes/inkling/assets/chat_template.patch.json @@ -0,0 +1,15 @@ +{ + "source": { + "repository": "thinkingmachines/Inkling-Small", + "revision": "8cc5877b44d343f88b92086aa1fb72897950f06a", + "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..7bb0054fe --- /dev/null +++ b/ignition/recipes/inkling/attention.py @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Paged learned-relative-bias attention with complete FP32 convolution state.""" + +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 KV_DTYPE, 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, device, *, 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, shard, source, scratch, metadata, pool, *, mode, + runtime, coordinator, session, name, workspace, buffers): + 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, workspace=workspace, 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, workspace=workspace, 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.lengths = buffers.zeros(metadata.lengths.shape, torch.int32) + self.slots = buffers.zeros(metadata.positions.shape, torch.int64).fill_(-1) + self.key_cache, self.value_cache = pool.cache(layer, "key"), pool.cache(layer, "value") + if a.window > 0: + 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: + 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, workspace=workspace, 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 and 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]) + if a.window < 0: + columns = (m.positions.clamp_min(0) // PAGE_TOKENS).clamp(max=m.token_page_table.shape[1] - 1) + pages = m.token_page_table[torch.arange(m.positions.numel(), device=m.positions.device), columns] + self.slots.copy_(torch.where(m.positions >= 0, pages.long() * PAGE_TOKENS + m.positions.remainder(PAGE_TOKENS), -1)) + self.lengths.copy_((m.starts + m.lengths).int()) + 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 diff --git a/ignition/recipes/inkling/bootstrap.py b/ignition/recipes/inkling/bootstrap.py new file mode 100644 index 000000000..2c8e55425 --- /dev/null +++ b/ignition/recipes/inkling/bootstrap.py @@ -0,0 +1,250 @@ +# 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.parallel import TensorParallelShard +from ignition.components.prompt_logprobs import PreparedScoredPrefill, PromptScoring, prefill_modes +from ignition.components.sampling import AdmissionBuffers, DeviceRequestState +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.collectives import ( + CollectivePreparation, create_all_gather_runtime, create_all_reduce_runtime, + create_dma_all_reduce_runtime, +) +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.rank_group import minimum_across_ranks +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, PreparedResume, 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 + devices: tuple[int, ...] = tuple(range(8)) + 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): + if len(self.devices) != 8 or len(set(self.devices)) != 8 or any(d < 0 for d in self.devices): + raise ValueError("Inkling-Small BF16 preparation requires eight distinct GPUs") + 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_rank(snapshot, config, *, rank, group, progress=None, package_storage): + from .recipe import RECIPE + + snapshot = Path(snapshot).resolve() + shard = TensorParallelShard(rank, len(config.devices)) + device = torch.device("cuda", config.devices[rank]) + torch.cuda.set_device(device) + 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 = minimum_across_ranks(torch.cuda.mem_get_info(device)[1], group) + 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 = CollectivePreparation(group) + routed_width = weights.config.text["num_experts_per_tok"] * weights.config.hidden + collective = create_all_reduce_runtime(group, device, collective_tuning=config.collective_tuning, + max_tokens=slots, hidden_size=routed_width, ipc=package_storage.peer_storage) + prefill_collective = create_dma_all_reduce_runtime(group, device, max_tokens=tokens, + hidden_size=routed_width, ipc=package_storage.peer_storage) + vocabulary_collective = create_all_gather_runtime(group, device, max_rows=slots, + columns=weights.config.vocabulary_partition(shard)[2] * shard.world_size, ipc=package_storage.peer_storage) + embedding_collective = create_all_gather_runtime(group, device, max_rows=min(tokens, 128), + columns=weights.config.hidden, ipc=package_storage.peer_storage) + identity = hashlib.sha256(json.dumps(dict(config=weights.config.text, 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, group=group, + ipc=package_storage.peer_storage, runtime=collective, coordinator=coordinator) + 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=prefill_collective if mode == "prefill" else collective, + embedding_runtime=embedding_collective, vocabulary_runtime=vocabulary_collective, + 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=collective, 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=collective, vocabulary_runtime=vocabulary_collective, 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=collective, 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 and rank == 0, 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=collective, 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=rank, world_size=shard.world_size, device=config.devices[rank], 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()) + channels = collective, prefill_collective, vocabulary_collective, embedding_collective + 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.devices[rank], 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, *channels, + scratch_pool, graph_buffers, private_buffers), + close_resources=tuple(c for c in (*channels, scoring) if c is not None)) diff --git a/ignition/recipes/inkling/config.py b/ignition/recipes/inkling/config.py new file mode 100644 index 000000000..75c230796 --- /dev/null +++ b/ignition/recipes/inkling/config.py @@ -0,0 +1,92 @@ +# 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 + + @classmethod + def load(cls, snapshot): + return cls.from_dict(json.loads((Path(snapshot) / "config.json").read_text())) + + @classmethod + def from_dict(cls, config): + 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 text preparation requires the BF16 checkpoint") + 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"] + return cls(c) + + @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..996fcf900 --- /dev/null +++ b/ignition/recipes/inkling/contract.py @@ -0,0 +1,26 @@ +# 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()}} + for kind in ("decode", "speculative"): + if kind in inputs: + inputs[kind].pop("token_ids", None) + 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..e3783a552 --- /dev/null +++ b/ignition/recipes/inkling/decoder.py @@ -0,0 +1,188 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepared Inkling text layers, shared sinks, and sharded 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.paged_resume import PreparedResume +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 + + +@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, device, 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): + values = [] + for field in self.__dataclass_fields__: + value = getattr(self, field) + if field == "bf16": + value = value.rows(tokens, self.route_ids.shape[1]) + elif field in ("attention", "dense", "shared"): + value = value.rows(tokens) + else: + value = value[:samples if field in ("hidden", "local_logits", "logits") else tokens] + values.append(value) + return type(self)(*values) + + +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 + def mlp(w, storage, suffix): + return PreparedMLP(s.normalized, w, storage.gate_up, storage.intermediate, storage.output, + session=session, name=name + suffix, workspace=workspace, round_silu=False) + self.dense = None if weights.dense is None else mlp(weights.dense, s.dense, ".dense") + 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") + 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) + 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(mlp(w, s.shared, f".shared{index}") 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() + 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, expert in enumerate(self.shared): + expert.up_projection(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_(expert.down_projection(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.layers = [] + for index, w in enumerate(weights.layers): + prefix = f"{name}.layer{index}" + attention = PreparedAttention(index, w, weights.config, weights.shard, s.normalized, + s.attention, metadata, pool, mode=mode, runtime=runtime, coordinator=coordinator, + session=session, name=prefix + ".attention", workspace=workspace, buffers=buffers) + 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, workspace=workspace, 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): + 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, *(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..b407f025f --- /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) +FRONTEND["reasoning"] = dict(kind=p.CONTENT_HEADERS, open="<|content_thinking|>", + close="<|end_message|>", wrapping_newlines=0, terminal_markers=[]) +FRONTEND["rejected_tokens"] = [200005, 200020, 200023, 200053, 200054] + + +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..7f1e72d17 --- /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 and FP32 sink routing without narrowing checkpoint parameters.""" + +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): + """Keep FP32 router logits, correction, and global scale, including shared 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..72c64f6d1 --- /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.text["hidden_size"],), torch.bfloat16), + ("consumed_tokens", (1,), torch.int64))) + layout = StateLayout.from_specs(regions) + # TMA stages divide the stride between circular histories in 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..df9885d0b --- /dev/null +++ b/ignition/recipes/inkling/recipe.py @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling-Small BF16 text preparation with learned relative attention.""" + +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 ignition.preparation.rank_group import prepare_group + from .bootstrap import PreparationConfig, prepare_rank + + if ranks is not None: + raise ValueError("Inkling-Small preparation requires eight GPUs on one host") + 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", + devices=tuple(range(plan.world_size)), 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) + return prepare_group(snapshot, config, prepare_rank, progress=progress, package_storage=package_storage, + checkpoint=plan.checkpoint) + + +def usage(prepared): + return tuple(RankUsage(rank["pages"], rank["free_device_bytes"]) + for rank in prepared.memory_report.get("ranks", (prepared.memory_report,))) + + +RECIPE = Recipe(name="inkling", served_model_name="Inkling-Small", + # Publisher guidance: thinking-machines-lab/tinker-cookbook, skills/inkling/SKILL.md. + sampling_defaults=SamplingDefaults(temperature=1., top_p=1., top_k=-1), prepare=prepare, usage=usage, + checkpoints=(Checkpoint(alias="inkling-small", repository="thinkingmachines/Inkling-Small", + revision="8cc5877b44d343f88b92086aa1fb72897950f06a", architecture="InklingForConditionalGeneration", + stored_bytes=531_912_898_740, device_bytes=527_948_358_944, expansion_bytes=1 << 30),), + context=262144, page_tokens=128, concurrency=4, max_concurrency=4, max_draft_tokens=0, prefill_chunk=4096, + ranks=MappingProxyType({8: RankCosts(14_024_704, 458_752, 8 << 30)})) diff --git a/ignition/recipes/inkling/weights.py b/ignition/recipes/inkling/weights.py new file mode 100644 index 000000000..69a77c9a3 --- /dev/null +++ b/ignition/recipes/inkling/weights.py @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct BF16 loading of the original interleaved Inkling checkpoint layout.""" + +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: Experts | 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 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")) + 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 4ef2aa404..62b910ce9 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/components/test_inkling_operators_cuda.py b/tests/components/test_inkling_operators_cuda.py new file mode 100644 index 000000000..5ee3c9ce1 --- /dev/null +++ b/tests/components/test_inkling_operators_cuda.py @@ -0,0 +1,240 @@ +# 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.scratch import ScratchArena +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: + arena = ScratchArena(device) + session.register_scratch(arena) + operation = PreparedRelativePagedAttention(query, key, value, pages, lengths, cu, relative, output, + window=window, softmax_scale=1 / dim, session=session, workspace=arena, 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) + from ignition.preparation.compilation import compile_forward + 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: + arena = ScratchArena(device) + session.register_scratch(arena) + operation = PreparedResidualShortConvolution(source, weights, history, m, output, + session=session, workspace=arena, 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_() + from ignition.preparation.compilation import compile_forward + 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() + + +@pytest.mark.parametrize("round_silu", [True, False]) +@torch.no_grad() +def test_bf16_experts_silu_rounding_and_capture(round_silu): + from ignition.components.bf16_experts import PreparedBF16Experts + from ignition.preparation.compilation import compile_forward + from ignition.preparation.scratch import GraphBufferPool + + torch.manual_seed(837) + source = torch.randn((17, 128), device="cuda", dtype=torch.bfloat16) + gate_up = (torch.randn((4, 128, 128), device="cuda") * .05).bfloat16() + down = (torch.randn((4, 128, 64), device="cuda") * .05).bfloat16() + ids = torch.rand((17, 4), device="cuda").topk(2, dim=-1).indices.int() + weights = torch.rand((17, 2), device="cuda") + valid = torch.tensor([13], device="cuda", dtype=torch.int32) + output = torch.empty((17, 2, 128), device="cuda", dtype=torch.bfloat16) + operation = PreparedBF16Experts(source, gate_up, down, ids, weights, output, valid, + 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) + # BF16 intermediate activation for existing users; Inkling's supported + # implementation computes SiLU and multiplication in FP32, rounding once. + 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]) + operation() + torch.testing.assert_close(operation.intermediate[:26], intermediate.flatten(0, 1), rtol=.008, atol=2e-5) + torch.testing.assert_close(output, expected, rtol=.008, atol=2e-4) + run = compile_forward(operation) + run() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + run() + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + torch.testing.assert_close(output, expected, rtol=.008, atol=2e-4) + 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/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/frontend/test_inkling.py b/tests/frontend/test_inkling.py new file mode 100644 index 000000000..e8c7806eb --- /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")) + + +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 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..2a22ee567 --- /dev/null +++ b/tests/recipes/inkling_helpers.py @@ -0,0 +1,75 @@ +# 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=2, 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 checkpoint(path): + torch.manual_seed(7821) + raw = configuration() + config = ModelConfig.from_dict(raw) + 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) + (path / "config.json").write_text(json.dumps(raw)) + save_file(tensors, path / "model.safetensors") + return config, tensors diff --git a/tests/recipes/test_inkling.py b/tests/recipes/test_inkling.py new file mode 100644 index 000000000..8ff7c1dda --- /dev/null +++ b/tests/recipes/test_inkling.py @@ -0,0 +1,108 @@ +# 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 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, continuation_layout, page_bytes +from ignition.recipes.inkling.recipe import RECIPE +from .inkling_helpers import configuration + + +def test_checkpoint_alias_and_canonical_geometry(): + from ignition.recipes import resolve + from ignition.recipes.inkling.bootstrap import PreparationConfig + + assert resolve("inkling-small").recipe is RECIPE + model = ModelConfig.from_dict(configuration()) + assert model.text["mlp_layer_types"] == ["dense", "sparse"] + assert model.text["intermediate_size"] == 256 + assert model.text["moe_intermediate_size"] == 128 + assert [model.attention(i).window for i in range(2)] == [128, -1] + assert model.vocabulary == 250 + assert RECIPE.speculation is None and RECIPE.max_draft_tokens == 0 + assert PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 + with pytest.raises(ValueError, match="eight distinct"): + PreparationConfig(devices=(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) + raw = configuration() + raw["quantization_config"] = {"quant_method": "modelopt", "quant_algo": "NVFP4"} + with pytest.raises(ValueError, match="BF16"): + ModelConfig.from_dict(raw) + + +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()), TensorParallelShard(0, 1) + pool = ContinuationPool.allocate(config, shard, 4, 3, "cpu") + assert page_bytes(config, shard) == 2 * 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 + pool.backing[1].random_(0, 255) + pool.backing[2].copy_(pool.backing[1]) + for region in pool.layout.regions: + assert torch.equal(pool.region(region.name)[1].view(torch.uint8), pool.region(region.name)[2].view(torch.uint8)) + 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) == 2 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..cec1db3f6 --- /dev/null +++ b/tests/recipes/test_inkling_cuda.py @@ -0,0 +1,253 @@ +# 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 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 ModelWeights +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 reference(weights, tokens): + 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) + for expert in range(c["n_routed_experts"]): + expert_out = mlp(w.experts.gate_up[expert], w.experts.down[expert]) + selection = ids == 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 + + +@torch.no_grad() +def test_original_checkpoint_loader_shards_interleaved_rows_without_losing_precision(tmp_path): + config, original = checkpoint(tmp_path) + manifest = inspect_indexed_checkpoint(tmp_path) + from ignition.recipes.inkling.weights import InklingWeightLoader + + with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(1, 2)) 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[:, 128::2], raw[:, 129::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)) + + +@torch.no_grad() +def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): + 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, 4, 5, device) + buffers = GraphBufferPool(device, chunk_bytes=2 << 20) + catalog = {} + 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 in (("prefill", 64), ("decode", 1)): + cursor = buffers.cursor() + metadata = Metadata.allocate(capacity, 1, 5, device, buffers=cursor) + scratch = Scratch.allocate(weights.config, shard, capacity, 1, 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) + catalog[mode] = metadata, scratch, decoder + session.tune() + graphs = {} + for mode, (metadata, scratch, decoder) in catalog.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() + graphs[mode] = graph, compiled + session.freeze() + pool.clear_for_preparation() + tokens = (torch.arange(259, device=device) * 17 % weights.config.vocabulary).long() + expected, expected_hidden = reference(weights, tokens) + 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, decoder = 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"] + graphs[mode][0].replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + start += count + # The fixed reduced checkpoint matches exactly across these BF16 boundaries. + torch.testing.assert_close(scratch.logits[0], expected[start - 1], atol=0, rtol=0) + torch.testing.assert_close(scratch.hidden[0], expected_hidden[start - 1], atol=0, rtol=0) + assert start == tokens.numel() + saved = pool.backing.clone() + pages = {name: value.clone() for name, value in pool.pages.items()} + metadata, scratch, decoder = catalog["decode"] + metadata.starts.fill_(start) + metadata.positions.fill_(start) + metadata.token_ids.fill_(13) + graphs["decode"][0].replay() + torch.cuda.synchronize() + branch = scratch.logits.clone() + pool.backing.copy_(saved) + for name, value in pages.items(): + pool.pages[name].copy_(value) + graphs["decode"][0].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_() + graphs["decode"][0].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): + 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, 5, 10, device) + buffers = GraphBufferPool(device, chunk_bytes=2 << 20) + catalog = {} + with RecordedPreparationSession(device=device, checkpoint="inkling-batched-test", workload_schema="inkling", + numerical_policy="default", compile_workers=1) as session: + arena = ScratchArena(device) + session.register_scratch(arena) + for mode, capacity, rows in (("prefill", 192, 1), ("decode", 4, 4)): + cursor = buffers.cursor() + metadata = Metadata.allocate(capacity, rows, 5, device, buffers=cursor) + scratch = Scratch.allocate(weights.config, shard, capacity, rows, 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) + catalog[mode] = metadata, scratch, decoder + session.tune() + graphs = {} + for mode, (metadata, _, decoder) in catalog.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() + graphs[mode] = graph, compiled + session.freeze() + pool.clear_for_preparation() + 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, _ = 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) + graphs["prefill"][0].replay() + untouched = pool.backing[[0, 3, 4]].clone() + m, s, _ = 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"] + graphs["decode"][0].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) + torch.testing.assert_close(s.logits[row], expected[-1], atol=0, rtol=0) diff --git a/tests/server/test_inkling.py b/tests/server/test_inkling.py new file mode 100644 index 000000000..b1981a980 --- /dev/null +++ b/tests/server/test_inkling.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Acceptance for a TP8 Inkling 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") + + +@pytest.fixture(scope="module") +def service(): + from transformers import PreTrainedTokenizerFast + + root = Path(os.environ["FLARE_INKLING_SNAPSHOT"]) + tokenizer = PreTrainedTokenizerFast.from_pretrained(root) + template = (root / "chat_template.jinja").read_text() + 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, request, card["id"] + + +def text(result): + return (result["choices"][0]["message"].get("content") or "").strip() + + +@pytest.mark.parametrize("index", range(20)) +def test_text_and_unicode(service, index): + ask, _, _ = service + if index < 12: + a, b = index + 13, 29 - index + prompt, expected = f"What is {a} times {b}? Reply with only the integer.", str(a*b) + else: + expected = ["INKLING-317", "café", "世界", "naïve", "á", "Δοκιμή", "مرحبا", "日本語"][index-12] + prompt = "Repeat exactly this text, without quotation marks or explanation: " + expected + result = ask([dict(role="user", content=prompt)]) + assert text(result) == expected + assert result["choices"][0]["finish_reason"] == "stop" + + +@pytest.mark.parametrize("effort", ["minimal", "low", "medium", "high", "max"]) +def test_reasoning_headers(service, effort): + result = service[0]([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"] + + +@pytest.mark.parametrize("required", [True, False]) +def test_json_tool_envelope(service, required): + value = dict(query="café 世界", count=3) + function = dict(name="record", parameters=dict(type="object", properties=dict(query=dict(type="string"), + count=dict(type="integer")), required=["query", "count"])) + choice = "required" if required else dict(type="function", function=dict(name="record")) + result = service[0]([dict(role="user", content="Call record with exactly " + json.dumps(value))], + tools=[dict(type="function", function=function)], tool_choice=choice) + call, = result["choices"][0]["message"]["tool_calls"] + assert call["function"]["name"] == "record" + assert json.loads(call["function"]["arguments"]) == value + assert result["choices"][0]["finish_reason"] == "tool_calls" + + +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[0]([*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_and_text_only_rejection(service): + result = service[0]([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()) + for content in ([dict(type="image_url", image_url=dict(url="data:image/png;base64,AA=="))], + [dict(type="input_audio", input_audio=dict(data="AA==", format="wav"))]): + with pytest.raises(urllib.error.HTTPError) as rejected: + service[1]("/v1/chat/completions", dict(model=service[2], messages=[dict(role="user", content=content)])) + assert rejected.value.code == 400 From 92aa0bd645bbb5859d9bfefcde734feff5de316a Mon Sep 17 00:00:00 2001 From: Arthur <xuyangc@nvidia.com> Date: Tue, 3 Nov 2026 17:06:44 -0800 Subject: [PATCH 2/5] Target Inkling-Small recipe at the official NVFP4 checkpoint Load hf_quant_config exclusions and preserve packed NVFP4 weights, block scales, FP32 global factors and the activation-calibration boundary. Use prepared A4 routed experts while retaining the excluded BF16 layers. Reduce raw expert outputs before applying route weights. Prepare TP2 locally or across two Sparks through existing RoCE transport, update physical memory budgets and frontend assets, and reject SM103's unsupported raw-route kernel interface before checkpoint loading. Validation: 37 recipe/topology/decoder/operator/sampling checks plus three packed NVFP4 GPU checks passed on both declared FlashInfer 560fef16 and locked 776facfd. Exact packed/calibration mapping, six-route execution, state restoration, inactive rows and allocation-free replay passed. Full model reference bounds follow measured BF16 softmax reduction rounding; max relative L2 was 0.00245 for logits and 0.00141 for hidden vectors on both pins. Actual NVFP4 tokenizer/template parity passed. Staged diff reviewed. Full-checkpoint TP2 export/native serving, RoCE, long-context and SM121 qualification remain unrun; the available SM120 GPU has 8 GB and its PCI ID is rejected by the existing package validator. Keep PR #191 as a draft. Design-Signed-Off-By: Codex (GPT-6); design-review=a38f Signed-off-by: Arthur <xuyangc@nvidia.com> --- docs/model-preparation.md | 73 ++++++---- ignition/recipes/inkling/__init__.py | 2 +- .../inkling/assets/chat_template.patch.json | 4 +- ignition/recipes/inkling/bootstrap.py | 46 ++++-- ignition/recipes/inkling/config.py | 48 +++++- ignition/recipes/inkling/decoder.py | 11 +- ignition/recipes/inkling/recipe.py | 23 +-- ignition/recipes/inkling/weights.py | 79 ++++++++-- tests/components/inkling_nvfp4_helpers.py | 72 +++++++++ tests/components/test_inkling_nvfp4_cuda.py | 137 ++++++++++++++++++ tests/frontend/test_inkling.py | 4 +- tests/recipes/inkling_helpers.py | 40 ++++- tests/recipes/test_inkling.py | 47 ++++-- tests/recipes/test_inkling_cuda.py | 64 ++++++-- tests/recipes/test_inkling_topology.py | 70 +++++++++ tests/server/test_inkling.py | 2 +- 16 files changed, 621 insertions(+), 101 deletions(-) create mode 100644 tests/components/inkling_nvfp4_helpers.py create mode 100644 tests/components/test_inkling_nvfp4_cuda.py create mode 100644 tests/recipes/test_inkling_topology.py diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 45ca6c003..9d3ff1621 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -983,16 +983,27 @@ 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 - -The `inkling-small` alias selects the BF16 -[`thinkingmachines/Inkling-Small`](https://huggingface.co/thinkingmachines/Inkling-Small) -checkpoint at revision `8cc5877b44d343f88b92086aa1fb72897950f06a`. -This text recipe prepares eight GPUs on one host, a default 262144-token context, -four concurrent requests, and 4096-token prefill chunks. This initial recipe caps -prepared context at 262144 tokens of the checkpoint's 1048576-token limit. Image, audio, video, and -MTP graphs are not prepared. The indexed download includes the publisher's MTP -weights; only `model.llm` tensors become serving weights. +## Inkling-Small NVFP4 + +The `inkling-small-nvfp4` alias selects +[`thinkingmachines/Inkling-Small-NVFP4`](https://huggingface.co/thinkingmachines/Inkling-Small-NVFP4) +at revision `b6a99534467840620d411e4cd4ad5819b2610d9c`. This text recipe +targets tensor parallelism two on SM120/SM121, using two local GPUs or one GPU +on each of two DGX Sparks through the shared RoCE transport. Defaults are a +262144-token context, four concurrent requests, and 4096-token prefill chunks. +Prepared context is capped at 262144 tokens of the checkpoint's 1048576-token +limit. Image, audio, video, and MTP graphs are not prepared. The indexed download +includes the publisher's MTP weights; only `model.llm` tensors become serving +weights. + +Quantization comes from the checkpoint's `hf_quant_config.json`. Its exclusions +retain BF16 attention, dense/shared experts, and the first routed layer; the +remaining routed experts use the original packed NVFP4 weights, E4M3 block +scales, FP32 global scales, and calibrated NVFP4 activations. Interleaved gate/up +rows are reordered with their matching scales before intermediate sharding. +Activation calibration preserves the FP32 scale boundary in the publisher-supported +[checkpoint loader](https://github.com/sgl-project/sglang/blob/dff6a0c3accf310f70eab81be1220a27b732c96b/python/sglang/srt/models/inkling.py#L1241). +Unweighted expert outputs are reduced across ranks before route weights apply. The 42-layer decoder retains 35 local 512-token KV rings and seven global paged histories in BF16. Query-dependent relative logits, head RMS normalization, @@ -1002,24 +1013,25 @@ and arithmetic. Every continuation row includes those histories, local rings, partial global pages, the consumed cursor, and the normalized and scaled hidden vector used by resume. -The BF16 checkpoint stores router correction biases and global scales in FP32. -They remain FP32, as do router logits and route normalization. Dense and expert -SwiGLU arithmetic uses FP32 before rounding the final intermediate to BF16; -shared sink weights apply before the down projection. These precision boundaries -follow the publisher-supported SGLang +Router correction biases and global scales remain FP32, as do router logits and +route normalization. Unquantized SwiGLU uses FP32 activation arithmetic after +BF16 projections; shared sink weights apply before the down projection. NVFP4 +experts retain FP32 scaled accumulators through SwiGLU, then round the intermediate +to BF16 before its calibrated NVFP4 activation quantizer. Routing and shared +sink placement follow the publisher-supported SGLang [router](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/moe.py) and [MLP implementation](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/dense_mlp.py). Transformers supplies the reference attention, normalization, and checkpoint layout; loading it with a blanket BF16 dtype also narrows the FP32 router parameters, so that load mode is not the precision reference for routing. -At tensor parallelism eight, resident text weights occupy 65,993,544,868 bytes -per rank, including replicated parameters and FP32 convolution weights. Each -continuation row occupies 14,024,704 bytes; each 128-token global KV page occupies -458,752 bytes per rank. The planner reserves additional space for preparation, -graphs, and caches. The complete indexed source tensors occupy 531,912,898,740 -bytes on disk. This BF16 recipe therefore requires GPUs with substantially more -memory than the 8 GB device used for the reduced model tests. +The indexed checkpoint contains 170,733,074,592 bytes of tensors, including +166,130,594,960 bytes of text weights. The planner conservatively budgets the +whole checkpoint for weights, plus preparation scratch and caches. At TP2, +each continuation row occupies 43,515,904 bytes and each 128-token global KV page +occupies 1,835,008 bytes per rank. One full 262144-token global KV history needs +3.5 GiB per rank. Spark's CPU, GPU, compiler processes, and OS share physical +memory; follow the [DGX Spark memory guidance](#dgx-spark). The publisher's [Inkling sampling guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, @@ -1027,16 +1039,23 @@ recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, owns the thinking-effort system message and content-header/tool syntax. ```sh -.venv/bin/ignition export inkling-small --gpus 0-7 --prompt-logprobs -.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-tp8.safetensors -flare/target/release/flare run /data/flare-runtime/inkling-small-tp8.safetensors --gpus 0,1,2,3,4,5,6,7 +.venv/bin/ignition export inkling-small-nvfp4 --gpus 0,1 --prompt-logprobs +.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-nvfp4-tp2.safetensors +flare/target/release/flare run /data/flare-runtime/inkling-small-nvfp4-tp2.safetensors --gpus 0,1 ``` +For two Sparks, prepare with `--gpus 0 --ranks 2 --rendezvous ZERO:29630` on +rank zero and `ignition join ZERO:29630 --rank 1 --ranks 2` on its peer. Follow +[multi-host preparation and serving](multi-host.md#prepare-the-package) for +checkpoint access, transport setup, and launching the resulting two-host package. + Reduced model validation covers original-format weight loading, learned relative attention, FP32 residual convolution, complete compiled decoder replay across prefill/decode and page/window boundaries, state restoration, inactive rows, and -allocation stability on SM120. Full-checkpoint TP8 export and native serving, -long-context behavior, and SM103/SM121 execution remain unqualified. Run +allocation stability on SM120. Full-checkpoint TP2 export and native serving, +RoCE execution, long-context behavior, and SM121 execution remain unqualified. +SM103's current expert implementation does not expose the unweighted route +outputs this recipe requires. Run `tests/server/test_inkling.py` against the exported package with `FLARE_RUN_CUDA_TESTS=1`, `FLARE_INKLING_TEST_URL`, and `FLARE_INKLING_SNAPSHOT` set before promoting this draft recipe. diff --git a/ignition/recipes/inkling/__init__.py b/ignition/recipes/inkling/__init__.py index 75078c828..3622a63c6 100644 --- a/ignition/recipes/inkling/__init__.py +++ b/ignition/recipes/inkling/__init__.py @@ -1,4 +1,4 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling-Small BF16 text preparation.""" +"""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 index 42cada405..f2eeae035 100644 --- a/ignition/recipes/inkling/assets/chat_template.patch.json +++ b/ignition/recipes/inkling/assets/chat_template.patch.json @@ -1,7 +1,7 @@ { "source": { - "repository": "thinkingmachines/Inkling-Small", - "revision": "8cc5877b44d343f88b92086aa1fb72897950f06a", + "repository": "thinkingmachines/Inkling-Small-NVFP4", + "revision": "b6a99534467840620d411e4cd4ad5819b2610d9c", "filename": "chat_template.jinja" }, "source_sha256": "0aa1aa0c729d90176dcaa00c440c8faffca2957ffb2cc4b79456ee6d02bcf43b", diff --git a/ignition/recipes/inkling/bootstrap.py b/ignition/recipes/inkling/bootstrap.py index 2c8e55425..215ec95b7 100644 --- a/ignition/recipes/inkling/bootstrap.py +++ b/ignition/recipes/inkling/bootstrap.py @@ -24,7 +24,7 @@ from ignition.preparation.checkpoint import inspect_indexed_checkpoint from ignition.preparation.collectives import ( CollectivePreparation, create_all_gather_runtime, create_all_reduce_runtime, - create_dma_all_reduce_runtime, + create_dma_all_reduce_runtime, create_roce_runtime, ) from ignition.preparation.disposable import storage_ranges from ignition.preparation.execution import GraphSignature @@ -54,7 +54,9 @@ class PreparationConfig: lock_gpu_clocks: bool = False autotune_effort: str = "default" tuning_replica: TuningReplica | None = None - devices: tuple[int, ...] = tuple(range(8)) + devices: tuple[int, ...] = (0, 1) + hosts: tuple[str, ...] | None = None + roce_ring: bool = False context: int = 262144 prefill_chunk_size: int = 4096 max_active: int = 4 @@ -66,8 +68,13 @@ class PreparationConfig: stream_overlap: bool = True def __post_init__(self): - if len(self.devices) != 8 or len(set(self.devices)) != 8 or any(d < 0 for d in self.devices): - raise ValueError("Inkling-Small BF16 preparation requires eight distinct GPUs") + if (not isinstance(self.devices, tuple) or len(self.devices) != 2 + or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != 2) + or len(set(zip(self.hosts or ("",) * 2, self.devices))) != 2 + or any(type(device) is not int or device < 0 for device in self.devices)): + raise ValueError("Inkling-Small NVFP4 preparation requires two distinct host/device placements") + if self.roce_ring and self.hosts is None: + raise ValueError("RoCE ring requires ranks on separate hosts") 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]") @@ -86,6 +93,9 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag shard = TensorParallelShard(rank, len(config.devices)) device = torch.device("cuda", config.devices[rank]) torch.cuda.set_device(device) + if torch.cuda.get_device_capability(device) not in ((12, 0), (12, 1)): + raise ValueError("Inkling NVFP4 preparation requires SM120 or SM121: " + "the A4 expert kernels must expose unweighted per-route outputs") with phase(progress, "Inspect checkpoint"): manifest = inspect_indexed_checkpoint(snapshot) headers = [s.header_sha256 for s in manifest.shards] @@ -116,15 +126,23 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag completion = CompletionOutputs.allocate((2, slots, VECTOR_TOKENS_FIELD + 1), device=device) coordinator = CollectivePreparation(group) routed_width = weights.config.text["num_experts_per_tok"] * weights.config.hidden - collective = create_all_reduce_runtime(group, device, collective_tuning=config.collective_tuning, - max_tokens=slots, hidden_size=routed_width, ipc=package_storage.peer_storage) - prefill_collective = create_dma_all_reduce_runtime(group, device, max_tokens=tokens, - hidden_size=routed_width, ipc=package_storage.peer_storage) - vocabulary_collective = create_all_gather_runtime(group, device, max_rows=slots, - columns=weights.config.vocabulary_partition(shard)[2] * shard.world_size, ipc=package_storage.peer_storage) - embedding_collective = create_all_gather_runtime(group, device, max_rows=min(tokens, 128), - columns=weights.config.hidden, ipc=package_storage.peer_storage) - identity = hashlib.sha256(json.dumps(dict(config=weights.config.text, headers=headers, + if coordinator.spans_hosts: + gather_bytes = max(slots * weights.config.vocabulary_partition(shard)[2] * 2, + tokens * (weights.config.hidden // shard.world_size) * 2) + collective = prefill_collective = vocabulary_collective = embedding_collective = create_roce_runtime( + group, device, max_tokens=slots, pipe_tokens=tokens, hidden_size=routed_width, + gather_bytes=gather_bytes, ring=config.roce_ring, package_storage=package_storage) + else: + collective = create_all_reduce_runtime(group, device, collective_tuning=config.collective_tuning, + max_tokens=slots, hidden_size=routed_width, ipc=package_storage.peer_storage) + prefill_collective = create_dma_all_reduce_runtime(group, device, max_tokens=tokens, + hidden_size=routed_width, ipc=package_storage.peer_storage) + vocabulary_collective = create_all_gather_runtime(group, device, max_rows=slots, + columns=weights.config.vocabulary_partition(shard)[2] * shard.world_size, ipc=package_storage.peer_storage) + embedding_collective = create_all_gather_runtime(group, device, max_rows=min(tokens, 128), + columns=weights.config.hidden, ipc=package_storage.peer_storage) + 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, @@ -229,7 +247,7 @@ def materialize(): 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()) - channels = collective, prefill_collective, vocabulary_collective, embedding_collective + channels = tuple(dict.fromkeys((collective, prefill_collective, vocabulary_collective, embedding_collective))) disposable = [prefill_storage, decode_storage, arena.tensor, metadata, graph_buffers.chunks, private_buffers.chunks] for forward in forwards.values(): if isinstance(forward, PreparedScoredPrefill): diff --git a/ignition/recipes/inkling/config.py b/ignition/recipes/inkling/config.py index 75c230796..88cc52d49 100644 --- a/ignition/recipes/inkling/config.py +++ b/ignition/recipes/inkling/config.py @@ -29,20 +29,23 @@ def local(self, shard): @dataclass(frozen=True) class ModelConfig: text: dict + quantization: dict @classmethod def load(cls, snapshot): - return cls.from_dict(json.loads((Path(snapshot) / "config.json").read_text())) + 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): + 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 text preparation requires the BF16 checkpoint") + 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"] @@ -59,7 +62,44 @@ def from_dict(cls, config): 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"] - return cls(c) + 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): diff --git a/ignition/recipes/inkling/decoder.py b/ignition/recipes/inkling/decoder.py index e3783a552..a13388b34 100644 --- a/ignition/recipes/inkling/decoder.py +++ b/ignition/recipes/inkling/decoder.py @@ -12,11 +12,13 @@ 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_resume import PreparedResume 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 .weights import Experts @dataclass(frozen=True) @@ -95,8 +97,12 @@ def mlp(w, storage, suffix): if self.dense is None: self.router = UnquantizedProjection(s.normalized, weights.router, s.router_logits, session=session, name=name + ".router") - 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) + 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(mlp(w, s.shared, f".shared{index}") for index, w in enumerate(weights.shared)) @@ -115,6 +121,7 @@ def forward(self, hidden_states): 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) diff --git a/ignition/recipes/inkling/recipe.py b/ignition/recipes/inkling/recipe.py index df9885d0b..65214b3b5 100644 --- a/ignition/recipes/inkling/recipe.py +++ b/ignition/recipes/inkling/recipe.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling-Small BF16 text preparation with learned relative attention.""" +"""Inkling-Small NVFP4 text preparation on two local GPUs or DGX Sparks.""" from types import MappingProxyType @@ -13,19 +13,19 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ from ignition.preparation.rank_group import prepare_group from .bootstrap import PreparationConfig, prepare_rank - if ranks is not None: - raise ValueError("Inkling-Small preparation requires eight GPUs on one host") 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", - devices=tuple(range(plan.world_size)), context=plan.context, max_active=plan.concurrency, + devices=tuple(range(plan.world_size)) if ranks is None else (0,) * plan.world_size, + hosts=None if ranks is None else ranks.hosts, roce_ring=plan.roce_ring, + 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) + retain_graphs=retain_graphs, kernel_cache=kernel_cache, stream_overlap=plan.stream_overlap) return prepare_group(snapshot, config, prepare_rank, progress=progress, package_storage=package_storage, - checkpoint=plan.checkpoint) + ranks=ranks, checkpoint=plan.checkpoint) def usage(prepared): @@ -33,11 +33,12 @@ def usage(prepared): for rank in prepared.memory_report.get("ranks", (prepared.memory_report,))) -RECIPE = Recipe(name="inkling", served_model_name="Inkling-Small", +RECIPE = Recipe(name="inkling", served_model_name="Inkling-Small-NVFP4", # Publisher guidance: thinking-machines-lab/tinker-cookbook, skills/inkling/SKILL.md. sampling_defaults=SamplingDefaults(temperature=1., top_p=1., top_k=-1), prepare=prepare, usage=usage, - checkpoints=(Checkpoint(alias="inkling-small", repository="thinkingmachines/Inkling-Small", - revision="8cc5877b44d343f88b92086aa1fb72897950f06a", architecture="InklingForConditionalGeneration", - stored_bytes=531_912_898_740, device_bytes=527_948_358_944, expansion_bytes=1 << 30),), + checkpoints=(Checkpoint(alias="inkling-small-nvfp4", repository="thinkingmachines/Inkling-Small-NVFP4", + revision="b6a99534467840620d411e4cd4ad5819b2610d9c", architecture="InklingForConditionalGeneration", + # Include unused multimodal/MTP tensors in the estimate to cover replicated text weights. + 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({8: RankCosts(14_024_704, 458_752, 8 << 30)})) + ranks=MappingProxyType({2: RankCosts(43_515_904, 1_835_008, 8 << 30)})) diff --git a/ignition/recipes/inkling/weights.py b/ignition/recipes/inkling/weights.py index 69a77c9a3..96d9f8363 100644 --- a/ignition/recipes/inkling/weights.py +++ b/ignition/recipes/inkling/weights.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Direct BF16 loading of the original interleaved Inkling checkpoint layout.""" +"""Direct loading of Inkling's interleaved NVFP4 and unquantized checkpoint tensors.""" from contextlib import nullcontext from dataclasses import dataclass @@ -38,7 +38,7 @@ class LayerWeights: dense: MLPWeights | None router: torch.Tensor | None correction: torch.Tensor | None - experts: Experts | None + experts: object | None shared: tuple[MLPWeights, ...] @@ -106,6 +106,62 @@ def _interleaved(self, name, down_name, inter, *, expert=None, destination=None) 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.preparation.tensor_metadata import record_numeric_tensor + + 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): + target = slice(offset * local, (offset + 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(swizzle_block_scale(scales)) + del scales + 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}" @@ -130,14 +186,17 @@ def conv(name, extent=None): scale = tensor("mlp.global_scale") else: router, correction, scale = (tensor("mlp.gate." + n) for n in ("weight", "bias", "global_scale")) - 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])) + 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"])) diff --git a/tests/components/inkling_nvfp4_helpers.py b/tests/components/inkling_nvfp4_helpers.py new file mode 100644 index 000000000..e27ddc76c --- /dev/null +++ b/tests/components/inkling_nvfp4_helpers.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Raw Inkling NVFP4 fixtures and an independent quantized arithmetic oracle.""" + +import torch + + +def unpack_weight(values, scales): + """Decode low-nibble-first E2M1 and unswizzled checkpoint E4M3 block scales.""" + magnitudes = torch.tensor([0., .5, 1., 1.5, 2., 3., 4., 6.], device=values.device) + codes = torch.stack((values & 15, values >> 4), -1).flatten(-2).long() + signed = magnitudes[codes & 7] * torch.where(codes < 8, 1., -1.) + return signed * scales.float().repeat_interleave(16, -1) + + +def quantize_activation(value, amax): + """Calibrated per-16 NVFP4 inner values and their FP32 reciprocal outer scale. + + The packed MMA consumes E2M1 values times E4M3 block scales. Its outer + calibration multiplies the accumulator, not each input value. Reciprocal + multiplication preserves the fast quantizer's E2M1 tie evaluation order. + """ + value = value.float() + blocks = value.reshape(*value.shape[:-1], -1, 16) + # The publisher first stores amax/2688 in FP32, then reciprocates that + # stored value. Directly rounding 2688/amax skips an observable boundary. + dequant = torch.tensor(float(amax.item()) / 2688., dtype=torch.float32, device=value.device) + encode = dequant.reciprocal() + sixth = 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() + inverse = torch.where(scales != 0, scales.reciprocal() * encode, 0.) + normalized = blocks * inverse + magnitude = normalized.abs() + code = ((magnitude > .25).int() + (magnitude >= .75).int() + (magnitude > 1.25).int() + + (magnitude >= 1.75).int() + (magnitude > 2.5).int() + (magnitude >= 3.5).int() + + (magnitude > 5.).int()) + levels = torch.tensor([0., .5, 1., 1.5, 2., 3., 4., 6.], device=value.device) + return (levels[code] * normalized.sign() * scales).reshape_as(value), encode + + +def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None): + """FP32 FC1 -> FP32 SwiGLU -> BF16 -> calibrated NVFP4 -> FP32 FC2 -> BF16. + + Decode checkpoint bytes only for the test oracle. Production kernels consume + packed weights directly. Route weights and TP reductions belong to the caller. + """ + first = prefix + ".w13_weight" + second = prefix + ".w2_weight" + tensors = {name: value.to(source.device) for name, value in tensors.items() if name.startswith(prefix + ".")} + intermediate = tensors[first].shape[1] // 2 + begin, end = (0, intermediate) if intermediate_range is None else intermediate_range + source_quantized, input_scale = quantize_activation(source, tensors[first + ".input_amax"]) + result = torch.zeros((*ids.shape, source.shape[-1]), dtype=torch.bfloat16, device=source.device) + for expert in range(tensors[first].shape[0]): + tokens, routes = torch.where(ids == expert) + if tokens.numel() == 0: + continue + rows = slice(2 * begin, 2 * end) + # Apply the outer multiplier after the dot product, matching the scaled + # FP4 MMA arithmetic rather than changing every weight before summation. + up_gate = unpack_weight(tensors[first][expert, rows], tensors[first + ".scale"][expert, rows]) + projected = (source_quantized[tokens] @ up_gate.T) * (tensors[first + ".scale2"][expert] / input_scale) + gate, up = projected[:, ::2], projected[:, 1::2] + activated = (torch.nn.functional.silu(gate) * up).bfloat16() + activated, intermediate_scale = quantize_activation(activated, tensors[second + ".input_amax"]) + down = unpack_weight(tensors[second][expert, :, begin // 2:end // 2], + tensors[second + ".scale"][expert, :, begin // 16:end // 16]) + result[tokens, routes] = ((activated @ down.T) + * (tensors[second + ".scale2"][expert] / intermediate_scale)).bfloat16() + return result diff --git a/tests/components/test_inkling_nvfp4_cuda.py b/tests/components/test_inkling_nvfp4_cuda.py new file mode 100644 index 000000000..ba7696698 --- /dev/null +++ b/tests/components/test_inkling_nvfp4_cuda.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Original packed Inkling experts through prepared, compiled NVFP4 A4 graphs.""" + +import os + +import pytest +import torch + +from ignition.components.moe import PreparedRoutedExperts +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 tests.recipes.inkling_helpers import checkpoint +from .inkling_nvfp4_helpers import nvfp4_routes + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an assigned CUDA GPU") + + +class ExpertForward: + 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) + for _ in experts] + self.reduced = torch.empty_like(self.routes[0]) + self.output = torch.empty_like(source) + self.operations = [PreparedRoutedExperts(source, value, self.active_ids, weights, output, + session=session, workspace=workspace, name=f"experts{rank}") + for rank, (value, output) in enumerate(zip(experts, self.routes, strict=True))] + + 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)) + for operation, output in zip(self.operations, self.routes, strict=True): + operation() + output.copy_(torch.where(self.active_ids[..., None] >= 0, output, 0.)) + # Both TP shards run on this device to check the intermediate partition + # and reduce-before-weight arithmetic; this is not a transport test. + self.reduced.copy_(self.routes[0].float() + self.routes[1].float()) + self.output.copy_(mix_routes(self.reduced, self.weights, self.active_ids)) + + +@pytest.mark.parametrize("tokens", [1, 129, 4096]) +@torch.no_grad() +def test_calibrated_packed_experts_tp_shards_compiled_replay(tmp_path, tokens): + expert_count, top_k = (8, 6) if tokens == 129 else (4, 2) + config, tensors = checkpoint(tmp_path, moe_intermediate=256, routed_experts=expert_count, top_k=top_k) + prefix = "model.llm.layers.2.mlp.experts" + manifest = inspect_indexed_checkpoint(tmp_path) + experts = [] + def unswizzle(scales, rows, columns): + # Invert the native 128x4 scale atom independently of the load helper. + return (scales.view(torch.uint8).reshape(rows // 128, columns // 4, 32, 4, 4) + .permute(0, 3, 2, 1, 4).contiguous().reshape(rows, columns)) + + for rank in range(2): + with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(rank, 2)) as loader: + expert = loader.load_layer(2).experts + impl = expert._impl + first, last = rank * 128, (rank + 1) * 128 + original = tensors[prefix + ".w13_weight"] + expected = torch.cat((original[:, 2*first:2*last:2], original[:, 2*first+1:2*last:2]), 1) + assert torch.equal(impl.w1_fp4.cpu(), expected) + scales = tensors[prefix + ".w13_weight.scale"] + expected_scales = torch.cat((scales[:, 2*first:2*last:2].view(torch.uint8), + scales[:, 2*first+1:2*last:2].view(torch.uint8)), 1) + for index in range(config.text["n_routed_experts"]): + actual = unswizzle(impl.w1_blockscale[index], 256, config.hidden // 16) + assert torch.equal(actual.cpu(), expected_scales[index]) + assert torch.equal(impl.w2_fp4.cpu(), tensors[prefix + ".w2_weight"][:, :, first//2:last//2]) + for index in range(config.text["n_routed_experts"]): + actual = unswizzle(impl.w2_blockscale[index], config.hidden, 128 // 16) + assert torch.equal(actual.cpu(), + tensors[prefix + ".w2_weight.scale"][index, :, first//16:last//16].view(torch.uint8)) + for attribute, alpha, projection in (("a1_gscale", "w1_alphas", "w13_weight"), + ("a2_gscale", "w2_alphas", "w2_weight")): + amax = tensors[prefix + "." + projection + ".input_amax"].float().item() + scale = torch.full((config.text["n_routed_experts"],), amax / 2688.).reciprocal() + assert scale[0] != torch.tensor(2688. / amax) + assert torch.equal(getattr(impl, attribute).cpu(), scale) + assert torch.equal(getattr(impl, alpha).cpu(), tensors[prefix + "." + projection + ".scale2"] / scale) + experts.append(expert) + + torch.manual_seed(4517 + tokens) + device = torch.device("cuda:0") + source = torch.randn((tokens, config.hidden), device=device, dtype=torch.bfloat16) + offsets = torch.arange(top_k, device=device) * (1 if top_k == 6 else 2) + ids = ((torch.arange(tokens, device=device)[:, None] + offsets) % expert_count).int() + # Distinct route weights include the router's global gain; kernels must leave + # every expert output unweighted until the TP shards have been combined. + weights = torch.rand((tokens, top_k), device=device) * .14234226942062378 * 8. + live = torch.tensor([tokens], dtype=torch.int32, device=device) + with RecordedPreparationSession(device=device, checkpoint="inkling-nvfp4-experts", + workload_schema="inkling", numerical_policy="default", compile_workers=1) as session: + arena = ScratchArena(device) + session.register_scratch(arena) + forward = ExpertForward(source, experts, ids, weights, live, session=session, workspace=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) + if tokens > 1: + ids[0, 1] = -1 + active = torch.where(torch.arange(tokens, device=device)[:, None] < count, ids, -1) + expected = [nvfp4_routes(source, active, tensors, prefix, intermediate_range=(rank*128, (rank+1)*128)) + for rank in range(2)] + allocations = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations + for actual, reference in zip(forward.routes, expected, strict=True): + # This reduced checkpoint is exactly repeatable across the + # captured capacities and the reference's BF16 boundaries. + torch.testing.assert_close(actual, reference, atol=0, rtol=0) + # Test reduction and routing separately from quantized GEMM error. + reduced = (forward.routes[0].float() + forward.routes[1].float()).bfloat16() + result = torch.zeros_like(source) + for expert_id in range(expert_count): + route = ((reduced.float() * weights[..., None]) + * (active == expert_id)[..., None]).sum(1).bfloat16() + result += route + assert torch.equal(forward.output, result) + assert not forward.output[count:].count_nonzero() + graph.reset() diff --git a/tests/frontend/test_inkling.py b/tests/frontend/test_inkling.py index e8c7806eb..0c8ad61e2 100644 --- a/tests/frontend/test_inkling.py +++ b/tests/frontend/test_inkling.py @@ -12,7 +12,7 @@ import pytest ROOT = Path(__file__).resolve().parents[2] -SNAPSHOT = Path(os.environ.get("FLARE_INKLING_SNAPSHOT", "/data/models/Inkling-Small")) +SNAPSHOT = Path(os.environ.get("FLARE_INKLING_SNAPSHOT", "/data/models/Inkling-Small-NVFP4")) def test_native_inkling_matches_checkpoint(tmp_path): @@ -22,7 +22,7 @@ def test_native_inkling_matches_checkpoint(tmp_path): from ignition.recipes.inkling.frontend import prepare_frontend, runtime_assets if not (SNAPSHOT / "tokenizer.json").is_file(): - pytest.skip("requires pinned Inkling-Small frontend assets") + 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")) diff --git a/tests/recipes/inkling_helpers.py b/tests/recipes/inkling_helpers.py index 2a22ee567..a4a5c83e2 100644 --- a/tests/recipes/inkling_helpers.py +++ b/tests/recipes/inkling_helpers.py @@ -13,7 +13,7 @@ def configuration(): return dict(architectures=["InklingForConditionalGeneration"], model_type="inkling_mm_model", eos_token_id=200006, - text_config=dict(hidden_size=256, num_hidden_layers=2, vocab_size=256, unpadded_vocab_size=250, + 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, @@ -26,10 +26,30 @@ def configuration(): log_scaling_n_floor=128, log_scaling_alpha=.1, rms_norm_eps=1e-6, torch_dtype="bfloat16")) -def checkpoint(path): +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): torch.manual_seed(7821) raw = configuration() - config = ModelConfig.from_dict(raw) + raw["text_config"]["intermediate_size"] = moe_intermediate + raw["text_config"]["n_routed_experts"] = routed_experts + raw["text_config"]["num_experts_per_tok"] = top_k + quant = quantization() + config = ModelConfig.from_dict(raw, quant) c, h = config.text, config.hidden tensors = {} def rand(name, shape, scale=.025, dtype=torch.bfloat16): @@ -70,6 +90,20 @@ def ones(name, shape): 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 + # Independent exact checkpoint bytes: signed 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/test_inkling.py b/tests/recipes/test_inkling.py index 8ff7c1dda..6c446fab0 100644 --- a/tests/recipes/test_inkling.py +++ b/tests/recipes/test_inkling.py @@ -16,23 +16,24 @@ from ignition.recipes.inkling.model import route, mix_routes from ignition.recipes.inkling.pool import ContinuationPool, continuation_layout, page_bytes from ignition.recipes.inkling.recipe import RECIPE -from .inkling_helpers import configuration +from .inkling_helpers import configuration, quantization def test_checkpoint_alias_and_canonical_geometry(): from ignition.recipes import resolve from ignition.recipes.inkling.bootstrap import PreparationConfig - assert resolve("inkling-small").recipe is RECIPE - model = ModelConfig.from_dict(configuration()) - assert model.text["mlp_layer_types"] == ["dense", "sparse"] + assert resolve("inkling-small-nvfp4").recipe is RECIPE + 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(2)] == [128, -1] + 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 assert PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 - with pytest.raises(ValueError, match="eight distinct"): + with pytest.raises(ValueError): PreparationConfig(devices=(0,)) @@ -44,11 +45,33 @@ def test_rejects_changed_arithmetic(change): raw = configuration() raw["text_config"].update(change) with pytest.raises(ValueError): - ModelConfig.from_dict(raw) + ModelConfig.from_dict(raw, quantization()) raw = configuration() raw["quantization_config"] = {"quant_method": "modelopt", "quant_algo": "NVFP4"} - with pytest.raises(ValueError, match="BF16"): - ModelConfig.from_dict(raw) + with pytest.raises(ValueError, match="hf_quant_config"): + ModelConfig.from_dict(raw, quantization()) + + +def test_checkpoint_quantization_requires_both_calibration_and_exclusions(tmp_path): + import json + + 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) + 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(): @@ -83,9 +106,9 @@ def test_routed_sum_uses_checkpoint_expert_order_and_bf16_boundaries(): def test_contract_snapshots_every_history_and_retains_bf16_pages(): - config, shard = ModelConfig.from_dict(configuration()), TensorParallelShard(0, 1) + config, shard = ModelConfig.from_dict(configuration(), quantization()), TensorParallelShard(0, 1) pool = ContinuationPool.allocate(config, shard, 4, 3, "cpu") - assert page_bytes(config, shard) == 2 * 128 * 128 * 2 + 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) @@ -103,6 +126,6 @@ def test_contract_snapshots_every_history_and_retains_bf16_pages(): 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) == 2 and all(r.storage.stride == 32768 for r in histories) + 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 index cec1db3f6..f83306e3e 100644 --- a/tests/recipes/test_inkling_cuda.py +++ b/tests/recipes/test_inkling_cuda.py @@ -19,6 +19,7 @@ from ignition.recipes.inkling.model import norm from ignition.recipes.inkling.pool import ContinuationPool from ignition.recipes.inkling.weights import 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") @@ -29,7 +30,17 @@ def convolution(x, weight): return (y[0, :, :x.shape[0]].T + x.float()).to(x.dtype) -def reference(weights, tokens): +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 @@ -75,11 +86,19 @@ def mlp(gate_up, down, gamma=None): 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: + routes = nvfp4_routes(source, ids, original, f"model.llm.layers.{index}.mlp.experts") for expert in range(c["n_routed_experts"]): - expert_out = mlp(w.experts.gate_up[expert], w.experts.down[expert]) selection = ids == expert - weight = (probabilities[:, :c["num_experts_per_tok"]] * selection).sum(-1) - routed += (expert_out * weight[:, None]).bfloat16() + 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() @@ -104,9 +123,31 @@ def test_original_checkpoint_loader_shards_interleaved_rows_without_losing_preci 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_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): +def test_loader_rejects_checkpoint_precision_disagreeing_with_exclusions(tmp_path, layer, excluded, error): + import json + from ignition.recipes.inkling.weights import InklingWeightLoader + 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): + _, 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, 4, 5, device) @@ -141,7 +182,7 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): session.freeze() pool.clear_for_preparation() tokens = (torch.arange(259, device=device) * 17 % weights.config.vocabulary).long() - expected, expected_hidden = reference(weights, tokens) + 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)): @@ -157,9 +198,8 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == before start += count - # The fixed reduced checkpoint matches exactly across these BF16 boundaries. - torch.testing.assert_close(scratch.logits[0], expected[start - 1], atol=0, rtol=0) - torch.testing.assert_close(scratch.hidden[0], expected_hidden[start - 1], atol=0, rtol=0) + 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()} @@ -189,7 +229,7 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): @torch.no_grad() def test_decoder_batched_decode_with_inactive_rows_after_window_wrap(tmp_path): - checkpoint(tmp_path) + _, 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, 5, 10, device) @@ -249,5 +289,5 @@ def test_decoder_batched_decode_with_inactive_rows_after_window_wrap(tmp_path): 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) - torch.testing.assert_close(s.logits[row], expected[-1], atol=0, rtol=0) + expected, _ = reference(weights, sequence, original) + assert_decoder_close(s.logits[row], expected[-1]) diff --git a/tests/recipes/test_inkling_topology.py b/tests/recipes/test_inkling_topology.py new file mode 100644 index 000000000..5336a922a --- /dev/null +++ b/tests/recipes/test_inkling_topology.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling NVFP4 placements and memory planning through the shared planner.""" + +import pytest + +from ignition import planning +from ignition.errors import CapacityError +from ignition.recipes import resolve +from ignition.recipes.inkling.recipe import RECIPE + + +@pytest.mark.parametrize('devices,hosts', [((0, 1), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b'))]) +def test_two_distinct_local_or_remote_placements(devices, hosts): + from ignition.recipes.inkling.bootstrap import PreparationConfig + + config = PreparationConfig(devices=devices, hosts=hosts) + assert config.devices == devices and config.hosts == hosts + + +@pytest.mark.parametrize('devices,hosts', [ + ((0,), None), ((0, 1, 2, 3), None), ((0, 0), None), ((0, -1), None), + ((0, 0), ('spark-a', 'spark-a')), ((0, 1), ('spark-a',)), +]) +def test_unsupported_placements_fail_before_loading(devices, hosts): + from ignition.recipes.inkling.bootstrap import PreparationConfig + + with pytest.raises(ValueError, match='two distinct host/device placements'): + PreparationConfig(devices=devices, hosts=hosts) + + +def test_roce_ring_requires_remote_placements(): + from ignition.recipes.inkling.bootstrap import PreparationConfig + + with pytest.raises(ValueError, match='ranks on separate hosts'): + PreparationConfig(roce_ring=True) + + +def test_sm103_is_rejected_before_checkpoint_loading(monkeypatch, tmp_path): + from ignition.recipes.inkling import bootstrap + + monkeypatch.setattr(bootstrap.torch.cuda, 'set_device', lambda device: None) + monkeypatch.setattr(bootstrap.torch.cuda, 'get_device_capability', lambda device: (10, 3)) + with pytest.raises(ValueError, match='A4 expert kernels must expose unweighted per-route outputs'): + bootstrap.prepare_rank(tmp_path / 'not-downloaded', bootstrap.PreparationConfig(), + rank=0, group=None, package_storage=None) + + +def test_nvfp4_plan_fits_two_sparks_with_host_reserve(): + model = resolve('inkling-small-nvfp4') + assert model.recipe is RECIPE and model.checkpoint.repository == 'thinkingmachines/Inkling-Small-NVFP4' + gpus = tuple(planning.Gpu(index, 'NVIDIA GB10', f'GPU-{index}', 121 << 30, 118 << 30, (12, 1)) + for index in range(2)) + plan = planning.plan(RECIPE, model.checkpoint, gpus, selected=(0, 1), + concurrency=4, reserve_bytes=4 << 30, speculation=None) + assert plan.world_size == 2 and plan.fits + assert plan.context == plan.guaranteed_tokens == 262144 + assert plan.costs.state_row_bytes == 43_515_904 + assert plan.costs.page_bytes == 1_835_008 + assert plan.weights_bytes >= 166_130_594_960 // 2 + assert plan.reserve_bytes == 4 << 30 + with pytest.raises(CapacityError, match='needs 2 GPUs'): + planning.plan(RECIPE, model.checkpoint, gpus[:1], selected=(0,), + concurrency=4, reserve_bytes=4 << 30, speculation=None) + small = tuple(planning.Gpu(index, 'NVIDIA RTX', f'GPU-{index}', 64 << 30, 63 << 30, (12, 0)) + for index in range(2)) + with pytest.raises(CapacityError): + planning.plan(RECIPE, model.checkpoint, small, selected=(0, 1), + concurrency=4, reserve_bytes=0, speculation=None) diff --git a/tests/server/test_inkling.py b/tests/server/test_inkling.py index b1981a980..9003bae2f 100644 --- a/tests/server/test_inkling.py +++ b/tests/server/test_inkling.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Acceptance for a TP8 Inkling package exported with prompt logprobs and served by Flare. +"""Acceptance for a TP2 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 d17d647efddff70b3a95e35620668ffdfc4e0d7f Mon Sep 17 00:00:00 2001 From: Arthur <xuyangc@nvidia.com> Date: Tue, 3 Nov 2026 23:12:04 -0800 Subject: [PATCH 3/5] Support Inkling NVFP4 on a single DGX Station Add TP1 planning and preparation without collectives, calibrated SM103 NVFP4 grouped GEMMs with explicit BF16 SwiGLU and raw route outputs, and shared recognition of the observed GB300 Station PCI identity. Preserve original packed weights, calibration, complete continuation state, and existing TP2 preparation. Full-checkpoint validation on a Colossus-leased GB300 Station passed: 29 graph captures, signed package export, native Flare loading/serving, all 29 endpoint acceptance cases, and clean shutdown. Twelve Station numerical checks and the reduced TP1 full-catalog test passed; the actual checkpoint expert layer matched the independent reference exactly. SM120 passed eight expert/decoder regressions and the TP1 catalog test. Focused CPU checks passed 32 cases; GB300 native checks passed nine. Full-checkpoint TP2/RoCE, SM121, and actual 262144-token request execution remain unqualified. Station tests use locked FlashInfer 776facfd; the inherited declared-revision discrepancy is unchanged. Three unrelated compressed-expert fixture failures reproduce on the unchanged parent. No package format, native policy, or graph operation family changes. Design-Signed-Off-By: Codex (GPT-6); design-review=a38f Signed-off-by: Arthur <xuyangc@nvidia.com> --- docs/model-preparation.md | 55 +++-- flare/src/hardware.rs | 5 +- heliopause/src/export/package.rs | 35 ++- helios/src/package/naming.rs | 19 +- ignition/components/moe_sm103.py | 174 ++++++++++++++- ignition/recipes/inkling/bootstrap.py | 28 ++- ignition/recipes/inkling/recipe.py | 7 +- ignition/recipes/inkling/weights.py | 12 +- tests/components/inkling_nvfp4_helpers.py | 71 +++++- .../test_inkling_nvfp4_sm103_cuda.py | 205 ++++++++++++++++++ tests/components/test_weight_metadata.py | 12 +- tests/recipes/test_inkling.py | 2 +- tests/recipes/test_inkling_cuda.py | 6 +- .../recipes/test_inkling_preparation_cuda.py | 169 +++++++++++++++ tests/recipes/test_inkling_topology.py | 68 +++++- tests/server/test_inkling.py | 2 +- 16 files changed, 802 insertions(+), 68 deletions(-) create mode 100644 tests/components/test_inkling_nvfp4_sm103_cuda.py create mode 100644 tests/recipes/test_inkling_preparation_cuda.py diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 9d3ff1621..364742b33 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -988,9 +988,10 @@ flare/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.safete The `inkling-small-nvfp4` alias selects [`thinkingmachines/Inkling-Small-NVFP4`](https://huggingface.co/thinkingmachines/Inkling-Small-NVFP4) at revision `b6a99534467840620d411e4cd4ad5819b2610d9c`. This text recipe -targets tensor parallelism two on SM120/SM121, using two local GPUs or one GPU -on each of two DGX Sparks through the shared RoCE transport. Defaults are a -262144-token context, four concurrent requests, and 4096-token prefill chunks. +targets one SM103 GPU on DGX Station, or tensor parallelism two on SM120/SM121, +using two local GPUs or one GPU on each of two DGX Sparks through the shared +RoCE transport. A single rank prepares complete weights and no collectives. +Defaults are a 262144-token context, four concurrent requests, and 4096-token prefill chunks. Prepared context is capped at 262144 tokens of the checkpoint's 1048576-token limit. Image, audio, video, and MTP graphs are not prepared. The indexed download includes the publisher's MTP weights; only `model.llm` tensors become serving @@ -1027,11 +1028,17 @@ parameters, so that load mode is not the precision reference for routing. The indexed checkpoint contains 170,733,074,592 bytes of tensors, including 166,130,594,960 bytes of text weights. The planner conservatively budgets the -whole checkpoint for weights, plus preparation scratch and caches. At TP2, -each continuation row occupies 43,515,904 bytes and each 128-token global KV page -occupies 1,835,008 bytes per rank. One full 262144-token global KV history needs -3.5 GiB per rank. Spark's CPU, GPU, compiler processes, and OS share physical -memory; follow the [DGX Spark memory guidance](#dgx-spark). +whole checkpoint for weights, plus preparation scratch and caches. Cache costs +per GPU are: + +| Tensor parallelism | Continuation row | 128-token global KV page | One 262144-token global KV history | +|---|---:|---:|---:| +| 1 | 82,837,504 bytes | 3,670,016 bytes | 7 GiB | +| 2 | 43,515,904 bytes | 1,835,008 bytes | 3.5 GiB | + +The planner uses detected free GPU memory for admission. Spark's CPU, GPU, +compiler processes, and OS share physical memory; follow the +[DGX Spark memory guidance](#dgx-spark). The publisher's [Inkling sampling guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, @@ -1039,11 +1046,14 @@ recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, owns the thinking-effort system message and content-header/tool syntax. ```sh -.venv/bin/ignition export inkling-small-nvfp4 --gpus 0,1 --prompt-logprobs -.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-nvfp4-tp2.safetensors -flare/target/release/flare run /data/flare-runtime/inkling-small-nvfp4-tp2.safetensors --gpus 0,1 +.venv/bin/ignition export inkling-small-nvfp4 --gpus 0 --prompt-logprobs +.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-nvfp4-tp1.safetensors +flare/target/release/flare run /data/flare-runtime/inkling-small-nvfp4-tp1.safetensors --gpus 0 ``` +For two local GPUs, use `--gpus 0,1` for export and serving, and convert that +export to a separate TP2 package. Each tensor-parallel size requires its own export. + For two Sparks, prepare with `--gpus 0 --ranks 2 --rendezvous ZERO:29630` on rank zero and `ignition join ZERO:29630 --rank 1 --ranks 2` on its peer. Follow [multi-host preparation and serving](multi-host.md#prepare-the-package) for @@ -1052,13 +1062,22 @@ checkpoint access, transport setup, and launching the resulting two-host package Reduced model validation covers original-format weight loading, learned relative attention, FP32 residual convolution, complete compiled decoder replay across prefill/decode and page/window boundaries, state restoration, inactive rows, and -allocation stability on SM120. Full-checkpoint TP2 export and native serving, -RoCE execution, long-context behavior, and SM121 execution remain unqualified. -SM103's current expert implementation does not expose the unweighted route -outputs this recipe requires. Run -`tests/server/test_inkling.py` against the exported package with -`FLARE_RUN_CUDA_TESTS=1`, `FLARE_INKLING_TEST_URL`, and -`FLARE_INKLING_SNAPSHOT` set before promoting this draft recipe. +allocation stability on SM120 and SM103. Reduced TP1 preparation and replay of +the complete graph catalog, including scored prefill, also pass on both GPUs. +SM103 expert checks cover calibrated activation quantization, reduced unweighted +route capture/replay at 1, 129, and 4096 tokens, and execution of an actual +checkpoint expert layer with 256 experts, hidden size 4096, and intermediate +size 2048. +Full-checkpoint TP1 export and native `flare run` pass on one GB300 DGX +Station with the default capacities above. All 29 endpoint acceptance cases pass, +including text/Unicode, reasoning effort, tools, concurrent cached-prefix branches, +prompt scoring, and media rejection. Native loading uses 158.2 GiB before the +runtime sizes its cache from available GPU memory. The tested environment uses +the locked FlashInfer revision `776facfd`. +Full-checkpoint TP2/RoCE execution, 262144-token context behavior, and SM121 +execution remain unqualified. Reproduce endpoint acceptance with +`tests/server/test_inkling.py`, setting `FLARE_RUN_CUDA_TESTS=1`, +`FLARE_INKLING_TEST_URL`, and `FLARE_INKLING_SNAPSHOT`. ## Muse Spark Open diff --git a/flare/src/hardware.rs b/flare/src/hardware.rs index 98841f50f..2c96039f3 100644 --- a/flare/src/hardware.rs +++ b/flare/src/hardware.rs @@ -112,7 +112,7 @@ pub fn detect(count: usize) -> Result<&'static str> { })?; if selected.is_some_and(|value| value != detected) { return Err( - "selected GPUs span gb10 and gb202; select one platform or specify --revision" + "selected GPUs span different platforms; select one platform or specify --revision" .into(), ); } @@ -186,6 +186,9 @@ mod tests { assert_eq!(platform(0x2bb110de), Some("gb202")); assert_eq!(platform(0x2bb510de), Some("gb202")); assert_eq!(platform(0x2b8510de), Some("gb202")); + assert_eq!(platform(0x31c210de), Some("gb300")); + assert_eq!(platform(0x31c310de), None); + assert_eq!(platform(0x31c21234), None); assert_eq!(platform(0x26b110de), None); assert_eq!(platform(0x2bb41234), None); } diff --git a/heliopause/src/export/package.rs b/heliopause/src/export/package.rs index 33aa6f848..2ea284c1e 100644 --- a/heliopause/src/export/package.rs +++ b/heliopause/src/export/package.rs @@ -720,7 +720,7 @@ pub(crate) fn publish_payload( .iter() .find_map(|rank| rank.hardware.clone()) .ok_or_else(|| { - invalid("export naming requires the capture device identity (gb10 or gb202)") + invalid("export naming requires the capture device identity (gb10, gb202, or gb300)") })?; let deployment_id = cluster .as_ref() @@ -4201,6 +4201,39 @@ mod payload_export_tests { let _ = std::fs::remove_dir_all(&base); } + #[test] + fn gb300_export_names_and_signs_the_station_platform() { + use helios_core::package::cache::Root; + use helios_core::package::schema::wire as pwire; + let sources = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + let mut rank = staged_rank(sources.path()); + rank.hardware = + helios_core::package::naming::platform_from_pci(0x31c2_10de).map(str::to_string); + rank.index.ranks[0].architecture = vec![10, 3]; + let published = publish_payload( + Path::new(""), + &[rank], + vec![], + None, + &publisher(), + Some(cache.path().to_path_buf()), + false, + "directory", + ) + .unwrap(); + let entry = published["entry"].as_str().unwrap(); + assert!(entry.starts_with("gb300-tp1-"), "{entry}"); + let root = Root::open(cache.path()).unwrap(); + let committed = root + .entry(published["model"].as_str().unwrap(), entry) + .unwrap(); + let metadata = Metadata::open(committed.directory()).unwrap(); + let envelope = helios_core::package::protection::envelope(&metadata.envelope).unwrap(); + let body = pwire::PackageBody::decode(envelope.package_body.as_slice()).unwrap(); + assert_eq!(body.hardware_identity, "gb300"); + } + #[test] fn cached_state_and_staged_globals_use_unique_payload_names() { use crate::export::{WeightPayloadGroup, WeightPayloadSourceSpan, WeightPayloadSources}; diff --git a/helios/src/package/naming.rs b/helios/src/package/naming.rs index 2436cd76c..df47459e9 100644 --- a/helios/src/package/naming.rs +++ b/helios/src/package/naming.rs @@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// Platforms a package may be named for. These are the NVIDIA device /// identifiers Flare already uses for revisions, not SM architecture names. -pub const PLATFORMS: [&str; 2] = ["gb10", "gb202"]; +pub const PLATFORMS: [&str; 3] = ["gb10", "gb202", "gb300"]; /// Platform for one NVIDIA PCI id in NVML's `device<<16 | vendor` layout. /// @@ -26,6 +26,9 @@ pub const GB202_DEVICES: [u32; 9] = [ /// RTX Spark N1X part, which NVML reports for the same SM121 platform. pub const GB10_DEVICES: [u32; 2] = [0x2e12, 0x2e03]; +/// GB300 device identifier reported by NVML on DGX Station. +pub const GB300_DEVICES: [u32; 1] = [0x31c2]; + pub fn platform_from_pci(pci_id: u32) -> Option<&'static str> { if pci_id & 0xffff != 0x10de { return None; @@ -34,6 +37,9 @@ pub fn platform_from_pci(pci_id: u32) -> Option<&'static str> { if GB10_DEVICES.contains(&device) { return Some("gb10"); } + if GB300_DEVICES.contains(&device) { + return Some("gb300"); + } GB202_DEVICES.contains(&device).then_some("gb202") } @@ -160,6 +166,10 @@ mod tests { candidate("gb10", 8, at(1_792_228_980)).as_deref(), Some("gb10-tp8-202610170923") ); + assert_eq!( + candidate("gb300", 1, at(1_792_228_980)).as_deref(), + Some("gb300-tp1-202610170923") + ); assert!(candidate("sm120", 1, at(0)).is_none()); assert!(candidate("gb202", 0, at(0)).is_none()); } @@ -180,6 +190,9 @@ mod tests { "{device:#06x}" ); } + assert_eq!(platform_from_pci(0x31c2_10de), Some("gb300")); + assert_eq!(platform_from_pci(0x31c2_1af4), None); + assert_eq!(platform_from_pci(0x31c3_10de), None); assert_eq!(platform_from_pci(0x2bbc_1af4), None); assert_eq!(platform_from_pci(0x1e02_10de), None); } @@ -202,6 +215,10 @@ mod tests { deployment_candidate(Some("gb202"), &[2, 1], at).as_deref(), Some("gb202-tp1+tp2-202610170923") ); + assert_eq!( + deployment_candidate(Some("gb300"), &[1], at).as_deref(), + Some("gb300-tp1-202610170923") + ); assert_eq!( deployment_candidate(Some("sm120"), &[1], at).as_deref(), Some("unknown-device-tp1-202610170923") diff --git a/ignition/components/moe_sm103.py b/ignition/components/moe_sm103.py index a1fec231c..3eb3b93ab 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. +* Calibrated W4A4 experts requiring a BF16 SwiGLU boundary use CuTe-DSL + grouped GEMMs around that explicit intermediate and return raw BF16 routes. 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): + """Calibrated W4A4 experts with BF16 SwiGLU intermediates and raw route output.""" + + 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: + """Preserve packed values and calibration while preparing BF16-intermediate W4A4.""" + 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,68 @@ def run(self, a, topk_ids, topk_weights, output, scratch): use_fused_finalize=False, enable_pdl=True, tactic=self.tactic, **clamp) +class _CuteNvfp4State: + """Calibrated A4 GEMMs with BF16 activation and independently rounded route outputs.""" + + 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) + # This explicit BF16 tensor is the arithmetic boundary before the calibrated FC2 input. + 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 +694,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 +796,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 +806,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 +847,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 +858,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 +866,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/recipes/inkling/bootstrap.py b/ignition/recipes/inkling/bootstrap.py index 215ec95b7..4c465d62c 100644 --- a/ignition/recipes/inkling/bootstrap.py +++ b/ignition/recipes/inkling/bootstrap.py @@ -54,7 +54,7 @@ class PreparationConfig: lock_gpu_clocks: bool = False autotune_effort: str = "default" tuning_replica: TuningReplica | None = None - devices: tuple[int, ...] = (0, 1) + devices: tuple[int, ...] = (0,) hosts: tuple[str, ...] | None = None roce_ring: bool = False context: int = 262144 @@ -68,12 +68,12 @@ class PreparationConfig: stream_overlap: bool = True def __post_init__(self): - if (not isinstance(self.devices, tuple) or len(self.devices) != 2 - or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != 2) - or len(set(zip(self.hosts or ("",) * 2, self.devices))) != 2 + if (not isinstance(self.devices, tuple) or len(self.devices) not in (1, 2) + or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != len(self.devices)) + or len(set(zip(self.hosts or ("",) * len(self.devices), self.devices))) != len(self.devices) or any(type(device) is not int or device < 0 for device in self.devices)): - raise ValueError("Inkling-Small NVFP4 preparation requires two distinct host/device placements") - if self.roce_ring and self.hosts is None: + raise ValueError("Inkling-Small NVFP4 preparation requires one or two distinct host/device placements") + if self.roce_ring and (self.hosts is None or len(set(self.hosts)) < 2): raise ValueError("RoCE ring requires ranks on separate hosts") request_capacity(self.max_active) if not PAGE_TOKENS <= self.context <= 262144 or self.context % PAGE_TOKENS: @@ -91,10 +91,12 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag snapshot = Path(snapshot).resolve() shard = TensorParallelShard(rank, len(config.devices)) + if (shard.world_size > 1) != (group is not None): + raise ValueError("an Inkling rank group exists exactly when more than one rank prepares") device = torch.device("cuda", config.devices[rank]) torch.cuda.set_device(device) - if torch.cuda.get_device_capability(device) not in ((12, 0), (12, 1)): - raise ValueError("Inkling NVFP4 preparation requires SM120 or SM121: " + if torch.cuda.get_device_capability(device) not in ((10, 3), (12, 0), (12, 1)): + raise ValueError("Inkling NVFP4 preparation requires SM103, SM120, or SM121: " "the A4 expert kernels must expose unweighted per-route outputs") with phase(progress, "Inspect checkpoint"): manifest = inspect_indexed_checkpoint(snapshot) @@ -124,15 +126,16 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag 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 = CollectivePreparation(group) + coordinator = CollectivePreparation(group) if group is not None else None + collective = prefill_collective = vocabulary_collective = embedding_collective = None routed_width = weights.config.text["num_experts_per_tok"] * weights.config.hidden - if coordinator.spans_hosts: + if coordinator is not None and coordinator.spans_hosts: gather_bytes = max(slots * weights.config.vocabulary_partition(shard)[2] * 2, tokens * (weights.config.hidden // shard.world_size) * 2) collective = prefill_collective = vocabulary_collective = embedding_collective = create_roce_runtime( group, device, max_tokens=slots, pipe_tokens=tokens, hidden_size=routed_width, gather_bytes=gather_bytes, ring=config.roce_ring, package_storage=package_storage) - else: + elif group is not None: collective = create_all_reduce_runtime(group, device, collective_tuning=config.collective_tuning, max_tokens=slots, hidden_size=routed_width, ipc=package_storage.peer_storage) prefill_collective = create_dma_all_reduce_runtime(group, device, max_tokens=tokens, @@ -247,7 +250,8 @@ def materialize(): 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()) - channels = tuple(dict.fromkeys((collective, prefill_collective, vocabulary_collective, embedding_collective))) + channels = tuple(dict.fromkeys(channel for channel in + (collective, prefill_collective, vocabulary_collective, embedding_collective) if channel is not None)) disposable = [prefill_storage, decode_storage, arena.tensor, metadata, graph_buffers.chunks, private_buffers.chunks] for forward in forwards.values(): if isinstance(forward, PreparedScoredPrefill): diff --git a/ignition/recipes/inkling/recipe.py b/ignition/recipes/inkling/recipe.py index 65214b3b5..96f84d317 100644 --- a/ignition/recipes/inkling/recipe.py +++ b/ignition/recipes/inkling/recipe.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling-Small NVFP4 text preparation on two local GPUs or DGX Sparks.""" +"""Inkling-Small NVFP4 text preparation on one or two GPUs.""" from types import MappingProxyType @@ -24,6 +24,8 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ 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) + if plan.world_size == 1: + return prepare_rank(snapshot, config, rank=0, group=None, progress=progress, package_storage=package_storage) return prepare_group(snapshot, config, prepare_rank, progress=progress, package_storage=package_storage, ranks=ranks, checkpoint=plan.checkpoint) @@ -41,4 +43,5 @@ def usage(prepared): # Include unused multimodal/MTP tensors in the estimate to cover replicated text weights. 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({2: RankCosts(43_515_904, 1_835_008, 8 << 30)})) + ranks=MappingProxyType({1: RankCosts(82_837_504, 3_670_016, 8 << 30), + 2: RankCosts(43_515_904, 1_835_008, 8 << 30)})) diff --git a/ignition/recipes/inkling/weights.py b/ignition/recipes/inkling/weights.py index 96d9f8363..04dbb532b 100644 --- a/ignition/recipes/inkling/weights.py +++ b/ignition/recipes/inkling/weights.py @@ -109,8 +109,10 @@ def _interleaved(self, name, down_name, inter, *, expert=None, destination=None) 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 = [], [], [], [] @@ -142,7 +144,8 @@ def _nvfp4_experts(self, prefix, inter): self._copy(scales[expert], scale[expert, :, first // 16:last // 16]) else: for offset in (0, 1): - target = slice(offset * local, (offset + 1) * local) + 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) @@ -152,8 +155,13 @@ def _nvfp4_experts(self, prefix, inter): inputs.append(activation_scale) self._session.flush() packed.append(values) - blocks.append(swizzle_block_scale(scales)) + 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)) diff --git a/tests/components/inkling_nvfp4_helpers.py b/tests/components/inkling_nvfp4_helpers.py index e27ddc76c..4f9bdd6c0 100644 --- a/tests/components/inkling_nvfp4_helpers.py +++ b/tests/components/inkling_nvfp4_helpers.py @@ -4,6 +4,41 @@ """Raw Inkling NVFP4 fixtures and an independent quantized arithmetic oracle.""" import torch +import triton +import triton.language as tl + + +@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): + """The native quantizer's CUDA reciprocal primitive, independent of its kernels.""" + 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 unpack_weight(values, scales): @@ -14,12 +49,12 @@ def unpack_weight(values, scales): return signed * scales.float().repeat_interleave(16, -1) -def quantize_activation(value, amax): +def quantize_activation(value, amax, *, quant_scale_math="b12x"): """Calibrated per-16 NVFP4 inner values and their FP32 reciprocal outer scale. The packed MMA consumes E2M1 values times E4M3 block scales. Its outer calibration multiplies the accumulator, not each input value. Reciprocal - multiplication preserves the fast quantizer's E2M1 tie evaluation order. + multiplication preserves the selected quantizer's E2M1 tie evaluation order. """ value = value.float() blocks = value.reshape(*value.shape[:-1], -1, 16) @@ -27,10 +62,21 @@ def quantize_activation(value, amax): # stored value. Directly rounding 2688/amax skips an observable boundary. dequant = torch.tensor(float(amax.item()) / 2688., dtype=torch.float32, device=value.device) encode = dequant.reciprocal() - sixth = torch.full_like(encode, 1. / 6.) + 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() - inverse = torch.where(scales != 0, scales.reciprocal() * encode, 0.) + if quant_scale_math == "b12x": + inverse = scales.reciprocal() * encode + elif quant_scale_math == "flashinfer": + # FlashInfer's native fast quantizer reciprocates the product of the + # rounded E4M3 scale and reciprocal calibration using rcp.approx.ftz. + # Either reassociation or correctly-rounded reciprocal changes E2M1 + # ties, including the publisher's amax=187 (quantization_utils.cuh). + 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.) normalized = blocks * inverse magnitude = normalized.abs() code = ((magnitude > .25).int() + (magnitude >= .75).int() + (magnitude > 1.25).int() @@ -40,7 +86,8 @@ def quantize_activation(value, amax): return (levels[code] * normalized.sign() * scales).reshape_as(value), encode -def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None): +def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None, + quant_scale_math="b12x"): """FP32 FC1 -> FP32 SwiGLU -> BF16 -> calibrated NVFP4 -> FP32 FC2 -> BF16. Decode checkpoint bytes only for the test oracle. Production kernels consume @@ -51,7 +98,8 @@ def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None): tensors = {name: value.to(source.device) for name, value in tensors.items() if name.startswith(prefix + ".")} intermediate = tensors[first].shape[1] // 2 begin, end = (0, intermediate) if intermediate_range is None else intermediate_range - source_quantized, input_scale = quantize_activation(source, tensors[first + ".input_amax"]) + 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) for expert in range(tensors[first].shape[0]): tokens, routes = torch.where(ids == expert) @@ -63,8 +111,15 @@ def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None): up_gate = unpack_weight(tensors[first][expert, rows], tensors[first + ".scale"][expert, rows]) projected = (source_quantized[tokens] @ up_gate.T) * (tensors[first + ".scale2"][expert] / input_scale) gate, up = projected[:, ::2], projected[:, 1::2] - activated = (torch.nn.functional.silu(gate) * up).bfloat16() - activated, intermediate_scale = quantize_activation(activated, tensors[second + ".input_amax"]) + 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 = unpack_weight(tensors[second][expert, :, begin // 2:end // 2], tensors[second + ".scale"][expert, :, begin // 16:end // 16]) result[tokens, routes] = ((activated @ down.T) 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..786327570 --- /dev/null +++ b/tests/components/test_inkling_nvfp4_sm103_cuda.py @@ -0,0 +1,205 @@ +# 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 + +import pytest +import torch + +from ignition.components.moe import PreparedRoutedExperts +from ignition.components.moe_sm103 import CuteNvfp4Experts +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 tests.recipes.inkling_helpers import checkpoint +from .inkling_nvfp4_helpers import nvfp4_routes, quantize_activation, unpack_weight + +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): + from ignition.components.moe_sm103 import _fp4_quantizer + + 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 = unpack_weight(values, scales[:64].view(torch.float8_e4m3fn).reshape(4, 16)) + 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) + + # Native CuTe FC1 is [up64;gate64], derived only by row permutation. + def interleave(tensor): + up_gate = torch.stack((tensor[:, 1::2], tensor[:, ::2]), 2) + return up_gate.reshape(8, 4, 64, 2, -1).transpose(2, 3).reshape_as(tensor) + + assert torch.equal(experts.w13.cpu(), interleave(tensors[prefix + ".w13_weight"])) + assert torch.equal(experts.w2.cpu(), tensors[prefix + ".w2_weight"]) + for storage, name, rows, columns, reorder in ( + (experts.scale_storage[0], "w13_weight", 512, 16, interleave), + (experts.scale_storage[1], "w2_weight", 256, 16, lambda x: x), + ): + actual = (storage.cpu().view(torch.uint8).reshape(8, rows // 128, columns // 4, 32, 4, 4) + .permute(0, 1, 4, 3, 2, 5).contiguous().reshape(8, rows, columns)) + assert torch.equal(actual, reorder(tensors[prefix + "." + name + ".scale"].view(torch.uint8))) + 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(): + from pathlib import Path + from safetensors import safe_open + + 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 = {} + # Read original bytes through safetensors, independently of the recipe's packed layout. + 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 + difference = forward.routes.float() - reference.float() + print({"max_absolute_error": difference.abs().max().item(), + "relative_l2_error": (difference.norm() / reference.float().norm().clamp_min(1e-12)).item()}) + 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_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/recipes/test_inkling.py b/tests/recipes/test_inkling.py index 6c446fab0..3654c87c1 100644 --- a/tests/recipes/test_inkling.py +++ b/tests/recipes/test_inkling.py @@ -34,7 +34,7 @@ def test_checkpoint_alias_and_canonical_geometry(): assert RECIPE.speculation is None and RECIPE.max_draft_tokens == 0 assert PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 with pytest.raises(ValueError): - PreparationConfig(devices=(0,)) + PreparationConfig(devices=(0, 1, 2)) @pytest.mark.parametrize("change", [ diff --git a/tests/recipes/test_inkling_cuda.py b/tests/recipes/test_inkling_cuda.py index f83306e3e..6a1b5c70b 100644 --- a/tests/recipes/test_inkling_cuda.py +++ b/tests/recipes/test_inkling_cuda.py @@ -88,7 +88,11 @@ def mlp(gate_up, down, gamma=None): routed = torch.zeros_like(source) quantized = index in weights.config.quantized_routed_layers if quantized: - routes = nvfp4_routes(source, ids, original, f"model.llm.layers.{index}.mlp.experts") + # 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: diff --git a/tests/recipes/test_inkling_preparation_cuda.py b/tests/recipes/test_inkling_preparation_cuda.py new file mode 100644 index 000000000..365a115c2 --- /dev/null +++ b/tests/recipes/test_inkling_preparation_cuda.py @@ -0,0 +1,169 @@ +# 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 json +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 safetensors.torch import save_file + 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_rank + from ignition.recipes.inkling.config import ModelConfig + from ignition.recipes.inkling.pool import ContinuationPool, continuation_layout + from .inkling_helpers import checkpoint + + snapshot = Path(os.environ.get("FLARE_INKLING_SNAPSHOT", "")) + if not (snapshot / "tokenizer.json").is_file(): + pytest.skip("requires pinned Inkling frontend assets") + _, tensors = checkpoint(tmp_path) + raw = json.loads((tmp_path / "config.json").read_text()) + # Keep the publisher's complete frontend and special-token IDs while reducing + # layer geometry; this exercises frontend/contract preparation without mocks. + publisher = ModelConfig.load(snapshot) + raw["text_config"].update(vocab_size=publisher.text["vocab_size"], + unpadded_vocab_size=publisher.vocabulary) + for name in ("embed", "unembed"): + tensors[f"model.llm.{name}.weight"] = ( + torch.randn(publisher.text["vocab_size"], 256) * .1).bfloat16() + (tmp_path / "config.json").write_text(json.dumps(raw)) + save_file(tensors, tmp_path / "model.safetensors") + (tmp_path / "model.safetensors.index.json").write_text(json.dumps(dict( + metadata={"total_size": sum(t.nbytes for t in tensors.values())}, + weight_map={name: "model.safetensors" for name in tensors}))) + for name in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja"): + (tmp_path / name).symlink_to(snapshot / name) + del tensors + config = ModelConfig.load(tmp_path) + preparation = PreparationConfig(devices=(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_rank(tmp_path, preparation, rank=0, group=None, 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["world_size"] == 1 + 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 + + def assert_state(actual, expected): + assert actual.keys() == expected.keys() + for name in expected: + torch.testing.assert_close(actual[name], expected[name], atol=0, rtol=0, msg=name) + + 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 + assert_state(state, expected_state) + 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() + assert scores[:126, 0].tolist() == prompt[1:] + assert torch.isfinite(scores[:126, 1].contiguous().view(torch.float32)).all() + assert (scores[:126, 1].contiguous().view(torch.float32) <= 0).all() + assert ((scores[:126, 2] >= 1) & (scores[:126, 2] <= config.vocabulary)).all() + assert (scores[126:, 0] == -1).all() + assert torch.isnan(scores[126:, 1].contiguous().view(torch.float32)).all() + tokens, state = continuation() + assert tokens == expected_tokens + assert_state(state, expected_state) + assert torch.equal(pool.backing[2], snapshot_row) diff --git a/tests/recipes/test_inkling_topology.py b/tests/recipes/test_inkling_topology.py index 5336a922a..c9cc21db0 100644 --- a/tests/recipes/test_inkling_topology.py +++ b/tests/recipes/test_inkling_topology.py @@ -11,8 +11,10 @@ from ignition.recipes.inkling.recipe import RECIPE -@pytest.mark.parametrize('devices,hosts', [((0, 1), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b'))]) -def test_two_distinct_local_or_remote_placements(devices, hosts): +@pytest.mark.parametrize('devices,hosts', [ + ((0,), None), ((3,), None), ((0, 1), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b')), +]) +def test_one_or_two_distinct_local_or_remote_placements(devices, hosts): from ignition.recipes.inkling.bootstrap import PreparationConfig config = PreparationConfig(devices=devices, hosts=hosts) @@ -20,13 +22,13 @@ def test_two_distinct_local_or_remote_placements(devices, hosts): @pytest.mark.parametrize('devices,hosts', [ - ((0,), None), ((0, 1, 2, 3), None), ((0, 0), None), ((0, -1), None), + ((), None), ((0, 1, 2, 3), None), ((0, 0), None), ((0, -1), None), ((0, 0), ('spark-a', 'spark-a')), ((0, 1), ('spark-a',)), ]) def test_unsupported_placements_fail_before_loading(devices, hosts): from ignition.recipes.inkling.bootstrap import PreparationConfig - with pytest.raises(ValueError, match='two distinct host/device placements'): + with pytest.raises(ValueError, match='one or two distinct host/device placements'): PreparationConfig(devices=devices, hosts=hosts) @@ -37,16 +39,66 @@ def test_roce_ring_requires_remote_placements(): PreparationConfig(roce_ring=True) -def test_sm103_is_rejected_before_checkpoint_loading(monkeypatch, tmp_path): +def test_unsupported_gpu_is_rejected_before_checkpoint_loading(monkeypatch, tmp_path): from ignition.recipes.inkling import bootstrap monkeypatch.setattr(bootstrap.torch.cuda, 'set_device', lambda device: None) - monkeypatch.setattr(bootstrap.torch.cuda, 'get_device_capability', lambda device: (10, 3)) - with pytest.raises(ValueError, match='A4 expert kernels must expose unweighted per-route outputs'): + monkeypatch.setattr(bootstrap.torch.cuda, 'get_device_capability', lambda device: (9, 0)) + with pytest.raises(ValueError, match='Inkling NVFP4 preparation requires SM'): bootstrap.prepare_rank(tmp_path / 'not-downloaded', bootstrap.PreparationConfig(), rank=0, group=None, package_storage=None) +@pytest.mark.parametrize('devices,group', [((0,), object()), ((0, 1), None)]) +def test_rank_group_matches_tensor_parallel_placement(tmp_path, devices, group): + from ignition.recipes.inkling import bootstrap + + with pytest.raises(ValueError, match='rank group exists exactly'): + bootstrap.prepare_rank(tmp_path, bootstrap.PreparationConfig(devices=devices), + rank=0, group=group, package_storage=None) + + +def test_nvfp4_plan_fits_one_station(): + # A conservative available-memory fixture for a DGX Station; the planner + # uses detected free GPU memory rather than a product-name memory constant. + station = planning.Gpu(0, 'NVIDIA GB300', 'GPU-0', 256 << 30, 240 << 30, (10, 3)) + plan = planning.plan(RECIPE, RECIPE.checkpoints[0], (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 + assert plan.costs.state_row_bytes == 82_837_504 + assert plan.costs.page_bytes == 3_670_016 + assert plan.costs.page_bytes * (plan.context // 128) == 7 << 30 + assert plan.weights_bytes >= 166_130_594_960 + + +@pytest.mark.parametrize('world', [1, 2]) +def test_recipe_dispatches_single_rank_or_rank_group(monkeypatch, tmp_path, world): + from ignition.preparation import rank_group + from ignition.recipes.inkling import bootstrap + + devices = tuple(planning.Gpu(i, 'NVIDIA GB300', f'GPU-{i}', 256 << 30, 240 << 30, (10, 3)) + for i in range(world)) + plan = planning.plan(RECIPE, RECIPE.checkpoints[0], devices, selected=tuple(range(world)), + concurrency=4, reserve_bytes=4 << 30, speculation=None) + result = object() + calls = [] + + def single(snapshot, config, *, rank, group, progress, package_storage): + calls.append(('single', config.devices, rank, group)) + return result + + def parallel(snapshot, config, prepare, **kwargs): + assert prepare is single and kwargs['ranks'] is None + calls.append(('parallel', config.devices)) + return result + + monkeypatch.setattr(bootstrap, 'prepare_rank', single) + monkeypatch.setattr(rank_group, 'prepare_group', parallel) + assert RECIPE.prepare(tmp_path, plan, compile_forwards=True, kernel_cache=None, progress=None) is result + assert calls == ([('single', (0,), 0, None)] if world == 1 else [('parallel', (0, 1))]) + + def test_nvfp4_plan_fits_two_sparks_with_host_reserve(): model = resolve('inkling-small-nvfp4') assert model.recipe is RECIPE and model.checkpoint.repository == 'thinkingmachines/Inkling-Small-NVFP4' @@ -60,7 +112,7 @@ def test_nvfp4_plan_fits_two_sparks_with_host_reserve(): assert plan.costs.page_bytes == 1_835_008 assert plan.weights_bytes >= 166_130_594_960 // 2 assert plan.reserve_bytes == 4 << 30 - with pytest.raises(CapacityError, match='needs 2 GPUs'): + with pytest.raises(CapacityError, match='weights'): planning.plan(RECIPE, model.checkpoint, gpus[:1], selected=(0,), concurrency=4, reserve_bytes=4 << 30, speculation=None) small = tuple(planning.Gpu(index, 'NVIDIA RTX', f'GPU-{index}', 64 << 30, 63 << 30, (12, 0)) diff --git a/tests/server/test_inkling.py b/tests/server/test_inkling.py index 9003bae2f..236d9e356 100644 --- a/tests/server/test_inkling.py +++ b/tests/server/test_inkling.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Acceptance for a TP2 Inkling NVFP4 package exported with prompt logprobs and served by Flare. +"""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 00b1af69c008f7d4166103290714148a02d295ee Mon Sep 17 00:00:00 2001 From: Arthur <xuyangc@nvidia.com> Date: Thu, 5 Nov 2026 16:10:46 -0800 Subject: [PATCH 4/5] Simplify Inkling tests and preparation guidance Consolidate API checks around one frontend fixture. Remove 18 duplicate prompt examples and redundant placement, mocked-dispatch and tensor-copy checks. Preserve all 50 fixed-budget generation inputs, default-sampling smokes, numerical bounds and CUDA/state coverage. Shorten repeated prose. Validation: 25 focused CPU tests and all 61 API cases pass, including the 262080-token input on one GB300 DGX Station. Executable production behavior is unchanged. Full-checkpoint TP2/RoCE and SM120/SM121 remain unqualified. Design-Signed-Off-By: Codex (GPT-6); design-review=4d3a Signed-off-by: Arthur <xuyangc@nvidia.com> --- docs/model-preparation.md | 112 ++++++++-------------- ignition/components/native_operator.py | 7 +- tests/components/inkling_nvfp4_helpers.py | 25 ++--- tests/recipes/test_inkling.py | 11 +-- tests/recipes/test_inkling_topology.py | 31 +----- tests/server/test_inkling.py | 91 +++++++++++++++--- tests/server/test_inkling_generation.py | 90 ----------------- 7 files changed, 127 insertions(+), 240 deletions(-) delete mode 100644 tests/server/test_inkling_generation.py diff --git a/docs/model-preparation.md b/docs/model-preparation.md index bd0bc48e5..9c57388f1 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1016,94 +1016,58 @@ flare/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.safete ## Inkling-Small NVFP4 -The `inkling-small-nvfp4` alias selects +`inkling-small-nvfp4` selects [`thinkingmachines/Inkling-Small-NVFP4`](https://huggingface.co/thinkingmachines/Inkling-Small-NVFP4) -at revision `b6a99534467840620d411e4cd4ad5819b2610d9c`. This text recipe -targets one SM103 GPU on DGX Station, or tensor parallelism two on SM120/SM121, -using two local GPUs or one GPU on each of two DGX Sparks through the shared -RoCE transport. A single rank prepares complete weights and no collectives. -Defaults are a 262144-token context, four concurrent requests, and 4096-token prefill chunks. -Prepared context is capped at 262144 tokens of the checkpoint's 1048576-token -limit. Image, audio, video, and MTP graphs are not prepared. The indexed download -includes the publisher's MTP weights; only `model.llm` tensors become serving -weights. - -Quantization comes from the checkpoint's `hf_quant_config.json`. Its exclusions -retain BF16 attention, dense/shared experts, and the first routed layer; the -remaining routed experts use the original packed NVFP4 weights, E4M3 block -scales, FP32 global scales, and calibrated NVFP4 activations. Interleaved gate/up -rows are reordered with their matching scales before intermediate sharding. -Activation calibration preserves the FP32 scale boundary in the publisher-supported -[checkpoint loader](https://github.com/sgl-project/sglang/blob/dff6a0c3accf310f70eab81be1220a27b732c96b/python/sglang/srt/models/inkling.py#L1241). -Unweighted expert outputs are reduced across ranks before route weights apply. - -The 42-layer decoder retains 35 local 512-token KV rings and seven global paged -histories in BF16. Query-dependent relative logits, head RMS normalization, -`1 / head_dim` attention scaling, and global logarithmic position scaling follow -the checkpoint. Four residual short convolutions per layer retain FP32 history -and arithmetic. Every continuation row includes those histories, local rings, -partial global pages, the consumed cursor, and the normalized and scaled hidden -vector used by resume. - -Router correction biases and global scales remain FP32, as do router logits and -route normalization. Unquantized SwiGLU uses FP32 activation arithmetic after -BF16 projections; shared sink weights apply before the down projection. NVFP4 -experts retain FP32 scaled accumulators through SwiGLU, then round the intermediate -to BF16 before its calibrated NVFP4 activation quantizer. Routing and shared -sink placement follow the publisher-supported SGLang +at revision `b6a99534467840620d411e4cd4ad5819b2610d9c`. It targets one +GB300 DGX Station (SM103), or TP2 on SM120/SM121 using local GPUs or two +DGX Sparks over RoCE. 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. Expert packing, activation +precision, shared sink placement and TP reduction follow the publisher-supported +SGLang [loader](https://github.com/sgl-project/sglang/blob/dff6a0c3accf310f70eab81be1220a27b732c96b/python/sglang/srt/models/inkling.py#L1241), [router](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/moe.py) -and [MLP implementation](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/dense_mlp.py). -Transformers supplies the reference attention, normalization, and checkpoint -layout; loading it with a blanket BF16 dtype also narrows the FP32 router -parameters, so that load mode is not the precision reference for routing. +and [MLP](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/dense_mlp.py). +Transformers provides the attention and normalization reference; blanket BF16 +loading narrows router parameters and is not the routing precision reference. -The indexed checkpoint contains 170,733,074,592 bytes of tensors, including -166,130,594,960 bytes of text weights. The planner conservatively budgets the -whole checkpoint for weights, plus preparation scratch and caches. Cache costs -per GPU are: +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. The planner budgets the full 170,733,074,592-byte +checkpoint, including 166,130,594,960 bytes of text weights, plus scratch and caches. | Tensor parallelism | Continuation row | 128-token global KV page | One 262144-token global KV history | |---|---:|---:|---:| | 1 | 82,837,504 bytes | 3,670,016 bytes | 7 GiB | | 2 | 43,515,904 bytes | 1,835,008 bytes | 3.5 GiB | -The planner uses detected free GPU memory for admission. Spark's CPU, GPU, -compiler processes, and OS share physical memory; follow the -[DGX Spark memory guidance](#dgx-spark). - -The publisher's [Inkling sampling guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) -recommends temperature 1.0. Unspecified filters remain disabled (`top_p=1`, -`top_k=-1`, `min_p=0`) and penalties are neutral. The pinned checkpoint template -owns the thinking-effort system message and content-header/tool syntax. +Admission uses detected free GPU memory. On Spark, CPU and GPU allocations share +physical memory; follow the [DGX Spark memory guidance](#dgx-spark). +The publisher's [guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) +recommends temperature 1.0. Unspecified filters stay disabled (`top_p=1`, +`top_k=-1`, `min_p=0`) and penalties stay neutral. The checkpoint template controls reasoning effort and tool syntax. ```sh .venv/bin/ignition export inkling-small-nvfp4 --gpus 0 --prompt-logprobs -.venv/bin/ignition convert CACHE_ENTRY --form packed --output /data/flare-runtime/inkling-small-nvfp4-tp1.safetensors -flare/target/release/flare run /data/flare-runtime/inkling-small-nvfp4-tp1.safetensors --gpus 0 +flare/target/release/flare run CACHE_ENTRY --gpus 0 ``` -For two local GPUs, use `--gpus 0,1` for export and serving, and convert that -export to a separate TP2 package. Each tensor-parallel size requires its own export. - -For two Sparks, prepare with `--gpus 0 --ranks 2 --rendezvous ZERO:29630` on -rank zero and `ignition join ZERO:29630 --rank 1 --ranks 2` on its peer. Follow -[multi-host preparation and serving](multi-host.md#prepare-the-package) for -checkpoint access, transport setup, and launching the resulting two-host package. - -With locked FlashInfer `1f8ed8a3c46e27d03cff54e08f23e9bc50476d57`, the full -checkpoint exports all 29 graphs and serves through native `flare run` on one -GB300 DGX Station at the default capacities above. All 22 numerical CUDA checks -pass, including an actual checkpoint expert layer, complete decoder replay, -state restoration, inactive rows, and allocation stability. All 79 native API -checks pass. The 50-prompt text/tool/long-context workload uses -`reasoning_effort=none` and a fixed 64-token output budget; the longest input -contains 262080 tokens. Other checks cover all five reasoning efforts, cached -prefix branches, prompt logprobs, and media rejection. - -Full-checkpoint TP2/RoCE and SM120/SM121 execution remain unqualified. Reproduce -endpoint acceptance with `tests/server/test_inkling.py` and -`tests/server/test_inkling_generation.py`, setting `FLARE_RUN_CUDA_TESTS=1`, -`FLARE_INKLING_TEST_URL`, and `FLARE_INKLING_SNAPSHOT`. +TP2 requires a separate export. Use `--gpus 0,1` for two local GPUs, or follow +[multi-host preparation and serving](multi-host.md#prepare-the-package) for two Sparks. + +On GB300 with locked FlashInfer `1f8ed8a3`, full-checkpoint export captures 29 graphs; +22 numerical CUDA checks and 61 native API checks pass. The 50-prompt generation +workload uses `reasoning_effort=none`, a fixed 64-token output budget and inputs +through 262080 tokens. Coverage includes checkpoint experts, decoder/state replay, +inactive rows, allocation stability, all reasoning efforts, prefix branches and +prompt scoring. Full-checkpoint TP2/RoCE and SM120/SM121 remain unqualified. +Run `tests/server/test_inkling.py` +with `FLARE_RUN_CUDA_TESTS=1`, `FLARE_INKLING_TEST_URL` and `FLARE_INKLING_SNAPSHOT`. ## Muse Spark Open diff --git a/ignition/components/native_operator.py b/ignition/components/native_operator.py index 46884045f..c4a0fc3d7 100644 --- a/ignition/components/native_operator.py +++ b/ignition/components/native_operator.py @@ -16,12 +16,7 @@ def compile_triton(kernel, grid, *args, **kwargs): - """Make an Ignition Triton factory's executable cache reclaimable by b12x. - - b12x discovers its own JIT functions automatically. Its mapping registration - also covers local functions, so deferred planning entries and losing tactics - are reclaimed at the same preparation boundaries. - """ + """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) diff --git a/tests/components/inkling_nvfp4_helpers.py b/tests/components/inkling_nvfp4_helpers.py index 4f9bdd6c0..81be132ef 100644 --- a/tests/components/inkling_nvfp4_helpers.py +++ b/tests/components/inkling_nvfp4_helpers.py @@ -50,16 +50,10 @@ def unpack_weight(values, scales): def quantize_activation(value, amax, *, quant_scale_math="b12x"): - """Calibrated per-16 NVFP4 inner values and their FP32 reciprocal outer scale. - - The packed MMA consumes E2M1 values times E4M3 block scales. Its outer - calibration multiplies the accumulator, not each input value. Reciprocal - multiplication preserves the selected quantizer's E2M1 tie evaluation order. - """ + """Return E2M1 values times E4M3 block scales, and separate FP32 calibration.""" value = value.float() blocks = value.reshape(*value.shape[:-1], -1, 16) - # The publisher first stores amax/2688 in FP32, then reciprocates that - # stored value. Directly rounding 2688/amax skips an observable boundary. + # 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.)) @@ -69,10 +63,8 @@ def quantize_activation(value, amax, *, quant_scale_math="b12x"): if quant_scale_math == "b12x": inverse = scales.reciprocal() * encode elif quant_scale_math == "flashinfer": - # FlashInfer's native fast quantizer reciprocates the product of the - # rounded E4M3 scale and reciprocal calibration using rcp.approx.ftz. - # Either reassociation or correctly-rounded reciprocal changes E2M1 - # ties, including the publisher's amax=187 (quantization_utils.cuh). + # 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}") @@ -88,11 +80,7 @@ def quantize_activation(value, amax, *, quant_scale_math="b12x"): def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None, quant_scale_math="b12x"): - """FP32 FC1 -> FP32 SwiGLU -> BF16 -> calibrated NVFP4 -> FP32 FC2 -> BF16. - - Decode checkpoint bytes only for the test oracle. Production kernels consume - packed weights directly. Route weights and TP reductions belong to the caller. - """ + """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 + ".")} @@ -106,8 +94,7 @@ def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None, if tokens.numel() == 0: continue rows = slice(2 * begin, 2 * end) - # Apply the outer multiplier after the dot product, matching the scaled - # FP4 MMA arithmetic rather than changing every weight before summation. + # Scaled FP4 MMA applies the outer multiplier after the dot product. up_gate = unpack_weight(tensors[first][expert, rows], tensors[first + ".scale"][expert, rows]) projected = (source_quantized[tokens] @ up_gate.T) * (tensors[first + ".scale2"][expert] / input_scale) gate, up = projected[:, ::2], projected[:, 1::2] diff --git a/tests/recipes/test_inkling.py b/tests/recipes/test_inkling.py index 3654c87c1..04bc74e20 100644 --- a/tests/recipes/test_inkling.py +++ b/tests/recipes/test_inkling.py @@ -46,10 +46,6 @@ def test_rejects_changed_arithmetic(change): raw["text_config"].update(change) with pytest.raises(ValueError): ModelConfig.from_dict(raw, quantization()) - raw = configuration() - raw["quantization_config"] = {"quant_method": "modelopt", "quant_algo": "NVFP4"} - with pytest.raises(ValueError, match="hf_quant_config"): - ModelConfig.from_dict(raw, quantization()) def test_checkpoint_quantization_requires_both_calibration_and_exclusions(tmp_path): @@ -59,6 +55,9 @@ def test_checkpoint_quantization_requires_both_calibration_and_exclusions(tmp_pa (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})) @@ -114,10 +113,6 @@ def test_contract_snapshots_every_history_and_retains_bf16_pages(): 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 - pool.backing[1].random_(0, 255) - pool.backing[2].copy_(pool.backing[1]) - for region in pool.layout.regions: - assert torch.equal(pool.region(region.name)[1].view(torch.uint8), pool.region(region.name)[2].view(torch.uint8)) 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))) diff --git a/tests/recipes/test_inkling_topology.py b/tests/recipes/test_inkling_topology.py index c9cc21db0..9c10b2101 100644 --- a/tests/recipes/test_inkling_topology.py +++ b/tests/recipes/test_inkling_topology.py @@ -12,7 +12,7 @@ @pytest.mark.parametrize('devices,hosts', [ - ((0,), None), ((3,), None), ((0, 1), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b')), + ((3,), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b')), ]) def test_one_or_two_distinct_local_or_remote_placements(devices, hosts): from ignition.recipes.inkling.bootstrap import PreparationConfig @@ -59,8 +59,6 @@ def test_rank_group_matches_tensor_parallel_placement(tmp_path, devices, group): def test_nvfp4_plan_fits_one_station(): - # A conservative available-memory fixture for a DGX Station; the planner - # uses detected free GPU memory rather than a product-name memory constant. station = planning.Gpu(0, 'NVIDIA GB300', 'GPU-0', 256 << 30, 240 << 30, (10, 3)) plan = planning.plan(RECIPE, RECIPE.checkpoints[0], (station,), selected=None, concurrency=4, reserve_bytes=4 << 30, speculation=None) @@ -72,33 +70,6 @@ def test_nvfp4_plan_fits_one_station(): assert plan.weights_bytes >= 166_130_594_960 -@pytest.mark.parametrize('world', [1, 2]) -def test_recipe_dispatches_single_rank_or_rank_group(monkeypatch, tmp_path, world): - from ignition.preparation import rank_group - from ignition.recipes.inkling import bootstrap - - devices = tuple(planning.Gpu(i, 'NVIDIA GB300', f'GPU-{i}', 256 << 30, 240 << 30, (10, 3)) - for i in range(world)) - plan = planning.plan(RECIPE, RECIPE.checkpoints[0], devices, selected=tuple(range(world)), - concurrency=4, reserve_bytes=4 << 30, speculation=None) - result = object() - calls = [] - - def single(snapshot, config, *, rank, group, progress, package_storage): - calls.append(('single', config.devices, rank, group)) - return result - - def parallel(snapshot, config, prepare, **kwargs): - assert prepare is single and kwargs['ranks'] is None - calls.append(('parallel', config.devices)) - return result - - monkeypatch.setattr(bootstrap, 'prepare_rank', single) - monkeypatch.setattr(rank_group, 'prepare_group', parallel) - assert RECIPE.prepare(tmp_path, plan, compile_forwards=True, kernel_cache=None, progress=None) is result - assert calls == ([('single', (0,), 0, None)] if world == 1 else [('parallel', (0, 1))]) - - def test_nvfp4_plan_fits_two_sparks_with_host_reserve(): model = resolve('inkling-small-nvfp4') assert model.recipe is RECIPE and model.checkpoint.repository == 'thinkingmachines/Inkling-Small-NVFP4' diff --git a/tests/server/test_inkling.py b/tests/server/test_inkling.py index 236d9e356..f334023a7 100644 --- a/tests/server/test_inkling.py +++ b/tests/server/test_inkling.py @@ -21,13 +21,22 @@ 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 service(): +def checkpoint_frontend(): from transformers import PreTrainedTokenizerFast root = Path(os.environ["FLARE_INKLING_SNAPSHOT"]) - tokenizer = PreTrainedTokenizerFast.from_pretrained(root) - template = (root / "chat_template.jinja").read_text() + 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() @@ -61,16 +70,12 @@ def text(result): return (result["choices"][0]["message"].get("content") or "").strip() -@pytest.mark.parametrize("index", range(20)) -def test_text_and_unicode(service, index): - ask, _, _ = service - if index < 12: - a, b = index + 13, 29 - index - prompt, expected = f"What is {a} times {b}? Reply with only the integer.", str(a*b) - else: - expected = ["INKLING-317", "café", "世界", "naïve", "á", "Δοκιμή", "مرحبا", "日本語"][index-12] - prompt = "Repeat exactly this text, without quotation marks or explanation: " + expected - result = ask([dict(role="user", content=prompt)]) +@pytest.mark.parametrize("prompt,expected", [ + ("What is 13 times 29? Reply with only the integer.", "377"), + ("Repeat exactly this text, without quotation marks or explanation: café", "café"), +], ids=["arithmetic", "unicode"]) +def test_default_sampling(service, prompt, expected): + result = service[0]([dict(role="user", content=prompt)]) assert text(result) == expected assert result["choices"][0]["finish_reason"] == "stop" @@ -122,3 +127,63 @@ def test_prompt_scores_and_text_only_rejection(service): with pytest.raises(urllib.error.HTTPError) as rejected: service[1]("/v1/chat/completions", dict(model=service[2], messages=[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(temperature=1., top_p=1., top_k=-1, min_p=0., + repetition_penalty=1., presence_penalty=0., frequency_penalty=0., + seed=58123, max_tokens=64, chat_template_kwargs=dict(reasoning_effort='none')) + 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) + function = dict(name='record_value', description='Record the supplied value exactly.', + parameters=dict(type='object', properties=dict(value=dict(type='integer')), + required=['value'], 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[0]([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] diff --git a/tests/server/test_inkling_generation.py b/tests/server/test_inkling_generation.py deleted file mode 100644 index d3f686d28..000000000 --- a/tests/server/test_inkling_generation.py +++ /dev/null @@ -1,90 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Fifty Inkling generation cases with a fixed 64-token output budget. - -Use the exported-package endpoint and checkpoint variables documented in -``test_inkling.py``. The package retains its default 262144-token context. -""" - -import json -import os -from pathlib import Path - -import pytest - -from tests.server.test_inkling import pytestmark, service, text - - -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 - - snapshot = Path(os.environ['FLARE_INKLING_SNAPSHOT']) - return (PreTrainedTokenizerFast.from_pretrained(snapshot), - (snapshot / 'chat_template.jinja').read_text()) - - -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(temperature=1., top_p=1., top_k=-1, min_p=0., - repetition_penalty=1., presence_penalty=0., frequency_penalty=0., - seed=58123, max_tokens=64, chat_template_kwargs=dict(reasoning_effort='none')) - 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) - function = dict(name='record_value', description='Record the supplied value exactly.', - parameters=dict(type='object', properties=dict(value=dict(type='integer')), - required=['value'], 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[0]([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] From bf5fed2b43f353b8180f718ec6b2636c96811e0a Mon Sep 17 00:00:00 2001 From: Arthur <xuyangc@nvidia.com> Date: Fri, 6 Nov 2026 15:11:11 -0800 Subject: [PATCH 5/5] Limit Inkling to one SM103 GPU and simplify the recipe The recipe also prepared two-GPU, two-Spark RoCE, and SM120/SM121 configurations that were never validated with the full checkpoint, and the planner selected them automatically when TP1 did not fit. Inkling-Small NVFP4 preparation now accepts only TP1 on one SM103 GPU (GB300 DGX Station), the configuration validated by full-checkpoint export and native serving: the recipe declares only TP1 rank costs, prepare() rejects other world sizes, and bootstrap rejects non-SM103 devices before loading the checkpoint. Placement, rank-group, and collective setup and their tests are removed. The SM120/SM121 b12x branch in InklingWeightLoader._nvfp4_experts is reached only by tests; docs/TODO.txt tracks its removal and multi-GPU support. Recognition of GB300 PCI ID 0x31c2 moves to #221, which export on such systems requires. Other changes, with no kernel or expert-packing changes: - Helios selects TML envelope control markers with one match, dispatches the TML grammar from compile_envelope, and keeps TML delimiter constants private. - Global attention layers share one PagedAttentionMetadata per decoder, as Gemma 4 and Nemotron-H do. Inactive rows now receive zero KV length and slot -1 for negative page entries; active rows are unchanged. - Shared experts are prepared as gate/up and down projections, so their unused SwiGLU activation plans are no longer declared and tuned. - Relative paged attention and residual convolution drop unused workspace arguments. - Tests use the NVFP4 reference helpers in ignition.reference.qwen38_quant, fold the BF16 expert SiLU test into tests/recipes/muse_spark/test_experts_cuda.py, derive declared cache costs from checkpoint geometry, and remove duplicate server cases. - The preparation guide states the configuration instead of a validation report. Validation on an 8 GB SM120 laptop GPU with locked FlashInfer 1f8ed8a3: relative attention and residual convolution operator tests, reduced decoder replay and inactive-row tests, the BF16 expert test, frontend template parity against the pinned checkpoint's tokenizer and template, the ignored Helios TML request test, CPU recipe and planner tests, and the Helios library suite passed. The decoder tests ran the b12x expert path, not the SM103 CuTe path. Failures that also occur on main: two sampling-default expectations, four Helios tests that need FLARE_TEST_TEMPLATE_DIR, and four CLI alias-list tests whose lists omit qwen3.8-27b-qad. The operator package test stops at export because NVML rejects the laptop GPU's PCI ID. Not run: SM103 expert tests, reduced and full-checkpoint preparation, export, and tests/server/test_inkling.py on a GB300. Design-Signed-Off-By: Claude Opus 5.5; design-review=4d3a Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Arthur <xuyangc@nvidia.com> --- docs/TODO.txt | 9 ++ docs/model-preparation.md | 45 ++---- flare/src/hardware.rs | 2 - heliopause/src/export/package.rs | 33 ---- helios/src/grammar.rs | 9 +- helios/src/model/contract.rs | 4 - helios/src/model/prompt.rs | 38 ++--- helios/src/output/pipeline.rs | 2 +- helios/src/output/tml.rs | 29 ++-- helios/src/package/naming.rs | 14 +- helios/src/server/request/tml_tests.rs | 4 +- .../tests/inkling_operator_package_fixture.py | 18 +-- ignition/components/moe_sm103.py | 11 +- .../components/relative_paged_attention.py | 5 +- ignition/components/residual_short_conv.py | 7 +- ignition/recipes/inkling/attention.py | 35 ++-- ignition/recipes/inkling/bootstrap.py | 84 +++------- ignition/recipes/inkling/contract.py | 3 - ignition/recipes/inkling/decoder.py | 50 +++--- ignition/recipes/inkling/frontend.py | 4 +- ignition/recipes/inkling/model.py | 4 +- ignition/recipes/inkling/pool.py | 4 +- ignition/recipes/inkling/recipe.py | 24 ++- tests/cli/test_models.py | 2 +- tests/components/inkling_nvfp4_helpers.py | 33 +--- tests/components/test_inkling_nvfp4_cuda.py | 137 ---------------- .../test_inkling_nvfp4_sm103_cuda.py | 33 +--- .../components/test_inkling_operators_cuda.py | 62 +------- tests/recipes/inkling_helpers.py | 7 +- tests/recipes/muse_spark/test_experts_cuda.py | 26 ++- tests/recipes/test_inkling.py | 15 +- tests/recipes/test_inkling_cuda.py | 150 ++++++++---------- .../recipes/test_inkling_preparation_cuda.py | 44 ++--- tests/recipes/test_inkling_topology.py | 96 ++++------- tests/server/test_inkling.py | 127 +++++++-------- 35 files changed, 368 insertions(+), 802 deletions(-) delete mode 100644 tests/components/test_inkling_nvfp4_cuda.py 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 9c57388f1..cb7c930d0 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1016,11 +1016,10 @@ flare/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.safete ## Inkling-Small NVFP4 -`inkling-small-nvfp4` selects +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), or TP2 on SM120/SM121 using local GPUs or two -DGX Sparks over RoCE. Defaults are a 262144-token context, concurrency four, +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. @@ -1028,47 +1027,27 @@ 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. Expert packing, activation -precision, shared sink placement and TP reduction follow the publisher-supported -SGLang [loader](https://github.com/sgl-project/sglang/blob/dff6a0c3accf310f70eab81be1220a27b732c96b/python/sglang/srt/models/inkling.py#L1241), -[router](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/moe.py) -and [MLP](https://github.com/sgl-project/sglang/blob/a4bef204c51e1c1b7ed59593b85993a940367591/python/sglang/srt/models/inkling_common/dense_mlp.py). -Transformers provides the attention and normalization reference; blanket BF16 -loading narrows router parameters and is not the routing precision reference. +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. The planner budgets the full 170,733,074,592-byte -checkpoint, including 166,130,594,960 bytes of text weights, plus scratch and caches. +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. -| Tensor parallelism | Continuation row | 128-token global KV page | One 262144-token global KV history | -|---|---:|---:|---:| -| 1 | 82,837,504 bytes | 3,670,016 bytes | 7 GiB | -| 2 | 43,515,904 bytes | 1,835,008 bytes | 3.5 GiB | +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. -Admission uses detected free GPU memory. On Spark, CPU and GPU allocations share -physical memory; follow the [DGX Spark memory guidance](#dgx-spark). -The publisher's [guidance](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/skills/inkling/SKILL.md) -recommends temperature 1.0. Unspecified filters stay disabled (`top_p=1`, -`top_k=-1`, `min_p=0`) and penalties stay neutral. The checkpoint template controls reasoning effort and tool syntax. +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 ``` -TP2 requires a separate export. Use `--gpus 0,1` for two local GPUs, or follow -[multi-host preparation and serving](multi-host.md#prepare-the-package) for two Sparks. - -On GB300 with locked FlashInfer `1f8ed8a3`, full-checkpoint export captures 29 graphs; -22 numerical CUDA checks and 61 native API checks pass. The 50-prompt generation -workload uses `reasoning_effort=none`, a fixed 64-token output budget and inputs -through 262080 tokens. Coverage includes checkpoint experts, decoder/state replay, -inactive rows, allocation stability, all reasoning efforts, prefix branches and -prompt scoring. Full-checkpoint TP2/RoCE and SM120/SM121 remain unqualified. -Run `tests/server/test_inkling.py` -with `FLARE_RUN_CUDA_TESTS=1`, `FLARE_INKLING_TEST_URL` and `FLARE_INKLING_SNAPSHOT`. - ## Muse Spark Open The `muse-spark-open-nvfp4` alias selects diff --git a/flare/src/hardware.rs b/flare/src/hardware.rs index cc5c8aa0c..f6ffdec41 100644 --- a/flare/src/hardware.rs +++ b/flare/src/hardware.rs @@ -186,8 +186,6 @@ mod tests { assert_eq!(platform(0x2bb110de), Some("gb202")); assert_eq!(platform(0x2bb510de), Some("gb202")); assert_eq!(platform(0x2b8510de), Some("gb202")); - assert_eq!(platform(0x31c210de), Some("gb300")); - assert_eq!(platform(0x31c21234), None); assert_eq!(platform(0x31c310de), Some("gb300")); assert_eq!(platform(0x26b110de), None); assert_eq!(platform(0x2bb41234), None); diff --git a/heliopause/src/export/package.rs b/heliopause/src/export/package.rs index 99e866e42..0cbafc3c5 100644 --- a/heliopause/src/export/package.rs +++ b/heliopause/src/export/package.rs @@ -4201,39 +4201,6 @@ mod payload_export_tests { let _ = std::fs::remove_dir_all(&base); } - #[test] - fn gb300_export_names_and_signs_the_station_platform() { - use helios_core::package::cache::Root; - use helios_core::package::schema::wire as pwire; - let sources = tempfile::tempdir().unwrap(); - let cache = tempfile::tempdir().unwrap(); - let mut rank = staged_rank(sources.path()); - rank.hardware = - helios_core::package::naming::platform_from_pci(0x31c2_10de).map(str::to_string); - rank.index.ranks[0].architecture = vec![10, 3]; - let published = publish_payload( - Path::new(""), - &[rank], - vec![], - None, - &publisher(), - Some(cache.path().to_path_buf()), - false, - "directory", - ) - .unwrap(); - let entry = published["entry"].as_str().unwrap(); - assert!(entry.starts_with("gb300-tp1-"), "{entry}"); - let root = Root::open(cache.path()).unwrap(); - let committed = root - .entry(published["model"].as_str().unwrap(), entry) - .unwrap(); - let metadata = Metadata::open(committed.directory()).unwrap(); - let envelope = helios_core::package::protection::envelope(&metadata.envelope).unwrap(); - let body = pwire::PackageBody::decode(envelope.package_body.as_slice()).unwrap(); - assert_eq!(body.hardware_identity, "gb300"); - } - #[test] fn cached_state_and_staged_globals_use_unique_payload_names() { use crate::export::{WeightPayloadGroup, WeightPayloadSourceSpan, WeightPayloadSources}; diff --git a/helios/src/grammar.rs b/helios/src/grammar.rs index b9b5db788..422b8f5d3 100644 --- a/helios/src/grammar.rs +++ b/helios/src/grammar.rs @@ -234,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() @@ -308,9 +312,6 @@ impl GrammarCompiler { } fn compile_recipient(&self, mut grammar: TopLevelGrammar, envelope: &RecipientEnvelope) -> Result<RequestGrammar> { - if envelope.syntax == crate::model::contract::ToolParserKind::TmlJson { - return self.compile_content_headers(grammar, envelope); - } use crate::output::tagged::OutputStart; let mut rules = String::new(); let marker = |text: &str| self.marker(text); diff --git a/helios/src/model/contract.rs b/helios/src/model/contract.rs index 1d946b14a..157ddd86b 100644 --- a/helios/src/model/contract.rs +++ b/helios/src/model/contract.rs @@ -795,10 +795,6 @@ mod tests { open: "<|content_thinking|>".into(), close: "<|end_message|>".into(), wrapping_newlines: 0, terminal_markers: vec![] }); assert!(syntax.validate().is_ok()); - let encoded = serde_json::to_value(&syntax).unwrap(); - assert_eq!(encoded["tools"]["kind"], 8); - assert_eq!(encoded["reasoning"]["kind"], 6); - assert!(serde_json::from_value::<FrontendContract>(encoded).unwrap().validate().is_ok()); syntax.reasoning.as_mut().unwrap().close = "</think>".into(); assert!(syntax.validate().is_err()); syntax.reasoning.as_mut().unwrap().close = "<|end_message|>".into(); diff --git a/helios/src/model/prompt.rs b/helios/src/model/prompt.rs index 5cee84ac9..6e552d57e 100644 --- a/helios/src/model/prompt.rs +++ b/helios/src/model/prompt.rs @@ -276,29 +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 | super::contract::ToolParserKind::TmlJson)) - { - let markers = if syntax.tools.as_ref().unwrap().kind == super::contract::ToolParserKind::Atem { - vec!["<|start|>", "<|message|>", "<|eom|>", "<|eot|>"] - } else if syntax.tools.as_ref().unwrap().kind == super::contract::ToolParserKind::TmlJson { - vec!["<|message_model|>", "<|content_text|>", "<|content_thinking|>", - "<|content_invoke_tool_json|>", "<|end_message|>", "<|content_model_end_sampling|>"] - } else { vec!["<|open|>", "<|close|>", "<|sep|>"] }; - markers.into_iter() - .map(|marker| { - let ids = frontend.encode(marker, false)?; - if ids.len() != 1 { - return Err("output envelope delimiters must each occupy one tokenizer token".into()); - } - Ok((ids[0], marker.to_owned())) - }) - .collect::<Result<Vec<_>>>()? - } else { - vec![] + let markers: &[&str] = match syntax.tools.as_ref().map(|tool| tool.kind) { + Some(super::contract::ToolParserKind::Xtml) => &["<|open|>", "<|close|>", "<|sep|>"], + Some(super::contract::ToolParserKind::Atem) => &["<|start|>", "<|message|>", "<|eom|>", "<|eot|>"], + Some(super::contract::ToolParserKind::TmlJson) => &["<|message_model|>", "<|content_text|>", "<|content_thinking|>", + "<|content_invoke_tool_json|>", "<|end_message|>", "<|content_model_end_sampling|>"], + _ => &[], }; + let mut control_tokens = markers + .iter() + .map(|&marker| { + let ids = frontend.encode(marker, false)?; + if ids.len() != 1 { + return Err("output envelope delimiters must each occupy one tokenizer token".into()); + } + Ok((ids[0], marker.to_owned())) + }) + .collect::<Result<Vec<_>>>()?; if syntax.tools.as_ref().is_some_and(|tool| tool.kind == super::contract::ToolParserKind::Dsml) { let tokenizer = frontend.tokenizer(); for token in [deepseek_recipe_core::special_tokens::SpecialToken::ThinkingEnd, diff --git a/helios/src/output/pipeline.rs b/helios/src/output/pipeline.rs index 7f324e0df..2846e13ed 100644 --- a/helios/src/output/pipeline.rs +++ b/helios/src/output/pipeline.rs @@ -109,7 +109,7 @@ 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 | ToolParserKind::TmlJson) => false, diff --git a/helios/src/output/tml.rs b/helios/src/output/tml.rs index f841a8ed4..ac454724a 100644 --- a/helios/src/output/tml.rs +++ b/helios/src/output/tml.rs @@ -13,12 +13,12 @@ use crate::Result; use serde_json::Value; use std::collections::VecDeque; -pub const START: &str = "<|message_model|>"; -pub const TEXT: &str = "<|content_text|>"; -pub const THINK: &str = "<|content_thinking|>"; -pub const TOOL: &str = "<|content_invoke_tool_json|>"; -pub const END: &str = "<|end_message|>"; -pub const TURN_END: &str = "<|content_model_end_sampling|>"; +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 { @@ -38,7 +38,7 @@ pub struct TmlOutput { calls: usize, received: usize, spans: Vec<Option<std::ops::Range<usize>>>, - controls: Vec<(u32, String)>, + control_tokens: Vec<(u32, String)>, pending_controls: VecDeque<String>, pending_text: String, } @@ -57,7 +57,7 @@ fn partial(text: &str, marker: &str) -> usize { } impl TmlOutput { - pub fn new(config: OutputConfig, controls: Vec<(u32, String)>) -> Self { + pub fn new(config: OutputConfig, control_tokens: Vec<(u32, String)>) -> Self { Self { state: match config.start { OutputStart::RecipientHeader => State::Header, @@ -72,7 +72,7 @@ impl TmlOutput { calls: 0, received: 0, spans: vec![], - controls, + control_tokens, pending_controls: VecDeque::new(), pending_text: String::new(), } @@ -93,7 +93,9 @@ impl TmlOutput { self.spans.clear(); let text = match input { Input::Token(id) => { - if let Some((_, marker)) = self.controls.iter().find(|(token, _)| *token == id) { + if let Some((_, marker)) = + self.control_tokens.iter().find(|(token, _)| *token == id) + { self.pending_controls.push_back(marker.clone()); } return Ok(vec![]); @@ -327,7 +329,12 @@ mod tests { } fn feed(p: &mut TmlOutput, marker: &str, fragmented: bool) -> Result<Vec<Event>> { - let id = p.controls.iter().find(|(_, m)| m == marker).unwrap().0; + 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() { diff --git a/helios/src/package/naming.rs b/helios/src/package/naming.rs index 02ac351cd..6f46567b8 100644 --- a/helios/src/package/naming.rs +++ b/helios/src/package/naming.rs @@ -26,8 +26,8 @@ pub const GB202_DEVICES: [u32; 9] = [ /// RTX Spark N1X part, which NVML reports for the same SM121 platform. pub const GB10_DEVICES: [u32; 2] = [0x2e12, 0x2e03]; -/// GB300 device identifiers reported by NVML on DGX Station. -pub const GB300_DEVICES: [u32; 2] = [0x31c2, 0x31c3]; +/// GB300 device identifiers. `0x31c3` is the SM103 GPU of DGX Station GB300. +pub const GB300_DEVICES: [u32; 1] = [0x31c3]; pub fn platform_from_pci(pci_id: u32) -> Option<&'static str> { if pci_id & 0xffff != 0x10de { @@ -166,10 +166,6 @@ mod tests { candidate("gb10", 8, at(1_792_228_980)).as_deref(), Some("gb10-tp8-202610170923") ); - assert_eq!( - candidate("gb300", 1, at(1_792_228_980)).as_deref(), - Some("gb300-tp1-202610170923") - ); assert!(candidate("sm120", 1, at(0)).is_none()); assert!(candidate("gb202", 0, at(0)).is_none()); } @@ -191,8 +187,6 @@ mod tests { "{device:#06x}" ); } - assert_eq!(platform_from_pci(0x31c2_10de), Some("gb300")); - assert_eq!(platform_from_pci(0x31c2_1af4), None); assert_eq!(platform_from_pci(0x2bbc_1af4), None); assert_eq!(platform_from_pci(0x31c3_1af4), None); assert_eq!(platform_from_pci(0x1e02_10de), None); @@ -216,10 +210,6 @@ mod tests { deployment_candidate(Some("gb202"), &[2, 1], at).as_deref(), Some("gb202-tp1+tp2-202610170923") ); - assert_eq!( - deployment_candidate(Some("gb300"), &[1], at).as_deref(), - Some("gb300-tp1-202610170923") - ); assert_eq!( deployment_candidate(Some("sm120"), &[1], at).as_deref(), Some("unknown-device-tp1-202610170923") diff --git a/helios/src/server/request/tml_tests.rs b/helios/src/server/request/tml_tests.rs index 40d4141b1..ca8978642 100644 --- a/helios/src/server/request/tml_tests.rs +++ b/helios/src/server/request/tml_tests.rs @@ -3,6 +3,8 @@ * 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; @@ -55,7 +57,7 @@ fn content_headers_preserve_requests_tools_and_constrained_answers() { 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| { diff --git a/helios/tests/inkling_operator_package_fixture.py b/helios/tests/inkling_operator_package_fixture.py index e4767ed95..b69cf4f13 100644 --- a/helios/tests/inkling_operator_package_fixture.py +++ b/helios/tests/inkling_operator_package_fixture.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Export relative attention and residual convolution for independent native replay.""" +"""Export relative attention and residual convolution for native replay.""" import json from pathlib import Path @@ -11,17 +11,16 @@ class OperatorForward: - def __init__(self, attention, convolution, result): - self.attention, self.convolution, self.result = attention, convolution, result + 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() - history = self.convolution.arguments[2] end = attention.numel() + convolution.numel() self.result[:attention.numel()].copy_(attention.flatten()) self.result[attention.numel():end].copy_(convolution.flatten()) - self.result[end:].copy_(history.flatten()) + self.result[end:].copy_(self.history.flatten()) def prepare(directory): @@ -35,7 +34,6 @@ def prepare(directory): 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.scratch import ScratchArena from ignition.preparation.tuning import RecordedPreparationSession from fixed_package_fixture import allocation_reference from fixture_frontend import server_config @@ -48,8 +46,6 @@ def prepare(directory): 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: - arena = ScratchArena(device) - session.register_scratch(arena) 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) @@ -59,7 +55,7 @@ def prepare(directory): 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, workspace=arena, name="relative-attention") + 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) @@ -70,9 +66,9 @@ def prepare(directory): metadata.query_start_loc.copy_(cu) convolution_output = torch.empty_like(source) convolution = PreparedResidualShortConvolution(source, weight, history, metadata, convolution_output, - session=session, workspace=arena, name="residual-convolution") + session=session, name="residual-convolution") result = torch.empty(query.numel() + source.numel() + history.numel(), device=device) - run = OperatorForward(attention, convolution, result) + run = OperatorForward(attention, convolution, history, result) session.tune(show_progress=False) signatures = {"decode": GraphSignature("decode", 1, 1)} stream = torch.cuda.Stream(device=device) diff --git a/ignition/components/moe_sm103.py b/ignition/components/moe_sm103.py index 3eb3b93ab..00690d4d9 100644 --- a/ignition/components/moe_sm103.py +++ b/ignition/components/moe_sm103.py @@ -13,8 +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. -* Calibrated W4A4 experts requiring a BF16 SwiGLU boundary use CuTe-DSL - grouped GEMMs around that explicit intermediate and return raw BF16 routes. +* 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 @@ -139,7 +139,7 @@ class CuteW4A16Experts(Sm103Experts): @dataclass(frozen=True, eq=False, kw_only=True) class CuteNvfp4Experts(CuteW4A16Experts): - """Calibrated W4A4 experts with BF16 SwiGLU intermediates and raw route output.""" + """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 @@ -262,7 +262,7 @@ def prepare_cute_w4a16_experts(w13, s13, w2, s2, w13_global, w2_global, *, swigl def prepare_cute_nvfp4_experts(w13, s13, w2, s2, scale_vectors) -> CuteNvfp4Experts: - """Preserve packed values and calibration while preparing BF16-intermediate W4A4.""" + """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") @@ -612,7 +612,7 @@ def run(self, a, topk_ids, topk_weights, output, scratch): class _CuteNvfp4State: - """Calibrated A4 GEMMs with BF16 activation and independently rounded route outputs.""" + """CuTe-DSL NVFP4 GEMMs: FC1 to BF16 SwiGLU rows, requantized for FC2, written as unweighted per-route rows.""" implementation = "cute_nvfp4_routes" @@ -652,7 +652,6 @@ def run(self, a, topk_ids, topk_weights, output, scratch): 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) - # This explicit BF16 tensor is the arithmetic boundary before the calibrated FC2 input. self.quantize(s["activated"], e.intermediate_global_scale, s["intermediate"], s["intermediate_scales"], 16, False, True, False, False, True, 0) diff --git a/ignition/components/relative_paged_attention.py b/ignition/components/relative_paged_attention.py index 524bd2c9e..6b8f96760 100644 --- a/ignition/components/relative_paged_attention.py +++ b/ignition/components/relative_paged_attention.py @@ -46,8 +46,7 @@ def _relative_attention(Q, K, V, Pages, Lengths, Cu, Bias, Out, 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) - # Two bounded scans preserve canonical BF16 softmax-probability rounding. - # A materialized [queries, context] score or probability tensor is unnecessary. + # 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) @@ -148,7 +147,7 @@ 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, workspace, name): + *, 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) diff --git a/ignition/components/residual_short_conv.py b/ignition/components/residual_short_conv.py index b7d1efc06..d6bfef6ee 100644 --- a/ignition/components/residual_short_conv.py +++ b/ignition/components/residual_short_conv.py @@ -98,12 +98,11 @@ def compile_convolution(payload, tactic, ordinal): @dataclass(frozen=True) class State: - query: Query tactic: tuple programs: dict def run(self, tensors): - x, _, _, states, _, _, cu, y = tensors + x, _, _, states, *_, y = tensors block, _ = self.tactic y.zero_() args = _arguments(tensors, block) @@ -128,7 +127,7 @@ def _fake(source, weight, history, states, starts, lengths, cu, output, handle): class PreparedResidualShortConvolution: """Commit chronological raw FP32 history after all packed outputs are computed.""" - def __init__(self, source, weight, history, metadata, output, *, session, workspace, name): + 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 @@ -158,7 +157,7 @@ def __init__(self, source, weight, history, metadata, output, *, session, worksp def materialize(tactic): programs = compile_convolution(payload, tactic, source.device.index) load_programs(programs) - return attach_programs(State(q, tactic, programs), *programs.values()) + 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, diff --git a/ignition/recipes/inkling/attention.py b/ignition/recipes/inkling/attention.py index 7bb0054fe..fdfd11d15 100644 --- a/ignition/recipes/inkling/attention.py +++ b/ignition/recipes/inkling/attention.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Paged learned-relative-bias attention with complete FP32 convolution state.""" +"""Paged attention with learned relative bias and residual K/V convolutions.""" from dataclasses import dataclass @@ -14,7 +14,7 @@ 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 KV_DTYPE, PAGE_TOKENS +from .pool import PAGE_TOKENS @dataclass(frozen=True) @@ -34,7 +34,7 @@ class AttentionScratch: window_value: torch.Tensor @classmethod - def allocate(cls, config, shard, tokens, device, *, requests, buffers): + 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") @@ -58,8 +58,8 @@ def rows(self, tokens): class PreparedAttention(torch.nn.Module): - def __init__(self, layer, weights, config, shard, source, scratch, metadata, pool, *, mode, - runtime, coordinator, session, name, workspace, buffers): + 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"): @@ -70,9 +70,9 @@ def __init__(self, layer, weights, config, shard, source, scratch, metadata, poo 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, workspace=workspace, name=name + ".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, workspace=workspace, name=name + ".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, @@ -82,10 +82,10 @@ def __init__(self, layer, weights, config, shard, source, scratch, metadata, poo session=session, name=name + ".output") self.reduction = PreparedChunkedAllReduce(s.partial, s.output, runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduce") - self.lengths = buffers.zeros(metadata.lengths.shape, torch.int32) - self.slots = buffers.zeros(metadata.positions.shape, torch.int64).fill_(-1) 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) @@ -94,12 +94,13 @@ def __init__(self, layer, weights, config, shard, source, scratch, metadata, poo 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, workspace=workspace, name=name + ".attention") + 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)) @@ -115,15 +116,11 @@ def forward(self, hidden_states, **kwargs): 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 and 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]) if a.window < 0: - columns = (m.positions.clamp_min(0) // PAGE_TOKENS).clamp(max=m.token_page_table.shape[1] - 1) - pages = m.token_page_table[torch.arange(m.positions.numel(), device=m.positions.device), columns] - self.slots.copy_(torch.where(m.positions >= 0, pages.long() * PAGE_TOKENS + m.positions.remainder(PAGE_TOKENS), -1)) - self.lengths.copy_((m.starts + m.lengths).int()) + 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) @@ -141,4 +138,4 @@ def forward(self, hidden_states, **kwargs): return self.reduction(self.output_projection(s.attended.flatten(1))).view_as(hidden_states), None def scratch_tensors(self): - return self.lengths, self.slots + 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 index 4c465d62c..649389755 100644 --- a/ignition/recipes/inkling/bootstrap.py +++ b/ignition/recipes/inkling/bootstrap.py @@ -16,21 +16,18 @@ 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.collectives import ( - CollectivePreparation, create_all_gather_runtime, create_all_reduce_runtime, - create_dma_all_reduce_runtime, create_roce_runtime, -) 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.rank_group import minimum_across_ranks from ignition.preparation.rebuild_manifest import declare_weights from ignition.preparation.scratch import GraphBufferPool, ScratchArena from ignition.preparation.tuning import RecordedPreparationSession, with_autotune_effort @@ -38,7 +35,7 @@ from ignition.progress import phase from .contract import prepare as prepare_contract -from .decoder import PreparedDecoder, PreparedResume, Scratch +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 @@ -54,9 +51,7 @@ class PreparationConfig: lock_gpu_clocks: bool = False autotune_effort: str = "default" tuning_replica: TuningReplica | None = None - devices: tuple[int, ...] = (0,) - hosts: tuple[str, ...] | None = None - roce_ring: bool = False + device: int = 0 context: int = 262144 prefill_chunk_size: int = 4096 max_active: int = 4 @@ -68,13 +63,6 @@ class PreparationConfig: stream_overlap: bool = True def __post_init__(self): - if (not isinstance(self.devices, tuple) or len(self.devices) not in (1, 2) - or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != len(self.devices)) - or len(set(zip(self.hosts or ("",) * len(self.devices), self.devices))) != len(self.devices) - or any(type(device) is not int or device < 0 for device in self.devices)): - raise ValueError("Inkling-Small NVFP4 preparation requires one or two distinct host/device placements") - if self.roce_ring and (self.hosts is None or len(set(self.hosts)) < 2): - raise ValueError("RoCE ring requires ranks on separate hosts") 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]") @@ -86,18 +74,15 @@ def __post_init__(self): @torch.no_grad() @with_autotune_effort -def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storage): +def prepare(snapshot, config, *, progress=None, package_storage): from .recipe import RECIPE snapshot = Path(snapshot).resolve() - shard = TensorParallelShard(rank, len(config.devices)) - if (shard.world_size > 1) != (group is not None): - raise ValueError("an Inkling rank group exists exactly when more than one rank prepares") - device = torch.device("cuda", config.devices[rank]) + shard = TensorParallelShard(0, 1) + device = torch.device("cuda", config.device) torch.cuda.set_device(device) - if torch.cuda.get_device_capability(device) not in ((10, 3), (12, 0), (12, 1)): - raise ValueError("Inkling NVFP4 preparation requires SM103, SM120, or SM121: " - "the A4 expert kernels must expose unweighted per-route outputs") + 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] @@ -113,7 +98,7 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag 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 = minimum_across_ranks(torch.cuda.mem_get_info(device)[1], group) + 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), @@ -126,24 +111,7 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag 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 = CollectivePreparation(group) if group is not None else None - collective = prefill_collective = vocabulary_collective = embedding_collective = None - routed_width = weights.config.text["num_experts_per_tok"] * weights.config.hidden - if coordinator is not None and coordinator.spans_hosts: - gather_bytes = max(slots * weights.config.vocabulary_partition(shard)[2] * 2, - tokens * (weights.config.hidden // shard.world_size) * 2) - collective = prefill_collective = vocabulary_collective = embedding_collective = create_roce_runtime( - group, device, max_tokens=slots, pipe_tokens=tokens, hidden_size=routed_width, - gather_bytes=gather_bytes, ring=config.roce_ring, package_storage=package_storage) - elif group is not None: - collective = create_all_reduce_runtime(group, device, collective_tuning=config.collective_tuning, - max_tokens=slots, hidden_size=routed_width, ipc=package_storage.peer_storage) - prefill_collective = create_dma_all_reduce_runtime(group, device, max_tokens=tokens, - hidden_size=routed_width, ipc=package_storage.peer_storage) - vocabulary_collective = create_all_gather_runtime(group, device, max_rows=slots, - columns=weights.config.vocabulary_partition(shard)[2] * shard.world_size, ipc=package_storage.peer_storage) - embedding_collective = create_all_gather_runtime(group, device, max_rows=min(tokens, 128), - columns=weights.config.hidden, ipc=package_storage.peer_storage) + 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() @@ -166,8 +134,7 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, package_storag 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, group=group, - ipc=package_storage.peer_storage, runtime=collective, coordinator=coordinator) + 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"): @@ -186,32 +153,31 @@ def add(name, forward, kind, rows, tokens, fields): 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=prefill_collective if mode == "prefill" else collective, - embedding_runtime=embedding_collective, vocabulary_runtime=vocabulary_collective, - coordinator=coordinator, session=session, name=name, workspace=arena, + 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=collective, coordinator=coordinator, session=session, + 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=collective, vocabulary_runtime=vocabulary_collective, coordinator=coordinator, + 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=collective, coordinator=coordinator, session=session, name=name, capacity=capacity, + 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 and rank == 0, console=stage.console) + 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() @@ -222,7 +188,7 @@ def materialize(): try: graphs, compiled = capture_forwards(forwards, signatures, session=session, device=device, stream=stream, - pool=graph_pool, collective=collective, coordinator=coordinator, compile_decoder=config.compile_decoder, + 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")) @@ -239,7 +205,7 @@ def materialize(): 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=rank, world_size=shard.world_size, device=config.devices[rank], weights_bytes=weights.allocated_bytes, + 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, @@ -250,8 +216,6 @@ def materialize(): 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()) - channels = tuple(dict.fromkeys(channel for channel in - (collective, prefill_collective, vocabulary_collective, embedding_collective) if channel is not None)) disposable = [prefill_storage, decode_storage, arena.tensor, metadata, graph_buffers.chunks, private_buffers.chunks] for forward in forwards.values(): if isinstance(forward, PreparedScoredPrefill): @@ -263,10 +227,10 @@ def materialize(): 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.devices[rank], graphs=graphs, buffers=buffers, signatures=signatures, max_active=config.max_active, + 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, *channels, + decode_storage, metadata, compiled, stream, graph_pool, session, coordinator, scratch_pool, graph_buffers, private_buffers), - close_resources=tuple(c for c in (*channels, scoring) if c is not None)) + close_resources=(() if scoring is None else (scoring,))) diff --git a/ignition/recipes/inkling/contract.py b/ignition/recipes/inkling/contract.py index 996fcf900..ef6bce7b4 100644 --- a/ignition/recipes/inkling/contract.py +++ b/ignition/recipes/inkling/contract.py @@ -12,9 +12,6 @@ def prepare(signatures, buffers, pool, *, vocabulary): inputs = {kind: c.text_inputs(kind) for kind in {s.kind for s in signatures.values()}} - for kind in ("decode", "speculative"): - if kind in inputs: - inputs[kind].pop("token_ids", None) 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()] diff --git a/ignition/recipes/inkling/decoder.py b/ignition/recipes/inkling/decoder.py index a13388b34..666710e68 100644 --- a/ignition/recipes/inkling/decoder.py +++ b/ignition/recipes/inkling/decoder.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Prepared Inkling text layers, shared sinks, and sharded vocabulary projection.""" +"""Prepared Inkling text layers, shared-expert sinks, and vocabulary projection.""" from dataclasses import dataclass @@ -13,11 +13,12 @@ from ignition.components.linear import UnquantizedProjection from ignition.components.mlp import MLPScratch, PreparedMLP from ignition.components.moe import PreparedRoutedExperts -from ignition.components.paged_resume import PreparedResume +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 @@ -52,7 +53,7 @@ def zeros(shape, dtype=torch.bfloat16): 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, device, requests=samples, buffers=buffers) + 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) @@ -70,17 +71,10 @@ def zeros(shape, dtype=torch.bfloat16): zeros((samples, config.vocabulary_partition(shard)[2])), zeros((samples, config.vocabulary))) def rows(self, tokens, samples): - values = [] - for field in self.__dataclass_fields__: - value = getattr(self, field) - if field == "bf16": - value = value.rows(tokens, self.route_ids.shape[1]) - elif field in ("attention", "dense", "shared"): - value = value.rows(tokens) - else: - value = value[:samples if field in ("hidden", "local_logits", "logits") else tokens] - values.append(value) - return type(self)(*values) + 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): @@ -88,10 +82,8 @@ def __init__(self, weights, config, scratch, metadata, *, runtime, coordinator, super().__init__() self.scratch, self.metadata, self.config, self.weights = scratch, metadata, config, weights s = scratch - def mlp(w, storage, suffix): - return PreparedMLP(s.normalized, w, storage.gate_up, storage.intermediate, storage.output, - session=session, name=name + suffix, workspace=workspace, round_silu=False) - self.dense = None if weights.dense is None else mlp(weights.dense, s.dense, ".dense") + 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: @@ -105,7 +97,10 @@ def mlp(w, storage, suffix): 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(mlp(w, s.shared, f".shared{index}") for index, w in enumerate(weights.shared)) + 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 @@ -125,11 +120,11 @@ def forward(self, hidden_states): 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, expert in enumerate(self.shared): - expert.up_projection(s.normalized) + 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_(expert.down_projection(s.shared.intermediate)) + 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) @@ -156,17 +151,18 @@ def __init__(self, weights, scratch, metadata, pool, *, mode, runtime, 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, weights.shard, s.normalized, + attention = PreparedAttention(index, w, weights.config, s.normalized, s.attention, metadata, pool, mode=mode, runtime=runtime, coordinator=coordinator, - session=session, name=prefix + ".attention", workspace=workspace, buffers=buffers) + 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, workspace=workspace, name=prefix + "." + kind + "_conv") + 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))) @@ -179,6 +175,7 @@ def convolution(kind, source, weight): 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: @@ -192,4 +189,5 @@ def __call__(self): self.head(s.hidden) def scratch_tensors(self): - return (self.head.gathered, *(layer.self_attn.scratch_tensors() for layer in self.layers)) + 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 index b407f025f..ab9f73612 100644 --- a/ignition/recipes/inkling/frontend.py +++ b/ignition/recipes/inkling/frontend.py @@ -13,10 +13,10 @@ FRONTEND = c.frontend(tools=p.TML_JSON, assistant_marker="<|message_model|>", - message_end_markers=["<|end_message|>", "<|content_model_end_sampling|>"], prefix_boundary=None) + 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=[]) -FRONTEND["rejected_tokens"] = [200005, 200020, 200023, 200053, 200054] def prepare_frontend(snapshot, *, eos_token_ids): diff --git a/ignition/recipes/inkling/model.py b/ignition/recipes/inkling/model.py index 7f1e72d17..9ca6b8464 100644 --- a/ignition/recipes/inkling/model.py +++ b/ignition/recipes/inkling/model.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling normalization and FP32 sink routing without narrowing checkpoint parameters.""" +"""Inkling normalization, FP32 sink routing, route mixing and decoder composition.""" import torch @@ -16,7 +16,7 @@ def norm(weight, eps): def route(logits, correction, scale, *, top_k, shared_experts, route_scale): - """Keep FP32 router logits, correction, and global scale, including shared sinks.""" + """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) diff --git a/ignition/recipes/inkling/pool.py b/ignition/recipes/inkling/pool.py index 72c64f6d1..3f8038d6c 100644 --- a/ignition/recipes/inkling/pool.py +++ b/ignition/recipes/inkling/pool.py @@ -44,10 +44,10 @@ def continuation_layout(config, shard): ("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.text["hidden_size"],), torch.bfloat16), + regions.extend((("last_hidden", (config.hidden,), torch.bfloat16), ("consumed_tokens", (1,), torch.int64))) layout = StateLayout.from_specs(regions) - # TMA stages divide the stride between circular histories in adjacent rows. + # 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) diff --git a/ignition/recipes/inkling/recipe.py b/ignition/recipes/inkling/recipe.py index 96f84d317..9b0210d2b 100644 --- a/ignition/recipes/inkling/recipe.py +++ b/ignition/recipes/inkling/recipe.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling-Small NVFP4 text preparation on one or two GPUs.""" +"""Inkling-Small NVFP4 text preparation on one SM103 GPU.""" from types import MappingProxyType @@ -10,38 +10,32 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_graphs=False, package_storage=None, ranks=None): - from ignition.preparation.rank_group import prepare_group - from .bootstrap import PreparationConfig, prepare_rank + 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", - devices=tuple(range(plan.world_size)) if ranks is None else (0,) * plan.world_size, - hosts=None if ranks is None else ranks.hosts, roce_ring=plan.roce_ring, 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) - if plan.world_size == 1: - return prepare_rank(snapshot, config, rank=0, group=None, progress=progress, package_storage=package_storage) - return prepare_group(snapshot, config, prepare_rank, progress=progress, package_storage=package_storage, - ranks=ranks, checkpoint=plan.checkpoint) + return prepare_model(snapshot, config, progress=progress, package_storage=package_storage) def usage(prepared): - return tuple(RankUsage(rank["pages"], rank["free_device_bytes"]) - for rank in prepared.memory_report.get("ranks", (prepared.memory_report,))) + return (RankUsage(prepared.memory_report["pages"], prepared.memory_report["free_device_bytes"]),) RECIPE = Recipe(name="inkling", served_model_name="Inkling-Small-NVFP4", - # Publisher guidance: thinking-machines-lab/tinker-cookbook, skills/inkling/SKILL.md. + # 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", - # Include unused multimodal/MTP tensors in the estimate to cover replicated text weights. + # 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), - 2: RankCosts(43_515_904, 1_835_008, 8 << 30)})) + ranks=MappingProxyType({1: RankCosts(82_837_504, 3_670_016, 8 << 30)})) 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 index 81be132ef..7422c0089 100644 --- a/tests/components/inkling_nvfp4_helpers.py +++ b/tests/components/inkling_nvfp4_helpers.py @@ -1,12 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Raw Inkling NVFP4 fixtures and an independent quantized arithmetic oracle.""" +"""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): @@ -18,7 +20,6 @@ def _reciprocal_approximate_kernel(source, output, count: tl.constexpr, BLOCK: t def _reciprocal_approximate(value): - """The native quantizer's CUDA reciprocal primitive, independent of its kernels.""" value = value.contiguous() output = torch.empty_like(value) _reciprocal_approximate_kernel[(triton.cdiv(value.numel(), 256),)](value, output, value.numel(), 256) @@ -41,14 +42,6 @@ def _exp2_approximate(value): return output -def unpack_weight(values, scales): - """Decode low-nibble-first E2M1 and unswizzled checkpoint E4M3 block scales.""" - magnitudes = torch.tensor([0., .5, 1., 1.5, 2., 3., 4., 6.], device=values.device) - codes = torch.stack((values & 15, values >> 4), -1).flatten(-2).long() - signed = magnitudes[codes & 7] * torch.where(codes < 8, 1., -1.) - return signed * scales.float().repeat_interleave(16, -1) - - def quantize_activation(value, amax, *, quant_scale_math="b12x"): """Return E2M1 values times E4M3 block scales, and separate FP32 calibration.""" value = value.float() @@ -69,33 +62,24 @@ def quantize_activation(value, amax, *, quant_scale_math="b12x"): else: raise ValueError(f"unknown NVFP4 quantizer arithmetic: {quant_scale_math}") inverse = torch.where(scales != 0, inverse, 0.) - normalized = blocks * inverse - magnitude = normalized.abs() - code = ((magnitude > .25).int() + (magnitude >= .75).int() + (magnitude > 1.25).int() - + (magnitude >= 1.75).int() + (magnitude > 2.5).int() + (magnitude >= 3.5).int() - + (magnitude > 5.).int()) - levels = torch.tensor([0., .5, 1., 1.5, 2., 3., 4., 6.], device=value.device) - return (levels[code] * normalized.sign() * scales).reshape_as(value), encode + return (round_e2m1(blocks * inverse) * scales).reshape_as(value), encode -def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None, - quant_scale_math="b12x"): +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 + ".")} - intermediate = tensors[first].shape[1] // 2 - begin, end = (0, intermediate) if intermediate_range is None else intermediate_range 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 - rows = slice(2 * begin, 2 * end) # Scaled FP4 MMA applies the outer multiplier after the dot product. - up_gate = unpack_weight(tensors[first][expert, rows], tensors[first + ".scale"][expert, rows]) + 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": @@ -107,8 +91,7 @@ def nvfp4_routes(source, ids, tensors, prefix, *, intermediate_range=None, 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 = unpack_weight(tensors[second][expert, :, begin // 2:end // 2], - tensors[second + ".scale"][expert, :, begin // 16:end // 16]) + 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_cuda.py b/tests/components/test_inkling_nvfp4_cuda.py deleted file mode 100644 index ba7696698..000000000 --- a/tests/components/test_inkling_nvfp4_cuda.py +++ /dev/null @@ -1,137 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Original packed Inkling experts through prepared, compiled NVFP4 A4 graphs.""" - -import os - -import pytest -import torch - -from ignition.components.moe import PreparedRoutedExperts -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 tests.recipes.inkling_helpers import checkpoint -from .inkling_nvfp4_helpers import nvfp4_routes - -pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", - reason="requires an assigned CUDA GPU") - - -class ExpertForward: - 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) - for _ in experts] - self.reduced = torch.empty_like(self.routes[0]) - self.output = torch.empty_like(source) - self.operations = [PreparedRoutedExperts(source, value, self.active_ids, weights, output, - session=session, workspace=workspace, name=f"experts{rank}") - for rank, (value, output) in enumerate(zip(experts, self.routes, strict=True))] - - 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)) - for operation, output in zip(self.operations, self.routes, strict=True): - operation() - output.copy_(torch.where(self.active_ids[..., None] >= 0, output, 0.)) - # Both TP shards run on this device to check the intermediate partition - # and reduce-before-weight arithmetic; this is not a transport test. - self.reduced.copy_(self.routes[0].float() + self.routes[1].float()) - self.output.copy_(mix_routes(self.reduced, self.weights, self.active_ids)) - - -@pytest.mark.parametrize("tokens", [1, 129, 4096]) -@torch.no_grad() -def test_calibrated_packed_experts_tp_shards_compiled_replay(tmp_path, tokens): - expert_count, top_k = (8, 6) if tokens == 129 else (4, 2) - config, tensors = checkpoint(tmp_path, moe_intermediate=256, routed_experts=expert_count, top_k=top_k) - prefix = "model.llm.layers.2.mlp.experts" - manifest = inspect_indexed_checkpoint(tmp_path) - experts = [] - def unswizzle(scales, rows, columns): - # Invert the native 128x4 scale atom independently of the load helper. - return (scales.view(torch.uint8).reshape(rows // 128, columns // 4, 32, 4, 4) - .permute(0, 3, 2, 1, 4).contiguous().reshape(rows, columns)) - - for rank in range(2): - with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(rank, 2)) as loader: - expert = loader.load_layer(2).experts - impl = expert._impl - first, last = rank * 128, (rank + 1) * 128 - original = tensors[prefix + ".w13_weight"] - expected = torch.cat((original[:, 2*first:2*last:2], original[:, 2*first+1:2*last:2]), 1) - assert torch.equal(impl.w1_fp4.cpu(), expected) - scales = tensors[prefix + ".w13_weight.scale"] - expected_scales = torch.cat((scales[:, 2*first:2*last:2].view(torch.uint8), - scales[:, 2*first+1:2*last:2].view(torch.uint8)), 1) - for index in range(config.text["n_routed_experts"]): - actual = unswizzle(impl.w1_blockscale[index], 256, config.hidden // 16) - assert torch.equal(actual.cpu(), expected_scales[index]) - assert torch.equal(impl.w2_fp4.cpu(), tensors[prefix + ".w2_weight"][:, :, first//2:last//2]) - for index in range(config.text["n_routed_experts"]): - actual = unswizzle(impl.w2_blockscale[index], config.hidden, 128 // 16) - assert torch.equal(actual.cpu(), - tensors[prefix + ".w2_weight.scale"][index, :, first//16:last//16].view(torch.uint8)) - for attribute, alpha, projection in (("a1_gscale", "w1_alphas", "w13_weight"), - ("a2_gscale", "w2_alphas", "w2_weight")): - amax = tensors[prefix + "." + projection + ".input_amax"].float().item() - scale = torch.full((config.text["n_routed_experts"],), amax / 2688.).reciprocal() - assert scale[0] != torch.tensor(2688. / amax) - assert torch.equal(getattr(impl, attribute).cpu(), scale) - assert torch.equal(getattr(impl, alpha).cpu(), tensors[prefix + "." + projection + ".scale2"] / scale) - experts.append(expert) - - torch.manual_seed(4517 + tokens) - device = torch.device("cuda:0") - source = torch.randn((tokens, config.hidden), device=device, dtype=torch.bfloat16) - offsets = torch.arange(top_k, device=device) * (1 if top_k == 6 else 2) - ids = ((torch.arange(tokens, device=device)[:, None] + offsets) % expert_count).int() - # Distinct route weights include the router's global gain; kernels must leave - # every expert output unweighted until the TP shards have been combined. - weights = torch.rand((tokens, top_k), device=device) * .14234226942062378 * 8. - live = torch.tensor([tokens], dtype=torch.int32, device=device) - with RecordedPreparationSession(device=device, checkpoint="inkling-nvfp4-experts", - workload_schema="inkling", numerical_policy="default", compile_workers=1) as session: - arena = ScratchArena(device) - session.register_scratch(arena) - forward = ExpertForward(source, experts, ids, weights, live, session=session, workspace=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) - if tokens > 1: - ids[0, 1] = -1 - active = torch.where(torch.arange(tokens, device=device)[:, None] < count, ids, -1) - expected = [nvfp4_routes(source, active, tensors, prefix, intermediate_range=(rank*128, (rank+1)*128)) - for rank in range(2)] - allocations = torch.cuda.memory_stats()["allocation.all.allocated"] - graph.replay() - torch.cuda.synchronize() - assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations - for actual, reference in zip(forward.routes, expected, strict=True): - # This reduced checkpoint is exactly repeatable across the - # captured capacities and the reference's BF16 boundaries. - torch.testing.assert_close(actual, reference, atol=0, rtol=0) - # Test reduction and routing separately from quantized GEMM error. - reduced = (forward.routes[0].float() + forward.routes[1].float()).bfloat16() - result = torch.zeros_like(source) - for expert_id in range(expert_count): - route = ((reduced.float() * weights[..., None]) - * (active == expert_id)[..., None]).sum(1).bfloat16() - result += route - assert torch.equal(forward.output, result) - assert not forward.output[count:].count_nonzero() - graph.reset() diff --git a/tests/components/test_inkling_nvfp4_sm103_cuda.py b/tests/components/test_inkling_nvfp4_sm103_cuda.py index 786327570..cc0515546 100644 --- a/tests/components/test_inkling_nvfp4_sm103_cuda.py +++ b/tests/components/test_inkling_nvfp4_sm103_cuda.py @@ -4,12 +4,14 @@ """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 +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 @@ -17,8 +19,9 @@ 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, unpack_weight +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") @@ -26,8 +29,6 @@ @pytest.mark.parametrize("amax", [1.8359375, 187., 4.]) def test_sm103_activation_calibration_and_fp4_ties(amax): - from ignition.components.moe_sm103 import _fp4_quantizer - if torch.cuda.get_device_capability() != (10, 3): pytest.skip("SM103 NVFP4 quantizer") generator = torch.Generator(device="cuda").manual_seed(103) @@ -41,7 +42,7 @@ def test_sm103_activation_calibration_and_fp4_ties(amax): 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 = unpack_weight(values, scales[:64].view(torch.float8_e4m3fn).reshape(4, 16)) + 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) @@ -72,21 +73,6 @@ def test_sm103_calibrated_raw_routes_compiled_replay(tmp_path, tokens): with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(0, 1)) as loader: experts = loader.load_layer(2).experts assert isinstance(experts, CuteNvfp4Experts) - - # Native CuTe FC1 is [up64;gate64], derived only by row permutation. - def interleave(tensor): - up_gate = torch.stack((tensor[:, 1::2], tensor[:, ::2]), 2) - return up_gate.reshape(8, 4, 64, 2, -1).transpose(2, 3).reshape_as(tensor) - - assert torch.equal(experts.w13.cpu(), interleave(tensors[prefix + ".w13_weight"])) - assert torch.equal(experts.w2.cpu(), tensors[prefix + ".w2_weight"]) - for storage, name, rows, columns, reorder in ( - (experts.scale_storage[0], "w13_weight", 512, 16, interleave), - (experts.scale_storage[1], "w2_weight", 256, 16, lambda x: x), - ): - actual = (storage.cpu().view(torch.uint8).reshape(8, rows // 128, columns // 4, 32, 4, 4) - .permute(0, 1, 4, 3, 2, 5).contiguous().reshape(8, rows, columns)) - assert torch.equal(actual, reorder(tensors[prefix + "." + name + ".scale"].view(torch.uint8))) for name, calibration, alpha in ( ("w13_weight", experts.input_global_scale, experts.w13_alpha), ("w2_weight", experts.intermediate_global_scale, experts.w2_alpha), @@ -144,9 +130,6 @@ def interleave(tensor): @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(): - from pathlib import Path - from safetensors import safe_open - if torch.cuda.get_device_capability() != (10, 3): pytest.skip("SM103 grouped NVFP4 execution") manifest = inspect_indexed_checkpoint(Path(os.environ["FLARE_INKLING_SNAPSHOT"])) @@ -157,7 +140,6 @@ def test_original_checkpoint_sm103_production_geometry(): assert (experts.num_experts, experts.hidden_size, experts.intermediate_size) == (256, 4096, 2048) selected = [255, 7, 33, 100, 127, 0] original = {} - # Read original bytes through safetensors, independently of the recipe's packed layout. for projection in ("w13_weight", "w2_weight"): for suffix in ("", ".scale", ".scale2", ".input_amax"): name = prefix + "." + projection + suffix @@ -194,9 +176,6 @@ def test_original_checkpoint_sm103_production_geometry(): graph.replay() torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations - difference = forward.routes.float() - reference.float() - print({"max_absolute_error": difference.abs().max().item(), - "relative_l2_error": (difference.norm() / reference.float().norm().clamp_min(1e-12)).item()}) torch.testing.assert_close(forward.routes, reference, atol=0, rtol=0) live.zero_() graph.replay() diff --git a/tests/components/test_inkling_operators_cuda.py b/tests/components/test_inkling_operators_cuda.py index 5ee3c9ce1..2baae99fc 100644 --- a/tests/components/test_inkling_operators_cuda.py +++ b/tests/components/test_inkling_operators_cuda.py @@ -12,7 +12,7 @@ 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.scratch import ScratchArena +from ignition.preparation.compilation import compile_forward from ignition.preparation.tuning import RecordedPreparationSession @@ -47,17 +47,14 @@ def test_relative_attention_canonical_paged_capture(window, counts, starts, capa 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: - arena = ScratchArena(device) - session.register_scratch(arena) operation = PreparedRelativePagedAttention(query, key, value, pages, lengths, cu, relative, output, - window=window, softmax_scale=1 / dim, session=session, workspace=arena, name="attention") + 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) - from ignition.preparation.compilation import compile_forward run = compile_forward(operation) run() graph = torch.cuda.CUDAGraph() @@ -123,17 +120,14 @@ def test_residual_convolution_canonical_chunking_and_state(capacity, channels): 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: - arena = ScratchArena(device) - session.register_scratch(arena) operation = PreparedResidualShortConvolution(source, weights, history, m, output, - session=session, workspace=arena, name="convolution") + 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_() - from ignition.preparation.compilation import compile_forward run = compile_forward(operation) run() graph = torch.cuda.CUDAGraph() @@ -188,53 +182,3 @@ def test_residual_convolution_canonical_chunking_and_state(capacity, channels): 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() - - -@pytest.mark.parametrize("round_silu", [True, False]) -@torch.no_grad() -def test_bf16_experts_silu_rounding_and_capture(round_silu): - from ignition.components.bf16_experts import PreparedBF16Experts - from ignition.preparation.compilation import compile_forward - from ignition.preparation.scratch import GraphBufferPool - - torch.manual_seed(837) - source = torch.randn((17, 128), device="cuda", dtype=torch.bfloat16) - gate_up = (torch.randn((4, 128, 128), device="cuda") * .05).bfloat16() - down = (torch.randn((4, 128, 64), device="cuda") * .05).bfloat16() - ids = torch.rand((17, 4), device="cuda").topk(2, dim=-1).indices.int() - weights = torch.rand((17, 2), device="cuda") - valid = torch.tensor([13], device="cuda", dtype=torch.int32) - output = torch.empty((17, 2, 128), device="cuda", dtype=torch.bfloat16) - operation = PreparedBF16Experts(source, gate_up, down, ids, weights, output, valid, - 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) - # BF16 intermediate activation for existing users; Inkling's supported - # implementation computes SiLU and multiplication in FP32, rounding once. - 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]) - operation() - torch.testing.assert_close(operation.intermediate[:26], intermediate.flatten(0, 1), rtol=.008, atol=2e-5) - torch.testing.assert_close(output, expected, rtol=.008, atol=2e-4) - run = compile_forward(operation) - run() - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - run() - before = torch.cuda.memory_stats()["allocation.all.allocated"] - graph.replay() - torch.cuda.synchronize() - assert torch.cuda.memory_stats()["allocation.all.allocated"] == before - torch.testing.assert_close(output, expected, rtol=.008, atol=2e-4) - 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/inkling_helpers.py b/tests/recipes/inkling_helpers.py index a4a5c83e2..11782107a 100644 --- a/tests/recipes/inkling_helpers.py +++ b/tests/recipes/inkling_helpers.py @@ -42,12 +42,14 @@ def quantization(): "*input_quantizer": quantizer.copy(), "default": {"enable": False}})) -def checkpoint(path, *, moe_intermediate=128, routed_experts=4, top_k=2): +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 @@ -95,8 +97,7 @@ def ones(name, shape): name = p + ".mlp.experts." + projection original = tensors[name] count, rows, columns = original.shape - # Independent exact checkpoint bytes: signed E2M1 codes, distinct - # block scales and per-expert gains expose row/column packing errors. + # 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) 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 index 04bc74e20..44e280b7f 100644 --- a/tests/recipes/test_inkling.py +++ b/tests/recipes/test_inkling.py @@ -3,6 +3,8 @@ """Inkling architecture, checkpoint-precision arithmetic, and complete cache contract.""" +import json + import pytest import torch from google.protobuf.json_format import ParseDict @@ -14,16 +16,12 @@ 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, continuation_layout, page_bytes +from ignition.recipes.inkling.pool import ContinuationPool, page_bytes from ignition.recipes.inkling.recipe import RECIPE from .inkling_helpers import configuration, quantization -def test_checkpoint_alias_and_canonical_geometry(): - from ignition.recipes import resolve - from ignition.recipes.inkling.bootstrap import PreparationConfig - - assert resolve("inkling-small-nvfp4").recipe is RECIPE +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 @@ -32,9 +30,6 @@ def test_checkpoint_alias_and_canonical_geometry(): assert model.quantized_routed_layers == (2,) assert model.vocabulary == 250 assert RECIPE.speculation is None and RECIPE.max_draft_tokens == 0 - assert PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 - with pytest.raises(ValueError): - PreparationConfig(devices=(0, 1, 2)) @pytest.mark.parametrize("change", [ @@ -49,8 +44,6 @@ def test_rejects_changed_arithmetic(change): def test_checkpoint_quantization_requires_both_calibration_and_exclusions(tmp_path): - import json - raw, quant = configuration(), quantization() (tmp_path / "config.json").write_text(json.dumps(raw)) with pytest.raises(FileNotFoundError, match="hf_quant_config"): diff --git a/tests/recipes/test_inkling_cuda.py b/tests/recipes/test_inkling_cuda.py index 6a1b5c70b..035ff8dc9 100644 --- a/tests/recipes/test_inkling_cuda.py +++ b/tests/recipes/test_inkling_cuda.py @@ -3,6 +3,8 @@ """Real prepared Inkling decoder replay across prefill, decode, and restored state.""" +import contextlib +import json import os import pytest @@ -18,7 +20,7 @@ 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 ModelWeights +from ignition.recipes.inkling.weights import InklingWeightLoader, ModelWeights from tests.components.inkling_nvfp4_helpers import nvfp4_routes from .inkling_helpers import checkpoint @@ -111,16 +113,57 @@ def mlp(gate_up, down, gamma=None): 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_shards_interleaved_rows_without_losing_precision(tmp_path): +def test_original_checkpoint_loader_deinterleaves_rows_without_losing_precision(tmp_path): config, original = checkpoint(tmp_path) manifest = inspect_indexed_checkpoint(tmp_path) - from ignition.recipes.inkling.weights import InklingWeightLoader - - with InklingWeightLoader(manifest, "cuda:0", shard=TensorParallelShard(1, 2)) as loader: + 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[:, 128::2], raw[:, 129::2]), dim=1)) + 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 @@ -130,9 +173,6 @@ def test_original_checkpoint_loader_shards_interleaved_rows_without_losing_preci @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): - import json - from ignition.recipes.inkling.weights import InklingWeightLoader - checkpoint(tmp_path) path = tmp_path / "hf_quant_config.json" metadata = json.loads(path.read_text()) @@ -151,46 +191,14 @@ def test_loader_rejects_checkpoint_precision_disagreeing_with_exclusions(tmp_pat @torch.no_grad() def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): - _, 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, 4, 5, device) - buffers = GraphBufferPool(device, chunk_bytes=2 << 20) - catalog = {} - 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 in (("prefill", 64), ("decode", 1)): - cursor = buffers.cursor() - metadata = Metadata.allocate(capacity, 1, 5, device, buffers=cursor) - scratch = Scratch.allocate(weights.config, shard, capacity, 1, 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) - catalog[mode] = metadata, scratch, decoder - session.tune() - graphs = {} - for mode, (metadata, scratch, decoder) in catalog.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() - graphs[mode] = graph, compiled - session.freeze() - pool.clear_for_preparation() + 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, decoder = catalog[mode] + 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), @@ -198,7 +206,7 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): values, torch.ones(1, device=device, dtype=torch.int32)) metadata.sample_indices.fill_(count - 1) before = torch.cuda.memory_stats()["allocation.all.allocated"] - graphs[mode][0].replay() + graph.replay() torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == before start += count @@ -207,17 +215,17 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): assert start == tokens.numel() saved = pool.backing.clone() pages = {name: value.clone() for name, value in pool.pages.items()} - metadata, scratch, decoder = catalog["decode"] + metadata, scratch, graph = catalog["decode"] metadata.starts.fill_(start) metadata.positions.fill_(start) metadata.token_ids.fill_(13) - graphs["decode"][0].replay() + graph.replay() torch.cuda.synchronize() branch = scratch.logits.clone() pool.backing.copy_(saved) for name, value in pages.items(): pool.pages[name].copy_(value) - graphs["decode"][0].replay() + graph.replay() torch.cuda.synchronize() assert torch.equal(branch, scratch.logits) saved = pool.backing.clone() @@ -226,51 +234,19 @@ def test_decoder_compiled_replay_cache_boundaries_and_restored_branch(tmp_path): metadata.live_counts.zero_() metadata.positions.fill_(-1) metadata.state_rows.zero_() - graphs["decode"][0].replay() + 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): - _, 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, 5, 10, device) - buffers = GraphBufferPool(device, chunk_bytes=2 << 20) - catalog = {} - with RecordedPreparationSession(device=device, checkpoint="inkling-batched-test", workload_schema="inkling", - numerical_policy="default", compile_workers=1) as session: - arena = ScratchArena(device) - session.register_scratch(arena) - for mode, capacity, rows in (("prefill", 192, 1), ("decode", 4, 4)): - cursor = buffers.cursor() - metadata = Metadata.allocate(capacity, rows, 5, device, buffers=cursor) - scratch = Scratch.allocate(weights.config, shard, capacity, rows, 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) - catalog[mode] = metadata, scratch, decoder - session.tune() - graphs = {} - for mode, (metadata, _, decoder) in catalog.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() - graphs[mode] = graph, compiled - session.freeze() - pool.clear_for_preparation() + 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, _ = catalog["prefill"] + 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), @@ -278,9 +254,9 @@ def test_decoder_batched_decode_with_inactive_rows_after_window_wrap(tmp_path): 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) - graphs["prefill"][0].replay() + graph.replay() untouched = pool.backing[[0, 3, 4]].clone() - m, s, _ = catalog["decode"] + 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), @@ -288,7 +264,7 @@ def test_decoder_batched_decode_with_inactive_rows_after_window_wrap(tmp_path): 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"] - graphs["decode"][0].replay() + graph.replay() torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == before assert torch.equal(untouched, pool.backing[[0, 3, 4]]) diff --git a/tests/recipes/test_inkling_preparation_cuda.py b/tests/recipes/test_inkling_preparation_cuda.py index 365a115c2..555ccda32 100644 --- a/tests/recipes/test_inkling_preparation_cuda.py +++ b/tests/recipes/test_inkling_preparation_cuda.py @@ -3,7 +3,6 @@ """Single-rank preparation and replay of the complete Inkling graph catalog.""" -import json import os from pathlib import Path @@ -16,45 +15,32 @@ @torch.no_grad() def test_single_rank_mixed_checkpoint_prepares_and_replays_catalog(tmp_path): - from safetensors.torch import save_file 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_rank + 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") - _, tensors = checkpoint(tmp_path) - raw = json.loads((tmp_path / "config.json").read_text()) - # Keep the publisher's complete frontend and special-token IDs while reducing - # layer geometry; this exercises frontend/contract preparation without mocks. + # Keep the publisher's frontend and special-token IDs while reducing layer geometry. publisher = ModelConfig.load(snapshot) - raw["text_config"].update(vocab_size=publisher.text["vocab_size"], - unpadded_vocab_size=publisher.vocabulary) - for name in ("embed", "unembed"): - tensors[f"model.llm.{name}.weight"] = ( - torch.randn(publisher.text["vocab_size"], 256) * .1).bfloat16() - (tmp_path / "config.json").write_text(json.dumps(raw)) - save_file(tensors, tmp_path / "model.safetensors") - (tmp_path / "model.safetensors.index.json").write_text(json.dumps(dict( - metadata={"total_size": sum(t.nbytes for t in tensors.values())}, - weight_map={name: "model.safetensors" for name in tensors}))) + 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) - del tensors config = ModelConfig.load(tmp_path) - preparation = PreparationConfig(devices=(0,), context=256, prefill_chunk_size=128, max_active=1, + 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_rank(tmp_path, preparation, rank=0, group=None, package_storage=storage) as model: + 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["world_size"] == 1 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)) @@ -129,11 +115,6 @@ def continuation(): for kind in ("key", "value")}) return tokens, state - def assert_state(actual, expected): - assert actual.keys() == expected.keys() - for name in expected: - torch.testing.assert_close(actual[name], expected[name], atol=0, rtol=0, msg=name) - admit(7) prefill() hidden = pool.last_hidden[1].clone() @@ -148,7 +129,7 @@ def assert_state(actual, expected): assert torch.equal(pool.last_hidden[1], hidden) tokens, state = continuation() assert tokens == expected_tokens - assert_state(state, expected_state) + torch.testing.assert_close(state, expected_state, atol=0, rtol=0) assert torch.equal(pool.backing[2], snapshot_row) admit(9) @@ -157,13 +138,14 @@ def assert_state(actual, expected): 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(scores[:126, 1].contiguous().view(torch.float32)).all() - assert (scores[:126, 1].contiguous().view(torch.float32) <= 0).all() + 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(scores[126:, 1].contiguous().view(torch.float32)).all() + assert torch.isnan(logprobs[126:]).all() tokens, state = continuation() assert tokens == expected_tokens - assert_state(state, expected_state) + 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 index 9c10b2101..ab88f65fa 100644 --- a/tests/recipes/test_inkling_topology.py +++ b/tests/recipes/test_inkling_topology.py @@ -1,93 +1,57 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Inkling NVFP4 placements and memory planning through the shared planner.""" +"""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.errors import CapacityError +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 -@pytest.mark.parametrize('devices,hosts', [ - ((3,), None), ((1, 3), None), ((0, 0), ('spark-a', 'spark-b')), -]) -def test_one_or_two_distinct_local_or_remote_placements(devices, hosts): - from ignition.recipes.inkling.bootstrap import PreparationConfig - - config = PreparationConfig(devices=devices, hosts=hosts) - assert config.devices == devices and config.hosts == hosts +def test_minimum_prefill_chunk_is_accepted(): + assert bootstrap.PreparationConfig(prefill_chunk_size=64).prefill_chunk_size == 64 -@pytest.mark.parametrize('devices,hosts', [ - ((), None), ((0, 1, 2, 3), None), ((0, 0), None), ((0, -1), None), - ((0, 0), ('spark-a', 'spark-a')), ((0, 1), ('spark-a',)), +@pytest.mark.parametrize('values,match', [ + (dict(context=100), '128-aligned'), (dict(prefill_chunk_size=96), '64-aligned'), ]) -def test_unsupported_placements_fail_before_loading(devices, hosts): - from ignition.recipes.inkling.bootstrap import PreparationConfig - - with pytest.raises(ValueError, match='one or two distinct host/device placements'): - PreparationConfig(devices=devices, hosts=hosts) - - -def test_roce_ring_requires_remote_placements(): - from ignition.recipes.inkling.bootstrap import PreparationConfig - - with pytest.raises(ValueError, match='ranks on separate hosts'): - PreparationConfig(roce_ring=True) +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): - from ignition.recipes.inkling import bootstrap - monkeypatch.setattr(bootstrap.torch.cuda, 'set_device', lambda device: None) - monkeypatch.setattr(bootstrap.torch.cuda, 'get_device_capability', lambda device: (9, 0)) - with pytest.raises(ValueError, match='Inkling NVFP4 preparation requires SM'): - bootstrap.prepare_rank(tmp_path / 'not-downloaded', bootstrap.PreparationConfig(), - rank=0, group=None, package_storage=None) - - -@pytest.mark.parametrize('devices,group', [((0,), object()), ((0, 1), None)]) -def test_rank_group_matches_tensor_parallel_placement(tmp_path, devices, group): - from ignition.recipes.inkling import bootstrap - - with pytest.raises(ValueError, match='rank group exists exactly'): - bootstrap.prepare_rank(tmp_path, bootstrap.PreparationConfig(devices=devices), - rank=0, group=group, package_storage=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, RECIPE.checkpoints[0], (station,), selected=None, + 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 - assert plan.costs.state_row_bytes == 82_837_504 - assert plan.costs.page_bytes == 3_670_016 - assert plan.costs.page_bytes * (plan.context // 128) == 7 << 30 - assert plan.weights_bytes >= 166_130_594_960 -def test_nvfp4_plan_fits_two_sparks_with_host_reserve(): - model = resolve('inkling-small-nvfp4') - assert model.recipe is RECIPE and model.checkpoint.repository == 'thinkingmachines/Inkling-Small-NVFP4' - gpus = tuple(planning.Gpu(index, 'NVIDIA GB10', f'GPU-{index}', 121 << 30, 118 << 30, (12, 1)) - for index in range(2)) - plan = planning.plan(RECIPE, model.checkpoint, gpus, selected=(0, 1), - concurrency=4, reserve_bytes=4 << 30, speculation=None) - assert plan.world_size == 2 and plan.fits - assert plan.context == plan.guaranteed_tokens == 262144 - assert plan.costs.state_row_bytes == 43_515_904 - assert plan.costs.page_bytes == 1_835_008 - assert plan.weights_bytes >= 166_130_594_960 // 2 - assert plan.reserve_bytes == 4 << 30 - with pytest.raises(CapacityError, match='weights'): - planning.plan(RECIPE, model.checkpoint, gpus[:1], selected=(0,), - concurrency=4, reserve_bytes=4 << 30, speculation=None) - small = tuple(planning.Gpu(index, 'NVIDIA RTX', f'GPU-{index}', 64 << 30, 63 << 30, (12, 0)) - for index in range(2)) - with pytest.raises(CapacityError): - planning.plan(RECIPE, model.checkpoint, small, selected=(0, 1), - concurrency=4, reserve_bytes=0, speculation=None) +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 index f334023a7..e4bdfad58 100644 --- a/tests/server/test_inkling.py +++ b/tests/server/test_inkling.py @@ -22,8 +22,8 @@ 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)]) +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") @@ -63,50 +63,26 @@ def ask(messages, **options): assert result["prompt_token_ids"] == expected assert result["usage"]["completion_tokens"] == len(result["choices"][0]["token_ids"]) return result - return ask, request, card["id"] + return ask def text(result): return (result["choices"][0]["message"].get("content") or "").strip() -@pytest.mark.parametrize("prompt,expected", [ - ("What is 13 times 29? Reply with only the integer.", "377"), - ("Repeat exactly this text, without quotation marks or explanation: café", "café"), -], ids=["arithmetic", "unicode"]) -def test_default_sampling(service, prompt, expected): - result = service[0]([dict(role="user", content=prompt)]) - assert text(result) == expected - assert result["choices"][0]["finish_reason"] == "stop" - - @pytest.mark.parametrize("effort", ["minimal", "low", "medium", "high", "max"]) def test_reasoning_headers(service, effort): - result = service[0]([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.")], + 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"] -@pytest.mark.parametrize("required", [True, False]) -def test_json_tool_envelope(service, required): - value = dict(query="café 世界", count=3) - function = dict(name="record", parameters=dict(type="object", properties=dict(query=dict(type="string"), - count=dict(type="integer")), required=["query", "count"])) - choice = "required" if required else dict(type="function", function=dict(name="record")) - result = service[0]([dict(role="user", content="Call record with exactly " + json.dumps(value))], - tools=[dict(type="function", function=function)], tool_choice=choice) - call, = result["choices"][0]["message"]["tool_calls"] - assert call["function"]["name"] == "record" - assert json.loads(call["function"]["arguments"]) == value - assert result["choices"][0]["finish_reason"] == "tool_calls" - - 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[0]([*history, dict(role="user", content=f"Reply with only INKLING-BRANCH-{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 @@ -115,75 +91,78 @@ def ask(index): assert [text(result) for result in results] == [f"INKLING-BRANCH-{i}" for i in range(4)] -def test_prompt_scores_and_text_only_rejection(service): - result = service[0]([dict(role="user", content="A cache preserves context. café 世界.")], max_tokens=1, prompt_logprobs=2) +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()) - for content in ([dict(type="image_url", image_url=dict(url="data:image/png;base64,AA=="))], - [dict(type="input_audio", input_audio=dict(data="AA==", format="wav"))]): - with pytest.raises(urllib.error.HTTPError) as rejected: - service[1]("/v1/chat/completions", dict(model=service[2], messages=[dict(role="user", content=content)])) - assert rejected.value.code == 400 + + +@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.' + 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)], + 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')) + 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 + 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]) +@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(temperature=1., top_p=1., top_k=-1, min_p=0., - repetition_penalty=1., presence_penalty=0., frequency_penalty=0., - seed=58123, max_tokens=64, chat_template_kwargs=dict(reasoning_effort='none')) - if kind == 'text': + 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.' + 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) - function = dict(name='record_value', description='Record the supplied value exactly.', - parameters=dict(type='object', properties=dict(value=dict(type='integer')), - required=['value'], 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) + 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[0]([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' + 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] + assert choice["finish_reason"] == "stop" + if kind == "long": + assert result["usage"]["prompt_tokens"] == LONG_INPUTS[index]