Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
342 lines
12 KiB
Rust
342 lines
12 KiB
Rust
//! Structural preflight for the current Qwen3.8 Flash Next Q2 MTP runtime.
|
|
//! Checks current MTP tensor geometry, not values, base-model pairing or draft quality.
|
|
use std::{
|
|
collections::HashMap,
|
|
fs::{self, File, OpenOptions},
|
|
io::Read,
|
|
path::Path,
|
|
};
|
|
|
|
const INDEX_LIMIT: u64 = 64 * 1024;
|
|
// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB.
|
|
const EXPERT_BYTES: u64 = 512 * 1_382_400;
|
|
// 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",
|
|
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> {
|
|
let mut options = OpenOptions::new();
|
|
options.read(true);
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
|
|
}
|
|
let file = options
|
|
.open(path)
|
|
.map_err(|_| "cannot open MTP runtime file")?;
|
|
let meta = file
|
|
.metadata()
|
|
.map_err(|_| "cannot inspect MTP runtime file")?;
|
|
if !meta.is_file()
|
|
|| fs::symlink_metadata(path)
|
|
.map_err(|_| "cannot inspect MTP file path")?
|
|
.file_type()
|
|
.is_symlink()
|
|
{
|
|
return Err("MTP runtime files must be regular files, not symlinks");
|
|
}
|
|
Ok(file)
|
|
}
|
|
|
|
pub fn check(directory: &Path) -> Result<(), &'static str> {
|
|
let meta = fs::symlink_metadata(directory).map_err(|_| "MTP runtime directory is absent")?;
|
|
if !meta.is_dir() || meta.file_type().is_symlink() {
|
|
return Err("MTP pack must be a directory, not a symlink");
|
|
}
|
|
let index = regular(&directory.join("dense.txt"))?;
|
|
if index
|
|
.metadata()
|
|
.map_err(|_| "cannot inspect MTP index")?
|
|
.len()
|
|
> INDEX_LIMIT
|
|
{
|
|
return Err("MTP index exceeds 64 KiB limit");
|
|
}
|
|
let mut text = String::new();
|
|
index
|
|
.take(INDEX_LIMIT + 1)
|
|
.read_to_string(&mut text)
|
|
.map_err(|_| "cannot read UTF-8 MTP index")?;
|
|
if text.len() as u64 > INDEX_LIMIT {
|
|
return Err("MTP index exceeds 64 KiB limit");
|
|
}
|
|
let dense = regular(&directory.join("dense.bin"))?
|
|
.metadata()
|
|
.map_err(|_| "cannot inspect MTP dense file")?
|
|
.len();
|
|
let experts = regular(&directory.join("experts.bin"))?
|
|
.metadata()
|
|
.map_err(|_| "cannot inspect MTP experts")?
|
|
.len();
|
|
if experts != EXPERT_BYTES {
|
|
return Err("MTP Q2 experts size does not match the 512-expert runtime profile");
|
|
}
|
|
validate_index(&text, dense)
|
|
}
|
|
|
|
fn validate_index(text: &str, dense_bytes: u64) -> Result<(), &'static str> {
|
|
if !text.is_ascii() {
|
|
return Err("MTP index must use the ASCII engine format");
|
|
}
|
|
let mut tensors = HashMap::new();
|
|
let mut ranges = Vec::new();
|
|
for line in text.lines().filter(|s| !s.is_empty()) {
|
|
let fields: Vec<_> = line.split_whitespace().collect();
|
|
if fields.len() != 6 || tensors.len() >= 128 {
|
|
return Err("malformed or oversized MTP tensor index");
|
|
}
|
|
let name = fields[0];
|
|
if name.len() > 180
|
|
|| !name
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b))
|
|
|| tensors.contains_key(name)
|
|
{
|
|
return Err("invalid or duplicate MTP tensor name");
|
|
}
|
|
let numbers = fields[2..]
|
|
.iter()
|
|
.map(|s| s.parse::<u64>())
|
|
.collect::<Result<Vec<_>, _>>()
|
|
.map_err(|_| "invalid MTP tensor dimensions or offsets")?;
|
|
let (rows, cols, offset, bytes) = (numbers[0], numbers[1], numbers[2], numbers[3]);
|
|
if rows == 0
|
|
|| cols == 0
|
|
|| rows > i32::MAX as u64
|
|
|| cols > i32::MAX as u64
|
|
|| offset % 256 != 0
|
|
{
|
|
return Err("invalid MTP tensor dimensions or alignment");
|
|
}
|
|
let row_bytes = match fields[1] {
|
|
"f32" if rows == 1 => cols.checked_mul(4),
|
|
"bf16" => cols.checked_mul(2),
|
|
"q8_0" if cols.is_multiple_of(32) => (cols / 32).checked_mul(34),
|
|
_ => return Err("unsupported MTP tensor kind or row shape"),
|
|
}
|
|
.ok_or("MTP tensor row size overflow")?;
|
|
if row_bytes.checked_mul(rows) != Some(bytes) {
|
|
return Err("MTP tensor byte count mismatch");
|
|
}
|
|
let end = offset
|
|
.checked_add(bytes)
|
|
.ok_or("MTP tensor range overflow")?;
|
|
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, 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();
|
|
if ranges.windows(2).any(|p| p[0].1 > p[1].0) {
|
|
return Err("MTP dense tensor ranges overlap");
|
|
}
|
|
if ranges.last().map(|r| r.1) != Some(dense_bytes) {
|
|
return Err("MTP dense file has unindexed trailing bytes");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
fn fixture() -> (String, u64) {
|
|
let mut text = String::new();
|
|
let mut end = 0u64;
|
|
for (name, kind, rows, cols) in REQUIRED.iter().chain(OPTIONAL) {
|
|
let at = end.div_ceil(256) * 256;
|
|
let bytes = match *kind {
|
|
"q8_0" => rows * (cols / 32) * 34,
|
|
"bf16" => rows * cols * 2,
|
|
_ => rows * cols * 4,
|
|
};
|
|
text.push_str(&format!("{name} {kind} {rows} {cols} {at} {bytes}\n"));
|
|
end = at + bytes;
|
|
}
|
|
(text, end)
|
|
}
|
|
#[test]
|
|
fn validates_layout_and_rejects_malformed_mtp() {
|
|
let (text, bytes) = fixture();
|
|
validate_index(&text, bytes).unwrap();
|
|
for invalid in [
|
|
text.replacen(' ', "\u{a0}", 1),
|
|
text.replacen("q8_0", "bf16", 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("2560 2560", "18446744073709551615 2560", 1),
|
|
] {
|
|
assert!(validate_index(&invalid, bytes).is_err());
|
|
}
|
|
assert!(validate_index(&text, bytes - 1).is_err());
|
|
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();
|
|
let (text, bytes) = fixture();
|
|
fs::write(dir.join("dense.txt"), text).unwrap();
|
|
File::create(dir.join("dense.bin"))
|
|
.unwrap()
|
|
.set_len(bytes)
|
|
.unwrap();
|
|
File::create(dir.join("experts.bin"))
|
|
.unwrap()
|
|
.set_len(EXPERT_BYTES)
|
|
.unwrap();
|
|
check(&dir).unwrap();
|
|
File::create(dir.join("experts.bin"))
|
|
.unwrap()
|
|
.set_len(EXPERT_BYTES - 1)
|
|
.unwrap();
|
|
assert!(check(&dir).is_err());
|
|
File::create(dir.join("experts.bin"))
|
|
.unwrap()
|
|
.set_len(EXPERT_BYTES)
|
|
.unwrap();
|
|
fs::remove_file(dir.join("dense.bin")).unwrap();
|
|
assert!(check(&dir).is_err());
|
|
#[cfg(unix)]
|
|
{
|
|
std::os::unix::fs::symlink(dir.join("experts.bin"), dir.join("dense.bin")).unwrap();
|
|
assert!(check(&dir).is_err());
|
|
fs::remove_file(dir.join("dense.bin")).unwrap();
|
|
}
|
|
File::create(dir.join("dense.bin"))
|
|
.unwrap()
|
|
.set_len(bytes)
|
|
.unwrap();
|
|
fs::write(dir.join("dense.txt"), " ".repeat(INDEX_LIMIT as usize + 1)).unwrap();
|
|
assert!(check(&dir).is_err());
|
|
#[cfg(unix)]
|
|
{
|
|
fs::remove_file(dir.join("dense.txt")).unwrap();
|
|
let path = std::ffi::CString::new(dir.join("dense.txt").as_os_str().as_encoded_bytes())
|
|
.unwrap();
|
|
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
|
|
assert!(check(&dir).is_err()); // Must return without waiting for a FIFO writer.
|
|
}
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
}
|