From a269656d225db229e2557525b3d46baed5b18866 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 05:37:57 +0200 Subject: [PATCH] Native runtime profile admission before pack preparation (#26) * feat: validate declared native runtime geometry before preparation * fix: preserve independent draft geometry for pruned targets --- .github/workflows/linux.yml | 2 + control-plane/src/gguf.rs | 163 ++++++++++++++++++++++++++++++ control-plane/src/native_model.rs | 13 ++- control-plane/src/preflight.rs | 2 + deploy/README.md | 19 ++++ scripts/smoke-mtp-pack.py | 8 +- scripts/smoke-native-pack.py | 4 +- scripts/smoke-runtime-profile.py | 96 ++++++++++++++++++ 8 files changed, 302 insertions(+), 5 deletions(-) create mode 100644 scripts/smoke-runtime-profile.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index c71d5bac..c7869cff 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -245,6 +245,8 @@ jobs: run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Pinned MTP structural preflight and native bootstrap run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native runtime profile metadata admission + run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native systemd unit syntax and path safety run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native installer with actual isolated systemd user service diff --git a/control-plane/src/gguf.rs b/control-plane/src/gguf.rs index c0089e4d..ec052e4b 100644 --- a/control-plane/src/gguf.rs +++ b/control-plane/src/gguf.rs @@ -52,6 +52,63 @@ pub struct TokenizerMetadata { pub chat_template: String, } +/// 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") { + return Err("runtime_profile requires general.architecture=qwen4exp".into()); + } + let required = [ + ("qwen4exp.block_count", Some(48)), + ("qwen4exp.embedding_length", Some(2560)), + ("qwen4exp.attention.head_count", Some(24)), + ("qwen4exp.attention.head_count_kv", Some(2)), + ("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}"))?; + if value == 0 || value > i32::MAX as u32 { + return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); + } + if let Some(expected) = expected + && value != expected + { + return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); + } + } + if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { + return Err( + "runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(), + ); + } + Ok(()) +} + /// Read only tokenizer fields after the complete GGUF header has passed inspection. pub fn tokenizer_metadata(path: &Path) -> Result { inspect(path)?; @@ -547,6 +604,112 @@ mod tests { out.extend_from_slice(value.as_bytes()); } + #[test] + fn admits_flash_metadata_and_rejects_incompatible_profiles() { + let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id())); + let fields = [ + ("qwen4exp.block_count", 48u32), + ("qwen4exp.embedding_length", 2560), + ("qwen4exp.attention.head_count", 24), + ("qwen4exp.attention.head_count_kv", 2), + ("qwen4exp.expert_count", 512), + ("qwen4exp.expert_used_count", 10), + ]; + let write = |entries: Vec<(&str, u32, Vec)>| { + let mut data = b"GGUF".to_vec(); + data.extend(3u32.to_le_bytes()); + data.extend(0u64.to_le_bytes()); + data.extend((entries.len() as u64 + 1).to_le_bytes()); + string(&mut data, "general.architecture"); + data.extend(8u32.to_le_bytes()); + string(&mut data, "qwen4exp"); + for (key, kind, bytes) in entries { + string(&mut data, key); + data.extend(kind.to_le_bytes()); + data.extend(bytes); + } + data.resize(data.len().div_ceil(32) * 32, 0); + std::fs::write(&path, data).unwrap(); + }; + let good = || { + fields + .iter() + .map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())) + .collect::>() + }; + write(good()); + check_flash_next_profile(&path).unwrap(); + for index in 0..fields.len() { + let mut entries = good(); + entries.remove(index); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[index].0) + ); + let mut entries = good(); + entries[index].2 = 0u32.to_le_bytes().to_vec(); + write(entries); + assert!(check_flash_next_profile(&path).is_err()); + } + for index in 0..4 { + let mut entries = good(); + entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("expected") + ); + } + for (kind, bytes) in [ + (7, vec![1]), + (6, 48f32.to_le_bytes().to_vec()), + (5, (-1i32).to_le_bytes().to_vec()), + (10, (1u64 << 32).to_le_bytes().to_vec()), + ] { + let mut entries = good(); + entries[0] = (fields[0].0, kind, bytes); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[0].0) + ); + } + let mut entries = good(); + entries[4].2 = 256u32.to_le_bytes().to_vec(); + write(entries); + check_flash_next_profile(&path).unwrap(); + let mut entries = good(); + entries[5].2 = 513u32.to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("exceeds") + ); + for kind in [0, 1, 2, 3, 4, 5, 10, 11] { + let mut entries = good(); + let bytes = 48u64.to_le_bytes(); + let n = match kind { + 0 | 1 => 1, + 2 | 3 => 2, + 4 | 5 => 4, + _ => 8, + }; + entries[0] = (fields[0].0, kind, bytes[..n].to_vec()); + write(entries); + check_flash_next_profile(&path).unwrap(); + } + std::fs::remove_file(path).unwrap(); + } + #[test] fn inspects_header_and_rejects_truncated_payload() { let mut gguf = b"GGUF".to_vec(); diff --git a/control-plane/src/native_model.rs b/control-plane/src/native_model.rs index ddd36af3..088690b3 100644 --- a/control-plane/src/native_model.rs +++ b/control-plane/src/native_model.rs @@ -27,12 +27,19 @@ const FILES: &[&str] = &[ "tokenizer/chat_template.jinja", ]; +#[derive(Clone, Copy, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum RuntimeProfile { + Qwen4expFlashNext, +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct NativeModel { pub manifest: PathBuf, pub source_dir: PathBuf, pub output: PathBuf, + pub runtime_profile: Option, } impl NativeModel { @@ -85,6 +92,10 @@ impl NativeModel { directory: self.source_dir.clone(), }]) .await?; + let primary = native_pack::primary_shard(&manifest, &self.source_dir)?; + if let Some(RuntimeProfile::Qwen4expFlashNext) = self.runtime_profile { + crate::gguf::check_flash_next_profile(&primary)?; + } let parent = self.output.parent().ok_or("pack directory has no parent")?; fs::create_dir_all(parent)?; let mut name = std::ffi::OsString::from("."); @@ -111,7 +122,7 @@ impl NativeModel { } Err(e) => return Err(e.into()), } - native_pack::primary_shard(&manifest, &self.source_dir) + Ok(primary) } } diff --git a/control-plane/src/preflight.rs b/control-plane/src/preflight.rs index bf6dbc74..534a9f50 100644 --- a/control-plane/src/preflight.rs +++ b/control-plane/src/preflight.rs @@ -49,6 +49,8 @@ pub fn check(path: Option<&Path>) -> Result { "engine": engine, "tokenizer_validated": config.tokenizer_dir.is_some() && !tokenizer_pending, "native_model_configured":config.native_model.is_some(), + "native_runtime_profile":config.native_model.as_ref().and_then(|native| native.runtime_profile), + "native_runtime_profile_checked":false, "mtp_pack": if config.mtp_pack.is_some() { "pinned_structural_check_pending" } else { "unconfigured" }, "native_model_verified":false, "inference_configured": config.worker.is_some() && config.tokenizer_dir.is_some() && !tokenizer_pending, diff --git a/deploy/README.md b/deploy/README.md index 8e087132..bc05f8cd 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -568,6 +568,25 @@ auxiliary pack with a separate pinned `assets` bundle and pass its explicit path keep its directory disjoint from managed sources/output. The baseline can run without optional MTP. Full-model and clean-node GPU qualification remain open. +For the current specialised engine, add +`"runtime_profile": "qwen4exp-flash-next"` inside `native_model`. After source +SHA verification and shard discovery, `provision`/`serve` check the first GGUF +shard **before pack preparation or output mutation**, including offline reuse. +The profile requires `qwen4exp` metadata with 48 blocks, hidden width 2560, +24 attention heads and 2 KV heads. Expert counts must be positive 32-bit signed +values and selected experts cannot exceed total experts; pruned counts remain +allowed with or without MTP. The engine uses an independent canonical draft +geometry for MTP, so its 512 experts need not match a pruned target. Missing, mistyped or incompatible fields identify the failing key. +Unknown profile names fail config validation; `check-config` reports the selected +`native_runtime_profile` and `native_runtime_profile_checked: false` without +reading model files or downloading anything. + +Omitting the profile preserves generic exact preparation. The profile checks +metadata compatibility only: tensor layout/values, checkpoint pairing, memory +fit and actual GPU/model/MTP qualification remain separate checks. It does not +change generated bytes or enable compression. Rejected versioned sources remain +available for diagnosis, and existing prepared versions remain unchanged. + For the current Qwen3.8 Flash Next **Q2 MTP runtime layout**, set `mtp_pack` to exactly one directory listed in `assets`: diff --git a/scripts/smoke-mtp-pack.py b/scripts/smoke-mtp-pack.py index eb7eeb0d..b7f8fb4e 100644 --- a/scripts/smoke-mtp-pack.py +++ b/scripts/smoke-mtp-pack.py @@ -12,6 +12,7 @@ import re import shutil import socket import subprocess +import struct import sys import tempfile import threading @@ -49,7 +50,10 @@ def main(): (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()) + fixture.write_gguf(source / 'model.gguf', fixture.fixtures(), extra_fields=[ + ('qwen4exp.' + k, 4, struct.pack('