diff --git a/docs/TODO.txt b/docs/TODO.txt index 591053d75..85547d14b 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -194,3 +194,7 @@ 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. + +[ ] Make tests/server/test_muse_glimmer.py pass against an exported Muse Glimmer + package on GB300. Some text, JSON, and tool cases exceed the 64-token output + budget or end without a completed tool call. Close when the suite passes. diff --git a/docs/model-preparation.md b/docs/model-preparation.md index e948c9a2d..fe3e897c6 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1086,9 +1086,40 @@ the canonical control-sequence escaping. flare/target/release/flare run /data/flare-runtime/muse-spark-tp8.safetensors --gpus 0,1,2,3,4,5,6,7 ``` +## Muse Glimmer + +The `muse-glimmer-30b-nvfp4` alias selects +[`nvidia/Muse-Glimmer-30B-NVFP4`](https://huggingface.co/nvidia/Muse-Glimmer-30B-NVFP4) +at revision `47818374517751c48c55cde2621594926b1888b6`. It prepares one GPU with +a 131072-token context, concurrency four and 4096-token prefill chunks. Weights +retain checkpoint NVFP4 W4A16, calibrated FP8 and excluded BF16 precision. +Image, audio and video requests are rejected; no vision encoder or draft is prepared. + +The FlashInfer dependency pinned in `pyproject.toml` provides the required operators; +unlike Muse Spark, no local FlashInfer checkout is needed. +All 52 layers retain BF16 KV; sliding layers use the 2048-token window. +A 128-token KV page occupies 6,815,744 bytes, a continuation row 6,829,312 bytes, +and a full-context KV history 6.5 GiB. The planner budgets the full 24.67 GB +checkpoint, including unused vision tensors, plus scratch and caches. + +Sampling defaults are temperature 1.0, top-p 0.95 and top-k 64. Set +`chat_template_kwargs.reasoning_strength` to override the template's `high` default. +Prompt rendering and output parsing follow [Muse Spark](#muse-spark-open), with +the template patch in `ignition/recipes/muse_glimmer/assets/chat_template.patch.json`. + +```sh +.venv/bin/ignition export muse-glimmer-30b-nvfp4 --gpus 0 --prompt-logprobs +flare/target/release/flare run CACHE_ENTRY --gpus 0 +``` + +Against an exported package on GB300, `tests/server/test_muse_glimmer.py` does not +yet pass: some text, JSON, and tool cases exceed its 64-token output budget or end +without a completed tool call. Full-checkpoint SM120/SM121 preparation and serving +performance have not been measured. + ## Storage and graph capacities -Gemma 4 and Muse Spark default to four concurrent requests. Gemma 4's speculative +Gemma 4, Muse Spark, and Muse Glimmer default to four concurrent requests. Gemma 4's speculative target-token capacity is the larger of padded concurrency and draft count plus one, giving six rows at its default settings. Muse Spark declares 32 packed target-token rows for seven DFlash2 drafts at concurrency four. Other recipes diff --git a/helios/src/output/recipient.rs b/helios/src/output/recipient.rs index 649e404c4..e34d7b54a 100644 --- a/helios/src/output/recipient.rs +++ b/helios/src/output/recipient.rs @@ -5,6 +5,7 @@ //! Recipient headers with internal message boundaries and ATEM function arguments. +use super::xtml::{escape, partial, unescape}; use super::{Event, Input, Termination, tagged::OutputConfig}; use crate::Result; use serde_json::{Map, Value}; @@ -38,19 +39,6 @@ pub struct RecipientOutput { pending_text: String, } -fn escape(text: &str) -> String { - text.replace('&', "&").replace("<|", "<|") -} -fn unescape(text: &str) -> String { - text.replace("<|", "<|").replace("&", "&") -} -fn partial(text: &str, marker: &str) -> usize { - (1..marker.len()) - .rev() - .find(|&n| text.ends_with(&marker[..n])) - .unwrap_or(0) -} - impl RecipientOutput { pub fn new(config: OutputConfig, control_tokens: Vec<(u32, String)>) -> Self { Self { @@ -503,12 +491,24 @@ mod tests { #[test] fn literal_boundary_spellings_do_not_close_content() { - let mut parser = parser(); - parser.state = State::Content; - let text = "Literal <|eom|><|start|>assistant to=self<|message|> text & café"; - let events = parser.push(Input::Text(text)).unwrap(); - assert_eq!(events, vec![Event::Content(text.into())]); - assert_eq!(parser.content_spans(), vec![Some(0..text.len())]); + let text = + "Literal <|eom|><|start|>assistant to=self<|message|> text <|eot|> < & 世界"; + let mut parser = parser_with_start(OutputStart::Content); + let mut actual = String::new(); + for character in text.chars() { + let events = parser.push(Input::Text(&character.to_string())).unwrap(); + for (event, span) in events.into_iter().zip(parser.content_spans()) { + let Event::Content(content) = event else { + panic!("literal spelling changed the output channel"); + }; + assert_eq!(span, Some(actual.len()..actual.len() + content.len())); + actual.push_str(&content); + } + } + assert_eq!(actual, text); + parser.push(Input::Token(4)).unwrap(); + assert!(parser.push(Input::Text(TURN_END)).unwrap().is_empty()); + assert!(parser.finish(Termination::Eos).unwrap().is_empty()); } #[test] diff --git a/helios/src/output/xtml.rs b/helios/src/output/xtml.rs index 32dffc332..79a85f92f 100644 --- a/helios/src/output/xtml.rs +++ b/helios/src/output/xtml.rs @@ -266,15 +266,15 @@ impl XtmlOutput { } } -fn escape(text: &str) -> String { +pub(super) fn escape(text: &str) -> String { text.replace('&', "&").replace('<', "<") } -fn unescape(text: &str) -> String { +pub(super) fn unescape(text: &str) -> String { text.replace("<", "<").replace("&", "&") } -fn partial(text: &str, marker: &str) -> usize { +pub(super) fn partial(text: &str, marker: &str) -> usize { (1..marker.len()) .rev() .find(|&length| text.ends_with(&marker[..length])) diff --git a/helios/src/server/request/recipient_tests.rs b/helios/src/server/request/recipient_tests.rs index 607ceaf5c..1a71f7178 100644 --- a/helios/src/server/request/recipient_tests.rs +++ b/helios/src/server/request/recipient_tests.rs @@ -18,7 +18,58 @@ mod support; #[test] #[ignore = "requires FLARE_MUSE_SPARK_SNAPSHOT checkpoint tokenizer"] fn recipient_request_preparation_preserves_protocols_tools_and_continuation() { - let snapshot = std::path::PathBuf::from(std::env::var_os("FLARE_MUSE_SPARK_SNAPSHOT").unwrap()); + // Tokenizer IDs from meta-models/Muse-Spark-Open-816B-A42B-NVFP4 + // at revision 4239e4db19376904f2e82c167e78f70abb5455fe for the Messages body in recipient_request_preparation. + let expected_tokens = [ + 200000, 200022, 15651, 200023, 4662, 583, 262, 19933, 12133, 43910, 1574, 111198, 67059, + 38, 220, 837, 34, 25, 1761, 25, 2468, 1574, 8048, 4282, 38, 220, 837, 34, 25, 580, 25, + 1704, 1574, 34956, 300, 9762, 38, 220, 36, 1574, 7533, 290, 10116, 41712, 393, 1789, 3623, + 4568, 25, 392, 2540, 1217, 1566, 35538, 341, 7935, 14479, 335, 25, 392, 13929, 811, 1217, + 1941, 130639, 26001, 18870, 2467, 290, 43910, 917, 6639, 6050, 24, 4414, 12485, 4298, 328, + 290, 1941, 3020, 537, 1867, 7935, 13915, 335, 25, 392, 1556, 1217, 12485, 511, 1352, 290, + 43910, 4651, 24, 2203, 486, 262, 13544, 3495, 537, 113026, 4097, 511, 110118, 393, 290, + 46103, 22383, 39, 641, 702, 1161, 393, 853, 55985, 18870, 537, 10453, 20276, 1574, 15, + 14757, 73965, 38, 392, 2540, 706, 392, 13929, 811, 706, 392, 1556, 4205, 200008, 200022, + 1556, 200023, 33692, 517, 1809, 198964, 4872, 132753, 26, 200008, 200022, 140680, + ]; + recipient_request_preparation( + "muse_spark", + "FLARE_MUSE_SPARK_SNAPSHOT", + "reasoning_effort", + "Reasoning strength: 8.", + &expected_tokens, + ); +} + +#[test] +#[ignore = "requires FLARE_MUSE_GLIMMER_SNAPSHOT checkpoint tokenizer"] +fn glimmer_request_preparation_preserves_protocols_tools_and_continuation() { + // Tokenizer IDs from nvidia/Muse-Glimmer-30B-NVFP4 + // at revision 47818374517751c48c55cde2621594926b1888b6 for the Messages body in recipient_request_preparation. + let expected_tokens = [ + 200000, 200022, 15651, 200023, 4662, 583, 262, 19933, 12133, 43910, 335, 111198, 67059, 38, + 220, 837, 34, 25, 1761, 25, 2468, 335, 8048, 4282, 38, 220, 837, 34, 25, 580, 25, 1704, + 1574, 34956, 300, 9762, 38, 4463, 1574, 15, 14757, 73965, 38, 392, 2540, 706, 392, 1556, + 4205, 200008, 200022, 1556, 200023, 33692, 517, 1809, 198964, 4872, 132753, 26, 200008, + 200022, 140680, + ]; + recipient_request_preparation( + "muse_glimmer", + "FLARE_MUSE_GLIMMER_SNAPSHOT", + "reasoning_strength", + "Reasoning strength: low.", + &expected_tokens, + ); +} + +fn recipient_request_preparation( + recipe: &str, + snapshot_variable: &str, + reasoning_option: &str, + reasoning_line: &str, + expected_tokens: &[u32], +) { + let snapshot = std::path::PathBuf::from(std::env::var_os(snapshot_variable).unwrap()); let asset = |path: std::path::PathBuf| { let bytes = std::fs::read(&path).unwrap(); Asset { @@ -34,9 +85,10 @@ fn recipient_request_preparation_preserves_protocols_tools_and_continuation() { snapshot.join("tokenizer_config.json"), )) .unwrap(), - chat_template: Some(asset( - crate::template_fixtures::path("muse_spark", "chat_template"), - )), + chat_template: Some(asset(crate::template_fixtures::path( + recipe, + "chat_template", + ))), }, json!({"add_generation_prompt":true,"current_date":"2026-10-27"}) .as_object() @@ -99,7 +151,7 @@ fn recipient_request_preparation_preserves_protocols_tools_and_continuation() { "messages":[{"role":"user","content":"Reply with only PROTOCOL-MESSAGES."}], "model":"Muse-Spark-Open-816B-A42B", "temperature":1,"top_p":1,"top_k":-1, - "chat_template_kwargs":{"reasoning_effort":"low","current_date":"2026-10-27"} + "chat_template_kwargs":{reasoning_option:"low","current_date":"2026-10-27"} }); let decoded = decode(Protocol::Messages, messages_body.clone(), false).unwrap(); let crate::server::inference::Input::Conversation(messages) = &decoded.request.input else { @@ -126,29 +178,15 @@ fn recipient_request_preparation_preserves_protocols_tools_and_continuation() { false, ) .unwrap(); - // Tokenizer IDs from meta-models/Muse-Spark-Open-816B-A42B-NVFP4 - // at revision 4239e4db19376904f2e82c167e78f70abb5455fe for the Messages body above. - let expected_tokens = [ - 200000, 200022, 15651, 200023, 4662, 583, 262, 19933, 12133, 43910, 1574, 111198, 67059, - 38, 220, 837, 34, 25, 1761, 25, 2468, 1574, 8048, 4282, 38, 220, 837, 34, 25, 580, 25, - 1704, 1574, 34956, 300, 9762, 38, 220, 36, 1574, 7533, 290, 10116, 41712, 393, 1789, 3623, - 4568, 25, 392, 2540, 1217, 1566, 35538, 341, 7935, 14479, 335, 25, 392, 13929, 811, 1217, - 1941, 130639, 26001, 18870, 2467, 290, 43910, 917, 6639, 6050, 24, 4414, 12485, 4298, 328, - 290, 1941, 3020, 537, 1867, 7935, 13915, 335, 25, 392, 1556, 1217, 12485, 511, 1352, 290, - 43910, 4651, 24, 2203, 486, 262, 13544, 3495, 537, 113026, 4097, 511, 110118, 393, 290, - 46103, 22383, 39, 641, 702, 1161, 393, 853, 55985, 18870, 537, 10453, 20276, 1574, 15, - 14757, 73965, 38, 392, 2540, 706, 392, 13929, 811, 706, 392, 1556, 4205, 200008, 200022, - 1556, 200023, 33692, 517, 1809, 198964, 4872, 132753, 26, 200008, 200022, 140680, - ]; - assert_eq!(request.prompt.tokens.as_slice(), &expected_tokens); + assert_eq!(request.prompt.tokens.as_slice(), expected_tokens); assert_eq!(request.prompt.max_new_tokens, 2048); - assert!(request.rendered_prompt.contains("Reasoning strength: 8.")); + assert!(request.rendered_prompt.contains(reasoning_line)); assert!( request .rendered_prompt .ends_with("Reply with only PROTOCOL-MESSAGES.<|eot|><|start|>assistant") ); - let tools = json!([{"type":"function","function":{"name":"lookup","parameters":{"type":"object","properties":{"query":{"type":"string"}}}}}]); + let tools = json!([{"type":"function","function":{"name":"lookup","description":"Look up a value","parameters":{"type":"object","properties":{"query":{"type":"string"}}}}}]); for choice in [ json!("none"), json!("auto"), diff --git a/ignition/components/gated_delta.py b/ignition/components/gated_delta.py index 01e55a571..3a14bfc13 100644 --- a/ignition/components/gated_delta.py +++ b/ignition/components/gated_delta.py @@ -281,7 +281,8 @@ def projection(key, inputs, output): weight = projections[key] options = dict(session=session, name=f"{name}.{key}") if isinstance(weight, TensorFP8Weight): - return TensorFP8Projection(inputs, weight, output, staging=projection_staging, **options) + return TensorFP8Projection(inputs, weight, output, staging=projection_staging, + workspace=projection_workspace, **options) if isinstance(weight, torch.Tensor): return UnquantizedProjection(inputs, weight, output, **options) return QuantizedProjection(inputs, weight, output, activation_mode="auto", diff --git a/ignition/components/linear.py b/ignition/components/linear.py index fc3701154..0fd7b1c25 100644 --- a/ignition/components/linear.py +++ b/ignition/components/linear.py @@ -22,18 +22,24 @@ from ignition.preparation.tuning import benchmark_resource, declare, register_context_plan, register_finalizer -def prepare_projection(source, weight, output, *, session, name, workspace, activation_mode="auto", staging=None): +def prepare_projection(source, weight, output, *, session, name, workspace, activation_mode="auto", staging=None, + quantized_staging=None): """Bind a projection without changing its checkpoint weight representation.""" from .block_fp8 import BlockFP8Projection, BlockFP8Weight + from .tensor_fp8 import TensorFP8Projection, TensorFP8Weight from .weights import GroupedLinearWeights if isinstance(weight, GroupedLinearWeights): return PreparedProjectionGroup(source, weight, output, session=session, name=name, workspace=workspace, - activation_mode=activation_mode, staging=staging) + activation_mode=activation_mode, staging=staging, + quantized_staging=quantized_staging) if isinstance(weight, torch.Tensor): return UnquantizedProjection(source, weight, output, session=session, name=name) if isinstance(weight, BlockFP8Weight): return BlockFP8Projection(source, weight, output, session=session, name=name) + if isinstance(weight, TensorFP8Weight): + return TensorFP8Projection(source, weight, output, session=session, name=name, staging=quantized_staging, + workspace=workspace) return QuantizedProjection(source, weight, output, session=session, name=name, workspace=workspace, activation_mode=activation_mode) @@ -41,20 +47,23 @@ def prepare_projection(source, weight, output, *, session, name, workspace, acti class PreparedProjectionGroup: """Project one source into ordered output slices with compatible weights fused.""" - def __init__(self, source, weight, output, *, session, name, workspace, activation_mode, staging): + def __init__(self, source, weight, output, *, session, name, workspace, activation_mode, staging, + quantized_staging): from .block_fp8 import BlockFP8Weight + from .tensor_fp8 import TensorFP8Weight self.output = output self.projections, self.copies = [], [] for index, (part, target) in enumerate(zip(weight.parts, output.split(weight.widths, dim=-1), strict=True)): destination = target - if not isinstance(part, (torch.Tensor, BlockFP8Weight)) and not target.is_contiguous(): + if not isinstance(part, (torch.Tensor, BlockFP8Weight, TensorFP8Weight)) and not target.is_contiguous(): if (staging is None or not staging.is_contiguous() or staging.numel() < target.numel() or staging.dtype != target.dtype or staging.device != target.device): raise ValueError("mixed packed projections require caller-owned contiguous staging") destination = staging.view(-1)[:target.numel()].view(target.shape) self.projections.append(prepare_projection(source, part, destination, session=session, - name=f"{name}.part{index}", workspace=workspace, activation_mode=activation_mode)) + name=f"{name}.part{index}", workspace=workspace, activation_mode=activation_mode, + quantized_staging=quantized_staging)) self.copies.append(None if destination is target else target) self.plans = tuple(projection.plan for projection in self.projections) diff --git a/ignition/components/tensor_fp8.py b/ignition/components/tensor_fp8.py index 10da92b9f..3a6bbf892 100644 --- a/ignition/components/tensor_fp8.py +++ b/ignition/components/tensor_fp8.py @@ -10,7 +10,10 @@ from b12x.preparation import PreparedCall from ignition.preparation.tensor_metadata import record_numeric_tensor -from ignition.preparation.tuning import benchmark_resource, declare +from ignition.preparation.scratch import prime_owners, scratch_storage +from ignition.preparation.tuning import benchmark_resource, declare, register_finalizer + +from .sm103 import is_sm103 @dataclass(frozen=True) @@ -18,9 +21,13 @@ class TensorFP8Weight: packed: object input_scale: torch.Tensor + @property + def out_features(self): + return self.packed.out_features + class TensorFP8Projection: - def __init__(self, source, weight, output, *, session, name, staging=None): + def __init__(self, source, weight, output, *, session, name, staging=None, workspace=None): if (source.ndim != 2 or source.dtype != torch.bfloat16 or source.shape[1] != weight.packed.in_features or output.shape != (source.shape[0], weight.packed.out_features) @@ -37,6 +44,39 @@ def __init__(self, source, weight, output, *, session, name, staging=None): or not staging.is_contiguous() or staging.numel() < source.numel()): raise ValueError("tensor-FP8 staging requires sufficient contiguous device bytes") self.quantized = staging.flatten()[:source.numel()].view(torch.float8_e4m3fn).view(source.shape) + self.sm103 = is_sm103(source.device) + if self.sm103: + from .tensor_fp8_sm103 import plan + + self.plan = plan(source.shape[0], weight.packed, source.device) + + def storage(): + return scratch_storage(workspace, nbytes=self.plan.memory_requirements().scratch_nbytes, + device=source.device) + + def prepare_native(state): + self.quantized.zero_() + scratch = storage() + return PreparedCall(run=lambda: state.run(self.quantized, weight.packed.values, + weight.packed.output_scale, output, scratch), + owners=(self.quantized, weight, output, *prime_owners(workspace, scratch))) + + def benchmark_native(state): + def make_inputs(): + seed = torch.randn(source.shape, device=source.device).clamp(-4, 4).to(torch.float8_e4m3fn) + return torch.empty_like(seed), seed, torch.empty_like(output) + + inputs, seed, result = benchmark_resource(session, ("tensor_fp8", name), make_inputs) + scratch = storage() + return PreparedCall(run=lambda: state.run(inputs, weight.packed.values, + weight.packed.output_scale, result, scratch), output=result, + produce=lambda: inputs.copy_(seed), + owners=(inputs, seed, weight, result, *prime_owners(workspace, scratch))) + + declare(session, (self.plan.request(name=name, prepare_call=prepare_native, + benchmark_call=benchmark_native),)) + register_finalizer(session, lambda: setattr(self, "workspace", storage()), workspace=workspace) + return self.plan = blockscaled.plan(blockscaled.query_from_call(self.quantized, weight.packed)) def prepare(state): @@ -58,5 +98,9 @@ def benchmark(state): def __call__(self, source): self.quantized.copy_((source.float() / self.weight.input_scale).clamp(-448, 448)) + if self.sm103: + torch.ops.flare.sm103_tensor_fp8_out(self.quantized, self.weight.packed.values, + self.weight.packed.output_scale, self.output, self.workspace, self.plan.handle) + return self.output self.output.copy_(blockscaled.mm(self.quantized, self.weight.packed, plan=self.plan)) return self.output diff --git a/ignition/components/tensor_fp8_sm103.py b/ignition/components/tensor_fp8_sm103.py new file mode 100644 index 000000000..175a53c3e --- /dev/null +++ b/ignition/components/tensor_fp8_sm103.py @@ -0,0 +1,92 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""SM103 tensor-FP8 GEMMs with original E4M3 values and FP32 output calibration.""" + +from dataclasses import dataclass + +import torch +from b12x.preparation import plan_from_handle, require_prepared + +from .native_operator import native_contract, native_plan + +COMPONENT = "flare.sm103.tensor_fp8_projection" +# The pinned CUTLASS getConfigs enumerates six CTA tiles and five cluster shapes. +_TACTICS = tuple(range(6 * 5)) + + +@dataclass(frozen=True) +class TensorFP8Query: + rows: int + in_features: int + padded_in_features: int + out_features: int + + +def _runner(): + from flashinfer.gemm.gemm_base import get_gemm_sm100_module_cutlass_fp8 + + return get_gemm_sm100_module_cutlass_fp8().cutlass_fp8_gemm_runner() + + +CONTRACT = native_contract(component_id=COMPONENT, query_type=TensorFP8Query, tactics=lambda query: _TACTICS) + + +def _layout(query): + from flashinfer.gemm.gemm_base import DEFAULT_WORKSPACE_SIZE + + output = 256 + DEFAULT_WORKSPACE_SIZE + padded = (output + query.rows * query.out_features * 2 + 255) // 256 * 256 + size = padded + (query.rows * query.padded_in_features + if query.in_features != query.padded_in_features else 0) + return output, padded, size + + +class PreparedTensorFP8: + def __init__(self, query, tactic): + self.query, self.tactic, self.runner = query, tactic, _runner() + if tuple(self.runner.get_valid_tactics([], None)) != _TACTICS: + raise RuntimeError("FlashInfer tensor-FP8 tactics differ from the declared CUTLASS catalog") + self.required_workspace = _layout(query)[2] + + def run(self, source, weight, scale, output, workspace): + q = self.query + output_offset, padded_offset, _ = _layout(q) + unit = workspace[:4].view(torch.float32) + unit.fill_(1) + if q.in_features != q.padded_in_features: + padded = workspace[padded_offset:padded_offset + q.rows * q.padded_in_features] + padded = padded.view(torch.float8_e4m3fn).view(q.rows, q.padded_in_features) + padded.zero_() + padded[:, :q.in_features].copy_(source) + source = padded + result = workspace[output_offset:output_offset + q.rows * q.out_features * 2] + result = result.view(torch.bfloat16).view(q.rows, q.out_features) + # Preserve the already-rounded combined scale; multiplying by one is exact. + self.runner(inputs=[source, weight.T, scale, unit, result, workspace[256:output_offset]], + tactic=self.tactic) + output.copy_(result) + return output + + +def plan(rows, weight, device): + query = TensorFP8Query(rows, weight.in_features, weight.padded_in_features, weight.out_features) + if (rows <= 0 or query.in_features <= 0 or query.in_features % 32 + or query.padded_in_features % 128 or query.in_features > query.padded_in_features + or query.out_features <= 0 or query.out_features % 8): + raise ValueError("SM103 tensor-FP8 GEMMs require positive rows, K32 with stored K128, and N8") + return native_plan(contract=CONTRACT, query=query, device=device, + scratch_bytes=lambda tactic: _layout(query)[2], + materialize=lambda tactic: PreparedTensorFP8(query, tactic)) + + +@torch.library.custom_op("flare::sm103_tensor_fp8_out", mutates_args=("output", "workspace")) +def project(source: torch.Tensor, weight: torch.Tensor, scale: torch.Tensor, + output: torch.Tensor, workspace: torch.Tensor, handle: int) -> None: + require_prepared(plan_from_handle(handle), COMPONENT, source.device).run( + source, weight, scale, output, workspace) + + +@project.register_fake +def _fake_project(source, weight, scale, output, workspace, handle): + pass diff --git a/ignition/recipes/__init__.py b/ignition/recipes/__init__.py index 1364eae62..77135a992 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 .muse_glimmer.recipe import RECIPE as muse_glimmer - 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, muse_glimmer def snapshot_directory(hub_cache: Path, checkpoint: Checkpoint) -> Path: diff --git a/ignition/recipes/gemma4/attention.py b/ignition/recipes/gemma4/attention.py index f603856d8..c5fb928b5 100644 --- a/ignition/recipes/gemma4/attention.py +++ b/ignition/recipes/gemma4/attention.py @@ -17,7 +17,7 @@ def prepare_projection(source, weight, output, *, session, name, workspace=None) if isinstance(weight, torch.Tensor): return UnquantizedProjection(source, weight, output, session=session, name=name) if isinstance(weight, TensorFP8Weight): - return TensorFP8Projection(source, weight, output, session=session, name=name) + return TensorFP8Projection(source, weight, output, session=session, name=name, workspace=workspace) return QuantizedProjection( source, weight, output, activation_mode="auto", session=session, workspace=workspace, name=name ) diff --git a/ignition/recipes/muse_glimmer/__init__.py b/ignition/recipes/muse_glimmer/__init__.py new file mode 100644 index 000000000..22538ef5c --- /dev/null +++ b/ignition/recipes/muse_glimmer/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Muse Glimmer text preparation.""" diff --git a/ignition/recipes/muse_glimmer/assets/chat_template.patch.json b/ignition/recipes/muse_glimmer/assets/chat_template.patch.json new file mode 100644 index 000000000..75cf3aa54 --- /dev/null +++ b/ignition/recipes/muse_glimmer/assets/chat_template.patch.json @@ -0,0 +1,13 @@ +{ + "source": { + "repository": "nvidia/Muse-Glimmer-30B-NVFP4", + "revision": "47818374517751c48c55cde2621594926b1888b6", + "filename": "chat_template.jinja" + }, + "source_sha256": "114f55ebdc1804c1af371197b9fdf2d6bb925966c9dfe46b73782a71bc07965e", + "result_sha256": "b916c7e78dc1dbf41f57fe12b8ee0cc59d3d75c19ff316dd424e8e550fd8a7f3", + "insertions": [ + 4977, + 7080 + ] +} diff --git a/ignition/recipes/muse_glimmer/attention.py b/ignition/recipes/muse_glimmer/attention.py new file mode 100644 index 000000000..ddd148397 --- /dev/null +++ b/ignition/recipes/muse_glimmer/attention.py @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Canonical normalized, rotary, gated attention over BF16 paged histories.""" + +from dataclasses import dataclass +import torch +from transformers.models.muse_glimmer.modeling_muse_glimmer import apply_rotary_pos_emb + +from ignition.components.linear import prepare_projection +from ignition.components.paged_attention import PreparedPagedAttention, PreparedPagedKVWriter +from .model import norm + + +@dataclass(frozen=True) +class AttentionScratch: + projected: torch.Tensor + staging: torch.Tensor + quantized: torch.Tensor + query: torch.Tensor + key: torch.Tensor + value: torch.Tensor + attended: torch.Tensor + gated: torch.Tensor + output: torch.Tensor + + @classmethod + def allocate(cls, config, tokens, device, *, buffers=None): + c = config.text + heads, kv, dim = c["num_attention_heads"], c["num_key_value_heads"], c["head_dim"] + def zeros(*shape, dtype=torch.bfloat16): + return (torch.zeros(shape, dtype=dtype, device=device) if buffers is None + else buffers.zeros(shape, dtype)) + return cls(zeros(tokens, 2 * (heads + kv) * dim), zeros(tokens, heads * dim), + zeros(tokens, max(config.hidden, heads * dim), dtype=torch.uint8), + zeros(tokens, heads, dim), zeros(tokens, kv, dim), zeros(tokens, kv, dim), + zeros(tokens, heads, dim), zeros(tokens, heads, dim), zeros(tokens, config.hidden)) + + def rows(self, tokens): + return type(self)(*(getattr(self, name)[:tokens] for name in self.__dataclass_fields__)) + + +class PreparedAttention(torch.nn.Module): + def __init__(self, layer, weights, config, source, scratch, metadata, pool, *, mode, + session, name, workspace, cache_metadata): + super().__init__() + if mode not in ("prefill", "decode"): + raise ValueError(f"unsupported Muse Glimmer attention mode: {mode}") + self.scratch, self.metadata = scratch, metadata + c = config.text + self.projection = prepare_projection(source, weights.qkv, scratch.projected, + session=session, name=name + ".qkv_gate", workspace=workspace, staging=scratch.staging, + quantized_staging=scratch.quantized) + self.output_projection = prepare_projection(scratch.gated.flatten(1), weights.output, scratch.output, + session=session, name=name + ".output", workspace=workspace, quantized_staging=scratch.quantized) + self.qk_norm = norm("rms", eps=c["rms_norm_eps"]) + self.query_factor, self.theta = c["qk_scale_factor"], c["layer_rope_theta"][layer] + dim = c["head_dim"] + self.inverse = (1. / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32, + device=source.device) / dim)) if self.theta else torch.empty(0, device=source.device)) + key, value = pool.cache(layer, "key"), pool.cache(layer, "value") + self.writer = PreparedPagedKVWriter(scratch.key, scratch.value, key, value, cache_metadata.slots, + session=session, name=name + ".cache_write") + self.attention = PreparedPagedAttention(scratch.query, key, value, metadata.page_table, cache_metadata.lengths, + metadata.query_start_loc, scratch.attended, mode=mode, window=config.window(layer), + tuning_page_count=int(pool.memory_capacity[1].item()), width=1, + session=session, workspace=workspace, name=name + ".attention") + + def forward(self, hidden_states, **kwargs): + s, m = self.scratch, self.metadata + projected = self.projection(hidden_states.reshape(-1, hidden_states.shape[-1])) + qdim, kvdim = s.query.shape[1] * s.query.shape[2], s.key.shape[1] * s.key.shape[2] + q, k, v, gate = projected.split((qdim, kvdim, kvdim, qdim), -1) + q = self.qk_norm(q.view_as(s.query)) * self.query_factor + k = self.qk_norm(k.view_as(s.key)) + if self.theta: + frequencies = m.positions.clamp_min(0).float()[:, None] * self.inverse[None] + angles = torch.cat((frequencies, frequencies), -1) + cos, sin = angles.cos().bfloat16(), angles.sin().bfloat16() + q, k = apply_rotary_pos_emb(q, k, cos, sin) + s.query.copy_(q) + s.key.copy_(k) + s.value.copy_(v.view_as(s.value)) + self.writer() + self.attention() + s.gated.copy_(s.attended * torch.sigmoid(gate.view_as(s.gated))) + return self.output_projection(s.gated.flatten(1)).view_as(hidden_states), None diff --git a/ignition/recipes/muse_glimmer/bootstrap.py b/ignition/recipes/muse_glimmer/bootstrap.py new file mode 100644 index 000000000..09381d0c7 --- /dev/null +++ b/ignition/recipes/muse_glimmer/bootstrap.py @@ -0,0 +1,228 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepare single-GPU Muse Glimmer text graphs.""" + +import contextlib +from dataclasses import dataclass +import hashlib +import json +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.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.disposable import storage_ranges +from ignition.preparation.execution import GraphSignature +from ignition.preparation.fixtures.recurrent import register_benchmark_state +from ignition.preparation.host_memory import release_unused +from ignition.preparation.model import PreparedModel +from ignition.preparation.rebuild_manifest import declare_weights +from ignition.preparation.scratch import GraphBufferPool, ScratchArena +from ignition.preparation.tuning import RecordedPreparationSession, with_autotune_effort +from ignition.preparation.tuning_replicas import TuningReplica +from ignition.progress import phase +from .contract import prepare as prepare_contract +from .decoder import PreparedDecoder, 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 + device: int = 0 + context: int = 131072 + prefill_chunk_size: int = 4096 + max_active: int = 4 + snapshot_budget_bytes: int = 1 << 30 + headroom_bytes: int = 4 << 30 + compile_decoder: bool = True + retain_graphs: bool = False + kernel_cache: Path | None = None + + def __post_init__(self): + request_capacity(self.max_active) + if not PAGE_TOKENS <= self.context <= 131072 or self.context % PAGE_TOKENS: + raise ValueError("Muse Glimmer context must be 128-aligned in [128,131072]") + if not 128 <= self.prefill_chunk_size <= self.context or self.prefill_chunk_size % 128: + raise ValueError("Muse Glimmer prefill chunk must be 128-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") + if self.native_dense_activations: + raise ValueError("Muse Glimmer W4A16 projections require BF16 activations") + + +@torch.no_grad() +@with_autotune_effort +def prepare(snapshot, config, *, progress=None, package_storage): + from .recipe import RECIPE + + snapshot = Path(snapshot).resolve() + device = torch.device("cuda", config.device) + 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, progress=progress, package_storage=package_storage) + del manifest + release_unused() + if config.context > weights.config.text["max_position_embeddings"]: + raise ValueError("prepared context exceeds the checkpoint context") + transient = contextlib.ExitStack() + transient.enter_context(package_storage.transient()) + layout = continuation_layout(weights.config) + snapshots = layout.snapshot_capacity(config.snapshot_budget_bytes) + if snapshots < 1: + raise ValueError("snapshot budget must hold a complete Muse Glimmer continuation") + slots, blocks = request_capacity(config.max_active), config.context // PAGE_TOKENS + state_rows, pages = slots + snapshots, config.prefill_chunk_size // PAGE_TOKENS + 2 * slots + total_memory = torch.cuda.mem_get_info(device)[1] + with phase(progress, "Allocate model state"): + pool = ContinuationPool.allocate(weights.config, state_rows + 1, pages, device, + storage=package_storage, maximum_pages=total_memory // page_bytes(weights.config), + 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(max(config.prefill_chunk_size, slots), 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) + identity = hashlib.sha256(json.dumps(dict(config=weights.config.text, headers=headers, + kv_dtype="bfloat16", contract="muse-glimmer.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="muse_glimmer", numerical_policy="default", + coordinator=None, headroom_bytes=config.headroom_bytes, benchmark_storage=package_storage) + session.__enter__() + register_benchmark_state(session, pool.reserved_backing, storage=pool.reserved_backing, + restore=pool.clear_for_preparation) + arena = ScratchArena(device) + 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, config.prefill_chunk_size, 1, device, + buffers=graph_buffers.cursor()) + decode_storage = Scratch.allocate(weights.config, slots, slots, device, buffers=graph_buffers.cursor()) + buffers = dict(inputs.buffers(), **commands.buffers(), + **{name: getattr(admission, name) for name in admission.__dataclass_fields__}, + state_pool=pool.backing, memory_capacity=pool.memory_capacity, request_pending_token=requests.pending_token, + sampling_grammar_mask=requests.grammar_mask, frame_index=frame, submission_sequence=sequence, + **completion.buffers()) + scoring = PromptScoring.allocate(config, device, buffers, frame=frame) + forwards, signatures, metadata = {}, {}, {} + prefills, batches = prefill_capacities(config.prefill_chunk_size), batch_capacities(config.max_active) + with phase(progress, "Construct graph catalog"): + def add(name, forward, kind, rows, tokens, fields): + if kind == "scored_prefill": + forward = PreparedScoredPrefill(forward, requests, inputs) + fields = (*fields, "prompt_target_tokens") + forwards[name] = forward + signatures[name] = GraphSignature(kind, rows, tokens, tuple(fields), speculation_enabled=False) + + 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, + session=session, name=name, workspace=arena, buffers=private, + scoring=scoring if kind == "scored_prefill" else None) + batch = PreparedBatch(inputs, requests, m, mode=mode, shard=weights.shard, pool=pool, buffers=private) + forward = PreparedGeneration(decoder, batch, completion, frame, sequence, + runtime=None, coordinator=None, session=session, name=name + ".generation", + workspace=arena, buffers=private) + add(name, forward, kind, rows, capacity if mode == "prefill" else 1, forward_inputs) + row_inputs = ("request_state_rows", "row_slot_ids", "row_generations", "live_rows") + for capacity in reversed(batches): + name = f"resume{capacity}" + forward = PreparedResume(weights, requests, pool, inputs, completion, frame, sequence, + rows=capacity, runtime=None, vocabulary_runtime=None, coordinator=None, + session=session, name=name, buffers=private_buffers.cursor()) + add(name, forward, "resume", capacity, 1, (*row_inputs, "sampling_grammar_mask")) + for mode in ("init", "restore", "snapshot"): + name = f"{mode}{capacity}" + forward = PreparedMaintenance(mode, requests, pool, commands, inputs, completion, frame, sequence, + runtime=None, coordinator=None, session=session, name=name, capacity=capacity, + admission_buffers=admission, draft_state=False, buffers=private_buffers.cursor()) + fields = row_inputs if mode == "snapshot" else ("request_state_rows", *admission.__dataclass_fields__) + add(name, forward, mode, capacity, 1, (*fields, "page_tables", *commands.buffers())) + with phase(progress, "Prepare and tune kernels") as stage, transient: + tuning = session.tune(show_progress=progress is not None, console=stage.console) + stream, graph_pool = torch.cuda.Stream(device=device), package_storage.graph_pool.id + if config.compile_decoder: + scratch_pool.release_backing() + + def materialize(): + scratch_pool.materialize() + pool.clear_for_preparation() + + try: + graphs, compiled = capture_forwards(forwards, signatures, session=session, device=device, stream=stream, + pool=graph_pool, collective=None, coordinator=None, 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() + 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=prepare_frontend(snapshot, eos_token_ids=weights.config.text["eos_token_id"]), + sampling_defaults=RECIPE.sampling_defaults.as_dict(), assets=runtime_assets(snapshot), + model_contract=prepare_contract(signatures, buffers, pool, vocabulary=vocabulary)) + free, total = torch.cuda.mem_get_info(device) + memory = dict(rank=0, world_size=1, device=config.device, weights_bytes=weights.allocated_bytes, + mapped_host_bytes=0, offloaded_bytes=0, continuation_bytes=pool.backing.nbytes, state_rows=state_rows, + preparation_state_rows=int(pool.memory_capacity[0].item()), + preparation_state_bytes=int(pool.memory_capacity[0].item()) * layout.row_bytes, + pages=pages, page_bytes=page_bytes(weights.config), page_tokens=PAGE_TOKENS, + kv_bytes=pages * page_bytes(weights.config), kv_dtype="bfloat16", completion_output_bytes=completion.nbytes, + operator_scratch_bytes=arena.nbytes, graphs=len(graphs), graph_buffer_bytes=graph_buffers.nbytes, + private_buffer_bytes=private_buffers.nbytes, prefill_capacities=prefills, free_device_bytes=free, + total_device_bytes=total, headroom_bytes=config.headroom_bytes, tuning=tuning, compiled_decoder=config.compile_decoder) + if scoring is not None: + memory.update(scoring.memory_report()) + disposable = [prefill_storage, decode_storage, arena.tensor, metadata, graph_buffers.chunks, private_buffers.chunks] + for forward in forwards.values(): + if isinstance(forward, PreparedScoredPrefill): + forward = forward.forward + if hasattr(forward, "scratch_tensors"): + disposable.append(forward.scratch_tensors()) + if hasattr(forward, "completion") and hasattr(forward.completion, "scratch_tensors"): + disposable.append(forward.completion.scratch_tensors) + if hasattr(forward, "decoder"): + disposable.append(forward.decoder.scratch_tensors()) + return PreparedModel(rebuild_weights=declare_weights(weights, components=("embedding", "norm", "head")), + device=config.device, graphs=graphs, buffers=buffers, signatures=signatures, max_active=config.max_active, + session=session, server_config=server_config, memory_report=memory, + export_zero_ranges=(*(() if scoring is None else scoring.zero_ranges()), *storage_ranges(disposable), *completion.zero_ranges()), + resources=(scoring, weights, pool, requests, inputs, admission, commands, arena, forwards, prefill_storage, + decode_storage, metadata, compiled, stream, graph_pool, session, scratch_pool, graph_buffers, private_buffers), + close_resources=(() if scoring is None else (scoring,))) diff --git a/ignition/recipes/muse_glimmer/config.py b/ignition/recipes/muse_glimmer/config.py new file mode 100644 index 000000000..dac9b4799 --- /dev/null +++ b/ignition/recipes/muse_glimmer/config.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Checkpoint geometry and per-projection precision.""" + +from dataclasses import dataclass +import json +from pathlib import Path + +from ignition.preparation.quantization import linear_format, quantized_layers + + +@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())) + + @classmethod + def from_dict(cls, config): + if (config.get("model_type") != "muse_glimmer" + or config.get("architectures") != ["MuseGlimmerForConditionalGeneration"]): + raise ValueError("Muse Glimmer requires MuseGlimmerForConditionalGeneration") + c, q = config["text_config"], quantized_layers(config) + if (c.get("model_type") != "muse_glimmer_text" or c.get("hidden_activation") != "silu" + or c.get("attention_bias") or c.get("tie_word_embeddings")): + raise ValueError("unsupported Muse Glimmer projection arithmetic") + for name in ("hidden_size", "intermediate_size", "num_hidden_layers", "vocab_size", + "num_attention_heads", "num_key_value_heads", "head_dim", "sliding_window"): + if type(c[name]) is not int or c[name] <= 0: + raise ValueError(f"{name} must be a positive integer") + if (c["num_attention_heads"] % c["num_key_value_heads"] or c["head_dim"] != 128 + or c.get("rope_parameters", {}).get("rope_type") != "default"): + raise ValueError("unsupported Muse Glimmer attention geometry") + if any(len(c[name]) != c["num_hidden_layers"] for name in ("layer_types", "layer_rope_theta")): + raise ValueError("attention types and RoPE must describe every decoder layer") + if any(v not in ("sliding_attention", "full_attention") for v in c["layer_types"]): + raise ValueError("unsupported Muse Glimmer attention type") + if any(theta < 0 for theta in c["layer_rope_theta"]): + raise ValueError("layer RoPE theta must be nonnegative") + if any(c[name] <= 0 for name in ("rms_norm_eps", "post_norm_eps", "qk_scale_factor", + "output_multiplier", "final_logit_softcapping")): + raise ValueError("normalization and output scales must be positive") + for prefix in ("lm_head", *(f"model.language_model.layers.{i}.{part}" for i in range(c["num_hidden_layers"]) + for part in ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.gate_proj", + "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"))): + if prefix in q and linear_format(q, prefix) not in ("nvfp4", "tensor_fp8"): + raise ValueError(f"{prefix}: expected NVFP4 or calibrated FP8") + if q["lm_head"]["quant_algo"] != "W4A16_NVFP4": + raise ValueError("Muse Glimmer requires an NVFP4 A16 vocabulary projection") + return cls(c, q) + + @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["vocab_size"] + + def window(self, layer): + return self.text["sliding_window"] - 1 if self.text["layer_types"][layer] == "sliding_attention" else -1 diff --git a/ignition/recipes/muse_glimmer/contract.py b/ignition/recipes/muse_glimmer/contract.py new file mode 100644 index 000000000..cf6c19576 --- /dev/null +++ b/ignition/recipes/muse_glimmer/contract.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Text graph bindings and complete paged attention continuations.""" + +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()}} + if "decode" in inputs: + inputs["decode"].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/muse_glimmer/decoder.py b/ignition/recipes/muse_glimmer/decoder.py new file mode 100644 index 000000000..4f6050ad4 --- /dev/null +++ b/ignition/recipes/muse_glimmer/decoder.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prepared decoder with centered norms and softcapped logits.""" + +from dataclasses import dataclass +import torch + +from ignition.components.embedding import PreparedEmbedding +from ignition.components.linear import prepare_projection +from ignition.components.paged_attention import PagedAttentionMetadata +from ignition.components.paged_resume import PreparedResume as _PreparedResume +from ignition.components.vocabulary import PreparedVocabularyProjection +from .attention import AttentionScratch, PreparedAttention +from .model import decoder_layer, norm +from .pool import PAGE_TOKENS + + +@dataclass(frozen=True) +class Scratch: + embedding: torch.Tensor + normalized: torch.Tensor + attention: AttentionScratch + gate_up: torch.Tensor + staging: torch.Tensor + quantized: torch.Tensor + activated: torch.Tensor + output: torch.Tensor + hidden: torch.Tensor + local_logits: torch.Tensor + logits: torch.Tensor + + @classmethod + def allocate(cls, config, tokens, samples, device, *, buffers): + def zeros(*shape): + return buffers.zeros(shape, torch.bfloat16) + inter = config.text["intermediate_size"] + embedding, normalized = zeros(tokens, config.hidden), zeros(tokens, config.hidden) + root = buffers + attn, mlp = buffers.fork(), buffers.fork() + attention = AttentionScratch.allocate(config, tokens, device, buffers=attn) + buffers = mlp + gate_up, staging, activated = zeros(tokens, 2 * inter), zeros(tokens, inter), zeros(tokens, inter) + quantized = buffers.zeros((tokens, max(config.hidden, inter)), torch.uint8) + output = zeros(tokens, config.hidden) + root.join(attn, mlp) + buffers = root + return cls(embedding, normalized, attention, gate_up, staging, quantized, activated, output, + zeros(samples, config.hidden), zeros(samples, config.vocabulary), zeros(samples, config.vocabulary)) + + def rows(self, tokens, samples): + return type(self)(*(getattr(self, name).rows(tokens) if name == "attention" else + getattr(self, name)[:samples if name in ("hidden", "local_logits", "logits") else tokens] + for name in self.__dataclass_fields__)) + + +class PreparedFeedForward(torch.nn.Module): + def __init__(self, weights, scratch, *, session, name, workspace): + super().__init__() + self.scratch = scratch + self.gate_up = prepare_projection(scratch.normalized, weights.gate_up, scratch.gate_up, + session=session, name=name + ".gate_up", workspace=workspace, staging=scratch.staging, + quantized_staging=scratch.quantized) + self.down = prepare_projection(scratch.activated, weights.down, scratch.output, + session=session, name=name + ".down", workspace=workspace, quantized_staging=scratch.quantized) + + def forward(self, hidden_states): + s = self.scratch + s.normalized.copy_(hidden_states.reshape_as(s.normalized)) + gate, up = self.gate_up(s.normalized).chunk(2, -1) + s.activated.copy_(torch.nn.functional.silu(gate) * up) + return self.down(s.activated).view_as(hidden_states) + + +class PreparedDecoder: + def __init__(self, weights, scratch, metadata, pool, *, mode, session, name, workspace, buffers, scoring=None): + self.weights, self.scratch, self.metadata, self.pool = weights, scratch, metadata, pool + c = weights.config.text + self.embedding = PreparedEmbedding(weights.embedding, metadata.token_ids, scratch.embedding, + session=session, name=name + ".embedding", num_rows=metadata.live_counts[:1]) + self.embedding_norm = norm("rms", eps=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, scratch.normalized, + scratch.attention, metadata, pool, mode=mode, session=session, name=prefix + ".attention", + workspace=workspace, cache_metadata=self.cache_metadata) + feedforward = PreparedFeedForward(w, scratch, session=session, name=prefix + ".mlp", workspace=workspace) + self.layers.append(decoder_layer(weights.config, w, attention, feedforward)) + self.norm = norm("rms", weights.norm, eps=c["rms_norm_eps"]) + self.scoring = None if scoring is None else scoring.prepare(scratch.embedding, weights.head, + vocabulary=weights.config.vocabulary, session=session, coordinator=None, name=name + ".prompt", copy_source=True) + if self.scoring is not None: + self.scoring.parts = [(source, SoftcappedProjection(projection, c["output_multiplier"], + c["final_logit_softcapping"]), reduction) for source, projection, reduction in self.scoring.parts] + self.head = PreparedVocabularyProjection(scratch.hidden, weights.head, scratch.local_logits, scratch.logits, + runtime=None, coordinator=None, session=session, name=name + ".head", buffers=buffers, workspace=workspace) + self.logits = SoftcappedProjection(self.head, c["output_multiplier"], c["final_logit_softcapping"]) + + def __call__(self): + self.cache_metadata() + 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.scoring() + self.scratch.hidden.copy_(self.scoring.source[self.metadata.sample_indices]) + else: + self.scratch.hidden.copy_(self.norm(hidden[self.metadata.sample_indices])) + self.logits(self.scratch.hidden) + + def scratch_tensors(self): + return self.head.gathered, self.cache_metadata.slots, self.cache_metadata.lengths + + +class SoftcappedProjection: + def __init__(self, projection, multiplier, softcap): + self.projection, self.multiplier, self.softcap = projection, multiplier, softcap + + def __call__(self, source): + value = self.projection(source) + value.copy_(torch.tanh(value * self.multiplier / self.softcap) * self.softcap) + return value + + +class PreparedResume(_PreparedResume): + def __init__(self, weights, *args, **kwargs): + super().__init__(weights, *args, **kwargs) + c = weights.config.text + self.projection = SoftcappedProjection(self.projection, c["output_multiplier"], c["final_logit_softcapping"]) diff --git a/ignition/recipes/muse_glimmer/frontend.py b/ignition/recipes/muse_glimmer/frontend.py new file mode 100644 index 000000000..ba2c1df13 --- /dev/null +++ b/ignition/recipes/muse_glimmer/frontend.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Recipient-header prompt syntax and ATEM tools for text-only Muse Glimmer.""" + +import hashlib +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.ATEM, + assistant_marker="<|start|>assistant", + message_end_markers=["<|eom|>", "<|eot|>"], + prefix_boundary=None, +) +FRONTEND["reasoning"] = dict( + kind=p.RECIPIENT_HEADERS, + open="<|start|>assistant to=self<|message|>", + close="<|eom|>", + wrapping_newlines=0, + terminal_markers=[], +) + + +def prepare_frontend(snapshot, *, eos_token_ids): + snapshot = Path(snapshot) + tokenizer = Tokenizer.from_file(str(snapshot / "tokenizer.json")) + for marker, expected in {"<|end_of_text|>": 200001, "<|start|>": 200022, + "<|message|>": 200023, "<|eom|>": 200007, + "<|eot|>": 200008}.items(): + if tokenizer.token_to_id(marker) != expected: + raise ValueError(f"Muse Glimmer requires {marker} token ID {expected}") + eos_token_ids = [eos_token_ids] if isinstance(eos_token_ids, int) else list(eos_token_ids) + if 200007 in eos_token_ids: + raise ValueError("Muse Glimmer <|eom|> is an internal message boundary") + return _prepare_frontend(snapshot, eos_token_ids=list(dict.fromkeys([*eos_token_ids, 200001, 200008]))) + + +def runtime_assets(snapshot): + snapshot = Path(snapshot) + tokenizer = snapshot / "tokenizer.json" + with tokenizer.open("rb") as source: + digest = hashlib.file_digest(source, "sha256").hexdigest() + return {"tokenizer": {"path": str(tokenizer), "sha256": digest}, + "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/muse_glimmer/model.py b/ignition/recipes/muse_glimmer/model.py new file mode 100644 index 000000000..202d48e64 --- /dev/null +++ b/ignition/recipes/muse_glimmer/model.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Centered normalization and decoder residuals.""" + +import torch + + +def norm(kind, weight=None, *, eps): + from transformers.models.muse_glimmer.modeling_muse_glimmer import ( + MuseGlimmerRMSNorm, MuseGlimmerTextCenteredRMSNorm, + ) + with torch.device("meta"): + module = (MuseGlimmerTextCenteredRMSNorm(weight.numel(), eps=eps) if kind == "centered" + else MuseGlimmerRMSNorm(None if weight is None else weight.numel(), eps=eps, + with_scale=weight is not None)) + if weight is not None: + module.weight = torch.nn.Parameter(weight, requires_grad=False) + return module.eval() + + +def decoder_layer(config, weights, attention, mlp): + from transformers.models.muse_glimmer.configuration_muse_glimmer import MuseGlimmerTextConfig + from transformers.models.muse_glimmer.modeling_muse_glimmer import MuseGlimmerTextDecoderLayer + + c = MuseGlimmerTextConfig.from_dict(config.text) + layer = MuseGlimmerTextDecoderLayer.__new__(MuseGlimmerTextDecoderLayer) + torch.nn.Module.__init__(layer) + layer.hidden_size, layer.config = c.hidden_size, c + layer.self_attn, layer.mlp = attention, mlp + for name, weight, eps in (("input_layernorm", weights.input_norm, c.rms_norm_eps), + ("post_attention_layernorm", weights.post_attention_norm, c.post_norm_eps), + ("pre_feedforward_layernorm", weights.pre_feedforward_norm, c.rms_norm_eps), + ("post_feedforward_layernorm", weights.post_feedforward_norm, c.post_norm_eps)): + setattr(layer, name, norm("centered", weight, eps=eps)) + return layer.eval() diff --git a/ignition/recipes/muse_glimmer/pool.py b/ignition/recipes/muse_glimmer/pool.py new file mode 100644 index 000000000..3d9445e59 --- /dev/null +++ b/ignition/recipes/muse_glimmer/pool.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""BF16 paged histories, partial-page snapshots, and saved normalized hidden rows.""" + +from dataclasses import dataclass +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): + c = config.text + size = PAGE_TOKENS * c["num_key_value_heads"] * c["head_dim"] * KV_DTYPE.itemsize + for layer in range(config.layers): + for kind in ("key", "value"): + yield f"layer{layer}.{kind}", (size,) + + +def page_bytes(config): + return sum(shape[0] for _, shape in page_specs(config)) + + +def continuation_layout(config): + return StateLayout.from_specs([*((name, shape, torch.uint8) for name, shape in page_specs(config)), + ("last_hidden", (config.hidden,), torch.bfloat16), ("consumed_tokens", (1,), torch.int64)]) + + +@dataclass(frozen=True) +class ContinuationPool(PagedStateStorage): + config: object + + @classmethod + def allocate(cls, config, slots, pages, device, *, storage=None, maximum_pages=None, + maximum_rows=None, backed_slots=None): + backing = PagedStateStorage.allocate(continuation_layout(config), page_specs(config), 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) + + def cache(self, layer, kind): + c = self.config.text + return self.pages[f"layer{layer}.{kind}"].view(KV_DTYPE).view( + -1, PAGE_TOKENS, c["num_key_value_heads"], c["head_dim"]) diff --git a/ignition/recipes/muse_glimmer/recipe.py b/ignition/recipes/muse_glimmer/recipe.py new file mode 100644 index 000000000..603eebae4 --- /dev/null +++ b/ignition/recipes/muse_glimmer/recipe.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Single-GPU Muse Glimmer mixed NVFP4/FP8 text preparation.""" + +from types import MappingProxyType + +from ignition.recipes.declaration import Checkpoint, RankCosts, RankUsage, Recipe, SamplingDefaults + + +def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_graphs=False, + package_storage=None, ranks=None): + from .bootstrap import PreparationConfig, prepare as prepare_model + + if plan.world_size != 1 or ranks is not None: + raise ValueError("Muse Glimmer preparation supports one local GPU") + config = PreparationConfig(collective_tuning=plan.collective_tuning, collective_ladder=plan.collective_ladder, + prompt_logprobs=plan.prompt_logprobs, compile_workers=plan.compile_workers, + autotune_effort=plan.autotune_effort, tuning_replica=plan.tuning_replica, + native_dense_activations=plan.native_dense_activations, + lock_gpu_clocks=plan.lock_gpu_clocks and plan.autotune_effort != "off", + context=plan.context, max_active=plan.concurrency, prefill_chunk_size=plan.prefill_chunk, + snapshot_budget_bytes=plan.snapshots * plan.costs.state_row_bytes, + headroom_bytes=plan.headroom_bytes + plan.reserve_bytes, compile_decoder=compile_forwards, + retain_graphs=retain_graphs, kernel_cache=kernel_cache) + return prepare_model(snapshot, config, progress=progress, package_storage=package_storage) + + +def usage(prepared): + return (RankUsage(prepared.memory_report["pages"], prepared.memory_report["free_device_bytes"]),) + + +RECIPE = Recipe(name="muse_glimmer", served_model_name="Muse-Glimmer-30B", prepare=prepare, usage=usage, + # https://huggingface.co/nvidia/Muse-Glimmer-30B-NVFP4#usage + sampling_defaults=SamplingDefaults(temperature=1., top_p=.95, top_k=64), + checkpoints=(Checkpoint(alias="muse-glimmer-30b-nvfp4", repository="nvidia/Muse-Glimmer-30B-NVFP4", + revision="47818374517751c48c55cde2621594926b1888b6", architecture="MuseGlimmerForConditionalGeneration", + stored_bytes=24_669_346_036, device_bytes=24_669_346_036, expansion_bytes=1 << 28),), + context=131072, page_tokens=128, concurrency=4, max_concurrency=16, max_draft_tokens=0, prefill_chunk=4096, + ranks=MappingProxyType({1: RankCosts(6_829_312, 6_815_744, 4 << 30)})) diff --git a/ignition/recipes/muse_glimmer/weights.py b/ignition/recipes/muse_glimmer/weights.py new file mode 100644 index 000000000..a0a3a326d --- /dev/null +++ b/ignition/recipes/muse_glimmer/weights.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Text weights with checkpoint NVFP4 and FP8 calibration.""" + +from contextlib import nullcontext +from dataclasses import dataclass +import torch + +from ignition.components.parallel import TensorParallelShard +from ignition.components.weights import DirectWeightLoader +from .config import ModelConfig + +PREFIX = "model.language_model" + + +@dataclass(frozen=True) +class LayerWeights: + qkv: object + output: object + gate_up: object + down: object + input_norm: torch.Tensor + post_attention_norm: torch.Tensor + pre_feedforward_norm: torch.Tensor + post_feedforward_norm: torch.Tensor + + +@dataclass(frozen=True) +class ModelWeights: + config: ModelConfig + shard: object + embedding: torch.Tensor + norm: torch.Tensor + head: object + layers: tuple[LayerWeights, ...] + allocated_bytes: int + draft: object | None = None + + @classmethod + def load(cls, manifest, device, *, progress=None, package_storage=None): + before = torch.cuda.memory_allocated(device) + loading = nullcontext if package_storage is None else package_storage.transient + with loading(), MuseGlimmerWeightLoader(manifest, device, progress=progress) as loader: + config = ModelConfig.load(manifest.snapshot) + embedding = loader.load_tensor(PREFIX + ".embed_tokens.weight") + norm = loader.load_tensor(PREFIX + ".norm.weight") + head = loader.load_linear("lm_head") + layers = tuple(loader.load_layer(i) for i in range(config.layers)) + return cls(config, TensorParallelShard(0, 1), embedding, norm, head, layers, + torch.cuda.memory_allocated(device) - before) + + +class MuseGlimmerWeightLoader(DirectWeightLoader): + def _selected_names(self): + return {n for n in super()._selected_names() if n.startswith((PREFIX + ".", "lm_head."))} + + def load_layer(self, layer): + prefix = f"{PREFIX}.layers.{layer}" + attn, mlp = prefix + ".self_attn", prefix + ".mlp" + return LayerWeights( + self.load_mixed_linear_group(tuple(attn + "." + name + "_proj" for name in ("q", "k", "v", "gate"))), + self.load_linear(attn + ".o_proj"), + self.load_mixed_linear_group((mlp + ".gate_proj", mlp + ".up_proj")), + self.load_linear(mlp + ".down_proj"), + *(self.load_tensor(prefix + "." + name + ".weight") for name in + ("input_layernorm", "post_attention_layernorm", "pre_feedforward_layernorm", "post_feedforward_layernorm"))) diff --git a/ignition/recipes/qwen38_dense/decoder.py b/ignition/recipes/qwen38_dense/decoder.py index 82102efb4..ef4ec9439 100644 --- a/ignition/recipes/qwen38_dense/decoder.py +++ b/ignition/recipes/qwen38_dense/decoder.py @@ -194,7 +194,7 @@ def projection(field, inputs, output): weight = weights.projections[prefix + field] if isinstance(weight, TensorFP8Weight): return TensorFP8Projection(inputs, weight, output, session=session, name=name + "." + field, - staging=projection_staging) + staging=projection_staging, workspace=workspace) return prepare_projection(inputs, weight, output, session=session, name=name + "." + field, workspace=workspace) operands = (*inputs, ("o_proj", self.attended, self.output)) diff --git a/pyproject.toml b/pyproject.toml index 2f61b3f50..52fc697d2 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.muse_glimmer" = ["assets/*"] "ignition.recipes.minimax_m3" = ["assets/*"] [tool.pytest.ini_options] diff --git a/tests/cli/test_models.py b/tests/cli/test_models.py index bf38254ba..837d54627 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', 'muse-glimmer-30b-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/test_tensor_fp8_cuda.py b/tests/components/test_tensor_fp8_cuda.py index 65b54879b..631de681d 100644 --- a/tests/components/test_tensor_fp8_cuda.py +++ b/tests/components/test_tensor_fp8_cuda.py @@ -3,55 +3,55 @@ """Checkpoint-calibrated FP8 projections and allocation-stable graph replay.""" -import json import os import pytest import torch -from safetensors.torch import save_file from ignition.components.tensor_fp8 import TensorFP8Projection from ignition.components.weights import DirectWeightLoader -from ignition.preparation.checkpoint import inspect_indexed_checkpoint +from tests.components.test_weight_formats_cuda import checkpoint pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="requires an explicitly assigned CUDA device") -@pytest.mark.parametrize("rows", [1, 17, 128]) +def assert_fp8_projection(actual, expected): + # FP32 reduction order can cross one BF16 output rounding boundary. + torch.testing.assert_close(actual.float().cpu(), expected.bfloat16().float(), + rtol=torch.finfo(torch.bfloat16).eps, atol=0) + + +@pytest.mark.parametrize("rows", [1, 17, 128, 4096]) @pytest.mark.parametrize("shared", [False, True]) @torch.no_grad() def test_tensor_fp8_calibration_survives_loading_and_replay(tmp_path, rows, shared): - from b12x.preparation import PreparationSession + from ignition.preparation.compilation import compile_forward + from ignition.preparation.tuning import RecordedPreparationSession generator = torch.Generator().manual_seed(2741) values = torch.randn((256, 512), generator=generator).mul(20).to(torch.float8_e4m3fn) - weight_scale, input_scale = .017, .031 - tensors = {"proj.weight": values, "proj.weight_scale": torch.tensor(weight_scale), - "proj.input_scale": torch.tensor(input_scale)} - save_file(tensors, str(tmp_path / "weights.safetensors")) - (tmp_path / "model.safetensors.index.json").write_text(json.dumps({ - "metadata": {"total_size": sum(t.nbytes for t in tensors.values())}, - "weight_map": {name: "weights.safetensors" for name in tensors}})) - (tmp_path / "config.json").write_text(json.dumps({"quantization_config": { - "quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", - "quantized_layers": {"proj": {"quant_algo": "FP8"}}}})) - with DirectWeightLoader(inspect_indexed_checkpoint(tmp_path), "cuda:0") as loader: + weight_scale, input_scale = torch.tensor(.017), torch.tensor(.031) + tensors = {"proj.weight": values, "proj.weight_scale": weight_scale, "proj.input_scale": input_scale} + with DirectWeightLoader(checkpoint(tmp_path, tensors, {"proj": {"quant_algo": "FP8"}}), "cuda:0") as loader: weight = loader.load_linear("proj", rows=(128, 256), columns=(32, 320)) assert loader._session.torch_copy_bytes == 0 source = torch.randn((rows, 288), generator=generator).mul(10).bfloat16() device_source = source.cuda() output = torch.empty((rows, 128), dtype=torch.bfloat16, device="cuda") staging = torch.empty(rows * 512, dtype=torch.uint8, device="cuda") if shared else None - with PreparationSession(device=device_source.device, autotune=False, compile_workers=0) as session: + with RecordedPreparationSession(device=device_source.device, checkpoint="tensor-fp8", + workload_schema="tensor-fp8", numerical_policy="default", compile_workers=1) as session: projection = TensorFP8Projection(device_source, weight, output, session=session, name="tensor-fp8", staging=staging) if shared: assert projection.quantized.data_ptr() == staging.data_ptr() - projection(device_source) + session.tune() + compiled = compile_forward(lambda: projection(device_source)) + compiled() torch.cuda.synchronize() graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - projection(device_source) + with session.capture(), torch.cuda.graph(graph): + compiled() for factor in (1., -.5, 2.): device_source.copy_(source * factor) output.fill_(float("nan")) @@ -60,5 +60,118 @@ def test_tensor_fp8_calibration_survives_loading_and_replay(tmp_path, rows, shar torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocations quantized = ((source * factor).float() / input_scale).clamp(-448, 448).to(torch.float8_e4m3fn) + assert torch.equal(projection.quantized.cpu().view(torch.uint8), quantized.view(torch.uint8)) expected = (quantized.float() @ values.float()[128:256, 32:320].T) * (weight_scale * input_scale) - torch.testing.assert_close(output.float().cpu(), expected, rtol=.015, atol=.03) + assert_fp8_projection(output, expected) + graph.reset() + + +@pytest.mark.parametrize('columns,outputs', [(6656, 19968), (19968, 6656)]) +@torch.no_grad() +def test_sm103_checkpoint_sized_fp8_state_does_not_allocate(columns, outputs): + """Glimmer's largest FP8 gate/up and down projections fit caller-owned workspace.""" + from b12x.gemm import blockscaled + from b12x.preparation import require_prepared + from ignition.components.tensor_fp8 import TensorFP8Weight + from ignition.components.tensor_fp8_sm103 import COMPONENT + from ignition.preparation.scratch import ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + + if torch.cuda.get_device_capability() != (10, 3): + pytest.skip('checks the SM103 native GEMM workspace contract') + source = torch.full((4096, columns), .031, device='cuda', dtype=torch.bfloat16) + values = torch.ones((outputs, columns), device='cuda', dtype=torch.float8_e4m3fn) + input_scale = torch.tensor(.031, device='cuda') + combined_scale = torch.tensor(.017, device='cuda') * input_scale + weight = TensorFP8Weight(blockscaled.pack_weight(values, combined_scale, recipe='tensor_fp8'), input_scale) + output = torch.empty((4096, outputs), device='cuda', dtype=torch.bfloat16) + with RecordedPreparationSession(device=source.device, checkpoint='glimmer-fp8-capacity', + workload_schema='tensor-fp8', numerical_policy='default', compile_workers=1) as session: + arena = ScratchArena(source.device) + session.register_scratch(arena) + projection = TensorFP8Projection(source, weight, output, session=session, + name='checkpoint-sized-fp8', workspace=arena) + session.tune() + projection(source) + assert bool((projection.quantized.float() == 1).all()) + state = require_prepared(projection.plan, COMPONENT, source.device) + + def run(): + state.run(projection.quantized, weight.packed.values, weight.packed.output_scale, + output, projection.workspace) + + run() + torch.cuda.synchronize() + allocations = torch.cuda.memory_stats()['allocation.all.allocated'] + for _ in range(3): + run() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()['allocation.all.allocated'] == allocations + expected = (combined_scale * columns).bfloat16().expand_as(output) + torch.testing.assert_close(output, expected, rtol=0, atol=0) + + +@pytest.mark.parametrize('rows', [17, 4096]) +@torch.no_grad() +def test_mixed_group_retains_distinct_fp8_calibration(tmp_path, rows): + from ignition.components.linear import prepare_projection + from ignition.components.weights import GroupedLinearWeights + from ignition.preparation.compilation import compile_forward + from ignition.preparation.scratch import ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + + torch.manual_seed(375) + tensors, declarations = {}, {} + source = torch.randn((rows, 256), dtype=torch.bfloat16, device='cuda') + original = source.cpu() + for name, scale in [('q', .013), ('k', .071)]: + values = torch.randn((128, 256)).mul(20).to(torch.float8_e4m3fn) + tensors.update({name + '.weight': values, name + '.weight_scale': torch.tensor(.017), + name + '.input_scale': torch.tensor(scale)}) + declarations[name] = {'quant_algo': 'FP8'} + tensors['v.weight'] = torch.randn((128, 256), dtype=torch.bfloat16) * .03 + with DirectWeightLoader(checkpoint(tmp_path, tensors, declarations), 'cuda:0') as loader: + weight = loader.load_mixed_linear_group(('q', 'k', 'v')) + assert isinstance(weight, GroupedLinearWeights) + assert weight.widths == (128, 128, 128) + output = torch.empty((rows, 384), dtype=torch.bfloat16, device='cuda') + + def check(value): + parts = [] + for name in ('q', 'k'): + scale = tensors[name + '.input_scale'] + quantized = (value.float() / scale).clamp(-448, 448).to(torch.float8_e4m3fn) + parts.append((quantized.float() @ tensors[name + '.weight'].float().T) + * (scale * tensors[name + '.weight_scale'])) + expected = torch.cat([*parts, value.float() @ tensors['v.weight'].float().T], -1) + assert_fp8_projection(output[:, :256], expected[:, :256]) + # The BF16 GEMM's FP32 reduction order differs near cancellation; measured + # excess beyond a BF16 ULP is at most 4.03e-7 on SM103 and SM120. + torch.testing.assert_close(output[:, 256:].float().cpu(), expected[:, 256:].bfloat16().float(), + rtol=torch.finfo(torch.bfloat16).eps, atol=2 ** -21) + + with RecordedPreparationSession(device=source.device, checkpoint='mixed-fp8', workload_schema='mixed-fp8', + numerical_policy='default', compile_workers=1) as session: + arena = ScratchArena(source.device) + session.register_scratch(arena) + staging = torch.empty(source.numel(), dtype=torch.uint8, device=source.device) + projection = prepare_projection(source, weight, output, session=session, name='mixed', workspace=arena, + quantized_staging=staging) + assert all(p.quantized.data_ptr() == staging.data_ptr() for p in projection.projections[:2]) + session.tune() + compiled = compile_forward(lambda: projection(source)) + compiled() + torch.cuda.synchronize() + check(original) + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + compiled() + for factor in (1., -.5, 2.): + source.copy_(original * factor) + output.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 + check(original * factor) + graph.reset() diff --git a/tests/frontend/test_muse_spark.py b/tests/frontend/test_muse.py similarity index 72% rename from tests/frontend/test_muse_spark.py rename to tests/frontend/test_muse.py index 628832522..86f83115c 100644 --- a/tests/frontend/test_muse_spark.py +++ b/tests/frontend/test_muse.py @@ -5,6 +5,7 @@ import copy import hashlib +from importlib import import_module import json import os from pathlib import Path @@ -13,24 +14,30 @@ import pytest ROOT = Path(__file__).resolve().parents[2] -SNAPSHOT = Path(os.environ.get('FLARE_MUSE_SPARK_SNAPSHOT', '/data/cache/huggingface/hub/models--meta-models--Muse-Spark-Open-816B-A42B-NVFP4/snapshots/4239e4db19376904f2e82c167e78f70abb5455fe')) -def test_native_muse_chat_matches_checkpoint(tmp_path): +@pytest.mark.parametrize('recipe,option,efforts', [ + ('muse_spark', 'reasoning_effort', ('low', 'medium', 'high', 'xhigh')), + ('muse_glimmer', 'reasoning_strength', ('low', 'medium', 'high')), +], ids=['muse_spark', 'muse_glimmer']) +def test_native_muse_chat_matches_checkpoint(tmp_path, recipe, option, efforts): from tokenizers import Tokenizer from transformers import PreTrainedTokenizerFast from transformers.utils.chat_template_utils import _compile_jinja_template - from ignition.recipes.muse_spark.frontend import prepare_frontend, runtime_assets - if not (SNAPSHOT / 'tokenizer.json').is_file(): - pytest.skip('requires pinned Muse Spark checkpoint frontend assets') - assets = runtime_assets(SNAPSHOT) - special = prepare_frontend(SNAPSHOT, eos_token_ids=[200001, 200008])['tokenizer'] - configured_eos = json.loads((SNAPSHOT / 'config.json').read_text())['text_config']['eos_token_id'] - assert prepare_frontend(SNAPSHOT, eos_token_ids=configured_eos) == prepare_frontend(SNAPSHOT, eos_token_ids=[200001, 200008]) - tokenizer = Tokenizer.from_file(str(SNAPSHOT / 'tokenizer.json')) - hf_tokenizer = PreTrainedTokenizerFast.from_pretrained(SNAPSHOT) - source = (SNAPSHOT / 'chat_template.jinja').read_text() + frontend = import_module(f'ignition.recipes.{recipe}.frontend') + checkpoint = import_module(f'ignition.recipes.{recipe}.recipe').RECIPE.checkpoints[0] + snapshot = Path(os.environ.get(f'FLARE_{recipe.upper()}_SNAPSHOT', Path('/data/cache/huggingface/hub') + / ('models--' + checkpoint.repository.replace('/', '--')) / 'snapshots' / checkpoint.revision)) + if not (snapshot / 'tokenizer.json').is_file(): + pytest.skip(f'requires pinned {recipe} checkpoint frontend assets') + assets = frontend.runtime_assets(snapshot) + special = frontend.prepare_frontend(snapshot, eos_token_ids=[200001, 200008])['tokenizer'] + configured_eos = json.loads((snapshot / 'config.json').read_text())['text_config']['eos_token_id'] + assert frontend.prepare_frontend(snapshot, eos_token_ids=configured_eos) == frontend.prepare_frontend(snapshot, eos_token_ids=[200001, 200008]) + tokenizer = Tokenizer.from_file(str(snapshot / 'tokenizer.json')) + hf_tokenizer = PreTrainedTokenizerFast.from_pretrained(snapshot) + source = (snapshot / 'chat_template.jinja').read_text() annotated = assets['chat_template']['text'] assert annotated.replace('{%- mark -%}', '') == source template = _compile_jinja_template(source) @@ -85,8 +92,8 @@ def add(name, messages, **options): for content in ['café 世界', ' repeated repeated ']: add('continuation_'+content, [user, dict(role='assistant', content=content)], continue_final_message=True, add_generation_prompt=False) - for effort in ['low', 'medium', 'high', 'xhigh']: - add(effort, [user], reasoning_effort=effort) + for effort in efforts: + add(effort, [user], **{option: effort}) for role in ['system', 'developer']: add(role, [dict(role=role, content='Reasoning effort should be precise.'), user]) add('history', [user, dict(role='assistant', reasoning_content='Plan 世界', content='Answer'), user]) @@ -103,7 +110,6 @@ def add(name, messages, **options): if hinted: message['_checkpoint_hints'] = [2] add(f'hints_{suffix}_{hinted}', [message]) - add('empty_schema', [user], tools=[dict(type='function', function=dict(name='empty'))]) calls = [dict(id='one', type='function', function=dict(name='lookup', arguments=dict( query=' 世界 <|eom|> & "quotes" \n', n=3, enabled=True, absent=None, nested=dict(text='中文'), items=[1, False], empty=[]))), @@ -114,17 +120,18 @@ def add(name, messages, **options): add('escaping_headers', [user, dict(role='assistant', content='', tool_calls=[dict(id='x', type='function', function=dict(name='a\r\n"<&', arguments={'k"<&': '<|start|>'}))]), dict(role='tool', tool_call_id='x', content='')], tools=tools) - for effort in ['none', 'minimal', 'max']: - cases.append(dict(name='invalid_'+effort, messages=[user], options=dict(reasoning_effort=effort), - error=f'Unsupported reasoning_effort: {effort}. Expected one of: low, medium, high, xhigh.')) - - incompatible = [user, dict(role='assistant', content='<|eom|> content')] - with pytest.raises(ValueError, match='final message does not appear'): - hf_tokenizer.apply_chat_template(incompatible, tokenize=False, chat_template=source, - continue_final_message=True, add_generation_prompt=False) - cases.append(dict(name='escaped_continuation_error', messages=incompatible, - options=dict(continue_final_message=True, add_generation_prompt=False), - error='continue_final_message is set but the final message does not appear in the chat after applying the chat template!')) + if recipe == 'muse_spark': + add('empty_schema', [user], tools=[dict(type='function', function=dict(name='empty'))]) + for effort in ['none', 'minimal', 'max']: + cases.append(dict(name='invalid_'+effort, messages=[user], options=dict(reasoning_effort=effort), + error=f'Unsupported reasoning_effort: {effort}. Expected one of: low, medium, high, xhigh.')) + incompatible = [user, dict(role='assistant', content='<|eom|> content')] + with pytest.raises(ValueError, match='final message does not appear'): + hf_tokenizer.apply_chat_template(incompatible, tokenize=False, chat_template=source, + continue_final_message=True, add_generation_prompt=False) + cases.append(dict(name='escaped_continuation_error', messages=incompatible, + options=dict(continue_final_message=True, add_generation_prompt=False), + error='continue_final_message is set but the final message does not appear in the chat after applying the chat template!')) samples = ['Hello café 世界 á 👨‍👩‍👧‍👦', ' to=self<|message|>Plan<|eom|><|start|>assistant to=user<|message|>Done'] encode_cases = [dict(name=f'encode{i}', text=text, add_special_tokens=False, token_ids=tokenizer.encode(text, add_special_tokens=False).ids) for i, text in enumerate(samples)] @@ -140,16 +147,16 @@ def add(name, messages, **options): runtime = tmp_path / 'runtime' runtime.mkdir() for name in ['tokenizer.json', 'tokenizer_config.json']: - (runtime / name).symlink_to(SNAPSHOT / name) + (runtime / name).symlink_to(snapshot / name) (runtime / 'chat_template.jinja').write_text(assets['chat_template']['text']) fingerprints = {'tokenizer.json': assets['tokenizer']['sha256'], 'chat_template.jinja': assets['chat_template']['sha256'], 'tokenizer_config.json': hashlib.sha256((runtime / 'tokenizer_config.json').read_bytes()).hexdigest()} fixture = tmp_path / 'chat.json' fixture.write_text(json.dumps(dict(assets=fingerprints, cases=cases, encode_cases=encode_cases, decode_cases=decode_cases, - template_defaults=dict(reasoning_effort='high', current_date='2026-10-27', add_generation_prompt=True), - default_overrides=[['high', {}], ['low', dict(reasoning_effort='low')], - ['closed_header', dict(reasoning_effort='xhigh', add_generation_prompt=False)]]))) + template_defaults=dict(current_date='2026-10-27', add_generation_prompt=True, **{option: 'high'}), + default_overrides=[['high', {}], ['low', {option: 'low'}], + ['closed_header', {option: efforts[-1], 'add_generation_prompt': False}]]))) 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..55cce81e9 100644 --- a/tests/preparation/test_frontend_metadata.py +++ b/tests/preparation/test_frontend_metadata.py @@ -22,7 +22,7 @@ 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, - 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.) + top_k=20 if qwen else 64 if recipe.name in ("gemma4", "muse_glimmer") 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}, "presence_penalty": {"min": 0., "max": 2.}} diff --git a/tests/recipes/muse_glimmer/test_attention_cuda.py b/tests/recipes/muse_glimmer/test_attention_cuda.py new file mode 100644 index 000000000..e006d89b4 --- /dev/null +++ b/tests/recipes/muse_glimmer/test_attention_cuda.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Captured Glimmer attention preserves BF16 cache pages, masks and inactive rows.""" + +import os +from types import SimpleNamespace + +import pytest +import torch + +pytestmark = pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', + reason='requires an explicitly assigned CUDA device') + + +def configuration(window): + from ignition.recipes.muse_glimmer.config import ModelConfig + return ModelConfig(dict(hidden_size=256, num_hidden_layers=1, num_attention_heads=4, + num_key_value_heads=2, head_dim=128, rms_norm_eps=1e-5, qk_scale_factor=3.87, + layer_rope_theta=[500000 if window > 0 else 0], sliding_window=window, + layer_types=['sliding_attention' if window > 0 else 'full_attention']), {}) + + +@pytest.mark.parametrize('window', [-1, 256]) +@torch.no_grad() +def test_chunked_prefill_matches_canonical_cache_and_gate(window): + from ignition.components.paged_attention import PagedAttentionMetadata + from ignition.components.paged_batch import Metadata + from ignition.preparation.compilation import compile_forward + from ignition.preparation.scratch import GraphBufferPool, ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + from ignition.recipes.muse_glimmer.attention import AttentionScratch, PreparedAttention + from ignition.recipes.muse_glimmer.pool import ContinuationPool + from transformers.models.muse_glimmer.modeling_muse_glimmer import MuseGlimmerRMSNorm, apply_rotary_pos_emb + + device, capacity, blocks = torch.device('cuda', 0), 129, 5 + torch.manual_seed(2381) + config = configuration(window) + pool = ContinuationPool.allocate(config, 3, blocks, device) + weights = SimpleNamespace(qkv=torch.randn((1536, 256), device=device).bfloat16() * .025, + output=torch.randn((256, 512), device=device).bfloat16() * .025) + source = torch.randn((capacity, 256), device=device).bfloat16() + metadata = Metadata.allocate(capacity, 1, blocks, device) + cache_metadata = PagedAttentionMetadata(metadata, page_tokens=128, + buffers=GraphBufferPool(device, chunk_bytes=2 << 20).cursor()) + pages = torch.arange(blocks, dtype=torch.int32, device=device)[None] + def set_metadata(start, count): + metadata.set(torch.tensor([start], device=device), torch.tensor([count], dtype=torch.int32, device=device), + torch.tensor([1], device=device), pages, torch.zeros((1, capacity), dtype=torch.int64, device=device), + torch.tensor([1], device=device)) + set_metadata(0, capacity) + with RecordedPreparationSession(device=device, checkpoint='glimmer-attention', workload_schema='glimmer-attention', + numerical_policy='default', compile_workers=1, autotune_effort='off') as session: + arena = ScratchArena(device) + session.register_scratch(arena) + scratch = AttentionScratch.allocate(config, capacity, device) + attention = PreparedAttention(0, weights, config, source, scratch, metadata, pool, + mode='prefill', session=session, name='prefill', workspace=arena, cache_metadata=cache_metadata) + session.tune() + compiled = compile_forward(lambda: (cache_metadata(), attention(source))) + compiled() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + compiled() + session.freeze() + pool.clear_for_preparation() + norm = MuseGlimmerRMSNorm(eps=1e-5, with_scale=False) + keys, values, start = [], [], 0 + for count in (127, 1, 1, 126, 1, 1, 0, 3): + source.normal_() + set_metadata(start, count) + q, k, v, gate = (source @ weights.qkv.T).split((512, 256, 256, 512), -1) + q, k = norm(q.view(capacity, 4, 128)) * 3.87, norm(k.view(capacity, 2, 128)) + v = v.view(capacity, 2, 128) + if window > 0: + inv = 1 / (500000 ** (torch.arange(0, 128, 2, device=device).float() / 128)) + freq = (start + torch.arange(capacity, device=device)).float()[:, None] * inv + angles = torch.cat((freq, freq), -1) + q_ref, k_ref = apply_rotary_pos_emb(q.transpose(0, 1)[None], k.transpose(0, 1)[None], + angles.cos().bfloat16()[None], angles.sin().bfloat16()[None]) + q, k = q_ref[0].transpose(0, 1), k_ref[0].transpose(0, 1) + keys.append(k[:count]) + values.append(v[:count]) + if count: + ks, vs = torch.cat(keys).repeat_interleave(2, 1).float(), torch.cat(values).repeat_interleave(2, 1).float() + scores = torch.einsum('qhd,thd->hqt', q[:count].float(), ks) / 128**.5 + ends = start + torch.arange(count, device=device) + 1 + positions = torch.arange(ks.shape[0], device=device) + valid = positions[None] < ends[:, None] + if window > 0: + valid &= positions[None] >= (ends - window)[:, None] + attended = torch.einsum('hqt,thd->qhd', scores.masked_fill(~valid[None], -torch.inf).softmax(-1), vs).bfloat16() + expected = (attended.flatten(1) * gate[:count].sigmoid()) @ weights.output.T + before = {kind: pool.cache(0, kind).clone() for kind in ('key', 'value')} + allocations = torch.cuda.memory_stats()['allocation.all.allocated'] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()['allocation.all.allocated'] == allocations + if count: + # BF16 attention rounding; measured max abs 0.00195, relative L2 0.0031. + torch.testing.assert_close(scratch.output[:count], expected, atol=.002, rtol=.004) + for kind, produced in [('key', scratch.key), ('value', scratch.value)]: + cache = pool.cache(0, kind).flatten(0, 1) + assert torch.equal(cache[start:start + count], produced[:count]) + assert torch.equal(cache[:start], before[kind].flatten(0, 1)[:start]) + assert torch.equal(cache[start + count:], before[kind].flatten(0, 1)[start + count:]) + start += count + graph.reset() diff --git a/tests/recipes/muse_glimmer/test_config.py b/tests/recipes/muse_glimmer/test_config.py new file mode 100644 index 000000000..7eb4ea0a6 --- /dev/null +++ b/tests/recipes/muse_glimmer/test_config.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Canonical Glimmer composition and checkpoint-derived planning geometry.""" + +import copy +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +from ignition.recipes import resolve +from ignition.recipes.muse_glimmer.config import ModelConfig +from ignition.recipes.muse_glimmer.model import decoder_layer +from ignition.recipes.muse_glimmer.pool import continuation_layout, page_bytes + +SNAPSHOT = Path(os.environ.get('FLARE_MUSE_GLIMMER_SNAPSHOT', + '/data/cache/huggingface/hub/models--nvidia--Muse-Glimmer-30B-NVFP4/snapshots/47818374517751c48c55cde2621594926b1888b6')) + + +def test_checkpoint_geometry_and_sampling(): + if not (SNAPSHOT / 'config.json').is_file(): + pytest.skip('requires pinned Muse Glimmer checkpoint metadata') + config = ModelConfig.load(SNAPSHOT) + model = resolve('muse-glimmer-30b-nvfp4') + assert model.checkpoint.architecture == 'MuseGlimmerForConditionalGeneration' + assert resolve(str(SNAPSHOT)).recipe.name == model.recipe.name + assert (config.hidden, config.layers, config.vocabulary) == (6656, 52, 202048) + assert [config.window(i) for i in range(4)] == [2047, 2047, 2047, -1] + assert config.text['layer_rope_theta'][:4] == [500000, 500000, 500000, 0] + assert config.quantization['model.language_model.layers.0.self_attn.q_proj']['quant_algo'] == 'FP8' + assert 'model.language_model.layers.7.self_attn.q_proj' not in config.quantization + costs = model.recipe.costs(1, None) + assert (continuation_layout(config).row_bytes, page_bytes(config)) == (costs.state_row_bytes, costs.page_bytes) + assert model.recipe.max_images == model.recipe.max_draft_tokens == 0 + assert model.recipe.speculation is None + sampling = model.recipe.sampling_defaults + assert (sampling.temperature, sampling.top_p, sampling.top_k) == (1., .95, 64) + + +def test_reject_changed_quantization_and_geometry(): + if not (SNAPSHOT / 'config.json').is_file(): + pytest.skip('requires pinned Muse Glimmer checkpoint metadata') + original = json.loads((SNAPSHOT / 'config.json').read_text()) + for section, key, value in [('quantization_config', 'kv_cache_quant_algo', 'FP8'), + ('text_config', 'hidden_activation', 'gelu'), + ('text_config', 'layer_rope_theta', [0]), + ('text_config', 'attention_bias', True)]: + changed = copy.deepcopy(original) + changed[section][key] = value + with pytest.raises(ValueError): + ModelConfig.from_dict(changed) + + +@torch.no_grad() +def test_canonical_centered_norms_and_residual_forward(): + from transformers.models.muse_glimmer.configuration_muse_glimmer import MuseGlimmerTextConfig + from transformers.models.muse_glimmer.modeling_muse_glimmer import MuseGlimmerTextDecoderLayer + + torch.manual_seed(332) + config = MuseGlimmerTextConfig(hidden_size=256, intermediate_size=512, + num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=1, head_dim=128, + layer_types=['full_attention'], layer_rope_theta=[0]) + config._attn_implementation = 'eager' + reference = MuseGlimmerTextDecoderLayer(config, layer_idx=0).eval().bfloat16() + for name, parameter in reference.named_parameters(): + if 'layernorm' in name: + parameter.copy_(torch.randn_like(parameter) * .15) + weights = SimpleNamespace(input_norm=reference.input_layernorm.weight, + post_attention_norm=reference.post_attention_layernorm.weight, + pre_feedforward_norm=reference.pre_feedforward_layernorm.weight, + post_feedforward_norm=reference.post_feedforward_layernorm.weight) + prepared = decoder_layer(SimpleNamespace(text=config.to_dict()), weights, + copy.deepcopy(reference.self_attn), copy.deepcopy(reference.mlp)) + source = torch.randn((2, 11, config.hidden_size), dtype=torch.bfloat16) + mask = torch.full((11, 11), float('-inf')).triu(1)[None, None] + actual = prepared(source, attention_mask=mask) + expected = reference(source, attention_mask=mask) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +def test_text_contract_preserves_all_paged_histories(): + from google.protobuf.json_format import ParseDict + from ignition.preparation import contract as c, runtime_package_pb2 as p + from ignition.preparation.execution import GraphSignature + from ignition.recipes.muse_glimmer.contract import prepare + from ignition.recipes.muse_glimmer.pool import ContinuationPool + + config = ModelConfig(dict(hidden_size=256, num_hidden_layers=2, num_key_value_heads=2, head_dim=128), {}) + pool = ContinuationPool.allocate(config, 3, 2, 'cpu') + buffers = {} + signatures = {kind: GraphSignature(kind, 1, 128 if 'prefill' in kind else 1, tuple(c.text_inputs(kind))) + for kind in ('init', 'restore', 'snapshot', 'prefill', 'scored_prefill', 'decode', 'resume')} + encoded = ParseDict(prepare(signatures, buffers, pool, vocabulary=202048), p.ModelContract()) + assert encoded.vision.max_images == 0 + assert encoded.frontend.tools.kind == p.ATEM + assert encoded.frontend.reasoning.kind == p.RECIPIENT_HEADERS + histories = [r for r in encoded.cache.regions if r.kind == p.PAGED_KEY_VALUE] + assert {r.storage.buffer for r in histories} == {f'cache.layer{i}.{kind}' + for i in range(2) for kind in ('key', 'value')} + assert all(r.storage.stride == 128 * 2 * 128 * 2 for r in histories) + for graph in encoded.graphs: + assert not graph.HasField('draft_cursor') + assert any(s.view.nbytes == pool.layout.row_bytes and s.access == p.READ_WRITE for s in graph.state) + decode = next(g for g in encoded.graphs if g.kind == p.DECODE) + assert decode.pending_token.buffer == 'request_pending_token' + assert all(b.source not in (p.PROMPT_TOKEN, p.PENDING_TOKEN) for b in decode.inputs) diff --git a/tests/recipes/muse_glimmer/test_preparation_cuda.py b/tests/recipes/muse_glimmer/test_preparation_cuda.py new file mode 100644 index 000000000..2ed865ac9 --- /dev/null +++ b/tests/recipes/muse_glimmer/test_preparation_cuda.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Reduced-shape mixed checkpoint loading and complete graph-catalog preparation.""" + +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_reduced_mixed_checkpoint_prepares_and_replays_catalog(tmp_path): + from safetensors.torch import save_file + from transformers.models.muse_glimmer.configuration_muse_glimmer import MuseGlimmerTextConfig + from transformers.models.muse_glimmer.modeling_muse_glimmer import MuseGlimmerTextModel + from ignition.preparation.package_storage import PackageStorage + from ignition.recipes.muse_glimmer.bootstrap import PreparationConfig, prepare + from ignition.recipes.muse_glimmer.config import ModelConfig + from ignition.recipes.muse_glimmer.pool import ContinuationPool, continuation_layout + from ignition.components.sampling import AdmissionBuffers, DeviceRequestState, RequestAdmission + + snapshot = Path(os.environ.get('FLARE_MUSE_GLIMMER_SNAPSHOT', '')) + if not (snapshot / 'tokenizer.json').is_file(): + pytest.skip('requires pinned Muse Glimmer frontend assets') + torch.manual_seed(573) + c = MuseGlimmerTextConfig(hidden_size=256, intermediate_size=512, num_hidden_layers=2, + num_attention_heads=2, num_key_value_heads=1, head_dim=128, vocab_size=202048, + layer_types=['sliding_attention', 'full_attention'], layer_rope_theta=[500000, 0], + sliding_window=128, max_position_embeddings=256, eos_token_id=200001) + canonical = MuseGlimmerTextModel(c).eval().bfloat16() + tensors = {'model.language_model.' + name: value.contiguous() for name, value in canonical.state_dict().items()} + declarations = {} + def nvfp4(prefix, rows, columns): + tensors[prefix + '.weight'] = torch.randint(0, 256, (rows, columns // 2), dtype=torch.uint8) + tensors[prefix + '.weight_scale'] = torch.full((rows, columns // 16), .0625, dtype=torch.float8_e4m3fn) + tensors[prefix + '.weight_scale_2'] = torch.tensor(.125) + declarations[prefix] = {'quant_algo': 'W4A16_NVFP4', 'group_size': 16} + nvfp4('lm_head', c.vocab_size, c.hidden_size) + nvfp4('model.language_model.layers.0.self_attn.v_proj', 128, c.hidden_size) + nvfp4('model.language_model.layers.1.mlp.down_proj', c.hidden_size, c.intermediate_size) + for suffix, weight_scale, input_scale in [ + ('0.self_attn.q_proj', 1/32, .031), + ('0.self_attn.k_proj', 1/16, .017), + ('1.mlp.up_proj', 1/64, .045)]: + prefix = 'model.language_model.layers.' + suffix + tensors[prefix + '.weight'] = (tensors[prefix + '.weight'].float() / weight_scale).to(torch.float8_e4m3fn) + tensors[prefix + '.weight_scale'], tensors[prefix + '.input_scale'] = torch.tensor(weight_scale), torch.tensor(input_scale) + declarations[prefix] = {'quant_algo': 'FP8'} + # Vision tensors are deliberately present: text preparation must not load them. + tensors['model.vision_model.unused.weight'] = torch.ones(256, dtype=torch.bfloat16) + raw = dict(model_type='muse_glimmer', architectures=['MuseGlimmerForConditionalGeneration'], + text_config=c.to_dict(), quantization_config=dict(quant_method='modelopt', quant_algo='MIXED_PRECISION', + quantized_layers=declarations)) + (tmp_path / 'config.json').write_text(json.dumps(raw)) + save_file(tensors, str(tmp_path / 'weights.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: 'weights.safetensors' for name in tensors}))) + for name in ('tokenizer.json', 'tokenizer_config.json', 'chat_template.jinja'): + (tmp_path / name).symlink_to(snapshot / name) + del canonical, tensors + config = PreparationConfig(context=256, prefill_chunk_size=128, max_active=1, + snapshot_budget_bytes=continuation_layout(ModelConfig.from_dict(raw)).row_bytes, + compile_workers=1, headroom_bytes=1 << 30, prompt_logprobs=True) + with PackageStorage(device=0) as storage: + with prepare(tmp_path, config, package_storage=storage) as model: + buffers = model.buffers + assert {s.kind for s in model.signatures.values()} == { + 'init', 'restore', 'snapshot', 'prefill', 'scored_prefill', 'decode', 'resume'} + assert model.memory_report['kv_dtype'] == 'bfloat16' + assert model.server_config['frontend']['eos_token_ids'] == [200001, 200008] + buffers['live_rows'].zero_() + buffers['admission_count'].zero_() + buffers['state_num_ops'].zero_() + before = buffers['state_pool'].clone() + 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(buffers['state_pool'], before) + 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['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 command(graph, source, destination, operation, expected): + for name, value in dict(request_slots=0, source_slots=source, destination_slots=destination, + operation=operation, expected_consumed=expected, num_ops=1).items(): + buffers['state_' + name].fill_(value) + replay(graph) + buffers['state_num_ops'].zero_() + + def admit(generation, *, restore=False): + admission = AdmissionBuffers.allocate('cpu', vocab_size=c.vocab_size, 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 + command('restore1' if restore else 'init1', 2 if restore else -1, 1, 0 if restore else 1, + 127 if restore else 0) + buffers['admission_count'].zero_() + + def prefill(tokens, *, scored=False): + buffers['query_lengths'][0] = len(tokens) + buffers['token_ids'][:len(tokens)].copy_(torch.tensor(tokens, device='cuda')) + buffers['sample_enabled'][0] = 0 + replay('scored_prefill128' if scored else 'prefill128') + + 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 + return tokens, pool.last_hidden[1].clone() + + admit(7) + prefill(prompt) + assert requests.consumed_tokens[0].item() == 127 + hidden = pool.last_hidden[1].clone() + cache = {(layer, kind): pool.cache(layer, kind).flatten(0, 1)[:127].clone() + for layer in range(2) for kind in ('key', 'value')} + + def assert_prompt_state(): + assert requests.consumed_tokens[0].item() == 127 + torch.testing.assert_close(pool.last_hidden[1], hidden, atol=0, rtol=0) + for (layer, kind), reference in cache.items(): + torch.testing.assert_close(pool.cache(layer, kind).flatten(0, 1)[:127], reference, + atol=0, rtol=0) + + command('snapshot1', 1, 2, 0, 127) + snapshot_row = pool.backing[2].clone() + expected_tokens, expected_hidden = continuation() + + admit(8) + prefill(prompt[:64]) + prefill(prompt[64:]) + assert_prompt_state() + tokens, final_hidden = continuation() + assert tokens == expected_tokens + torch.testing.assert_close(final_hidden, expected_hidden, atol=0, rtol=0) + assert torch.equal(pool.backing[2], snapshot_row) + + admit(9, restore=True) + assert_prompt_state() + tokens, final_hidden = continuation() + assert tokens == expected_tokens + torch.testing.assert_close(final_hidden, expected_hidden, atol=0, rtol=0) + assert torch.equal(pool.backing[2], snapshot_row) + + admit(10) + buffers['prompt_target_tokens'].fill_(-1) + buffers['prompt_target_tokens'][:126].copy_(torch.tensor(prompt[1:], device='cuda')) + prefill(prompt, scored=True) + assert_prompt_state() + 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] <= c.vocab_size)).all() + assert (scores[126:, 0] == -1).all() + assert torch.isnan(scores[126:, 1].contiguous().view(torch.float32)).all() + assert torch.equal(pool.backing[2], snapshot_row) diff --git a/tests/recipes/muse_glimmer/test_state_cuda.py b/tests/recipes/muse_glimmer/test_state_cuda.py new file mode 100644 index 000000000..2eee56964 --- /dev/null +++ b/tests/recipes/muse_glimmer/test_state_cuda.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""BF16 partial pages and normalized hidden states remain exact through snapshot forks.""" + +import os + +import pytest +import torch + +from ignition.recipes.muse_glimmer.config import ModelConfig +from ignition.recipes.muse_glimmer.pool import ContinuationPool +from tests.recipes.test_muse_spark_state_cuda import assert_snapshot_forks + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an explicitly assigned CUDA device") + + +@pytest.mark.parametrize("endpoint", [127, 128, 129, 2047, 2048, 2049]) +@torch.no_grad() +def test_captured_snapshot_forks_preserve_bf16_histories(endpoint): + config = ModelConfig(dict(num_hidden_layers=2, hidden_size=256, num_key_value_heads=2, head_dim=128), {}) + pool = ContinuationPool.allocate(config, 8, 5, "cuda:0") + assert_snapshot_forks(pool, endpoint) diff --git a/tests/recipes/test_muse_spark_state_cuda.py b/tests/recipes/test_muse_spark_state_cuda.py index c1ee2159f..7788c1314 100644 --- a/tests/recipes/test_muse_spark_state_cuda.py +++ b/tests/recipes/test_muse_spark_state_cuda.py @@ -20,19 +20,7 @@ reason="requires an explicitly assigned CUDA device") -@pytest.mark.parametrize("endpoint", [127, 128, 129, 2047, 2048, 2049]) -@pytest.mark.parametrize("dflash", [False, True]) -@torch.no_grad() -def test_captured_snapshot_forks_preserve_fp8_histories(endpoint, dflash): - config = SimpleNamespace(layers=2, attention=lambda i: Geometry(2048 if i == 0 else -1), - text={"hidden_size": 128}, - draft=SimpleNamespace(layers=5, attention=Geometry(2048)) if dflash else None) - pool = ContinuationPool.allocate(config, TensorParallelShard(0, 1), 8, 5, "cuda:0") - if dflash: - for layer in range(5): - for kind in ('key', 'value'): - region = pool.layout.region(f'draft{layer}.{kind}') - assert region.dtype == torch.float8_e4m3fn and region.shape == (2048, 2, 64) +def assert_snapshot_forks(pool, endpoint): commands = StateCommands.allocate("cuda:0", capacity=4) tables = torch.full((4, 17), -1, dtype=torch.int32, device="cuda:0") consumed = pool.region("consumed_tokens") @@ -92,10 +80,26 @@ def replay(operations): assert not plane[3:].count_nonzero() pool.region("last_hidden")[2].zero_() assert torch.equal(pool.backing[5], expected) + graph.reset() + + +@pytest.mark.parametrize("endpoint", [127, 128, 129, 2047, 2048, 2049]) +@pytest.mark.parametrize("dflash", [False, True]) +@torch.no_grad() +def test_captured_snapshot_forks_preserve_fp8_histories(endpoint, dflash): + config = SimpleNamespace(layers=2, attention=lambda i: Geometry(2048 if i == 0 else -1), + text={"hidden_size": 128}, + draft=SimpleNamespace(layers=5, attention=Geometry(2048)) if dflash else None) + pool = ContinuationPool.allocate(config, TensorParallelShard(0, 1), 8, 5, "cuda:0") + if dflash: + for layer in range(5): + for kind in ('key', 'value'): + region = pool.layout.region(f'draft{layer}.{kind}') + assert region.dtype == torch.float8_e4m3fn and region.shape == (2048, 2, 64) + assert_snapshot_forks(pool, endpoint) stride = pool.window_page_stride(0) for kind in ("key", "value"): paged = pool.window_pages(0, kind) for row in (0, 2, 3, 5, 7): torch.testing.assert_close(paged[row * stride:row * stride + 16].flatten(0, 1), pool.cache(0, kind)[row], atol=0, rtol=0, equal_nan=True) - graph.reset() diff --git a/tests/server/test_muse_glimmer.py b/tests/server/test_muse_glimmer.py new file mode 100644 index 000000000..f53f4ae1b --- /dev/null +++ b/tests/server/test_muse_glimmer.py @@ -0,0 +1,160 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Muse Glimmer acceptance against an exported package served by ``flare run``. + +Set FLARE_RUN_CUDA_TESTS=1, FLARE_MUSE_GLIMMER_TEST_URL and +FLARE_MUSE_GLIMMER_SNAPSHOT. Export with --prompt-logprobs, the default +131072-token context, concurrency four and a 4096-token prefill chunk. +""" + +import json +import math +import os +from pathlib import Path +import time + +import pytest + +from tests.server.test_muse_spark import (NativeMuse, content, test_concurrency_four_and_prefix_reuse, + test_unsupported_media_is_rejected) + +pytestmark = pytest.mark.skipif( + os.environ.get('FLARE_RUN_CUDA_TESTS') != '1' or not os.environ.get('FLARE_MUSE_GLIMMER_TEST_URL'), + reason='requires an exported Muse Glimmer package running through flare run', +) + +LONG_INPUTS = (4097, 8193, 16385, 32769, 65537, 131008) +CASES = ([('text', i) for i in range(20)] + [('tool', i) for i in range(12)] + + [('json', i) for i in range(12)] + [('long', i) for i in range(6)]) + + +class NativeGlimmer(NativeMuse): + def __init__(self): + from transformers import PreTrainedTokenizerFast + + self.url = os.environ['FLARE_MUSE_GLIMMER_TEST_URL'].rstrip('/') + self.key = os.environ.get('FLARE_API_TEST_KEY', 'local') + self.snapshot = Path(os.environ['FLARE_MUSE_GLIMMER_SNAPSHOT']) + self.tokenizer = PreTrainedTokenizerFast.from_pretrained(self.snapshot) + self.template = (self.snapshot / 'chat_template.jinja').read_text() + card, = self.request('/v1/models')['data'] + self.model = card['id'] + assert 'glimmer' in self.model.lower(), self.model + assert card['max_model_len'] == 131072 + assert card['flare']['max_concurrency'] == 4 + assert card['flare']['input_modalities'] == ['text'] + defaults = card['flare']['sampling_defaults'] + assert defaults['temperature'] == 1 + assert defaults['top_p'] == pytest.approx(.95) + assert defaults['top_k'] == 64 + + def body(self, prompt, **options): + body = dict(model=self.model, messages=[dict(role='user', content=prompt)], + temperature=1., top_p=.95, top_k=64, seed=41873, max_tokens=64, return_token_ids=True, + chat_template_kwargs=dict(reasoning_strength='low', current_date='2026-11-03', + add_generation_prompt=True)) + body.update(options) + return body + + +@pytest.fixture(scope='module') +def service(): + return NativeGlimmer() + + +@pytest.mark.parametrize('kind,index', CASES, ids=[f'{kind}-{i}' for kind, i in CASES]) +def test_fifty_prompt_cases(service, kind, index): + if kind == 'text': + if index < 10: + a, b = 17 + index, 23 - index + result = service.ask(f'What is {a} times {b}? Reply with only the integer.', compare_prompt=True) + assert content(result) == str(a * b) + else: + value = ['GLIMMER-53197', 'café', '世界', 'naïve', 'á', 'Δοκιμή', + 'مرحبا', '日本語', 'Straße', '한국어'][index - 10] + result = service.ask(f'Repeat exactly this text, without quotation marks or explanation: {value}', + compare_prompt=True) + assert content(result) == value + elif kind == 'tool': + value = dict(value=index + 2) + function = dict(name='record_value', description='Record the supplied values exactly.', + parameters=dict(type='object', properties=dict(value=dict(type='integer')), + required=['value'], additionalProperties=False)) + choice = 'required' if index % 2 else dict(type='function', function=dict(name='record_value')) + result = service.ask('Call record_value once with exactly these argument values:\n' + json.dumps(value), + tools=[dict(type='function', function=function)], tool_choice=choice) + call, = result['choices'][0]['message']['tool_calls'] + assert call['function']['name'] == 'record_value' + assert json.loads(call['function']['arguments']) == value + assert result['choices'][0]['finish_reason'] == 'tool_calls' + elif kind == 'json': + value = dict(index=index, text='世界 café', enabled=bool(index % 2)) + result = service.ask('Return the requested JSON object.', response_format=dict(type='json_schema', + json_schema=dict(name='exact_value', strict=True, schema=dict(const=value)))) + assert json.loads(content(result)) == value + else: + target = LONG_INPUTS[index] + result = service.ask(service.long_prompt(target), compare_prompt=True) + assert target - 8 <= result['usage']['prompt_tokens'] <= target + assert content(result) == 'MUSE53197' + + +def test_streamed_and_buffered_replay_agree(service): + prompt = 'Reply with only GLIMMER-STREAM.' + buffered = service.ask(prompt) + events = [] + with service.open('/v1/chat/completions', service.body(prompt, stream=True, + stream_options=dict(include_usage=True))) as response: + for line in response: + if not line.startswith(b'data: '): + continue + if line.strip() == b'data: [DONE]': + break + events.append(json.loads(line[6:])) + else: + pytest.fail('stream ended without [DONE]') + choices = [choice for event in events for choice in event['choices']] + assert ''.join(choice.get('delta', {}).get('content') or '' for choice in choices).strip() == content(buffered) + assert [token for choice in choices for token in choice.get('token_ids', [])] == buffered['choices'][0]['token_ids'] + assert choices[-1]['finish_reason'] == 'stop' + assert any(event['usage']['completion_tokens'] > 0 for event in events if event.get('usage')) + + +def test_prompt_logprobs_match_checkpoint_token_ids(service): + tokens = service.expected_prompt(service.body('A cache preserves context. café 世界 17 times 23 equals 391.')) + result = service.request('/v1/completions', dict(model=service.model, prompt=tokens, + max_tokens=0, prompt_logprobs=2)) + assert result['usage']['prompt_tokens'] == len(tokens) + assert result['usage']['completion_tokens'] == 0 + scores = result['choices'][0]['prompt_logprobs'] + assert len(scores) == len(tokens) and scores[0] is None + for token, values in zip(tokens[1:], scores[1:], strict=True): + assert str(token) in values + assert 2 <= len(values) <= 3 + for token_id, value in values.items(): + assert 0 <= int(token_id) < len(service.tokenizer) + assert math.isfinite(value['logprob']) and value['logprob'] <= 0 + assert value['rank'] >= 1 + + +def test_cancel_drains_and_recovers(service): + before = service.metrics() + saw_token = False + with service.open('/v1/chat/completions', service.body( + 'List the integers from 1 through 2000, one per line.', stream=True, max_tokens=2048)) as response: + for line in response: + if line.startswith(b'data: ') and line.strip() != b'data: [DONE]': + if any(choice.get('token_ids') for choice in json.loads(line[6:]).get('choices', [])): + saw_token = True + break + assert saw_token + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + after = service.metrics() + if after['flare_active_requests'] == after['flare_http_inflight_requests'] == 0: + break + time.sleep(.02) + assert after['flare_active_requests'] == after['flare_http_inflight_requests'] == 0 + assert after['flare_requests_cancelled_total'] > before['flare_requests_cancelled_total'] + assert content(service.ask('Reply with only GLIMMER-RECOVER.')) == 'GLIMMER-RECOVER'