feat(model): prepare native GGUF serving packs without Python

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 18:27:04 +02:00
parent 99684304db
commit a2ca3eb636
7 changed files with 725 additions and 3 deletions
+3 -1
View File
@@ -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
+13 -1
View File
@@ -19,6 +19,7 @@ pub struct Summary {
pub architecture: Option<String>,
pub split_no: Option<u64>,
pub split_count: Option<u64>,
pub split_tensors_count: Option<u64>,
pub data_start: u64,
pub file_size: u64,
pub types: BTreeMap<u32, u64>,
@@ -199,6 +200,7 @@ fn read_index(path: &Path, strict: bool) -> Result<TensorIndex> {
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<TensorIndex> {
("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<TensorIndex> {
architecture,
split_no,
split_count,
split_tensors_count,
data_start,
file_size: size,
types,
+1
View File
@@ -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;
+8 -1
View File
@@ -12,6 +12,13 @@ use strata_control::{
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = 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<dyn std::error::Error>> {
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()),
}
}
+491
View File
@@ -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<T> = std::result::Result<T, Box<dyn Error>>;
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<u64> {
Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64)
}
fn form(name: &str) -> Option<u32> {
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<Vec<Shard>> {
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<String> {
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::<u64>()?;
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::<Vec<_>>();
let filenames = roles
.iter()
.map(|(s, _)| {
if *s == 0 {
String::new()
} else {
shards[*s]
.path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned()
}
})
.collect::<Vec<_>>();
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<serde_json::Value> {
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::<Vec<_>>();
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(())
}
+43
View File
@@ -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.
+166
View File
@@ -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('<Q', len(b)) + b
def write_gguf(path, tensors, split=None, architecture='qwen4exp', tokenizer=True):
fields = []
if architecture:
fields.append(('general.architecture', 8, string(architecture)))
if split is not None:
fields += [('split.no', 2, struct.pack('<H', split[0])),
('split.count', 2, struct.pack('<H', split[1])),
('split.tensors.count', 5, struct.pack('<i', split[2]))]
if tokenizer:
fields += [(k, 8, string(v)) for k, v in [
('tokenizer.ggml.model', 'gpt2'), ('tokenizer.ggml.pre', 'qwen35'),
('tokenizer.chat_template', '{{ messages }}')]]
for k, vals in [('tokenizer.ggml.tokens', ['a', 'b', 'ab', '<|im_end|>']),
('tokenizer.ggml.merges', ['a b'])]:
fields.append((k, 9, struct.pack('<IQ', 8, len(vals)) + b''.join(map(string, vals))))
fields.append(('tokenizer.ggml.token_type', 9, struct.pack('<IQ4I', 4, 4, 1, 1, 1, 3)))
fields.append(('tokenizer.ggml.eos_token_id', 4, struct.pack('<I', 3)))
header = b'GGUF' + struct.pack('<IQQ', 3, len(tensors), len(fields))
for k, kind, value in fields:
header += string(k) + struct.pack('<I', kind) + value
body = b''
for name, dims, kind, raw in tensors:
header += string(name) + struct.pack('<I', len(dims))
header += struct.pack('<' + 'Q' * len(dims), *dims) + struct.pack('<IQ', kind, len(body))
body += raw
body += bytes(-len(body) % 32)
header += bytes(-len(header) % 32)
path.write_bytes(header + body)
def fixtures():
# GGUF dimensions are fastest-first. Quantized expert bytes are opaque;
# both packers preserve them in GGUF, and only derive per-role offsets.
return [
('blk.0.ffn_gate_inp.weight', [256, 2], 0, struct.pack('<f', 1.5) * 512),
('blk.0.attn_q_norm.weight', [256], 30, struct.pack('<H', 0x3fc0) * 256),
('blk.0.attn_k_norm.weight', [256], 1, struct.pack('<e', -2.0) * 256),
('blk.1.ple_conv1d.weight', [2], 0, struct.pack('<2f', 1.5, -2.0)),
('unlisted_float.weight', [3], 1, struct.pack('<3e', 1, 2, 3)),
('token_embd.weight', [256, 2], 21, bytes(range(110)) * 2),
('blk.1.ple_key.weight', [256, 2], 8, bytes(range(34)) * 16),
('per_layer_token_embd.weight', [256, 2], 8, bytes(range(34)) * 16),
*[(f'blk.0.ffn_{r}_exps.weight', [256, 256, 2], 21, bytes(range(110)) * 512)
for r in ['gate', 'up', 'down']]]
def main():
binary = str(Path(sys.argv[1]).resolve())
count = 0
with tempfile.TemporaryDirectory(prefix='strata-native-pack-') as tmp:
root = Path(tmp).resolve()
manifest_path = root / 'manifest.json'
env = {'PATH': os.defpath}
def run(paths, output, ok=True):
nonlocal count
manifest = {'schema_version': 1, 'files': [
{'name': p.name, 'url': 'https://example.invalid/' + p.name,
'size': p.stat().st_size, 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}
for p in reversed(paths)]}
manifest_path.write_text(json.dumps(manifest))
result = subprocess.run([binary, 'model', 'prepare-native-pack', str(manifest_path),
'--source-dir', str(root), '--output', str(output)],
env=env, text=True, capture_output=True, timeout=15)
assert (result.returncode == 0) == ok, result.stdout + result.stderr
assert not list(root.glob(f'.{output.name}.native-pack-*.tmp')), 'unremoved failed stage'
if ok:
report = json.loads(result.stdout)
assert report['prepared'] and not report['lossy_conversions'] and not report['gpu_validated']
count += 1
return result
for split in [False, True]:
tensors = fixtures()
paths = [root / 'single.gguf'] if not split else [root / f'split-{n:05}-of-00002.gguf' for n in [1, 2]]
if split:
write_gguf(paths[0], tensors[:-1], (0, 2, len(tensors)))
write_gguf(paths[1], tensors[-1:], (1, 2, len(tensors)), architecture=None, tokenizer=False)
else:
write_gguf(paths[0], tensors)
source_before = [p.read_bytes() for p in paths]
output = root / ('rust-split' if split else 'rust-single')
oracle = root / ('oracle-split' if split else 'oracle-single')
oracle.mkdir()
with contextlib.redirect_stdout(io.StringIO()):
model = iq_pack.Model(paths[0])
table = iq_pack.expert_layout(model, paths[0])
assert not isinstance(table, str), table
assert iq_pack.index_standalone(paths[0], oracle, model) == 0
run(paths, output)
assert (output / 'dense.bin').read_bytes() == (oracle / 'dense.bin').read_bytes()
assert (output / 'index.txt').read_text().splitlines()[1:] == (oracle / 'index.txt').read_text().splitlines()[1:]
assert (output / 'native_experts.txt').read_text() == table[1]
native_conv = json.loads((output / 'conversions.json').read_text())['tensors']
oracle_conv = json.loads((oracle / 'conversions.json').read_text())['tensors']
assert len(native_conv) == len(oracle_conv)
for a, b in zip(native_conv, oracle_conv):
assert all(a[k] == b[k] for k in ['name', 'shard', 'src_type', 'dst_type', 'exact', 'max_abs_err', 'source_sha256'])
assert json.loads((output / 'tokenizer/vocab.json').read_text()) == {'a': 0, 'b': 1, 'ab': 2, '<|im_end|>': 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('<f', 1.00001) * 512); cases.append(t)
t = fixtures(); t[3] = (*t[3][:3], struct.pack('<2f', 1.00001, -2)); cases.append(t)
t = fixtures(); t.pop(); cases.append(t) # missing expert role
t = fixtures(); t[-1] = (t[-1][0], [512, 128, 2], *t[-1][2:]); cases.append(t)
t = fixtures(); t[0] = (*t[0][:3], struct.pack('<f', float('inf')) * 512); cases.append(t)
for index, tensors in enumerate(cases):
write_gguf(source, tensors)
output = root / f'rejected-{index}'
run([source], output, ok=False)
assert not output.exists()
write_gguf(source, fixtures(), architecture='unsupported')
run([source], root / 'wrong-arch', ok=False)
write_gguf(source, fixtures(), (0, 2, len(fixtures())))
run([source], root / 'missing-shard', ok=False)
paths = [root / f'bad-{n:05}-of-00002.gguf' for n in [1, 2]]
write_gguf(paths[0], fixtures()[:-1], (0, 2, len(fixtures())))
write_gguf(paths[1], fixtures()[-1:], (1, 2, 999), architecture=None, tokenizer=False)
run(paths, root / 'bad-total', ok=False)
assert not (root / 'bad-total').exists()
# Full source SHA is checked before any pack can be published.
pins = json.loads(manifest_path.read_text())
pins['files'][0]['sha256'] = '0' * 64
manifest_path.write_text(json.dumps(pins))
result = subprocess.run([binary, 'model', 'prepare-native-pack', str(manifest_path),
'--source-dir', str(root), '--output', str(root / 'bad-sha')],
env=env, capture_output=True, text=True, timeout=15)
assert result.returncode != 0 and 'SHA-256' in result.stderr, result.stderr
assert not (root / 'bad-sha').exists()
count += 1
print(json.dumps({'status': 'passed', 'scenarios': count, 'oracle': 'pinned tools/iq_pack.py',
'dense_bytes_and_layout_tolerance': 0, 'real_model': False, 'gpu_used': False}))
if __name__ == '__main__':
main()