From a2ca3eb636bcdcc83ee6e12aa39b75ab0a513986 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 18:27:04 +0200 Subject: [PATCH] feat(model): prepare native GGUF serving packs without Python --- .github/workflows/linux.yml | 4 +- control-plane/src/gguf.rs | 14 +- control-plane/src/lib.rs | 1 + control-plane/src/main.rs | 9 +- control-plane/src/native_pack.rs | 491 +++++++++++++++++++++++++++++++ deploy/README.md | 43 +++ scripts/smoke-native-pack.py | 166 +++++++++++ 7 files changed, 725 insertions(+), 3 deletions(-) create mode 100644 control-plane/src/native_pack.rs create mode 100644 scripts/smoke-native-pack.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 32cd870c..86dc6fbe 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -61,7 +61,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils + run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | rustup toolchain install 1.99.0 --profile minimal @@ -101,6 +101,8 @@ jobs: run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Atomic pinned assets before native serving run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native GGUF pack preparation against upstream oracle + run: python3 scripts/smoke-native-pack.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 deployment configuration without worker launch diff --git a/control-plane/src/gguf.rs b/control-plane/src/gguf.rs index 95f5f9ee..c0089e4d 100644 --- a/control-plane/src/gguf.rs +++ b/control-plane/src/gguf.rs @@ -19,6 +19,7 @@ pub struct Summary { pub architecture: Option, pub split_no: Option, pub split_count: Option, + pub split_tensors_count: Option, pub data_start: u64, pub file_size: u64, pub types: BTreeMap, @@ -199,6 +200,7 @@ fn read_index(path: &Path, strict: bool) -> Result { let mut architecture = None; let mut split_no = None; let mut split_count = None; + let mut split_tensors_count = None; let mut alignment = 32u64; let mut keys = HashSet::new(); for _ in 0..metadata { @@ -212,7 +214,16 @@ fn read_index(path: &Path, strict: bool) -> Result { ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), - ("split.tensors.count", 5) => cursor.skip(4)?, + ("split.tensors.count", 5) => { + let count = cursor.u32()?; + if count > i32::MAX as u32 { + return Err("negative GGUF split tensor count".into()); + } + split_tensors_count = Some(u64::from(count)); + } + ("split.no" | "split.count" | "split.tensors.count", _) => { + return Err("GGUF split metadata has an invalid integer type".into()); + } _ => cursor.skip_value(kind)?, } } @@ -322,6 +333,7 @@ fn read_index(path: &Path, strict: bool) -> Result { architecture, split_no, split_count, + split_tensors_count, data_start, file_size: size, types, diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 1d792725..4c36ea38 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -26,6 +26,7 @@ pub mod lifecycle; pub mod metrics; pub mod model; pub mod model_pipeline; +pub mod native_pack; pub mod preflight; pub mod prepare_preview; pub mod prompt; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 61653856..43505352 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -12,6 +12,13 @@ use strata_control::{ async fn main() -> Result<(), Box> { let args: Vec = env::args().skip(1).collect(); match args.as_slice() { + [model, action, spec, source_flag, source, output_flag, output] + if model == "model" && action == "prepare-native-pack" + && source_flag == "--source-dir" && output_flag == "--output" => { + let manifest = strata_control::model::Manifest::from_spec(spec).await?; + println!("{}", strata_control::native_pack::prepare(&manifest, Path::new(source), Path::new(output)).await?); + Ok(()) + } [command, flag, path] if command == "provision" && flag == "--config" => { let config = Config::load_with_path(Some(Path::new(path)))?; strata_control::asset_bundle::provision(&config.assets).await?; @@ -731,7 +738,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [serve [--config FILE]|provision --config FILE|check-config [--config FILE]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|doctor|engine-info|engine-help|--ggml-license|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + _ => Err("usage: strata-next [serve [--config FILE]|provision --config FILE|check-config [--config FILE]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), } } diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs new file mode 100644 index 00000000..93e82224 --- /dev/null +++ b/control-plane/src/native_pack.rs @@ -0,0 +1,491 @@ +//! Native GGUF serving-pack preparation. Quantized tensors remain in source +//! shards; only exact float conversions are accepted. No runtime Python. +use std::{ + collections::{BTreeMap, HashSet}, + error::Error, + fs::{self, File}, + io::Write, + path::{Path, PathBuf}, +}; + +use serde_json::json; +use sha2::{Digest, Sha256}; + +use crate::{gguf, gguf_f32_stream, kar_codec, model, tokenizer, tokenizer_assets}; + +type Result = std::result::Result>; + +struct Shard { + path: PathBuf, + index: gguf::TensorIndex, +} + +fn safe_name(name: &str) -> bool { + !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) +} + +fn align(bytes: u64) -> Result { + Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64) +} + +fn form(name: &str) -> Option { + let name = if let Some(rest) = name.strip_prefix("blk.") { + rest.split_once('.').map_or(name, |(_, suffix)| suffix) + } else { + name + }; + match name { + "ffn_gate_inp.weight" + | "ffn_gate_inp_shexp.weight" + | "hc_attn_down.weight" + | "hc_attn_up.weight" + | "hc_attn_inject.weight" + | "hc_ffn_down.weight" + | "hc_ffn_up.weight" + | "hc_ffn_inject.weight" + | "output_hc_down.weight" + | "output_hc_up.weight" + | "indexer.k_proj.weight" + | "indexer.q_proj.weight" + | "ssm_alpha.weight" + | "ssm_beta.weight" + | "ple_key.weight" + | "ple_value.weight" => Some(30), + "ple_conv1d.weight" => Some(1), + "attn_q_norm.weight" + | "attn_k_norm.weight" + | "hc_attn_norm.weight" + | "hc_ffn_norm.weight" + | "output_hc_norm.weight" + | "indexer.q_norm.weight" + | "indexer.k_norm.weight" + | "ple_norm_conv.weight" + | "ple_norm_key.weight" + | "ple_norm_query.weight" + | "ssm_a" + | "ssm_conv1d.weight" + | "ssm_dt.bias" + | "ssm_norm.weight" => Some(0), + _ => None, + } +} + +fn float_name(kind: u32) -> &'static str { + match kind { + 0 => "F32", + 1 => "F16", + 30 => "BF16", + _ => "unsupported", + } +} + +fn expert(name: &str) -> bool { + name.starts_with("blk.") && name.ends_with("_exps.weight") +} + +fn shards(manifest: &model::Manifest, source: &Path) -> Result> { + let mut shards = Vec::new(); + let mut names = HashSet::new(); + for file in &manifest.files { + if !safe_name(&file.name) || !file.name.ends_with(".gguf") { + return Err("native pack manifest must contain GGUF shard filenames only".into()); + } + let path = source.join(&file.name); + let index = gguf::tensor_index(&path)?; + for tensor in &index.tensors { + if !safe_name(&tensor.name) || !names.insert(tensor.name.clone()) { + return Err("invalid or duplicate tensor name across GGUF shards".into()); + } + } + shards.push(Shard { path, index }); + } + if shards.is_empty() { + return Err("native pack has no source shards".into()); + } + shards.sort_by_key(|s| s.index.summary.split_no.unwrap_or(0)); + let first = &shards[0].index.summary; + if first.architecture.as_deref() != Some("qwen4exp") { + return Err("native pack preparation currently requires qwen4exp architecture".into()); + } + let count = shards.len() as u64; + let total = shards + .iter() + .try_fold(0u64, |sum, s| sum.checked_add(s.index.summary.tensors)) + .ok_or("split tensor count overflow")?; + if count == 1 && (first.split_count.unwrap_or(1) != 1 || first.split_no.unwrap_or(0) != 0) { + return Err("manifest is missing GGUF shards".into()); + } + let filename = shards[0].path.file_name().unwrap().to_str().unwrap(); + let suffix = format!("-00001-of-{count:05}.gguf"); + let prefix = if count > 1 { + Some( + filename + .strip_suffix(&suffix) + .ok_or("first shard filename does not match split count")?, + ) + } else { + None + }; + for (number, shard) in shards.iter().enumerate() { + let summary = &shard.index.summary; + if count > 1 + && (summary.split_no != Some(number as u64) + || summary.split_count != Some(count) + || summary.split_tensors_count != first.split_tensors_count) + { + return Err("inconsistent GGUF split identity".into()); + } + if summary.split_tensors_count.is_some_and(|n| n != total) { + return Err("GGUF split tensor total does not match manifest shards".into()); + } + if summary + .architecture + .as_ref() + .is_some_and(|arch| arch != "qwen4exp") + { + return Err("GGUF shard architecture mismatch".into()); + } + if let Some(prefix) = prefix { + let expected = format!("{prefix}-{:05}-of-{count:05}.gguf", number + 1); + if shard.path.file_name().unwrap() != expected.as_str() { + return Err("GGUF shard names do not form a discoverable family".into()); + } + } + } + Ok(shards) +} + +fn expert_table(shards: &[Shard]) -> Result { + let mut tensors = BTreeMap::new(); + let mut layers = 0u64; + for (shard, source) in shards.iter().enumerate() { + for tensor in &source.index.tensors { + tensors.insert(tensor.name.as_str(), (shard, tensor)); + if expert(&tensor.name) { + let mut parts = tensor.name.split('.'); + parts.next(); + let layer = parts.next().ok_or("expert layer absent")?.parse::()?; + if layer > 1023 { + return Err("unreasonable expert layer count".into()); + } + layers = layers.max(layer + 1); + if !["gate", "up", "down"] + .iter() + .any(|r| tensor.name == format!("blk.{layer}.ffn_{r}_exps.weight")) + { + return Err("unsupported expert role".into()); + } + } + } + } + if layers == 0 { + return Err("native pack requires expert tensors".into()); + } + let (_, router) = tensors + .get("blk.0.ffn_gate_inp.weight") + .ok_or("missing expert router")?; + if router.dimensions.len() != 2 { + return Err("router must have two dimensions".into()); + } + let experts = router.dimensions[1]; + let mut offset = 0u64; + let mut lines = Vec::new(); + let mut split_roles = false; + for layer in 0..layers { + let router_name = format!("blk.{layer}.ffn_gate_inp.weight"); + let (_, router) = tensors + .get(router_name.as_str()) + .ok_or("missing layer router")?; + if router.dimensions.len() != 2 || router.dimensions[1] != experts { + return Err("routers disagree on expert count".into()); + } + let mut roles = Vec::new(); + for role in ["gate", "up", "down"] { + let name = format!("blk.{layer}.ffn_{role}_exps.weight"); + let (shard, tensor) = *tensors.get(name.as_str()).ok_or("missing expert role")?; + if tensor.dimensions.len() != 3 + || tensor.dimensions[2] != experts + || !tensor.bytes.is_multiple_of(experts) + { + return Err("invalid expert shape".into()); + } + roles.push((shard, tensor)); + } + let gate = roles[0].1; + let up = roles[1].1; + let down = roles[2].1; + if gate.kind != up.kind + || gate.dimensions != up.dimensions + || gate.dimensions[0] != down.dimensions[1] + || gate.dimensions[1] != down.dimensions[0] + || router.dimensions[0] != gate.dimensions[0] + { + return Err("expert gate/up/down geometry mismatch".into()); + } + let blob = gate + .bytes + .checked_add(up.bytes) + .and_then(|n| n.checked_add(down.bytes)) + .ok_or("expert byte count overflow")? + / experts; + let absolute = roles + .iter() + .map(|(s, t)| shards[*s].index.summary.data_start + t.offset) + .collect::>(); + let filenames = roles + .iter() + .map(|(s, _)| { + if *s == 0 { + String::new() + } else { + shards[*s] + .path + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_owned() + } + }) + .collect::>(); + let same = filenames.iter().all(|f| f == &filenames[0]); + split_roles |= !same; + let column = if same { + filenames[0].clone() + } else { + filenames.join(",") + }; + let column = if column.is_empty() { + column + } else { + format!(" {column}") + }; + lines.push(format!( + "{layer} {} {} {offset} {blob} {} {} {}{column}\n", + gate.kind, down.kind, absolute[0], absolute[1], absolute[2] + )); + offset = blob + .checked_mul(experts) + .and_then(|n| offset.checked_add(n)) + .ok_or("expert arena overflow")?; + } + let name = shards[0].path.file_name().unwrap().to_str().unwrap(); + let header = if split_roles { + format!( + "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it - per role where the column is gate,up,down)\n" + ) + } else { + format!( + "# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it)\n" + ) + }; + Ok(header + &lines.concat()) +} + +fn dense_files(shards: &[Shard], output: &Path) -> Result<()> { + let mut dense = File::create(output.join("dense.bin"))?; + let mut at = 0u64; + let mut pool = 0u64; + let mut rows = Vec::new(); + let mut conversions = Vec::new(); + for shard in shards { + let mut input = File::open(&shard.path)?; + for tensor in &shard.index.tensors { + if expert(&tensor.name) || tensor.name == "per_layer_token_embd.weight" { + continue; + } + if tensor.dimensions.len() > 2 { + return Err("dense pack index accepts at most two dimensions".into()); + } + let ne0 = tensor.dimensions[0]; + let ne1 = tensor.dimensions.get(1).copied().unwrap_or(0); + let float = matches!(tensor.kind, 0 | 1 | 30); + let required = form(&tensor.name); + let native = !float + && (required.is_none() + || (tensor.name == "blk.1.ple_key.weight" && matches!(tensor.kind, 8 | 42))); + if native { + rows.push(format!( + "{} 0 0 0 0 {pool} 0 {ne0} {ne1} 8 0 32 0 0 0 0 0 0 0\n", + tensor.name + )); + continue; + } + if !float { + return Err("quantized projection requires unsupported lossy conversion".into()); + } + let target = required.unwrap_or(tensor.kind); + if target != tensor.kind + && !matches!((tensor.kind, target), (0, 30) | (0, 1) | (1 | 30, 0)) + { + return Err("unsupported native pack float conversion".into()); + } + let mut written = 0u64; + let mut digest = Sha256::new(); + gguf_f32_stream::visit( + &mut input, + shard.index.summary.data_start + tensor.offset, + tensor.kind, + tensor.bytes, + |raw, values| { + digest.update(raw); + let mut converted = Vec::new(); + let bytes = if target == tensor.kind { + raw + } else { + for bits in values.as_chunks::<4>().0 { + let value = f32::from_le_bytes(*bits); + if !value.is_finite() { + return Err("non-finite conversion refused".into()); + } + match target { + 30 => { + if value.to_bits() & 0xffff != 0 { + return Err("lossy F32 to BF16 conversion refused".into()); + } + converted.extend_from_slice( + &((value.to_bits() >> 16) as u16).to_le_bytes(), + ); + } + 1 => { + let half = kar_codec::f32_to_f16_bits(value); + if kar_codec::f16_bits_to_f32(half).to_bits() != value.to_bits() + { + return Err("lossy F32 to F16 conversion refused".into()); + } + // Index kind3 stores F32; the existing loader narrows it. + converted.extend_from_slice(bits); + } + 0 => converted.extend_from_slice(bits), + _ => unreachable!(), + } + } + &converted + }; + dense.write_all(bytes).map_err(|e| e.to_string())?; + written += bytes.len() as u64; + Ok(()) + }, + )?; + let kind = if target == 1 && tensor.kind == 0 { + 3 + } else { + match target { + 0 => 2, + 1 => 5, + 30 => 4, + _ => unreachable!(), + } + }; + let dst = if kind == 3 { written / 2 } else { written }; + rows.push(format!( + "{} 0 {kind} {at} {written} {pool} {dst} {ne0} {ne1} 0 0 1 0 0 0 0 0 0 0\n", + tensor.name + )); + let padded = align(written)?; + dense.write_all(&[0u8; 64][..(padded - written) as usize])?; + at = at.checked_add(padded).ok_or("dense file offset overflow")?; + pool = pool.checked_add(align(dst)?).ok_or("dense pool overflow")?; + if target != tensor.kind { + conversions.push(json!({"name":tensor.name, "shard":shard.path.file_name().unwrap().to_str().unwrap(), + "src_type":float_name(tensor.kind), "dst_type":float_name(target), "exact":true, + "max_abs_err":0.0, "source_sha256":hex::encode(digest.finalize())})); + } + } + } + dense.sync_all()?; + let source = shards[0].path.file_name().unwrap().to_str().unwrap(); + let text = format!( + "# strata pack index v3 -- generated by strata-next (native experts) from {source}\n# align 64 pool {pool} tensors {}\n{}", + rows.len(), + rows.concat() + ); + write(output.join("index.txt"), text.as_bytes())?; + write( + output.join("conversions.json"), + &serde_json::to_vec_pretty( + &json!({"schema":1,"tool":"strata-next","compat_bf16":false,"tensors":conversions}), + )?, + )?; + Ok(()) +} + +fn write(path: PathBuf, bytes: &[u8]) -> Result<()> { + let mut file = File::create(path)?; + file.write_all(bytes)?; + file.sync_all()?; + Ok(()) +} + +pub async fn prepare( + manifest: &model::Manifest, + source: &Path, + output: &Path, +) -> Result { + if output.exists() || output.is_symlink() { + return Err("native pack output already exists; choose a new versioned directory".into()); + } + model::verify(manifest, source).await?; + let shards = shards(manifest, source)?; + let experts = expert_table(&shards)?; + // Validate tokenizer before writing any pack files. + tokenizer_assets_preflight(&shards[0].path)?; + let parent = output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + let name = output + .file_name() + .ok_or("native pack output has no filename")?; + let mut stage_name = std::ffi::OsString::from("."); + stage_name.push(name); + stage_name.push(format!(".native-pack-{}.tmp", std::process::id())); + let stage = parent.join(stage_name); + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&stage)?; + let result = (|| -> Result<()> { + dense_files(&shards, &stage)?; + let tokenizer_dir = tokenizer_assets::extract(&shards[0].path, &stage)?; + tokenizer::Tokenizer::from_assets(&tokenizer_dir)?; + write(stage.join("native_experts.txt"), experts.as_bytes())?; + let sources = manifest + .files + .iter() + .map(|f| json!({"name":f.name,"size":f.size,"sha256":f.sha256})) + .collect::>(); + write( + stage.join("source.json"), + &serde_json::to_vec_pretty( + &json!({"schema":1,"kind":"native-gguf","source_shards":sources,"lossy_conversions":false}), + )?, + )?; + File::open(&stage)?.sync_all()?; + if output.exists() || output.is_symlink() { + return Err("native pack destination appeared during preparation".into()); + } + fs::rename(&stage, output)?; + File::open(parent)?.sync_all()?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_dir_all(&stage); + } + result?; + Ok( + json!({"prepared":true,"format":"native-gguf","source_shards":shards.len(),"lossy_conversions":false,"gpu_validated":false}), + ) +} + +fn tokenizer_assets_preflight(source: &Path) -> Result<()> { + gguf::tokenizer_metadata(source)?; + Ok(()) +} diff --git a/deploy/README.md b/deploy/README.md index dfb07302..6c0da29a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -471,3 +471,46 @@ conversion or full KAR model preparation. The complete-package Linux/GPU clean-node acceptance gate remains separate. The CPU smoke uses synthetic pack bytes and tokenizer files; it proves publication and startup ordering, not model inference or performance. + +## Prepare a native serving pack from GGUF + +The native CLI can now build a Qwen `qwen4exp` serving pack from locally present, +manifest-pinned GGUF shards: + +```sh +strata-next model prepare-native-pack /absolute/shards.json \ + --source-dir /absolute/models --output /absolute/packs/model-v1 +``` + +The command verifies source sizes and SHA-256, split shard identity/counts, +unique tensors, expert router counts and gate/up/down geometry. It emits +`dense.bin`, `index.txt`, `native_experts.txt`, `conversions.json`, +`source.json` and `tokenizer/` through a private staging directory, then renames +the completed directory into place. Existing output is refused; retain the +old version and configuration for rollback. Failed ordinary preparation +removes its own stage; after a killed process an unused +`.NAME.native-pack-PID.tmp` may be removed before retrying. No existing pack is +replaced and no worker is started. + +Use the result with the existing engine's `--native --gguf` source-shard option +and `--pack` output directory, plus the pack's `tokenizer/` for native Responses. +The quantized expert weights, native dense projections and large PLE table +remain in the original GGUF shards: **retain those shards**. This command does +not create `experts.bin`, add KAR compression or reduce the model's quantization. +Source shard filenames must form the engine's usual split-file family. + +Preparation currently accepts matching float types, exact F32-to-BF16, +F16/BF16-to-F32 widening, and exact F32-to-F16 through the loader's index kind3. +It rejects conversions that would round weights; there is no `--compat-bf16` +option. Unsupported architectures, missing expert roles, incompatible shapes, +quantized projections requiring conversion, and non-finite converted values +fail without publishing a pack. `conversions.json` records the exact changes +and source tensor hashes; `source.json` records the verified shard identities. + +`scripts/smoke-native-pack.py` compares dense bytes, index rows and the complete +v3/v4 expert table against the unmodified pinned `tools/iq_pack.py` oracle on +small single/split GGUF fixtures, including per-role shard offsets. Numerical +and byte tolerance is zero. Python/numpy are test-only dependencies. This does +not establish full-model GPU readiness: real-model pack parity and clean-node +GPU startup still require their separate gates. Automatic fetch/prepare/start +orchestration remains a subsequent integration step. diff --git a/scripts/smoke-native-pack.py b/scripts/smoke-native-pack.py new file mode 100644 index 00000000..f076cb0f --- /dev/null +++ b/scripts/smoke-native-pack.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Independent pinned Python pack oracle versus the native Rust CLI, CPU only.""" +import contextlib +import hashlib +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'engine/strata/tools')) +import iq_pack # Existing oracle, unchanged; numpy is test-only. + + +def string(s): + b = s.encode() + return struct.pack('']), + ('tokenizer.ggml.merges', ['a b'])]: + fields.append((k, 9, struct.pack('': 3} + assert (output / 'tokenizer/merges.txt').read_text() == 'a b' + assert [p.read_bytes() for p in paths] == source_before + before = (output / 'dense.bin').read_bytes() + run(paths, output, ok=False) + assert (output / 'dense.bin').read_bytes() == before + + # Failed preparation must publish no output, even after partial dense writes. + source = root / 'failure.gguf' + cases = [] + t = fixtures(); t[0] = (*t[0][:3], struct.pack('