STRA-83: validate MTP tensor geometry before model acquisition (#25)

This commit is contained in:
Pavlo Ratushnyi
2026-10-05 05:05:04 +02:00
committed by GitHub
parent 66583b5331
commit 22de91c08f
3 changed files with 162 additions and 52 deletions
+122 -42
View File
@@ -1,5 +1,5 @@
//! Structural preflight for the current Qwen3.8 Flash Next Q2 MTP runtime.
//! This does not validate tensor values, model geometry, CUDA or draft quality.
//! Checks current MTP tensor geometry, not values, base-model pairing or draft quality.
use std::{
collections::HashMap,
fs::{self, File, OpenOptions},
@@ -10,36 +10,80 @@ use std::{
const INDEX_LIMIT: u64 = 64 * 1024;
// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB.
const EXPERT_BYTES: u64 = 512 * 1_382_400;
const REQUIRED: &[(&str, &str)] = &[
("fc_embedding.weight", "q8_0"),
("fc_hidden.weight", "q8_0"),
("self_attn.q_proj.weight", "q8_0"),
("self_attn.k_proj.weight", "q8_0"),
("self_attn.v_proj.weight", "q8_0"),
("self_attn.o_proj.weight", "q8_0"),
("mlp.shared_expert.gate_proj.weight", "q8_0"),
("mlp.shared_expert.up_proj.weight", "q8_0"),
("mlp.shared_expert.down_proj.weight", "q8_0"),
("attn_hyper_connection.block_inject_weight.weight", "bf16"),
("attn_hyper_connection.input_mix_weight_down.weight", "bf16"),
("attn_hyper_connection.input_mix_weight_up.weight", "bf16"),
// Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py.
// Consumer: engine/strata/src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256).
const REQUIRED: &[(&str, &str, u64, u64)] = &[
("fc_embedding.weight", "q8_0", 2560, 2560),
("fc_hidden.weight", "q8_0", 2560, 2560),
("self_attn.q_proj.weight", "q8_0", 12288, 2560),
("self_attn.k_proj.weight", "q8_0", 512, 2560),
("self_attn.v_proj.weight", "q8_0", 512, 2560),
("self_attn.o_proj.weight", "q8_0", 2560, 6144),
("mlp.shared_expert.gate_proj.weight", "q8_0", 640, 2560),
("mlp.shared_expert.up_proj.weight", "q8_0", 640, 2560),
("mlp.shared_expert.down_proj.weight", "q8_0", 2560, 640),
(
"attn_hyper_connection.block_inject_weight.weight",
"bf16",
4,
10240,
),
(
"attn_hyper_connection.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
(
"attn_hyper_connection.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
(
"hyper_connection_mixer.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
("hyper_connection_mixer.input_mix_weight_up.weight", "bf16"),
("mlp.gate.weight", "bf16"),
("mlp.shared_expert_gate.weight", "bf16"),
("mlp_hyper_connection.block_inject_weight.weight", "bf16"),
("mlp_hyper_connection.input_mix_weight_down.weight", "bf16"),
("mlp_hyper_connection.input_mix_weight_up.weight", "bf16"),
("attn_hyper_connection.hc_norm.weight", "f32"),
("hyper_connection_mixer.hc_norm.weight", "f32"),
("mlp_hyper_connection.hc_norm.weight", "f32"),
("pre_fc_norm_embedding.weight", "f32"),
("pre_fc_norm_hidden.weight", "f32"),
("self_attn.k_norm.weight", "f32"),
("self_attn.q_norm.weight", "f32"),
(
"hyper_connection_mixer.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
("mlp.gate.weight", "bf16", 512, 2560),
("mlp.shared_expert_gate.weight", "bf16", 1, 2560),
(
"mlp_hyper_connection.block_inject_weight.weight",
"bf16",
4,
10240,
),
(
"mlp_hyper_connection.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
(
"mlp_hyper_connection.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
("attn_hyper_connection.hc_norm.weight", "f32", 1, 10240),
("hyper_connection_mixer.hc_norm.weight", "f32", 1, 10240),
("mlp_hyper_connection.hc_norm.weight", "f32", 1, 10240),
("pre_fc_norm_embedding.weight", "f32", 1, 2560),
("pre_fc_norm_hidden.weight", "f32", 1, 10240),
("self_attn.k_norm.weight", "f32", 1, 256),
("self_attn.q_norm.weight", "f32", 1, 256),
];
const OPTIONAL: &[(&str, &str, u64, u64)] = &[
("self_attn.indexer.index_qk_proj.weight", "q8_0", 640, 2560),
("self_attn.indexer.k_layernorm.weight", "f32", 1, 128),
("self_attn.indexer.q_layernorm.weight", "f32", 1, 128),
];
fn regular(path: &Path) -> Result<File, &'static str> {
@@ -119,7 +163,7 @@ fn validate_index(text: &str, dense_bytes: u64) -> Result<(), &'static str> {
|| !name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b))
|| tensors.insert(name, fields[1]).is_some()
|| tensors.contains_key(name)
{
return Err("invalid or duplicate MTP tensor name");
}
@@ -153,11 +197,20 @@ fn validate_index(text: &str, dense_bytes: u64) -> Result<(), &'static str> {
if end > dense_bytes {
return Err("MTP dense tensor extends beyond file");
}
tensors.insert(name, (fields[1], rows, cols));
ranges.push((offset, end));
}
for &(name, kind) in REQUIRED {
if tensors.get(name) != Some(&kind) {
return Err("MTP runtime lacks a required tensor or expected dtype");
for &(name, kind, rows, cols) in REQUIRED {
if tensors.get(name) != Some(&(kind, rows, cols)) {
return Err("MTP required tensor dtype or geometry does not match the current runtime");
}
}
for &(name, kind, rows, cols) in OPTIONAL {
if tensors
.get(name)
.is_some_and(|shape| *shape != (kind, rows, cols))
{
return Err("MTP optional tensor dtype or geometry does not match the current runtime");
}
}
ranges.sort_unstable();
@@ -176,14 +229,14 @@ mod tests {
fn fixture() -> (String, u64) {
let mut text = String::new();
let mut end = 0u64;
for (name, kind) in REQUIRED {
for (name, kind, rows, cols) in REQUIRED.iter().chain(OPTIONAL) {
let at = end.div_ceil(256) * 256;
let bytes = match *kind {
"q8_0" => 34,
"bf16" => 64,
_ => 128,
"q8_0" => rows * (cols / 32) * 34,
"bf16" => rows * cols * 2,
_ => rows * cols * 4,
};
text.push_str(&format!("{name} {kind} 1 32 {at} {bytes}\n"));
text.push_str(&format!("{name} {kind} {rows} {cols} {at} {bytes}\n"));
end = at + bytes;
}
(text, end)
@@ -195,15 +248,15 @@ mod tests {
for invalid in [
text.replacen(' ', "\u{a0}", 1),
text.replacen("q8_0", "bf16", 1),
text.replacen("1 32", "0 32", 1),
text.replacen("1 32", "1 31", 1),
text.replacen("0 34", "1 34", 1),
text.replacen("0 34", "0 35", 1),
text.replacen("256 34", "0 34", 1),
text.replacen("2560 2560", "0 2560", 1),
text.replacen("2560 2560", "2560 31", 1),
text.replacen("0 6963200", "1 6963200", 1),
text.replacen("0 6963200", "0 6963201", 1),
text.replacen("6963200 6963200", "0 6963200", 1),
text.lines().skip(1).collect::<Vec<_>>().join("\n"),
format!("{text}{}\n", text.lines().next().unwrap()),
text.replacen("fc_hidden", "fc_embedding", 1),
text.replacen("1 32", "18446744073709551615 32", 1),
text.replacen("2560 2560", "18446744073709551615 2560", 1),
] {
assert!(validate_index(&invalid, bytes).is_err());
}
@@ -211,6 +264,33 @@ mod tests {
assert!(validate_index(&text, bytes + 1).is_err());
}
#[test]
fn rejects_byte_consistent_transposed_or_undersized_tensors() {
let (text, bytes) = fixture();
for (name, _, _, _) in REQUIRED.iter().chain(OPTIONAL) {
let mut lines: Vec<String> = text.lines().map(str::to_owned).collect();
let line = lines
.iter_mut()
.find(|line| line.starts_with(&format!("{name} ")))
.unwrap();
let mut fields: Vec<String> = line.split_whitespace().map(str::to_owned).collect();
let rows: u64 = fields[2].parse().unwrap();
let cols: u64 = fields[3].parse().unwrap();
if fields[1] != "f32" && rows != cols {
fields.swap(2, 3); // Same elements, range and byte count; wrong kernel geometry.
} else {
fields[3] = (cols / 2).to_string();
fields[5] = (fields[5].parse::<u64>().unwrap() / 2).to_string();
}
*line = fields.join(" ");
assert!(
validate_index(&lines.join("\n"), bytes)
.unwrap_err()
.contains("geometry"),
"{name}"
);
}
}
#[test]
fn checks_sparse_files_without_loading_payloads() {
let dir = std::env::temp_dir().join(format!("strata-mtp-{}", std::process::id()));
fs::create_dir(&dir).unwrap();
+11 -2
View File
@@ -587,7 +587,7 @@ control plane appends `--mtp /models/mtp-v1`; remove any manual `--mtp` or
without `mtp_pack` retain their behavior.
The check validates an ASCII index of at most 64 KiB / 128 tensors, required
current-engine tensor names/dtypes, positive dimensions, exact dtype byte counts,
current-engine tensor names/dtypes and exact rows/columns, exact dtype byte counts,
256-byte alignment, non-overlapping in-file ranges and exact dense file extent.
The Q2 expert blob must have exactly 707788800 bytes (512 × 1382400). Files must
be readable regular files, not symlinks; read-only host volumes can use another
@@ -597,7 +597,16 @@ reading the pack; `provision` reports `mtp_pack_structurally_validated: true`
only after verification. Missing or malformed packs fail before fetching the
base model, preserving existing versioned directories.
This is a structural check, **not proof of model geometry, weight values,
Required tensor geometry is pinned to the current Flash Next MTP consumer
(2560 hidden width, four hyper-connection streams, 24 query heads of width 256,
two KV heads, 640 expert width). The optional three indexer tensors must also
match their pinned geometry when present. Dimensions are checked independently
of byte count: a rectangular matrix with swapped dimensions is rejected even
when its byte length and offsets remain consistent. Sparse CPU fixtures take
their shapes from the upstream checkpoint manifest and compare against this
preflight; a transposed Q projection is rejected before base acquisition.
This is a structural and MTP geometry check, **not proof of compatible base-model geometry, weight values,
source-model pairing, Gemma norm conversion, quality, VRAM capacity or GPU
readiness**. It neither converts a raw MTP GGUF nor quantizes new weights. The
existing offline `mtp_rt.py` conversion remains separate; its dense Q8 conversion
+29 -8
View File
@@ -31,15 +31,22 @@ def main():
# Independent engine-consumer names, rather than the validator's own table.
consumer = (REPO / 'engine/strata/src/core/mtp.cpp').read_text()
names = sorted(set(re.findall(r'\b(q8|bf16|f32)\("([^" ]+)"\)', consumer)))
dense = bytearray(); lines = []
records = json.loads((REPO / 'engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json').read_text())
shapes = {t['name'].removeprefix('mtp.').removeprefix('layers.0.'): t['shape'] for t in records}
names += [('q8', 'self_attn.indexer.index_qk_proj.weight'), ('f32', 'self_attn.indexer.k_layernorm.weight'), ('f32', 'self_attn.indexer.q_layernorm.weight')]
offset = 0; lines = []
for kind, name in names:
kind = 'q8_0' if kind == 'q8' else kind
dense.extend(bytes(-len(dense) % 256))
size = {'q8_0': 34, 'bf16': 64, 'f32': 128}[kind]
lines.append(f'{name} {kind} 1 32 {len(dense)} {size}')
dense.extend(bytes(size))
(source / 'dense.bin').write_bytes(dense)
(source / 'dense.txt').write_text('\n'.join(lines) + '\n')
shape = shapes[name]
rows, cols = (1, shape[0]) if len(shape) == 1 else shape
offset = (offset + 255) // 256 * 256
size = rows * (cols // 32 * 34 if kind == 'q8_0' else cols * (4 if kind == 'f32' else 2))
lines.append(f'{name} {kind} {rows} {cols} {offset} {size}')
offset += size
with (source / 'dense.bin').open('wb') as f:
f.truncate(offset) # sparse synthetic values; geometry from independent pinned source
good_index = '\n'.join(lines) + '\n'
(source / 'dense.txt').write_text(good_index)
# Invalid pinned pack is deliberately tiny: verify no base-model fetch.
(source / 'experts.bin').write_bytes(b'invalid')
fixture.write_gguf(source / 'model.gguf', fixture.fixtures())
@@ -118,6 +125,20 @@ while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
mtp = root / 'mtp-v2'
config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp)
# Correct bytes/ranges, but transpose the rectangular Q projection.
bad_index = good_index.replace('self_attn.q_proj.weight q8_0 12288 2560', 'self_attn.q_proj.weight q8_0 2560 12288')
assert bad_index != good_index
(source / 'dense.txt').write_text(bad_index)
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
assert b'geometry' in run(ok=False).stderr
assert not (root / 'base').exists() and not marker.exists()
assert '/model.gguf' not in requests
assert (mtp / 'dense.txt').read_text() == bad_index
# Publish the good profile as a new version; preserve both rejected versions.
(source / 'dense.txt').write_text(good_index)
manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
mtp = root / 'mtp-v3'
config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp)
assert json.loads(run().stdout)['mtp_pack_structurally_validated'] is True
assert requests[-4:] == ['/dense.txt', '/dense.bin', '/experts.bin', '/model.gguf']
assert (root / 'mtp-v1/experts.bin').read_bytes() == invalid and not marker.exists()
@@ -144,7 +165,7 @@ while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done
process.kill(); process.wait(timeout=5)
if thread.is_alive():
server.shutdown(); server.server_close(); thread.join()
print('MTP bootstrap passed: pinned HTTP, invalid pack before base fetch/worker, exact args, offline reuse and previous version preserved; synthetic layout only, no GPU/model qualification')
print('MTP bootstrap passed: pinned HTTP, invalid pack before base fetch/worker, exact args, offline reuse and previous version preserved; independent pinned geometry and byte-consistent transpose rejection, synthetic values only, no GPU/model quality qualification')
if __name__ == '__main__':