From b1300329ff764beb5663ba3e29e63f27733f5d2a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 18:47:09 +0200 Subject: [PATCH] feat(model): bind pinned Qwen topology and bounded tensor rows [skip ci] --- crates/model-format/src/gguf.rs | 348 ++++- crates/model-format/src/lib.rs | 1 + crates/model-format/src/qwen4exp.rs | 1166 +++++++++++++++++ .../tests/qwen_artifact_binding/fixtures.rs | 418 ++++++ .../tests/qwen_artifact_binding/mod.rs | 791 +++++++++++ 5 files changed, 2683 insertions(+), 41 deletions(-) create mode 100644 crates/model-format/src/qwen4exp.rs create mode 100644 crates/model-format/tests/qwen_artifact_binding/fixtures.rs create mode 100644 crates/model-format/tests/qwen_artifact_binding/mod.rs diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index ac8c727c..9156301a 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -41,7 +41,7 @@ pub struct TensorIndex { pub tensors: Vec, } -#[derive(Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct TokenizerMetadata { pub model: String, pub pre: String, @@ -52,6 +52,31 @@ pub struct TokenizerMetadata { pub chat_template: String, } +/// Bounded, owned values for the model metadata keys consumed by model-format +/// admission. Unknown keys continue to be skipped by the GGUF reader. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum MetadataValue { + Unsigned(u64), + Signed(i64), + Boolean(bool), + Float(f64), + Text(String), + UnsignedArray(Vec), + SignedArray(Vec), + FloatArray(Vec), + TextArray(Vec), +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct MetadataSnapshot { + pub architecture: Option, + pub split_no: Option, + pub split_count: Option, + pub split_tensors_count: Option, + pub values: BTreeMap, + pub tokenizer: Option, +} + /// An owned GGUF file whose complete bytes matched the declared digest at open. /// /// The private file and index stay paired across pathname replacements. This is @@ -65,6 +90,53 @@ pub struct VerifiedGgufFile { } const STREAM_BUFFER_BYTES: usize = 64 * 1024; +const FLASH_NEXT_PROFILE_KEYS: &[&str] = &[ + "qwen4exp.block_count", + "qwen4exp.embedding_length", + "qwen4exp.attention.head_count", + "qwen4exp.attention.head_count_kv", + "qwen4exp.expert_count", + "qwen4exp.expert_used_count", +]; +const QWEN4EXP_BINDING_KEYS: &[&str] = &[ + "qwen4exp.context_length", + "qwen4exp.block_count", + "qwen4exp.embedding_length", + "qwen4exp.embedding_length_per_layer_input", + "qwen4exp.attention.compress_ratios", + "qwen4exp.full_attention_interval", + "qwen4exp.expert_count", + "qwen4exp.expert_used_count", + "qwen4exp.expert_feed_forward_length", + "qwen4exp.expert_shared_feed_forward_length", + "qwen4exp.attention.head_count", + "qwen4exp.attention.head_count_kv", + "qwen4exp.attention.key_length", + "qwen4exp.attention.value_length", + "qwen4exp.attention.layer_norm_rms_epsilon", + "qwen4exp.hyper_connection.count", + "qwen4exp.hyper_connection.low_rank", + "qwen4exp.rope.dimension_count", + "qwen4exp.rope.dimension_sections", + "qwen4exp.rope.freq_base", + "qwen4exp.attention.indexer.head_count", + "qwen4exp.attention.indexer.key_length", + "qwen4exp.attention.indexer.top_k", + "qwen4exp.ssm.conv_kernel", + "qwen4exp.ssm.state_size", + "qwen4exp.ssm.group_count", + "qwen4exp.ssm.time_step_rank", + "qwen4exp.ssm.inner_size", + "qwen4exp.ple.layers", + "qwen4exp.ple.ngram_size", + "qwen4exp.ple.heads_per_ngram", + "qwen4exp.ple.conv_kernel", + "qwen4exp.ple.eos_token_id", + "qwen4exp.ple.image_token_id", + "qwen4exp.ple.head_offsets", + "qwen4exp.ple.head_vocab_sizes", + "qwen4exp.ple.layer_multipliers", +]; impl VerifiedGgufFile { /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. @@ -114,6 +186,44 @@ impl VerifiedGgufFile { self.artifact_sha256 } + /// Parse the bounded model/tokenizer metadata through the already verified + /// descriptor. The path is never reopened and the indexed file size is + /// checked on both sides of the snapshot. + #[cfg(test)] + pub(crate) fn metadata_snapshot(&mut self) -> Result { + self.check_size()?; + let snapshot = read_metadata_snapshot( + &mut self.file, + self.index.summary.file_size, + Some(QWEN4EXP_BINDING_KEYS), + true, + )?; + self.check_size()?; + Ok(snapshot) + } + + /// Parse only Qwen profile fields, deferring tokenizer work so the model + /// binder can preserve profile-before-tokenizer error precedence. + pub(crate) fn profile_snapshot(&mut self) -> Result { + self.check_size()?; + let snapshot = read_metadata_snapshot( + &mut self.file, + self.index.summary.file_size, + Some(QWEN4EXP_BINDING_KEYS), + false, + )?; + self.check_size()?; + Ok(snapshot) + } + + pub(crate) fn tokenizer_snapshot(&mut self) -> Result> { + self.check_size()?; + let snapshot = + read_metadata_snapshot(&mut self.file, self.index.summary.file_size, None, true)?; + self.check_size()?; + Ok(snapshot.tokenizer) + } + /// Stream an exact byte range within an indexed tensor through a buffer of /// at most 64 KiB. The consumer may return an I/O error to abort the stream. /// No pathname is reopened; all range checks precede the first callback. @@ -213,8 +323,15 @@ fn stream_file_span( /// Metadata admission for the specialised engine, before expensive preparation. /// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. pub fn check_flash_next_profile(path: &Path) -> Result<()> { - let summary = inspect(path)?; - if summary.architecture.as_deref() != Some("qwen4exp") { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + read_index_file(&mut file, size, false)?; + let snapshot = read_metadata_snapshot(&mut file, size, Some(FLASH_NEXT_PROFILE_KEYS), false)?; + validate_flash_next_profile(&snapshot) +} + +fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result<()> { + if snapshot.architecture.as_deref() != Some("qwen4exp") { return Err("runtime_profile requires general.architecture=qwen4exp".into()); } let required = [ @@ -225,31 +342,19 @@ pub fn check_flash_next_profile(path: &Path) -> Result<()> { ("qwen4exp.expert_count", None), ("qwen4exp.expert_used_count", None), ]; - let mut cursor = Cursor { - file: File::open(path)?, - size: summary.file_size, - }; - cursor.skip(24)?; let mut values = BTreeMap::new(); - for _ in 0..summary.metadata { - let key = cursor.string()?; - let kind = cursor.u32()?; - if required.iter().any(|(name, _)| *name == key) { - if !matches!(kind, 0..=5 | 10 | 11) { - return Err(format!("runtime_profile: {key} must be an integer").into()); - } - let value = cursor.integer(kind).map_err(|_| { - format!("runtime_profile: {key} must be a nonnegative 32-bit integer") - })?; - values.insert(key, value); - } else { - cursor.skip_value(kind)?; - } - } for (key, expected) in required { - let value = *values - .get(key) - .ok_or_else(|| format!("runtime_profile: missing {key}"))?; + let value = match snapshot.values.get(key) { + Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(|_| { + format!("runtime_profile: {key} must be a nonnegative 32-bit integer") + })?, + Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(|_| { + format!("runtime_profile: {key} must be a nonnegative 32-bit integer") + })?, + None => return Err(format!("runtime_profile: missing {key}").into()), + _ => return Err(format!("runtime_profile: {key} must be an integer").into()), + }; + values.insert(key, value); if value == 0 || value > i32::MAX as u32 { return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); } @@ -269,12 +374,33 @@ pub fn check_flash_next_profile(path: &Path) -> Result<()> { /// Read only tokenizer fields after the complete GGUF header has passed inspection. pub fn tokenizer_metadata(path: &Path) -> Result { - inspect(path)?; - let file = File::open(path)?; + let mut file = File::open(path)?; let size = file.metadata()?.len(); + read_index_file(&mut file, size, false)?; + validate_tokenizer_metadata( + read_metadata_snapshot(&mut file, size, None, true)? + .tokenizer + .ok_or("GGUF is missing required tokenizer metadata")?, + ) +} + +fn read_metadata_snapshot( + file: &mut File, + size: u64, + qwen_keys: Option<&[&str]>, + parse_tokenizer: bool, +) -> Result { + file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor { file, size }; cursor.skip(16)?; // magic, version, tensor count let count = cursor.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + let mut architecture = None; + let mut split_no = None; + let mut split_count = None; + let mut split_tensors_count = None; let mut model = None; let mut pre = None; let mut tokens = None; @@ -282,27 +408,83 @@ pub fn tokenizer_metadata(path: &Path) -> Result { let mut token_types = None; let mut special_ids = BTreeMap::new(); let mut chat_template = None; + let mut values = BTreeMap::new(); + let mut seen = HashSet::new(); for _ in 0..count { let key = cursor.string()?; + if !seen.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } let kind = cursor.u32()?; match key.as_str() { - "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), - "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), - "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), - _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { + "general.architecture" if kind == 8 => architecture = Some(cursor.string()?), + "split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)), + "split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)), + "split.tensors.count" if kind == 5 => { + split_tensors_count = Some(u64::from(cursor.u32()?)) + } + "split.no" | "split.count" | "split.tensors.count" => { + return Err("GGUF split metadata has an invalid integer type".into()); + } + "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => { + model = Some(cursor.string()?) + } + "tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?), + "tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" if parse_tokenizer => { + token_types = Some(cursor.integer_array(kind)?) + } + "tokenizer.chat_template" if parse_tokenizer && kind == 8 => { + chat_template = Some(cursor.string()?) + } + _ if parse_tokenizer + && key.starts_with("tokenizer.ggml.") + && key.ends_with("_token_id") => + { special_ids.insert(key, cursor.integer(kind)?); } + _ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => { + values.insert(key, cursor.metadata_value(kind)?); + } _ => cursor.skip_value(kind)?, } } - let model = model.ok_or("GGUF is missing tokenizer.ggml.model")?; - let tokens = tokens.ok_or("GGUF is missing tokenizer.ggml.tokens")?; - let merges = merges.ok_or("GGUF is missing tokenizer.ggml.merges")?; - let chat_template = chat_template.ok_or("GGUF is missing tokenizer.chat_template")?; - if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { + let tokenizer = match (model, tokens, merges, chat_template) { + (Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata { + model, + pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types, + special_ids, + chat_template, + }), + _ => None, + }; + Ok(MetadataSnapshot { + architecture, + split_no, + split_count, + split_tensors_count, + values, + tokenizer, + }) +} + +pub(crate) fn validate_tokenizer_metadata( + tokenizer: TokenizerMetadata, +) -> Result { + let TokenizerMetadata { + model, + pre, + tokens, + merges, + token_types, + special_ids, + chat_template, + } = tokenizer; + if model != "gpt2" || pre != "qwen35" { return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); } if tokens.is_empty() || chat_template.is_empty() { @@ -340,7 +522,7 @@ pub fn tokenizer_metadata(path: &Path) -> Result { } Ok(TokenizerMetadata { model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + pre, tokens, merges, token_types, @@ -711,6 +893,90 @@ impl Cursor { } } + fn metadata_value(&mut self, kind: u32) -> Result { + Ok(match kind { + 0 => MetadataValue::Unsigned(u64::from(self.u8()?)), + 7 => MetadataValue::Boolean(self.u8()? != 0), + 1 => MetadataValue::Signed(i64::from(self.u8()? as i8)), + 2 => MetadataValue::Unsigned(u64::from(self.u16()?)), + 3 => MetadataValue::Signed(i64::from(self.u16()? as i16)), + 4 => MetadataValue::Unsigned(u64::from(self.u32()?)), + 5 => MetadataValue::Signed(i64::from(self.u32()? as i32)), + 6 => MetadataValue::Float(f64::from(f32::from_bits(self.u32()?))), + 8 => MetadataValue::Text(self.string()?), + 9 => self.metadata_array()?, + 10 => MetadataValue::Unsigned(self.u64()?), + 11 => MetadataValue::Signed(self.u64()? as i64), + 12 => MetadataValue::Float(f64::from_bits(self.u64()?)), + _ => return Err(format!("unknown GGUF metadata type {kind}").into()), + }) + } + + fn metadata_array(&mut self) -> Result { + let element = self.u32()?; + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF metadata array count".into()); + } + let capacity = count as usize; + match element { + 0 | 7 | 2 | 4 | 10 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(match element { + 0 | 7 => u64::from(self.u8()?), + 2 => u64::from(self.u16()?), + 4 => u64::from(self.u32()?), + 10 => self.u64()?, + _ => unreachable!(), + }); + } + Ok(MetadataValue::UnsignedArray(values)) + } + 1 | 3 | 5 | 11 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(match element { + 1 => i64::from(self.u8()? as i8), + 3 => i64::from(self.u16()? as i16), + 5 => i64::from(self.u32()? as i32), + 11 => self.u64()? as i64, + _ => unreachable!(), + }); + } + Ok(MetadataValue::SignedArray(values)) + } + 6 | 12 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(if element == 6 { + f64::from(f32::from_bits(self.u32()?)) + } else { + f64::from_bits(self.u64()?) + }); + } + Ok(MetadataValue::FloatArray(values)) + } + 8 => { + let mut total = 0u64; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or("GGUF metadata array size overflow")?; + if total > 512 * 1024 * 1024 { + return Err("GGUF metadata string array exceeds 512 MiB".into()); + } + values.push(value); + } + Ok(MetadataValue::TextArray(values)) + } + 9 => Err("nested GGUF arrays are unsupported".into()), + _ => Err(format!("invalid GGUF metadata array element type {element}").into()), + } + } + fn skip_value(&mut self, kind: u32) -> Result<()> { match kind { 0 | 1 | 7 => self.skip(1), diff --git a/crates/model-format/src/lib.rs b/crates/model-format/src/lib.rs index b954b632..b1c0b6c2 100644 --- a/crates/model-format/src/lib.rs +++ b/crates/model-format/src/lib.rs @@ -7,3 +7,4 @@ //! Its only direct dependency is the Rust SHA-256 implementation in `sha2`. pub mod gguf; +pub mod qwen4exp; diff --git a/crates/model-format/src/qwen4exp.rs b/crates/model-format/src/qwen4exp.rs new file mode 100644 index 00000000..6731e2a3 --- /dev/null +++ b/crates/model-format/src/qwen4exp.rs @@ -0,0 +1,1166 @@ +//! Closed Qwen4Exp artifact admission over two already-verified GGUF owners. +//! +//! This module validates metadata and tensor layout only. It does not decode +//! quantized values, allocate device memory, or execute model operations. + +use crate::gguf::{ + self, MetadataSnapshot, MetadataValue, TensorIndex, TokenizerMetadata, VerifiedGgufFile, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + error::Error, + fmt, io, +}; + +const PINNED_IDENTITIES: [(u64, [u8; 32]); 2] = [ + ( + 54_817_524_224, + [ + 0x4c, 0x1e, 0xb2, 0xce, 0xb4, 0x91, 0x5e, 0x11, 0x92, 0xf4, 0xf3, 0x86, 0x02, 0x18, + 0x97, 0xbd, 0xe5, 0x6a, 0x97, 0xf4, 0x0a, 0x0b, 0xb7, 0x8b, 0xb8, 0x64, 0x65, 0xe0, + 0xf7, 0xd2, 0xac, 0xa3, + ], + ), + ( + 28_800_138_432, + [ + 0x31, 0x6b, 0x46, 0xf3, 0xa2, 0xdb, 0xd6, 0x8c, 0x90, 0x0f, 0x43, 0x13, 0x6a, 0xb9, + 0x44, 0x9f, 0x9d, 0xcc, 0x37, 0x25, 0xdf, 0x8d, 0xc7, 0x94, 0x84, 0x7c, 0x20, 0x4b, + 0xc1, 0x61, 0xe1, 0x13, + ], + ), +]; + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum GlobalRole { + TokenEmbedding, + Output, + OutputHcDown, + OutputHcNorm, + OutputHcUp, + PerLayerTokenEmbedding, +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum LayerRole { + HcAttnDown, + HcAttnUp, + HcAttnInject, + HcAttnNorm, + HcFfnDown, + HcFfnUp, + HcFfnInject, + HcFfnNorm, + FfnGateInp, + FfnGateInpShared, + FfnGateShared, + FfnUpShared, + FfnDownShared, + FfnGateExperts, + FfnUpExperts, + FfnDownExperts, + AttnQkv, + AttnGate, + SsmOut, + SsmConv1d, + SsmAlpha, + SsmBeta, + SsmA, + SsmDtBias, + SsmNorm, + AttnQ, + AttnK, + AttnV, + AttnOutput, + AttnQNorm, + AttnKNorm, + IndexerQProj, + IndexerKProj, + IndexerQNorm, + IndexerKNorm, + PleConv1d, + PleKey, + PleNormConv, + PleNormKey, + PleNormQuery, + PleValue, +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum TensorRole { + Global(GlobalRole), + Layer { layer: u8, role: LayerRole }, +} + +/// Stable, path-free admission failures. The display text intentionally names +/// only a category and a fixed metadata/role identifier. +#[derive(Debug)] +pub enum BindingError { + Identity(u8), + Split(&'static str), + Metadata(&'static str), + Tokenizer(&'static str), + Role(&'static str), + Geometry(&'static str), + Range(&'static str), + Io(Box), +} + +impl fmt::Display for BindingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Identity(shard) => write!(f, "artifact identity rejected for shard {shard}"), + Self::Split(field) => write!(f, "split metadata rejected: {field}"), + Self::Metadata(field) => write!(f, "model metadata rejected: {field}"), + Self::Tokenizer(field) => write!(f, "tokenizer metadata rejected: {field}"), + Self::Role(role) => write!(f, "tensor role rejected: {role}"), + Self::Geometry(role) => write!(f, "tensor geometry rejected: {role}"), + Self::Range(role) => write!(f, "tensor range rejected: {role}"), + Self::Io(_) => f.write_str("GGUF stream I/O failed"), + } + } +} + +impl Error for BindingError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Io(error) => Some(error.as_ref()), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Qwen4ExpTopology { + architecture: String, + block_count: u32, + embedding_length: u32, + context_length: u32, + compression_ratios: Vec, + full_attention_interval: u32, + expert_count: u32, + expert_used_count: u32, + expert_feed_forward_length: u32, + expert_shared_feed_forward_length: u32, + attention_head_count: u32, + attention_head_count_kv: u32, + attention_key_length: u32, + attention_value_length: u32, + rms_epsilon: f64, + hc_count: u32, + hc_low_rank: u32, + rope_dimension_count: u32, + rope_dimension_sections: Vec, + rope_frequency_base: f64, + indexer_head_count: u32, + indexer_key_length: u32, + indexer_top_k: u32, + ssm_conv_kernel: u32, + ssm_state_size: u32, + ssm_group_count: u32, + ssm_time_step_rank: u32, + ssm_inner_size: u32, + per_layer_embedding_length: u32, + ple_layers: Vec, + ple_ngram_size: u32, + ple_heads_per_ngram: u32, + ple_conv_kernel: u32, + ple_eos_token_id: u32, + ple_image_token_id: u32, + ple_head_offsets: Vec, + ple_head_vocab_sizes: Vec, + ple_layer_multipliers: Vec, +} + +macro_rules! topology_u32_accessors { + ($($method:ident => $field:ident),+ $(,)?) => {$( + pub fn $method(&self) -> u32 { self.$field } + )+}; +} + +impl Qwen4ExpTopology { + pub fn architecture(&self) -> &str { + &self.architecture + } + pub fn rms_epsilon(&self) -> f64 { + self.rms_epsilon + } + pub fn rope_frequency_base(&self) -> f64 { + self.rope_frequency_base + } + pub fn compression_ratios(&self) -> &[u64] { + &self.compression_ratios + } + pub fn rope_dimension_sections(&self) -> &[u64] { + &self.rope_dimension_sections + } + pub fn ple_layers(&self) -> &[u64] { + &self.ple_layers + } + pub fn ple_head_offsets(&self) -> &[u64] { + &self.ple_head_offsets + } + pub fn ple_head_vocab_sizes(&self) -> &[u64] { + &self.ple_head_vocab_sizes + } + pub fn ple_layer_multipliers(&self) -> &[u64] { + &self.ple_layer_multipliers + } + topology_u32_accessors!( + block_count => block_count, + embedding_length => embedding_length, + context_length => context_length, + full_attention_interval => full_attention_interval, + expert_count => expert_count, + expert_used_count => expert_used_count, + expert_feed_forward_length => expert_feed_forward_length, + expert_shared_feed_forward_length => expert_shared_feed_forward_length, + attention_head_count => attention_head_count, + attention_head_count_kv => attention_head_count_kv, + attention_key_length => attention_key_length, + attention_value_length => attention_value_length, + hc_count => hc_count, + hc_low_rank => hc_low_rank, + rope_dimension_count => rope_dimension_count, + indexer_head_count => indexer_head_count, + indexer_key_length => indexer_key_length, + indexer_top_k => indexer_top_k, + ssm_conv_kernel => ssm_conv_kernel, + ssm_state_size => ssm_state_size, + ssm_group_count => ssm_group_count, + ssm_time_step_rank => ssm_time_step_rank, + ssm_inner_size => ssm_inner_size, + per_layer_embedding_length => per_layer_embedding_length, + ple_ngram_size => ple_ngram_size, + ple_heads_per_ngram => ple_heads_per_ngram, + ple_conv_kernel => ple_conv_kernel, + ple_eos_token_id => ple_eos_token_id, + ple_image_token_id => ple_image_token_id, + ); +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ResolvedTensor { + shard: u8, + tensor_number: usize, + name: String, + kind: u32, + dimensions: Vec, + absolute_start: u64, + byte_length: u64, + file_size: u64, +} + +impl ResolvedTensor { + pub fn shard(&self) -> u8 { + self.shard + } + pub fn tensor_number(&self) -> usize { + self.tensor_number + } + pub fn name(&self) -> &str { + &self.name + } + pub fn kind(&self) -> u32 { + self.kind + } + pub fn dimensions(&self) -> &[u64] { + &self.dimensions + } + pub fn absolute_start(&self) -> u64 { + self.absolute_start + } + pub fn byte_length(&self) -> u64 { + self.byte_length + } +} + +/// Fully admitted model-specific view. File owners are retained for the entire +/// lifetime of locations and row streams. +pub struct Qwen4ExpArtifact { + shards: [VerifiedGgufFile; 2], + topology: Qwen4ExpTopology, + tokenizer: TokenizerMetadata, + roles: BTreeMap, +} + +impl Qwen4ExpArtifact { + pub fn bind(shard0: VerifiedGgufFile, shard1: VerifiedGgufFile) -> Result { + let owners = [shard0, shard1]; + for (index, owner) in owners.iter().enumerate() { + let (size, digest) = PINNED_IDENTITIES[index]; + if owner.index().summary.file_size != size || owner.artifact_sha256() != digest { + return Err(BindingError::Identity(index as u8)); + } + } + Self::bind_after_identity(owners) + } + + fn bind_after_identity(owners: [VerifiedGgufFile; 2]) -> Result { + validate_owner_split(&owners)?; + let mut owners = owners; + let mut snapshots = [ + owners[0].profile_snapshot().map_err(BindingError::Io)?, + owners[1].profile_snapshot().map_err(BindingError::Io)?, + ]; + // Profile/topology admission precedes tokenizer parsing and validation. + if snapshots[0].architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + if snapshots[1] + .architecture + .as_deref() + .is_some_and(|value| value != "qwen4exp") + { + return Err(BindingError::Metadata("general.architecture")); + } + topology(&snapshots[0])?; + snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; + let [metadata0, metadata1] = snapshots; + let views = [ + LogicalShardView { + index: owners[0].index(), + metadata: metadata0, + }, + LogicalShardView { + index: owners[1].index(), + metadata: metadata1, + }, + ]; + let validated = validate_logical_views(views)?; + Ok(Self { + shards: owners, + topology: validated.topology, + tokenizer: validated.tokenizer, + roles: validated.roles, + }) + } + + pub fn topology(&self) -> &Qwen4ExpTopology { + &self.topology + } + pub fn tokenizer(&self) -> &TokenizerMetadata { + &self.tokenizer + } + + pub fn tensor(&self, role: TensorRole) -> Result<&ResolvedTensor, BindingError> { + self.roles + .get(&role) + .ok_or(BindingError::Role("not_present")) + } + + pub fn stream_row( + &mut self, + role: TensorRole, + row: u64, + mut consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_row(tensor, row, None)?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { + consume(chunk) + }) + .map_err(BindingError::Io) + } + + pub fn stream_expert_row( + &mut self, + role: TensorRole, + expert: u64, + row: u64, + mut consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_row(tensor, row, Some(expert))?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { + consume(chunk) + }) + .map_err(BindingError::Io) + } +} + +fn validate_owner_split(owners: &[VerifiedGgufFile; 2]) -> Result<(), BindingError> { + for (number, owner) in owners.iter().enumerate() { + let summary = &owner.index().summary; + if summary.split_no != Some(number as u64) { + return Err(BindingError::Split("split.no")); + } + if summary.split_count != Some(2) { + return Err(BindingError::Split("split.count")); + } + if summary.split_tensors_count != Some(1224) { + return Err(BindingError::Split("split.tensors.count")); + } + } + for (number, owner) in owners.iter().enumerate() { + let expected = if number == 0 { 1223 } else { 1 }; + if owner.index().tensors.len() != expected { + return Err(BindingError::Split("indexed_tensor_count")); + } + } + Ok(()) +} + +struct LogicalShardView<'a> { + index: &'a TensorIndex, + metadata: MetadataSnapshot, +} + +struct ValidatedBindingView { + topology: Qwen4ExpTopology, + tokenizer: TokenizerMetadata, + roles: BTreeMap, +} + +fn required_uint(metadata: &MetadataSnapshot, key: &'static str) -> Result { + match metadata.values.get(key) { + Some(MetadataValue::Unsigned(value)) => Ok(*value), + Some(MetadataValue::Signed(value)) if *value >= 0 => Ok(*value as u64), + _ => Err(BindingError::Metadata(key)), + } +} + +fn required_u32( + metadata: &MetadataSnapshot, + key: &'static str, + expected: u32, +) -> Result { + let value = required_uint(metadata, key)?; + if value != u64::from(expected) { + return Err(BindingError::Metadata(key)); + } + Ok(expected) +} + +fn required_float(metadata: &MetadataSnapshot, key: &'static str) -> Result { + match metadata.values.get(key) { + Some(MetadataValue::Float(value)) if value.is_finite() && *value > 0.0 => Ok(*value), + Some(MetadataValue::Unsigned(value)) if *value > 0 => Ok(*value as f64), + Some(MetadataValue::Signed(value)) if *value > 0 => Ok(*value as f64), + _ => Err(BindingError::Metadata(key)), + } +} + +fn required_array( + metadata: &MetadataSnapshot, + key: &'static str, + expected: &[u64], +) -> Result, BindingError> { + let values = match metadata.values.get(key) { + Some(MetadataValue::UnsignedArray(values)) => values.clone(), + Some(MetadataValue::SignedArray(values)) => values + .iter() + .map(|value| u64::try_from(*value).map_err(|_| BindingError::Metadata(key))) + .collect::, _>>()?, + _ => return Err(BindingError::Metadata(key)), + }; + if values != expected { + return Err(BindingError::Metadata(key)); + } + Ok(values) +} + +fn topology(metadata: &MetadataSnapshot) -> Result { + if metadata.architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + let block_count = required_u32(metadata, "qwen4exp.block_count", 48)?; + let embedding_length = required_u32(metadata, "qwen4exp.embedding_length", 2560)?; + let compression_ratios = required_array( + metadata, + "qwen4exp.attention.compress_ratios", + &(0..48) + .map(|layer| if layer % 4 == 3 { 4 } else { 0 }) + .collect::>(), + )?; + let full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; + let expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; + let expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; + let expert_feed_forward_length = + required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; + let expert_shared_feed_forward_length = + required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; + let attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; + let attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; + let attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; + let attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; + let rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; + if (rms_epsilon - 1.0e-6).abs() > 1.0e-12 { + return Err(BindingError::Metadata( + "qwen4exp.attention.layer_norm_rms_epsilon", + )); + } + let hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; + let hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; + let rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; + let rope_dimension_sections = required_array( + metadata, + "qwen4exp.rope.dimension_sections", + &[11, 11, 10, 0], + )?; + let rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; + if rope_frequency_base != 10_000_000.0 { + return Err(BindingError::Metadata("qwen4exp.rope.freq_base")); + } + let indexer_head_count = required_u32(metadata, "qwen4exp.attention.indexer.head_count", 4)?; + let indexer_key_length = required_u32(metadata, "qwen4exp.attention.indexer.key_length", 128)?; + let indexer_top_k = required_u32(metadata, "qwen4exp.attention.indexer.top_k", 2048)?; + let ssm_conv_kernel = required_u32(metadata, "qwen4exp.ssm.conv_kernel", 4)?; + let ssm_state_size = required_u32(metadata, "qwen4exp.ssm.state_size", 128)?; + let ssm_group_count = required_u32(metadata, "qwen4exp.ssm.group_count", 16)?; + let ssm_time_step_rank = required_u32(metadata, "qwen4exp.ssm.time_step_rank", 48)?; + let ssm_inner_size = required_u32(metadata, "qwen4exp.ssm.inner_size", 6144)?; + let per_layer_embedding_length = + required_u32(metadata, "qwen4exp.embedding_length_per_layer_input", 160)?; + let ple_layers = required_array(metadata, "qwen4exp.ple.layers", &[1])?; + let ple_ngram_size = required_u32(metadata, "qwen4exp.ple.ngram_size", 3)?; + let ple_heads_per_ngram = required_u32(metadata, "qwen4exp.ple.heads_per_ngram", 8)?; + let ple_conv_kernel = required_u32(metadata, "qwen4exp.ple.conv_kernel", 4)?; + let ple_eos_token_id = required_u32(metadata, "qwen4exp.ple.eos_token_id", 248_044)?; + let ple_image_token_id = required_u32(metadata, "qwen4exp.ple.image_token_id", 248_056)?; + let ple_head_offsets = required_array( + metadata, + "qwen4exp.ple.head_offsets", + &[ + 0, + 20_000_003, + 40_000_026, + 60_000_059, + 80_000_106, + 100_000_165, + 120_000_228, + 140_000_297, + 160_000_374, + 180_000_455, + 200_000_548, + 220_000_655, + 240_000_802, + 260_000_955, + 280_001_114, + 300_001_275, + ], + )?; + let ple_head_vocab_sizes = required_array( + metadata, + "qwen4exp.ple.head_vocab_sizes", + &[ + 20_000_003, 20_000_023, 20_000_033, 20_000_047, 20_000_059, 20_000_063, 20_000_069, + 20_000_077, 20_000_081, 20_000_093, 20_000_107, 20_000_147, 20_000_153, 20_000_159, + 20_000_161, 20_000_171, + ], + )?; + let ple_layer_multipliers = required_array( + metadata, + "qwen4exp.ple.layer_multipliers", + &[23_703_573_157_769, 20_109_073_645_365, 8_052_911_324_071], + )?; + let context_length = required_u32(metadata, "qwen4exp.context_length", 262_144)?; + Ok(Qwen4ExpTopology { + architecture: "qwen4exp".to_owned(), + block_count, + embedding_length, + context_length, + compression_ratios, + full_attention_interval, + expert_count, + expert_used_count, + expert_feed_forward_length, + expert_shared_feed_forward_length, + attention_head_count, + attention_head_count_kv, + attention_key_length, + attention_value_length, + rms_epsilon, + hc_count, + hc_low_rank, + rope_dimension_count, + rope_dimension_sections, + rope_frequency_base, + indexer_head_count, + indexer_key_length, + indexer_top_k, + ssm_conv_kernel, + ssm_state_size, + ssm_group_count, + ssm_time_step_rank, + ssm_inner_size, + per_layer_embedding_length, + ple_layers, + ple_ngram_size, + ple_heads_per_ngram, + ple_conv_kernel, + ple_eos_token_id, + ple_image_token_id, + ple_head_offsets, + ple_head_vocab_sizes, + ple_layer_multipliers, + }) +} + +fn validate_tokenizer(tokenizer: &TokenizerMetadata) -> Result<(), BindingError> { + let id = |name: &str| tokenizer.special_ids.get(name).copied(); + if id("tokenizer.ggml.bos_token_id") != Some(248_044) { + return Err(BindingError::Tokenizer("tokenizer.ggml.bos_token_id")); + } + if id("tokenizer.ggml.padding_token_id") != Some(248_044) { + return Err(BindingError::Tokenizer("tokenizer.ggml.padding_token_id")); + } + if id("tokenizer.ggml.eos_token_id") != Some(248_046) { + return Err(BindingError::Tokenizer("tokenizer.ggml.eos_token_id")); + } + Ok(()) +} + +fn validate_logical_views( + mut shards: [LogicalShardView<'_>; 2], +) -> Result { + for (number, shard) in shards.iter().enumerate() { + let (expected_no, expected_count) = (number as u64, 2); + if shard.index.summary.split_no != Some(expected_no) + || shard.metadata.split_no != Some(expected_no) + { + return Err(BindingError::Split("split.no")); + } + if shard.index.summary.split_count != Some(expected_count) + || shard.metadata.split_count != Some(expected_count) + { + return Err(BindingError::Split("split.count")); + } + if shard.index.summary.split_tensors_count != Some(1224) + || shard.metadata.split_tensors_count != Some(1224) + { + return Err(BindingError::Split("split.tensors.count")); + } + } + for (number, shard) in shards.iter().enumerate() { + let expected_tensors = if number == 0 { 1223 } else { 1 }; + if shard.index.tensors.len() != expected_tensors { + return Err(BindingError::Split("indexed_tensor_count")); + } + } + if shards[0].metadata.architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + if shards[1] + .metadata + .architecture + .as_deref() + .is_some_and(|value| value != "qwen4exp") + { + return Err(BindingError::Metadata("general.architecture")); + } + let topology = topology(&shards[0].metadata)?; + let tokenizer = gguf::validate_tokenizer_metadata( + shards[0] + .metadata + .tokenizer + .take() + .ok_or(BindingError::Tokenizer("required_fields"))?, + ) + .map_err(|_| BindingError::Tokenizer("invalid_metadata"))?; + validate_tokenizer(&tokenizer)?; + let roles = validate_role_inventory(&shards)?; + Ok(ValidatedBindingView { + topology, + tokenizer, + roles, + }) +} + +struct ExpectedTensor { + role: TensorRole, + name: String, + dimensions: Vec, + shard: u8, + kind: Option, +} + +fn expected_inventory() -> Vec { + let mut expected = Vec::with_capacity(1224); + let mut add = |role, name: String, dimensions: &[u64], shard, kind| { + expected.push(ExpectedTensor { + role, + name, + dimensions: dimensions.to_vec(), + shard, + kind, + }); + }; + for (role, name, dimensions, kind) in [ + ( + GlobalRole::TokenEmbedding, + "token_embd.weight", + &[2560, 248320][..], + None, + ), + ( + GlobalRole::Output, + "output.weight", + &[2560, 248320][..], + None, + ), + ( + GlobalRole::OutputHcDown, + "output_hc_down.weight", + &[10240, 320][..], + None, + ), + ( + GlobalRole::OutputHcNorm, + "output_hc_norm.weight", + &[10240][..], + Some(0), + ), + ( + GlobalRole::OutputHcUp, + "output_hc_up.weight", + &[320, 10240][..], + None, + ), + ] { + add( + TensorRole::Global(role), + name.to_owned(), + dimensions, + 0, + kind, + ); + } + add( + TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), + "per_layer_token_embd.weight".to_owned(), + &[160, 320_001_536], + 1, + Some(20), + ); + + for layer in 0..48u8 { + let prefix = format!("blk.{layer}."); + let common = [ + ( + LayerRole::HcAttnDown, + "hc_attn_down.weight", + &[10240, 320][..], + None, + ), + ( + LayerRole::HcAttnUp, + "hc_attn_up.weight", + &[320, 10240][..], + None, + ), + ( + LayerRole::HcAttnInject, + "hc_attn_inject.weight", + &[10240, 4][..], + None, + ), + ( + LayerRole::HcAttnNorm, + "hc_attn_norm.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::HcFfnDown, + "hc_ffn_down.weight", + &[10240, 320][..], + None, + ), + ( + LayerRole::HcFfnUp, + "hc_ffn_up.weight", + &[320, 10240][..], + None, + ), + ( + LayerRole::HcFfnInject, + "hc_ffn_inject.weight", + &[10240, 4][..], + None, + ), + ( + LayerRole::HcFfnNorm, + "hc_ffn_norm.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::FfnGateInp, + "ffn_gate_inp.weight", + &[2560, 512][..], + Some(30), + ), + ( + LayerRole::FfnGateInpShared, + "ffn_gate_inp_shexp.weight", + &[2560][..], + Some(30), + ), + ( + LayerRole::FfnGateShared, + "ffn_gate_shexp.weight", + &[2560, 640][..], + None, + ), + ( + LayerRole::FfnUpShared, + "ffn_up_shexp.weight", + &[2560, 640][..], + None, + ), + ( + LayerRole::FfnDownShared, + "ffn_down_shexp.weight", + &[640, 2560][..], + None, + ), + ( + LayerRole::FfnGateExperts, + "ffn_gate_exps.weight", + &[2560, 640, 512][..], + None, + ), + ( + LayerRole::FfnUpExperts, + "ffn_up_exps.weight", + &[2560, 640, 512][..], + None, + ), + ( + LayerRole::FfnDownExperts, + "ffn_down_exps.weight", + &[640, 2560, 512][..], + None, + ), + ]; + for (role, name, dimensions, kind) in common { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + let family = if layer % 4 == 3 { + [ + (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288][..], None), + (LayerRole::AttnK, "attn_k.weight", &[2560, 512][..], None), + (LayerRole::AttnV, "attn_v.weight", &[2560, 512][..], None), + ( + LayerRole::AttnOutput, + "attn_output.weight", + &[6144, 2560][..], + None, + ), + ( + LayerRole::AttnQNorm, + "attn_q_norm.weight", + &[256][..], + Some(0), + ), + ( + LayerRole::AttnKNorm, + "attn_k_norm.weight", + &[256][..], + Some(0), + ), + ( + LayerRole::IndexerQProj, + "indexer.q_proj.weight", + &[2560, 512][..], + None, + ), + ( + LayerRole::IndexerKProj, + "indexer.k_proj.weight", + &[2560, 128][..], + None, + ), + ( + LayerRole::IndexerQNorm, + "indexer.q_norm.weight", + &[128][..], + Some(0), + ), + ( + LayerRole::IndexerKNorm, + "indexer.k_norm.weight", + &[128][..], + Some(0), + ), + ] + .to_vec() + } else { + [ + ( + LayerRole::AttnQkv, + "attn_qkv.weight", + &[2560, 10240][..], + None, + ), + ( + LayerRole::AttnGate, + "attn_gate.weight", + &[2560, 6144][..], + None, + ), + (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560][..], None), + ( + LayerRole::SsmConv1d, + "ssm_conv1d.weight", + &[4, 10240][..], + None, + ), + ( + LayerRole::SsmAlpha, + "ssm_alpha.weight", + &[2560, 48][..], + None, + ), + (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48][..], None), + (LayerRole::SsmA, "ssm_a", &[48][..], Some(0)), + (LayerRole::SsmDtBias, "ssm_dt.bias", &[48][..], Some(0)), + (LayerRole::SsmNorm, "ssm_norm.weight", &[128][..], Some(0)), + ] + .to_vec() + }; + for (role, name, dimensions, kind) in family { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + if layer == 1 { + for (role, name, dimensions, kind) in [ + ( + LayerRole::PleConv1d, + "ple_conv1d.weight", + &[4, 10240][..], + Some(1), + ), + ( + LayerRole::PleKey, + "ple_key.weight", + &[2560, 10240][..], + Some(30), + ), + ( + LayerRole::PleNormConv, + "ple_norm_conv.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleNormKey, + "ple_norm_key.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleNormQuery, + "ple_norm_query.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleValue, + "ple_value.weight", + &[2560, 2560][..], + Some(30), + ), + ] { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + } + } + expected +} + +fn validate_role_inventory( + shards: &[LogicalShardView<'_>; 2], +) -> Result, BindingError> { + let expected = expected_inventory(); + if expected.len() != 1224 { + return Err(BindingError::Role("registry_count")); + } + let by_name = expected + .iter() + .map(|item| (item.name.as_str(), item)) + .collect::>(); + let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42] + .into_iter() + .collect(); + let mut actual = BTreeMap::new(); + let mut roles = BTreeMap::new(); + let mut spans: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()]; + for (shard_number, shard) in shards.iter().enumerate() { + for (tensor_number, tensor) in shard.index.tensors.iter().enumerate() { + if actual + .insert( + tensor.name.as_str(), + (shard_number as u8, tensor_number, tensor), + ) + .is_some() + { + return Err(BindingError::Role("duplicate_name")); + } + } + } + for spec in &expected { + let (shard_number, tensor_number, tensor) = actual + .get(spec.name.as_str()) + .ok_or(BindingError::Role("missing_name"))?; + if spec.shard != *shard_number { + return Err(BindingError::Role("wrong_shard")); + } + if tensor.dimensions != spec.dimensions { + return Err(BindingError::Geometry("dimensions")); + } + if !allowed_kinds.contains(&tensor.kind) + || spec.kind.is_some_and(|kind| kind != tensor.kind) + { + return Err(BindingError::Geometry("kind")); + } + let (block_elements, block_bytes) = + gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + if tensor.dimensions.first().copied().unwrap_or(0) == 0 + || tensor.dimensions[0] % block_elements != 0 + { + return Err(BindingError::Geometry("block_alignment")); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |value, dim| value.checked_mul(*dim)) + .ok_or(BindingError::Geometry("element_count"))?; + let bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or(BindingError::Geometry("byte_count"))?; + if tensor.bytes == 0 || tensor.bytes != bytes { + return Err(BindingError::Geometry("indexed_byte_count")); + } + let shard = &shards[*shard_number as usize]; + let absolute_start = shard + .index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or(BindingError::Range("absolute_start"))?; + if absolute_start < shard.index.summary.data_start { + return Err(BindingError::Range("data_bounds")); + } + let absolute_end = absolute_start + .checked_add(tensor.bytes) + .ok_or(BindingError::Range("absolute_end"))?; + if absolute_end > shard.index.summary.file_size { + return Err(BindingError::Range("file_bounds")); + } + spans[*shard_number as usize].push((absolute_start, absolute_end)); + let resolved = ResolvedTensor { + shard: *shard_number, + tensor_number: *tensor_number, + name: tensor.name.clone(), + kind: tensor.kind, + dimensions: tensor.dimensions.clone(), + absolute_start, + byte_length: tensor.bytes, + file_size: shard.index.summary.file_size, + }; + if roles.insert(spec.role, resolved).is_some() { + return Err(BindingError::Role("duplicate_role")); + } + } + if actual.keys().any(|name| !by_name.contains_key(name)) || roles.len() != expected.len() { + return Err(BindingError::Role("missing_name")); + } + for span_set in &mut spans { + span_set.sort_unstable(); + if span_set.windows(2).any(|pair| pair[0].1 > pair[1].0) { + return Err(BindingError::Range("overlapping_tensors")); + } + } + Ok(roles) +} + +fn plan_row( + tensor: &ResolvedTensor, + row: u64, + expert: Option, +) -> Result<(u64, u64), BindingError> { + let dimensions = &tensor.dimensions; + match (dimensions.len(), expert) { + (2, None) | (3, Some(_)) => {} + (2, Some(_)) | (3, None) => return Err(BindingError::Role("rank_mismatch")), + _ => return Err(BindingError::Role("rank")), + } + let (block_elements, block_bytes) = + gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; + if dim0 == 0 || dim0 % block_elements != 0 { + return Err(BindingError::Geometry("block_alignment")); + } + let elements = dimensions + .iter() + .try_fold(1u64, |value, dim| value.checked_mul(*dim)) + .ok_or(BindingError::Geometry("element_count"))?; + let indexed_bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or(BindingError::Geometry("byte_count"))?; + if tensor.byte_length == 0 || indexed_bytes != tensor.byte_length { + return Err(BindingError::Geometry("indexed_byte_count")); + } + let row_bytes = (dim0 / block_elements) + .checked_mul(block_bytes) + .ok_or(BindingError::Range("row_bytes"))?; + let relative = match (dimensions.len(), expert) { + (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), + (3, Some(expert)) if expert < dimensions[2] && row < dimensions[1] => expert + .checked_mul(dimensions[1]) + .and_then(|base| base.checked_add(row)) + .and_then(|index| index.checked_mul(row_bytes)), + (2 | 3, _) => return Err(BindingError::Range("row_index")), + _ => unreachable!("rank checked above"), + } + .ok_or(BindingError::Range("row_offset"))?; + if row_bytes == 0 + || relative + .checked_add(row_bytes) + .is_none_or(|end| end > tensor.byte_length) + { + return Err(BindingError::Range("tensor_bounds")); + } + if tensor + .absolute_start + .checked_add(relative) + .and_then(|start| start.checked_add(row_bytes)) + .is_none_or(|end| end > tensor.file_size) + { + return Err(BindingError::Range("file_bounds")); + } + Ok((relative, row_bytes)) +} + +#[cfg(test)] +#[path = "../tests/qwen_artifact_binding/mod.rs"] +mod qwen_artifact_binding_tests; diff --git a/crates/model-format/tests/qwen_artifact_binding/fixtures.rs b/crates/model-format/tests/qwen_artifact_binding/fixtures.rs new file mode 100644 index 00000000..6a8696b6 --- /dev/null +++ b/crates/model-format/tests/qwen_artifact_binding/fixtures.rs @@ -0,0 +1,418 @@ +//! Independently constructed synthetic data from Speck143 v3, not product output. +use crate::gguf::{Summary, TensorIndex, TensorInfo, VerifiedGgufFile}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; + +pub const FORMATS: [(u32, u64, u64); 13] = [ + (0, 1, 4), + (1, 1, 2), + (8, 32, 34), + (12, 256, 144), + (13, 256, 176), + (14, 256, 210), + (18, 256, 98), + (20, 32, 18), + (21, 256, 110), + (22, 256, 82), + (23, 256, 136), + (30, 1, 2), + (42, 64, 18), +]; + +pub fn geometry(kind: u32) -> (u64, u64) { + let &(_, elements, bytes) = FORMATS.iter().find(|x| x.0 == kind).unwrap(); + (elements, bytes) +} + +pub fn byte_len(kind: u32, dims: &[u64]) -> u64 { + let (elements, bytes) = geometry(kind); + assert_eq!(dims[0] % elements, 0); + (dims[0] / elements) * bytes * dims[1..].iter().product::() +} + +/// Actual dimensions, synthetic packed kinds/ranges. No private inventory payload. +pub fn logical_indexes() -> [TensorIndex; 2] { + let mut tensors = Vec::new(); + let mut next_kind = [8, 12, 13, 14, 18, 21, 23, 42].into_iter(); + let mut add = |name: String, dims: &[u64], required: Option| { + let kind = required.unwrap_or_else(|| { + if dims[0].is_multiple_of(256) { + next_kind.next().unwrap_or(22) + } else if dims[0].is_multiple_of(32) { + 20 + } else { + 1 + } + }); + tensors.push(TensorInfo { + name, + dimensions: dims.to_vec(), + kind, + offset: 0, + bytes: byte_len(kind, dims), + }); + }; + for (name, dims) in [ + ("token_embd.weight", vec![2560, 248320]), + ("output.weight", vec![2560, 248320]), + ("output_hc_down.weight", vec![10240, 320]), + ("output_hc_norm.weight", vec![10240]), + ("output_hc_up.weight", vec![320, 10240]), + ] { + add( + name.to_owned(), + &dims, + if dims.len() == 1 { Some(0) } else { None }, + ); + } + for layer in 0..48 { + for (name, dims, required) in [ + ("hc_attn_down.weight", vec![10240, 320], None), + ("hc_ffn_down.weight", vec![10240, 320], None), + ("hc_attn_up.weight", vec![320, 10240], None), + ("hc_ffn_up.weight", vec![320, 10240], None), + ("hc_attn_inject.weight", vec![10240, 4], None), + ("hc_ffn_inject.weight", vec![10240, 4], None), + ("hc_attn_norm.weight", vec![10240], Some(0)), + ("hc_ffn_norm.weight", vec![10240], Some(0)), + ("ffn_gate_inp.weight", vec![2560, 512], Some(30)), + ("ffn_gate_inp_shexp.weight", vec![2560], Some(30)), + ("ffn_gate_shexp.weight", vec![2560, 640], None), + ("ffn_up_shexp.weight", vec![2560, 640], None), + ("ffn_down_shexp.weight", vec![640, 2560], None), + ("ffn_gate_exps.weight", vec![2560, 640, 512], None), + ("ffn_up_exps.weight", vec![2560, 640, 512], None), + ("ffn_down_exps.weight", vec![640, 2560, 512], None), + ] { + add(format!("blk.{layer}.{name}"), &dims, required); + } + if layer % 4 == 3 { + for (name, dims, required) in [ + ("attn_q.weight", vec![2560, 12288], None), + ("attn_k.weight", vec![2560, 512], None), + ("attn_v.weight", vec![2560, 512], None), + ("attn_output.weight", vec![6144, 2560], None), + ("attn_q_norm.weight", vec![256], Some(0)), + ("attn_k_norm.weight", vec![256], Some(0)), + ("indexer.q_proj.weight", vec![2560, 512], None), + ("indexer.k_proj.weight", vec![2560, 128], None), + ("indexer.q_norm.weight", vec![128], Some(0)), + ("indexer.k_norm.weight", vec![128], Some(0)), + ] { + add(format!("blk.{layer}.{name}"), &dims, required); + } + } else { + for (name, dims, required) in [ + ("attn_qkv.weight", vec![2560, 10240], None), + ("attn_gate.weight", vec![2560, 6144], None), + ("ssm_out.weight", vec![6144, 2560], None), + ("ssm_conv1d.weight", vec![4, 10240], Some(1)), + ("ssm_alpha.weight", vec![2560, 48], None), + ("ssm_beta.weight", vec![2560, 48], None), + ("ssm_a", vec![48], Some(0)), + ("ssm_dt.bias", vec![48], Some(0)), + ("ssm_norm.weight", vec![128], Some(0)), + ] { + add(format!("blk.{layer}.{name}"), &dims, required); + } + } + if layer == 1 { + for (name, dims, kind) in [ + ("ple_conv1d.weight", vec![4, 10240], 1), + ("ple_key.weight", vec![2560, 10240], 30), + ("ple_norm_conv.weight", vec![10240], 0), + ("ple_norm_key.weight", vec![10240], 0), + ("ple_norm_query.weight", vec![10240], 0), + ("ple_value.weight", vec![2560, 2560], 30), + ] { + add(format!("blk.{layer}.{name}"), &dims, Some(kind)); + } + } + } + assert_eq!(tensors.len(), 1223); + let mut offset = 0u64; + for tensor in &mut tensors { + offset = offset.div_ceil(32) * 32; + tensor.offset = offset; + offset += tensor.bytes; + } + assert!(offset + 4096 < 54_817_524_224); + let table = TensorInfo { + name: "per_layer_token_embd.weight".to_owned(), + dimensions: vec![160, 320001536], + kind: 20, + offset: 0, + bytes: 28_800_138_240, + }; + [ + index(0, tensors, 4096, 54_817_524_224), + index(1, vec![table], 192, 28_800_138_432), + ] +} + +pub fn index(shard: u64, tensors: Vec, data_start: u64, file_size: u64) -> TensorIndex { + let mut types = BTreeMap::new(); + for tensor in &tensors { + *types.entry(tensor.kind).or_insert(0) += 1; + } + TensorIndex { + summary: Summary { + tensors: tensors.len() as u64, + metadata: 0, + architecture: if shard == 0 { + Some("qwen4exp".to_owned()) + } else { + None + }, + split_no: Some(shard), + split_count: Some(2), + split_tensors_count: Some(1224), + data_start, + file_size, + types, + }, + tensors, + } +} + +#[derive(Clone)] +pub enum Meta { + U16(u16), + I32(i32), + U64(u64), + F32(f32), + Text(String), + U64s(Vec), + Texts(Vec), +} + +pub fn metadata() -> BTreeMap { + let mut map = BTreeMap::new(); + for (key, value) in [ + ("block_count", 48), + ("context_length", 262144), + ("embedding_length", 2560), + ("embedding_length_per_layer_input", 160), + ("full_attention_interval", 4), + ("expert_count", 512), + ("expert_used_count", 10), + ("expert_feed_forward_length", 640), + ("expert_shared_feed_forward_length", 640), + ("attention.head_count", 24), + ("attention.head_count_kv", 2), + ("attention.key_length", 256), + ("attention.value_length", 256), + ("hyper_connection.count", 4), + ("hyper_connection.low_rank", 320), + ("rope.dimension_count", 64), + ("attention.indexer.head_count", 4), + ("attention.indexer.key_length", 128), + ("attention.indexer.top_k", 2048), + ("ssm.conv_kernel", 4), + ("ssm.state_size", 128), + ("ssm.group_count", 16), + ("ssm.time_step_rank", 48), + ("ssm.inner_size", 6144), + ("ple.ngram_size", 3), + ("ple.heads_per_ngram", 8), + ("ple.conv_kernel", 4), + ("ple.eos_token_id", 248044), + ("ple.image_token_id", 248056), + ] { + map.insert(format!("qwen4exp.{key}"), Meta::U64(value)); + } + map.insert( + "general.architecture".to_owned(), + Meta::Text("qwen4exp".to_owned()), + ); + map.insert( + "qwen4exp.attention.layer_norm_rms_epsilon".to_owned(), + Meta::F32(0.000001), + ); + map.insert("qwen4exp.rope.freq_base".to_owned(), Meta::F32(10_000_000.)); + for (key, values) in [ + ("attention.compress_ratios", [0, 0, 0, 4].repeat(12)), + ("rope.dimension_sections", vec![11, 11, 10, 0]), + ("ple.layers", vec![1]), + ( + "ple.head_offsets", + vec![ + 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, + 160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, + 300001275, + ], + ), + ( + "ple.head_vocab_sizes", + vec![ + 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, + 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171, + ], + ), + ( + "ple.layer_multipliers", + vec![23703573157769, 20109073645365, 8052911324071], + ), + ] { + map.insert(format!("qwen4exp.{key}"), Meta::U64s(values)); + } + map.insert( + "tokenizer.ggml.model".to_owned(), + Meta::Text("gpt2".to_owned()), + ); + map.insert( + "tokenizer.ggml.pre".to_owned(), + Meta::Text("qwen35".to_owned()), + ); + map.insert( + "tokenizer.ggml.tokens".to_owned(), + Meta::Texts((0..248320).map(|i| format!("synthetic_{i}")).collect()), + ); + map.insert("tokenizer.ggml.merges".to_owned(), Meta::Texts(vec![])); + map.insert( + "tokenizer.chat_template".to_owned(), + Meta::Text("synthetic template".to_owned()), + ); + for (key, id) in [("bos", 248044), ("padding", 248044), ("eos", 248046)] { + map.insert(format!("tokenizer.ggml.{key}_token_id"), Meta::U64(id)); + } + map +} + +pub struct TinyOwner { + pub directory: PathBuf, + pub path: PathBuf, + pub tensors: Vec, + pub payloads: Vec>, + pub bytes: Vec, +} +fn string(bytes: &mut Vec, value: &str) { + bytes.extend((value.len() as u64).to_le_bytes()); + bytes.extend(value.as_bytes()); +} +impl TinyOwner { + pub fn new( + shard: u64, + rows: &[(String, u32, Vec)], + mut metadata: BTreeMap, + ) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "leleka-sdet143-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&directory).unwrap(); + let path = directory.join("synthetic.gguf"); + metadata.insert("split.no".to_owned(), Meta::U16(shard as u16)); + metadata.insert("split.count".to_owned(), Meta::U16(2)); + metadata.insert("split.tensors.count".to_owned(), Meta::I32(1224)); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend((rows.len() as u64).to_le_bytes()); + bytes.extend((metadata.len() as u64).to_le_bytes()); + for (key, value) in metadata { + string(&mut bytes, &key); + match value { + Meta::U16(v) => { + bytes.extend(2u32.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + Meta::I32(v) => { + bytes.extend(5u32.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + Meta::U64(v) => { + bytes.extend(10u32.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + Meta::F32(v) => { + bytes.extend(6u32.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + Meta::Text(v) => { + bytes.extend(8u32.to_le_bytes()); + string(&mut bytes, &v); + } + Meta::U64s(v) => { + bytes.extend(9u32.to_le_bytes()); + bytes.extend(10u32.to_le_bytes()); + bytes.extend((v.len() as u64).to_le_bytes()); + for x in v { + bytes.extend(x.to_le_bytes()); + } + } + Meta::Texts(v) => { + bytes.extend(9u32.to_le_bytes()); + bytes.extend(8u32.to_le_bytes()); + bytes.extend((v.len() as u64).to_le_bytes()); + for x in v { + string(&mut bytes, &x); + } + } + } + } + let mut tensors = Vec::new(); + let mut payloads = Vec::new(); + let mut offset = 0u64; + for (number, (name, kind, dims)) in rows.iter().enumerate() { + offset = offset.div_ceil(32) * 32; + let size = byte_len(*kind, dims); + string(&mut bytes, name); + bytes.extend((dims.len() as u32).to_le_bytes()); + for d in dims { + bytes.extend(d.to_le_bytes()); + } + bytes.extend(kind.to_le_bytes()); + bytes.extend(offset.to_le_bytes()); + tensors.push(TensorInfo { + name: name.clone(), + dimensions: dims.clone(), + kind: *kind, + offset, + bytes: size, + }); + payloads.push( + (0..size) + .map(|i| ((i * 17 + number as u64 * 43 + shard * 97) % 251) as u8) + .collect::>(), + ); + offset += size; + } + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + let data_start = bytes.len(); + for (tensor, payload) in tensors.iter().zip(&payloads) { + bytes.resize(data_start + tensor.offset as usize, 0); + bytes.extend(payload); + } + std::fs::write(&path, &bytes).unwrap(); + Self { + directory, + path, + tensors, + payloads, + bytes, + } + } + pub fn open(&self) -> VerifiedGgufFile { + let digest = Sha256::digest(&self.bytes); + let hex = digest + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + VerifiedGgufFile::open(&self.path, &format!("sha256:{hex}")).unwrap() + } + pub fn replace_path(&self) { + std::fs::rename(&self.path, self.directory.join("original-owned.gguf")).unwrap(); + std::fs::write(&self.path, b"PATH REPLACEMENT MUST NOT BE READ").unwrap(); + } +} +impl Drop for TinyOwner { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } +} diff --git a/crates/model-format/tests/qwen_artifact_binding/mod.rs b/crates/model-format/tests/qwen_artifact_binding/mod.rs new file mode 100644 index 00000000..c39306ad --- /dev/null +++ b/crates/model-format/tests/qwen_artifact_binding/mod.rs @@ -0,0 +1,791 @@ +//! Independent SDET143 component oracles. [SEC][UC-143] adversarial cases. +//! Logical extents are not opened real model files; miniature owners never pass pins. +use super::*; +mod fixtures; +use fixtures::{Meta, TinyOwner}; + +#[test] +fn legacy_profile_check_ignores_well_formed_unrelated_tokenizer_value_types() { + for field in ["tokenizer.ggml.tokens", "tokenizer.ggml.bos_token_id"] { + let mut metadata = fixtures::metadata(); + metadata.insert( + field.to_owned(), + Meta::Text("synthetic unrelated field".to_owned()), + ); + let fixture = TinyOwner::new(0, &[("fixture.profile".to_owned(), 0, vec![1])], metadata); + crate::gguf::check_flash_next_profile(&fixture.path).unwrap(); + assert!( + crate::gguf::tokenizer_metadata(&fixture.path).is_err(), + "tokenizer reader must reject {field}" + ); + } +} + +fn snapshots() -> [MetadataSnapshot; 2] { + let values = fixtures::metadata() + .into_iter() + .filter_map(|(key, value)| { + if !key.starts_with("qwen4exp.") { + return None; + } + let value = match value { + Meta::U64(v) => MetadataValue::Unsigned(v), + Meta::F32(v) => MetadataValue::Float(f64::from(v)), + Meta::U64s(v) => MetadataValue::UnsignedArray(v), + _ => panic!("unexpected profile value"), + }; + Some((key, value)) + }) + .collect(); + let tokenizer = TokenizerMetadata { + model: "gpt2".to_owned(), + pre: "qwen35".to_owned(), + tokens: (0..248320).map(|i| format!("synthetic_{i}")).collect(), + merges: vec![], + token_types: None, + special_ids: BTreeMap::from([ + ("tokenizer.ggml.bos_token_id".to_owned(), 248044), + ("tokenizer.ggml.padding_token_id".to_owned(), 248044), + ("tokenizer.ggml.eos_token_id".to_owned(), 248046), + ]), + chat_template: "synthetic template".to_owned(), + }; + [ + MetadataSnapshot { + architecture: Some("qwen4exp".to_owned()), + split_no: Some(0), + split_count: Some(2), + split_tensors_count: Some(1224), + values, + tokenizer: Some(tokenizer), + }, + MetadataSnapshot { + architecture: None, + split_no: Some(1), + split_count: Some(2), + split_tensors_count: Some(1224), + values: BTreeMap::new(), + tokenizer: None, + }, + ] +} +fn validate( + indexes: &[TensorIndex; 2], + metadata: &[MetadataSnapshot; 2], +) -> Result { + validate_logical_views([ + LogicalShardView { + index: &indexes[0], + metadata: metadata[0].clone(), + }, + LogicalShardView { + index: &indexes[1], + metadata: metadata[1].clone(), + }, + ]) +} +fn failure(indexes: &[TensorIndex; 2], metadata: &[MetadataSnapshot; 2]) -> BindingError { + match validate(indexes, metadata) { + Ok(_) => panic!("invalid logical binding published"), + Err(error) => error, + } +} +fn role(name: &str) -> TensorRole { + let global = match name { + "token_embd.weight" => Some(GlobalRole::TokenEmbedding), + "output.weight" => Some(GlobalRole::Output), + "output_hc_down.weight" => Some(GlobalRole::OutputHcDown), + "output_hc_norm.weight" => Some(GlobalRole::OutputHcNorm), + "output_hc_up.weight" => Some(GlobalRole::OutputHcUp), + "per_layer_token_embd.weight" => Some(GlobalRole::PerLayerTokenEmbedding), + _ => None, + }; + if let Some(global) = global { + return TensorRole::Global(global); + } + let remainder = name.strip_prefix("blk.").unwrap(); + let (layer, name) = remainder.split_once('.').unwrap(); + let role = match name { + "hc_attn_down.weight" => LayerRole::HcAttnDown, + "hc_attn_up.weight" => LayerRole::HcAttnUp, + "hc_attn_inject.weight" => LayerRole::HcAttnInject, + "hc_attn_norm.weight" => LayerRole::HcAttnNorm, + "hc_ffn_down.weight" => LayerRole::HcFfnDown, + "hc_ffn_up.weight" => LayerRole::HcFfnUp, + "hc_ffn_inject.weight" => LayerRole::HcFfnInject, + "hc_ffn_norm.weight" => LayerRole::HcFfnNorm, + "ffn_gate_inp.weight" => LayerRole::FfnGateInp, + "ffn_gate_inp_shexp.weight" => LayerRole::FfnGateInpShared, + "ffn_gate_shexp.weight" => LayerRole::FfnGateShared, + "ffn_up_shexp.weight" => LayerRole::FfnUpShared, + "ffn_down_shexp.weight" => LayerRole::FfnDownShared, + "ffn_gate_exps.weight" => LayerRole::FfnGateExperts, + "ffn_up_exps.weight" => LayerRole::FfnUpExperts, + "ffn_down_exps.weight" => LayerRole::FfnDownExperts, + "attn_qkv.weight" => LayerRole::AttnQkv, + "attn_gate.weight" => LayerRole::AttnGate, + "ssm_out.weight" => LayerRole::SsmOut, + "ssm_conv1d.weight" => LayerRole::SsmConv1d, + "ssm_alpha.weight" => LayerRole::SsmAlpha, + "ssm_beta.weight" => LayerRole::SsmBeta, + "ssm_a" => LayerRole::SsmA, + "ssm_dt.bias" => LayerRole::SsmDtBias, + "ssm_norm.weight" => LayerRole::SsmNorm, + "attn_q.weight" => LayerRole::AttnQ, + "attn_k.weight" => LayerRole::AttnK, + "attn_v.weight" => LayerRole::AttnV, + "attn_output.weight" => LayerRole::AttnOutput, + "attn_q_norm.weight" => LayerRole::AttnQNorm, + "attn_k_norm.weight" => LayerRole::AttnKNorm, + "indexer.q_proj.weight" => LayerRole::IndexerQProj, + "indexer.k_proj.weight" => LayerRole::IndexerKProj, + "indexer.q_norm.weight" => LayerRole::IndexerQNorm, + "indexer.k_norm.weight" => LayerRole::IndexerKNorm, + "ple_conv1d.weight" => LayerRole::PleConv1d, + "ple_key.weight" => LayerRole::PleKey, + "ple_norm_conv.weight" => LayerRole::PleNormConv, + "ple_norm_key.weight" => LayerRole::PleNormKey, + "ple_norm_query.weight" => LayerRole::PleNormQuery, + "ple_value.weight" => LayerRole::PleValue, + _ => panic!("unexpected independent fixture role"), + }; + TensorRole::Layer { + layer: layer.parse().unwrap(), + role, + } +} + +#[test] +fn complete_1224_logical_manifest_matches_all_roles_locations_and_13_formats() { + let indexes = fixtures::logical_indexes(); + let metadata = snapshots(); + let actual = validate(&indexes, &metadata).unwrap(); + assert_eq!(actual.roles.len(), 1224); + let mut kinds = BTreeSet::new(); + for (shard, index) in indexes.iter().enumerate() { + for (number, expected) in index.tensors.iter().enumerate() { + let found = &actual.roles[&role(&expected.name)]; + assert_eq!( + (found.shard(), found.tensor_number()), + (shard as u8, number) + ); + assert_eq!(found.name(), expected.name); + assert_eq!(found.dimensions(), expected.dimensions); + assert_eq!(found.kind(), expected.kind); + assert_eq!( + found.byte_length(), + fixtures::byte_len(expected.kind, &expected.dimensions) + ); + assert_eq!( + found.absolute_start(), + index.summary.data_start + expected.offset + ); + kinds.insert(found.kind()); + } + } + assert_eq!(kinds, fixtures::FORMATS.iter().map(|x| x.0).collect()); + for layer in 0..48 { + let qsa = TensorRole::Layer { + layer, + role: LayerRole::AttnQ, + }; + let gdn = TensorRole::Layer { + layer, + role: LayerRole::AttnQkv, + }; + assert_eq!(actual.roles.contains_key(&qsa), layer % 4 == 3); + assert_eq!(actual.roles.contains_key(&gdn), layer % 4 != 3); + } + assert_eq!( + actual.tokenizer.special_ids["tokenizer.ggml.eos_token_id"], + 248046 + ); + assert_eq!(actual.topology.ple_eos_token_id, 248044); + assert_eq!(actual.tokenizer.tokens.len(), 248320); + println!( + "complete logical manifest:1224 roles,13 formats,36GDN/12QSA; no real pinned-bind claim" + ); +} + +#[test] +fn typed_topology_retains_all_frozen_scalar_and_array_values() { + let indexes = fixtures::logical_indexes(); + let metadata = snapshots(); + let actual = validate(&indexes, &metadata).unwrap(); + let t = &actual.topology; + assert_eq!(t.architecture, "qwen4exp"); + assert_eq!(t.context_length(), 262144); + assert_eq!( + [ + t.block_count, + t.embedding_length, + t.full_attention_interval, + t.expert_count, + t.expert_used_count, + t.expert_feed_forward_length, + t.expert_shared_feed_forward_length + ], + [48, 2560, 4, 512, 10, 640, 640] + ); + assert_eq!( + [ + t.attention_head_count, + t.attention_head_count_kv, + t.attention_key_length, + t.attention_value_length, + t.hc_count, + t.hc_low_rank + ], + [24, 2, 256, 256, 4, 320] + ); + assert_eq!( + [ + t.rope_dimension_count, + t.indexer_head_count, + t.indexer_key_length, + t.indexer_top_k, + t.ssm_conv_kernel, + t.ssm_state_size, + t.ssm_group_count, + t.ssm_time_step_rank, + t.ssm_inner_size, + t.per_layer_embedding_length + ], + [64, 4, 128, 2048, 4, 128, 16, 48, 6144, 160] + ); + assert_eq!( + [ + t.ple_ngram_size, + t.ple_heads_per_ngram, + t.ple_conv_kernel, + t.ple_eos_token_id, + t.ple_image_token_id + ], + [3, 8, 4, 248044, 248056] + ); + assert_eq!(t.compression_ratios, [0, 0, 0, 4].repeat(12)); + assert_eq!(t.rope_dimension_sections, [11, 11, 10, 0]); + assert_eq!(t.ple_layers, [1]); + assert_eq!(t.rope_frequency_base, 10_000_000.); + assert_eq!(t.rms_epsilon, f64::from(0.000001f32)); + for (key, actual) in [ + ("ple.head_offsets", &t.ple_head_offsets), + ("ple.head_vocab_sizes", &t.ple_head_vocab_sizes), + ("ple.layer_multipliers", &t.ple_layer_multipliers), + ] { + let Meta::U64s(expected) = fixtures::metadata() + .remove(&format!("qwen4exp.{key}")) + .unwrap() + else { + panic!() + }; + assert_eq!(actual, &expected); + } +} + +#[test] +fn sec_uc143_every_profile_field_missing_or_mismatched_fails_before_publication() { + // [SEC][UC-143] field omission/type confusion/fixed-value mismatch. + let indexes = fixtures::logical_indexes(); + let mut metadata = snapshots(); + let keys = metadata[0].values.keys().cloned().collect::>(); + for key in keys { + let original = metadata[0].values.remove(&key).unwrap(); + assert!( + matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), + "missing {key}" + ); + metadata[0].values.insert( + key.clone(), + MetadataValue::Text("malicious type confusion".to_owned()), + ); + assert!( + matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), + "type {key}" + ); + let changed = match &original { + MetadataValue::Unsigned(v) => MetadataValue::Unsigned(v + 1), + MetadataValue::Float(_) => MetadataValue::Float(f64::NAN), + MetadataValue::UnsignedArray(v) => { + let mut v = v.clone(); + v[0] += 1; + MetadataValue::UnsignedArray(v) + } + _ => panic!(), + }; + metadata[0].values.insert(key.clone(), changed); + assert!( + matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), + "value {key}" + ); + metadata[0].values.insert(key, original); + } +} + +#[test] +fn sec_uc143_split_topology_tokenizer_role_error_precedence_and_safe_messages() { + // [SEC][UC-143] multiple faults must expose deterministic first category. + let mut indexes = fixtures::logical_indexes(); + let mut metadata = snapshots(); + indexes[0].summary.split_no = Some(1); + metadata[0].values.clear(); + indexes[0].tensors[0].name = "../../secret\0payload".to_owned(); + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Split("split.no") + )); + indexes[0].summary.split_no = Some(0); + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Metadata(_) + )); + metadata = snapshots(); + metadata[0] + .tokenizer + .as_mut() + .unwrap() + .special_ids + .insert("tokenizer.ggml.eos_token_id".to_owned(), 248044); + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Tokenizer(_) + )); + metadata = snapshots(); + let error = failure(&indexes, &metadata); + assert!(matches!(error, BindingError::Role(_))); + assert!(!error.to_string().contains("secret")); + assert!(!error.to_string().contains("payload")); + assert!(!error.to_string().contains("../")); +} + +#[test] +fn sec_uc143_split_identity_and_tokenizer_special_ids_reject_independently() { + // [SEC][UC-143] both owners and separate PLE/tokenizer EOS contracts. + for shard in 0..2 { + for field in 0..5 { + let mut indexes = fixtures::logical_indexes(); + let mut metadata = snapshots(); + match field { + 0 => metadata[shard].split_no = Some(9), + 1 => indexes[shard].summary.split_count = Some(3), + 2 => metadata[shard].split_tensors_count = Some(1225), + 3 => { + indexes[shard].tensors.pop(); + } + _ => metadata[shard].architecture = Some("other".to_owned()), + }; + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Split(_) | BindingError::Metadata(_) + )); + } + } + let indexes = fixtures::logical_indexes(); + let mut metadata = snapshots(); + for key in ["bos", "padding", "eos"] { + let key = format!("tokenizer.ggml.{key}_token_id"); + let token = metadata[0].tokenizer.as_mut().unwrap(); + let previous = token.special_ids.insert(key.clone(), 1).unwrap(); + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Tokenizer(_) + )); + metadata[0] + .tokenizer + .as_mut() + .unwrap() + .special_ids + .insert(key, previous); + } + metadata[0].tokenizer = None; + assert!(matches!( + failure(&indexes, &metadata), + BindingError::Tokenizer(_) + )); +} + +#[test] +fn sec_uc143_inventory_missing_extra_duplicate_wrong_family_shard_shape_kind_and_range() { + // [SEC][UC-143] adversarial closed inventory with zero published partial object. + let metadata = snapshots(); + for case in 0..10 { + let mut indexes = fixtures::logical_indexes(); + match case { + 0 => indexes[0].tensors[0].name = "unregistered.weight".to_owned(), + 1 => indexes[1].tensors[0].name = indexes[0].tensors[0].name.clone(), + 2 => { + let t = indexes[0] + .tensors + .iter_mut() + .find(|t| t.name == "blk.0.attn_qkv.weight") + .unwrap(); + t.name = "blk.0.attn_q.weight".to_owned(); + } + 3 => { + let a = indexes[0].tensors[0].name.clone(); + indexes[0].tensors[0].name = "per_layer_token_embd.weight".to_owned(); + indexes[1].tensors[0].name = a; + } + 4 => indexes[0].tensors[0].dimensions[1] += 1, + 5 => indexes[0].tensors[0].kind = 24, + 6 => { + indexes[0] + .tensors + .iter_mut() + .find(|t| t.name == "blk.0.ffn_gate_inp.weight") + .unwrap() + .kind = 0 + } + 7 => indexes[0].tensors[0].bytes -= 1, + 8 => indexes[0].tensors[0].offset = u64::MAX, + _ => indexes[0].summary.file_size = 4097, + }; + let error = failure(&indexes, &metadata); + assert!( + match case { + 0..=3 => matches!(error, BindingError::Role(_)), + 4..=7 => matches!(error, BindingError::Geometry(_)), + _ => matches!(error, BindingError::Range(_)), + }, + "case {case}: {error}" + ); + } +} + +fn miniature() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { + let metadata = snapshots(); + let topology = topology(&metadata[0]).unwrap(); + let mut rows = fixtures::FORMATS + .iter() + .map(|&(kind, _, _)| (format!("fixture.kind{kind}"), kind, vec![256, 3])) + .collect::>(); + rows.push(("fixture.expert".to_owned(), 14, vec![256, 3, 2])); + rows.push(("fixture.large".to_owned(), 0, vec![32768, 3])); + let first = TinyOwner::new(0, &rows, fixtures::metadata()); + let second = TinyOwner::new( + 1, + &[("fixture.ple".to_owned(), 20, vec![160, 5])], + BTreeMap::new(), + ); + let owners = [first.open(), second.open()]; + for (owner, fixture) in owners.iter().zip([&first, &second]) { + for (actual, expected) in owner.index().tensors.iter().zip(&fixture.tensors) { + assert_eq!(actual.dimensions, expected.dimensions); + assert_eq!( + (actual.kind, actual.offset, actual.bytes), + (expected.kind, expected.offset, expected.bytes) + ); + } + } + let mut roles = BTreeMap::new(); + for (i, &(kind, _, _)) in fixtures::FORMATS.iter().enumerate() { + let role = TensorRole::Layer { + layer: i as u8, + role: LayerRole::FfnUpShared, + }; + roles.insert(role, resolved(&owners[0], 0, i)); + assert_eq!(owners[0].index().tensors[i].kind, kind); + } + roles.insert( + TensorRole::Layer { + layer: 0, + role: LayerRole::FfnUpExperts, + }, + resolved(&owners[0], 0, 13), + ); + roles.insert( + TensorRole::Global(GlobalRole::Output), + resolved(&owners[0], 0, 14), + ); + roles.insert( + TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), + resolved(&owners[1], 1, 0), + ); + ( + Qwen4ExpArtifact { + shards: owners, + topology, + tokenizer: metadata.into_iter().next().unwrap().tokenizer.unwrap(), + roles, + }, + [first, second], + ) +} +fn resolved(owner: &VerifiedGgufFile, shard: u8, number: usize) -> ResolvedTensor { + let index = owner.index(); + let t = &index.tensors[number]; + ResolvedTensor { + shard, + tensor_number: number, + name: t.name.clone(), + kind: t.kind, + dimensions: t.dimensions.clone(), + absolute_start: index.summary.data_start + t.offset, + byte_length: t.bytes, + file_size: index.summary.file_size, + } +} + +#[test] +fn actual_public_bind_rejects_minis_at_identity_before_split_or_metadata() { + let a = TinyOwner::new( + 1, + &[("fixture.pin".to_owned(), 0, vec![1])], + BTreeMap::new(), + ); + let b = TinyOwner::new( + 0, + &[("fixture.pin".to_owned(), 0, vec![1])], + BTreeMap::new(), + ); + let error = match Qwen4ExpArtifact::bind(a.open(), b.open()) { + Ok(_) => panic!("public pins bypassed"), + Err(error) => error, + }; + assert!(matches!(error, BindingError::Identity(0))); + assert_eq!(error.to_string(), "artifact identity rejected for shard 0"); +} + +#[test] +fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_bytes() { + // [SEC][UC-143] reopen/substitution attack on BOTH original filenames. + let (mut artifact, fixtures) = miniature(); + for fixture in &fixtures { + fixture.replace_path(); + } + let snapshot = artifact.shards[0].metadata_snapshot().unwrap(); + assert_eq!(snapshot.architecture.as_deref(), Some("qwen4exp")); + assert_eq!( + snapshot.tokenizer.unwrap().tokens[248046], + "synthetic_248046" + ); + let secondary = artifact.shards[1].metadata_snapshot().unwrap(); + assert!(secondary.architecture.is_none()); + assert!(secondary.tokenizer.is_none()); + assert_eq!(secondary.split_no, Some(1)); + for (number, &(kind, _, _)) in fixtures::FORMATS.iter().enumerate() { + for row in [0, 2] { + let mut actual = Vec::new(); + artifact + .stream_row( + TensorRole::Layer { + layer: number as u8, + role: LayerRole::FfnUpShared, + }, + row, + |chunk| { + assert!(chunk.len() <= 65536); + actual.extend_from_slice(chunk); + Ok(()) + }, + ) + .unwrap(); + let width = fixtures::byte_len(kind, &[256]); + assert_eq!( + actual, + &fixtures[0].payloads[number][(row * width) as usize..((row + 1) * width) as usize] + ); + } + } + for expert in 0..2 { + for row in 0..3 { + let mut actual = Vec::new(); + artifact + .stream_expert_row( + TensorRole::Layer { + layer: 0, + role: LayerRole::FfnUpExperts, + }, + expert, + row, + |chunk| { + actual.extend_from_slice(chunk); + Ok(()) + }, + ) + .unwrap(); + let start = ((expert * 3 + row) * 210) as usize; + assert_eq!(actual, fixtures[0].payloads[13][start..start + 210]); + } + } + for row in [0, 4] { + let mut actual = Vec::new(); + artifact + .stream_row( + TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), + row, + |chunk| { + actual.extend_from_slice(chunk); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + actual, + fixtures[1].payloads[0][row as usize * 90..(row as usize + 1) * 90] + ); + } +} + +#[test] +fn large_rows_chunk_at_64k_abort_immediately_then_recover_exact_cursor() { + let (mut artifact, fixtures) = miniature(); + let role = TensorRole::Global(GlobalRole::Output); + let mut sizes = Vec::new(); + let mut actual = Vec::new(); + artifact + .stream_row(role, 1, |chunk| { + sizes.push(chunk.len()); + actual.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(sizes, [65536, 65536]); + assert_eq!(actual, fixtures[0].payloads[14][131072..262144]); + let mut callbacks = 0; + let error = artifact + .stream_row(role, 0, |chunk| { + callbacks += 1; + assert_eq!(chunk, &fixtures[0].payloads[14][..65536]); + Err(io::Error::new( + io::ErrorKind::Interrupted, + "synthetic callback abort", + )) + }) + .unwrap_err(); + assert_eq!(callbacks, 1); + assert!(matches!(error, BindingError::Io(_))); + assert_eq!( + error.source().unwrap().to_string(), + "synthetic callback abort" + ); + let mut recovered = Vec::new(); + artifact + .stream_row(role, 2, |chunk| { + recovered.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(recovered, fixtures[0].payloads[14][262144..393216]); +} + +#[test] +fn sec_uc143_invalid_role_rank_row_expert_and_file_size_fail_before_callback() { + // [SEC][UC-143] malicious rank/index/size cannot deliver partial bytes. + let (mut artifact, fixtures) = miniature(); + let plain = TensorRole::Global(GlobalRole::Output); + let expert = TensorRole::Layer { + layer: 0, + role: LayerRole::FfnUpExperts, + }; + let mut calls = 0; + assert!( + artifact + .stream_row(plain, 3, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert!( + artifact + .stream_row(expert, 0, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert!( + artifact + .stream_expert_row(plain, 0, 0, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert!( + artifact + .stream_expert_row(expert, 2, 0, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert!( + artifact + .stream_expert_row(expert, 0, u64::MAX, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert!( + artifact + .stream_row( + TensorRole::Layer { + layer: 48, + role: LayerRole::SsmA + }, + 0, + |_| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + std::fs::OpenOptions::new() + .write(true) + .open(&fixtures[0].path) + .unwrap() + .set_len(32) + .unwrap(); + assert!( + artifact + .stream_row(plain, 0, |_| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert_eq!(calls, 0); +} + +#[test] +fn sec_uc143_checked_row_planner_refuses_alignment_product_tensor_and_file_overflow() { + // [SEC][UC-143] pure corrupted descriptor probes never require huge files. + let (artifact, _fixtures) = miniature(); + let base = artifact.roles[&TensorRole::Global(GlobalRole::Output)].clone(); + for case in 0..11 { + let mut tensor = base.clone(); + match case { + 0 => tensor.kind = u32::MAX, + 1 => { + tensor.kind = 14; + tensor.dimensions[0] = 255; + } + 2 => tensor.dimensions[0] = 0, + 3 => { + tensor.dimensions[0] = u64::MAX; + tensor.dimensions[1] = 2; + } + 4 => tensor.absolute_start = u64::MAX, + 5 => tensor.byte_length = 1, + 6 => tensor.file_size = 1, + 7 => tensor.dimensions = vec![32768], + 8 => tensor.byte_length -= 1, + 9 => tensor.dimensions[1] = u64::MAX, + _ => tensor.byte_length += 1, + }; + assert!( + plan_row(&tensor, 0, None).is_err(), + "malformed descriptor case{case}" + ); + } + let mut tensor = base; + tensor.dimensions = vec![256, u64::MAX, 2]; + tensor.kind = 14; + tensor.byte_length = u64::MAX; + assert!(plan_row(&tensor, 0, Some(1)).is_err()); +}