feat(model): bind pinned Qwen topology and bounded tensor rows [skip ci]

This commit is contained in:
Pavlo Ratushnyi
2026-10-08 18:47:09 +02:00
parent 08dcb1d4a2
commit b1300329ff
5 changed files with 2683 additions and 41 deletions
+307 -41
View File
@@ -41,7 +41,7 @@ pub struct TensorIndex {
pub tensors: Vec<TensorInfo>,
}
#[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<u64>),
SignedArray(Vec<i64>),
FloatArray(Vec<f64>),
TextArray(Vec<String>),
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct MetadataSnapshot {
pub architecture: Option<String>,
pub split_no: Option<u64>,
pub split_count: Option<u64>,
pub split_tensors_count: Option<u64>,
pub values: BTreeMap<String, MetadataValue>,
pub tokenizer: Option<TokenizerMetadata>,
}
/// 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<MetadataSnapshot> {
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<MetadataSnapshot> {
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<Option<TokenizerMetadata>> {
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<TokenizerMetadata> {
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<MetadataSnapshot> {
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<TokenizerMetadata> {
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<TokenizerMetadata> {
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<TokenizerMetadata> {
}
Ok(TokenizerMetadata {
model,
pre: pre.unwrap_or_else(|| "qwen35".to_owned()),
pre,
tokens,
merges,
token_types,
@@ -711,6 +893,90 @@ impl<R: Read + Seek> Cursor<R> {
}
}
fn metadata_value(&mut self, kind: u32) -> Result<MetadataValue> {
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<MetadataValue> {
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),
+1
View File
@@ -7,3 +7,4 @@
//! Its only direct dependency is the Rust SHA-256 implementation in `sha2`.
pub mod gguf;
pub mod qwen4exp;
File diff suppressed because it is too large Load Diff
@@ -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::<u64>()
}
/// 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<u32>| {
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<TensorInfo>, 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<u64>),
Texts(Vec<String>),
}
pub fn metadata() -> BTreeMap<String, Meta> {
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<TensorInfo>,
pub payloads: Vec<Vec<u8>>,
pub bytes: Vec<u8>,
}
fn string(bytes: &mut Vec<u8>, 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<u64>)],
mut metadata: BTreeMap<String, Meta>,
) -> 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::<Vec<_>>(),
);
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::<String>();
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);
}
}
@@ -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<ValidatedBindingView, BindingError> {
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::<Vec<_>>();
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::<Vec<_>>();
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());
}