Files
leleka/control-plane/src/native_pack.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 0d073e08aa feat(native-pack): match iq_pack.py conversions, add --compat-bf16/--base/--experts-bin and the exhaustive differential
- ple_conv1d inexact F32->F16 is accepted and recorded exact=false, as the oracle does
- conversions.json now carries method/exact/max_abs_err/source_shards like iq_pack.py
- opt-in --compat-bf16 (dequantize + RNE to BF16/F16/F32), --base (index_from_base, extra.bin),
  --experts-bin (+ experts.bin.src.json); receipts list the optional files present
- scripts/offline/diff_native_pack.py: 2700+ cases against the unmodified tools/iq_pack.py
- unit tests: real golden expert tables, numpy/gguf-py F16/BF16 rounding vectors
- fix three pre-existing clippy lints in leleka-model-format

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:20:15 +02:00

1300 lines
47 KiB
Rust

//! Native GGUF serving-pack preparation. Quantized tensors remain in source
//! shards; float conversions are exact unless `--compat-bf16` is given. No runtime Python.
use std::{
collections::{BTreeMap, HashSet},
error::Error,
fs::{self, File},
io::{Read, Seek, SeekFrom, 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 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)
}
struct Layout<'a> {
text: String,
n_expert: u64,
total: u64,
/// Per layer: the gate, up and down tensors with the index of the shard holding each.
layers: Vec<[(usize, &'a gguf::TensorInfo); 3]>,
}
fn expert_layout(shards: &[Shard]) -> Result<Layout<'_>> {
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;
let mut layer_roles = Vec::new();
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));
}
layer_roles.push([roles[0], roles[1], roles[2]]);
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(Layout {
text: header + &lines.concat(),
n_expert: experts,
total: offset,
layers: layer_roles,
})
}
/// GGML type names as `tools/gguf_reader.py` spells them (`GGML_TYPES`).
pub(crate) fn kind_name(kind: u32) -> &'static str {
match kind {
0 => "F32",
1 => "F16",
2 => "Q4_0",
3 => "Q4_1",
6 => "Q5_0",
7 => "Q5_1",
8 => "Q8_0",
9 => "Q8_1",
10 => "Q2_K",
11 => "Q3_K",
12 => "Q4_K",
13 => "Q5_K",
14 => "Q6_K",
15 => "Q8_K",
16 => "IQ2_XXS",
17 => "IQ2_XS",
18 => "IQ3_XXS",
19 => "IQ1_S",
20 => "IQ4_NL",
21 => "IQ3_S",
22 => "IQ2_S",
23 => "IQ4_XS",
24 => "I8",
28 => "F64",
29 => "IQ1_M",
30 => "BF16",
39 => "MXFP4",
40 => "NVFP4",
42 => "Q2_0",
_ => "unsupported",
}
}
/// ggml's `ggml_compute_fp32_to_bf16`, as `gguf.quants.BF16.quantize_blocks` spells it: NaN is quieted, everything
/// else rounds to nearest even in 64-bit arithmetic and truncates to 16 bits.
pub(crate) fn bf16_round_nearest_even(value: f32) -> u16 {
let mut n = value.to_bits();
if n & 0x7fff_ffff > 0x7f80_0000 {
n = (n & 0xffff_0000) | (64 << 16);
}
((u64::from(n) + 0x7fff + u64::from((n >> 16) & 1)) >> 16) as u16
}
/// Running comparison of converted values with their sources, as `iq_pack.convert` reports it.
struct Error64 {
exact: bool,
max_abs_err: f64,
}
impl Error64 {
fn new() -> Self {
Self {
exact: true,
max_abs_err: 0.0,
}
}
fn note(&mut self, converted: f32, source: f32) {
if converted != source {
self.exact = false;
}
let err = (f64::from(converted) - f64::from(source)).abs();
if err > self.max_abs_err {
self.max_abs_err = err;
}
}
}
struct Record {
name: String,
shard: String,
src_type: &'static str,
dst_type: &'static str,
method: String,
exact: bool,
max_abs_err: f64,
source_sha256: String,
}
struct Converted {
/// Index `kind` column.
index_kind: u32,
written: u64,
dst: u64,
/// `(method, exact, max_abs_err)` when `conversions.json` lists the tensor.
record: Option<(String, bool, f64)>,
source_sha256: String,
}
fn values_of(bits: &[u8]) -> impl Iterator<Item = f32> + '_ {
bits.as_chunks::<4>()
.0
.iter()
.map(|b| f32::from_le_bytes(*b))
}
/// Stream one tensor's values as F32 (floats exactly, quantized kinds through the pinned dequantizers).
fn stream_f32(
input: &mut File,
shard: &Shard,
tensor: &gguf::TensorInfo,
mut each: impl FnMut(&[u8], &[u8]) -> std::result::Result<(), String>,
) -> Result<()> {
gguf_f32_stream::visit(
input,
shard.index.summary.data_start + tensor.offset,
tensor.kind,
tensor.bytes,
&mut each,
)?;
Ok(())
}
/// The pack form of one tensor the engine reads from `dense.bin` when it is stored otherwise. Mirrors
/// `tools/iq_pack.py::convert` for every source kind: same accept/reject decision, same bytes, same record.
#[allow(clippy::too_many_arguments)]
fn convert_tensor(
input: &mut File,
shard: &Shard,
tensor: &gguf::TensorInfo,
target: u32,
compat_bf16: bool,
dense: &mut File,
) -> Result<Converted> {
let src = tensor.kind;
let src_lower = kind_name(src).to_ascii_lowercase();
let float_source = matches!(src, 0 | 1 | 30);
let need_compat = |what: &str| -> Result<()> {
if compat_bf16 {
Ok(())
} else {
Err(format!(
"{}: stored as {what} but the engine reads {}; use --compat-bf16",
tensor.name,
kind_name(target)
)
.into())
}
};
let mut digest = Sha256::new();
let mut written = 0u64;
let mut write = |dense: &mut File, bytes: &[u8]| -> std::result::Result<(), String> {
dense.write_all(bytes).map_err(|e| e.to_string())?;
written += bytes.len() as u64;
Ok(())
};
let mut out = Vec::new();
match target {
30 => {
// F32 whose values are all exactly BF16 (low 16 bits zero): the exact path, whole tensor or nothing.
let all_bf16 = src == 0 && {
let mut all = true;
stream_f32(input, shard, tensor, |_, values| {
all &= values_of(values).all(|v| v.to_bits() & 0xffff == 0);
Ok(())
})?;
all
};
if all_bf16 {
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{} is F32 with non-finite values; refused rather than converted",
tensor.name
));
}
out.extend_from_slice(&((v.to_bits() >> 16) as u16).to_le_bytes());
}
write(dense, &out)
})?;
return Ok(Converted {
index_kind: 4,
written,
dst: written,
record: Some((
"f32->bf16: the values are BF16's (low 16 bits zero)".to_owned(),
true,
0.0,
)),
source_sha256: hex::encode(digest.finalize()),
});
}
need_compat(if src == 0 {
"F32 with values that are not BF16"
} else {
kind_name(src)
})?;
let mut stats = Error64::new();
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{}: cannot convert non-finite weights to BF16",
tensor.name
));
}
let bits = bf16_round_nearest_even(v);
let back = f32::from_bits(u32::from(bits) << 16);
if back.is_infinite() {
// iq_pack.py writes the infinity and records max_abs_err=inf; a pack must not carry it.
return Err(format!(
"{}: a value rounds beyond BF16's range, which the engine reads it as",
tensor.name
));
}
stats.note(back, v);
out.extend_from_slice(&bits.to_le_bytes());
}
write(dense, &out)
})?;
let method = if float_source {
format!("{src_lower}->bf16 round-to-nearest-even (--compat-bf16)")
} else {
"dequantize->bf16 round-to-nearest-even (--compat-bf16)".to_owned()
};
Ok(Converted {
index_kind: 4,
written,
dst: written,
record: Some((method, stats.exact, stats.max_abs_err)),
source_sha256: hex::encode(digest.finalize()),
})
}
1 => {
// The PLE conv kernel reads F16. F32 goes in as index kind 3 (the loader narrows it); anything else
// is narrowed here, which only --compat-bf16 allows.
if src != 0 {
need_compat(kind_name(src))?;
}
let mut stats = Error64::new();
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{}: cannot convert non-finite weights to F16",
tensor.name
));
}
let half = kar_codec::f32_to_f16_bits(v);
let back = kar_codec::f16_bits_to_f32(half);
if !back.is_finite() {
return Err(format!(
"{}: a value is beyond F16's range, which the engine reads it as",
tensor.name
));
}
stats.note(back, v);
if src == 0 {
// Index kind 3 stores F32; the existing loader narrows it.
out.extend_from_slice(&v.to_le_bytes());
} else {
out.extend_from_slice(&half.to_le_bytes());
}
}
write(dense, &out)
})?;
let (index_kind, dst, method) = if src == 0 {
(
3,
written / 2,
"f32->f16 by the loader (index kind 3, round-to-nearest-even)".to_owned(),
)
} else {
(
5,
written,
format!("{src_lower}->f16 round-to-nearest-even (--compat-bf16)"),
)
};
Ok(Converted {
index_kind,
written,
dst,
record: Some((method, stats.exact, stats.max_abs_err)),
source_sha256: hex::encode(digest.finalize()),
})
}
0 => {
if !float_source {
need_compat(kind_name(src))?;
}
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
if src != 1 {
return write(dense, values);
}
// F16 -> F32 as numpy/IEEE conversion does it: a signaling NaN comes out quiet.
out.clear();
for v in values_of(values) {
let bits = v.to_bits();
out.extend_from_slice(
&(if v.is_nan() { bits | 0x0040_0000 } else { bits }).to_le_bytes(),
);
}
write(dense, &out)
})?;
Ok(Converted {
index_kind: 2,
written,
dst: written,
record: Some((format!("{src_lower}->f32 widening"), true, 0.0)),
source_sha256: hex::encode(digest.finalize()),
})
}
_ => Err("unsupported native pack conversion target".into()),
}
}
/// `tools/iq_pack.py::index_standalone`: every non-expert tensor of the model. Floats the engine reads from the pack
/// go into `dense.bin` in the form it reads them; quantized ones are served natively from the GGUF.
fn dense_files(shards: &[Shard], output: &Path, options: &Options) -> 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 records = Vec::new();
let mut compat_entries = Vec::new();
for shard in shards {
let mut input = File::open(&shard.path)?;
let shard_name = shard.path.file_name().unwrap().to_str().unwrap();
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;
}
let target = required.unwrap_or(tensor.kind);
let (index_kind, written, dst) = if target == tensor.kind {
// Stored as the engine reads it (or an unlisted float): copied verbatim.
let mut written = 0u64;
gguf_f32_stream::visit(
&mut input,
shard.index.summary.data_start + tensor.offset,
tensor.kind,
tensor.bytes,
|raw, _| {
dense.write_all(raw).map_err(|e| e.to_string())?;
written += raw.len() as u64;
Ok(())
},
)?;
let kind = match tensor.kind {
0 => 2,
1 => 5,
_ => 4,
};
(kind, written, written)
} else {
let converted = convert_tensor(
&mut input,
shard,
tensor,
target,
options.compat_bf16,
&mut dense,
)?;
let (method, exact, max_abs_err) = converted.record.clone().unwrap();
if method.contains("--compat-bf16") {
compat_entries.push(json!({"name":tensor.name,
"source_type":kind_name(tensor.kind), "bytes":converted.written}));
}
records.push(Record {
name: tensor.name.clone(),
shard: shard_name.to_owned(),
src_type: kind_name(tensor.kind),
dst_type: kind_name(target),
method,
exact,
max_abs_err,
source_sha256: converted.source_sha256,
});
(converted.index_kind, converted.written, converted.dst)
};
rows.push(format!(
"{} 0 {index_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")?;
}
}
dense.sync_all()?;
write_index(output, shards, pool, &rows)?;
let sources = shards
.iter()
.map(|s| {
json!({"name":s.path.file_name().unwrap().to_str().unwrap(),
"size":s.index.summary.file_size})
})
.collect::<Vec<_>>();
let tensors = records
.iter()
.map(|r| {
json!({"name":r.name, "shard":r.shard, "src_type":r.src_type, "dst_type":r.dst_type,
"method":r.method, "exact":r.exact, "max_abs_err":r.max_abs_err,
"source_sha256":r.source_sha256})
})
.collect::<Vec<_>>();
write_conversions(
output,
&json!({"schema":1,"tool":"strata-next","compat_bf16":options.compat_bf16,
"source_shards":sources,"tensors":tensors}),
)?;
if options.compat_bf16 {
write(
output.join("compat-bf16.json"),
&serde_json::to_vec_pretty(&json!({
"source": shards[0].path.to_str().unwrap_or_default(),
"rounding": "nearest-even", "tensors": compat_entries}))?,
)?;
}
Ok(())
}
fn write_index(output: &Path, shards: &[Shard], pool: u64, rows: &[String]) -> Result<()> {
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())
}
fn write_conversions(output: &Path, value: &serde_json::Value) -> Result<()> {
write(
output.join("conversions.json"),
&serde_json::to_vec_pretty(value)?,
)
}
fn write(path: PathBuf, bytes: &[u8]) -> Result<()> {
let mut file = File::create(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
/// Optional parts of `tools/iq_pack.py` beyond the exact default pack.
#[derive(Clone, Debug, Default)]
pub struct Options {
/// Dequantize/round the small projections the engine reads as BF16/F16/F32 (`--compat-bf16`).
pub compat_bf16: bool,
/// Also write `experts.bin` and its `experts.bin.src.json` sidecar (`--experts-bin`).
pub experts_bin: bool,
/// Reuse the float tensors of a canonical base pack (`--base`): `index.txt` and `extra.bin` are derived from
/// it, `dense.bin` is linked.
pub base: Option<PathBuf>,
}
pub async fn prepare(
manifest: &model::Manifest,
source: &Path,
output: &Path,
) -> Result<serde_json::Value> {
prepare_with(manifest, source, output, &Options::default()).await
}
pub async fn prepare_with(
manifest: &model::Manifest,
source: &Path,
output: &Path,
options: &Options,
) -> Result<serde_json::Value> {
if options.compat_bf16 && options.base.is_some() {
return Err("--compat-bf16 cannot reuse --base dense weights".into());
}
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 layout = expert_layout(&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 mut lossy = false;
let result = (|| -> Result<()> {
match &options.base {
Some(base) => base_files(&shards, &stage, base)?,
None => dense_files(&shards, &stage, options)?,
}
let base_tokenizer = options
.base
.as_ref()
.map(|b| b.join("tokenizer"))
.filter(|t| t.join("vocab.json").is_file() && t.join("chat_template.jinja").is_file());
let tokenizer_dir = match base_tokenizer {
Some(base_tokenizer) => copy_directory(&base_tokenizer, &stage.join("tokenizer"))?,
None => tokenizer_assets::extract(&shards[0].path, &stage)?,
};
tokenizer::Tokenizer::from_assets(&tokenizer_dir)?;
write(stage.join("native_experts.txt"), layout.text.as_bytes())?;
if options.experts_bin {
write_experts_bin(&shards, &layout, &stage)?;
}
lossy = conversions_inexact(&stage)?;
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":lossy}),
)?,
)?;
crate::native_model::write_receipt(manifest, &stage)?;
File::open(&stage)?.sync_all()?;
if output.exists() || output.is_symlink() {
return Err("native pack destination appeared during preparation".into());
}
crate::immutable_directory::publish(&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":lossy,"gpu_validated":false}),
)
}
/// Whether any recorded conversion rounded a weight (`exact: false`).
fn conversions_inexact(stage: &Path) -> Result<bool> {
let value: serde_json::Value =
serde_json::from_slice(&fs::read(stage.join("conversions.json"))?)?;
Ok(value["tensors"]
.as_array()
.is_some_and(|t| t.iter().any(|r| r["exact"] == false)))
}
pub fn primary_shard(manifest: &model::Manifest, source: &Path) -> Result<PathBuf> {
Ok(shards(manifest, source)?[0].path.clone())
}
fn tokenizer_assets_preflight(source: &Path) -> Result<()> {
gguf::tokenizer_metadata(source)?;
Ok(())
}
fn copy_directory(from: &Path, to: &Path) -> Result<PathBuf> {
fs::create_dir(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
let kind = entry.file_type()?;
if !kind.is_file() || kind.is_symlink() {
return Err("base pack tokenizer must contain regular files only".into());
}
fs::copy(entry.path(), to.join(entry.file_name()))?;
File::open(to.join(entry.file_name()))?.sync_all()?;
}
File::open(to)?.sync_all()?;
Ok(to.to_owned())
}
/// `experts.bin`: per layer, `n_expert` blobs of `[gate row | up row | down row]`, the raw GGUF slices, plus the
/// `experts.bin.src.json` sidecar naming what it was cut from (shards, size, hash of `native_experts.txt`).
fn write_experts_bin(shards: &[Shard], layout: &Layout, output: &Path) -> Result<()> {
let mut files = shards
.iter()
.map(|s| File::open(&s.path))
.collect::<std::io::Result<Vec<_>>>()?;
let mut out =
std::io::BufWriter::with_capacity(8 << 20, File::create(output.join("experts.bin"))?);
let mut buffer = Vec::new();
for roles in &layout.layers {
for expert in 0..layout.n_expert {
for (shard, tensor) in roles {
let per = tensor.bytes / layout.n_expert;
buffer.resize(per as usize, 0);
let at = shards[*shard].index.summary.data_start + tensor.offset + expert * per;
files[*shard].seek(SeekFrom::Start(at))?;
files[*shard].read_exact(&mut buffer)?;
out.write_all(&buffer)?;
}
}
}
out.flush()?;
out.into_inner().map_err(|e| e.into_error())?.sync_all()?;
let sidecar = json!({
"schema": 1,
"shards": shards.iter().map(|s| json!({"name": s.path.file_name().unwrap().to_str().unwrap(),
"size": s.index.summary.file_size})).collect::<Vec<_>>(),
"native_experts_sha256": hex::encode(Sha256::digest(layout.text.as_bytes())),
"bytes": layout.total,
});
write(
output.join("experts.bin.src.json"),
&serde_json::to_vec_pretty(&sidecar)?,
)
}
/// `tools/iq_pack.py::index_from_base`: the float tensors come from the base pack's `dense.bin` (byte-identical in
/// this model, checked), tensors that are float here but quantized there go to `extra.bin`, quantized ones are
/// served natively. Rows follow the base index.
fn base_files(shards: &[Shard], output: &Path, base: &Path) -> Result<()> {
if shards.iter().skip(1).any(|s| {
s.index
.tensors
.iter()
.any(|t| t.name != "per_layer_token_embd.weight")
}) {
return Err("--base needs a model whose tensors are all in shard 1".into());
}
let manifest: serde_json::Value =
serde_json::from_slice(&fs::read(base.join("manifest.json"))?)?;
let base_source = manifest["source"]["shard1"]
.as_str()
.map(PathBuf::from)
.filter(|p| p.is_file())
.ok_or("cannot find the base pack's shard 1 from its manifest.json")?;
let base_index = gguf::tensor_index(&base_source)?;
let new: BTreeMap<&str, &gguf::TensorInfo> = shards
.iter()
.flat_map(|s| s.index.tensors.iter())
.map(|t| (t.name.as_str(), t))
.collect();
let old: BTreeMap<&str, &gguf::TensorInfo> = base_index
.tensors
.iter()
.map(|t| (t.name.as_str(), t))
.collect();
let mut rows: Vec<Vec<String>> = Vec::new();
let mut positions: BTreeMap<String, usize> = BTreeMap::new();
for line in fs::read_to_string(base.join("index.txt"))?.lines() {
if line.starts_with('#') {
continue;
}
let fields = line
.split_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
if fields.len() < 9 {
return Err("base pack index row is too short".into());
}
match positions.get(&fields[0]) {
Some(&at) => rows[at] = fields,
None => {
positions.insert(fields[0].clone(), rows.len());
rows.push(fields);
}
}
}
let mut new_file = File::open(&shards[0].path)?;
let mut old_file = File::open(&base_source)?;
let mut extra: Vec<Vec<u8>> = Vec::new();
let mut new_rows = Vec::new();
for fields in &rows {
let name = fields[0].as_str();
let (Some(t), Some(bt)) = (new.get(name), old.get(name)) else {
return Err(format!("tensor {name} missing from one of the models").into());
};
let new_float = matches!(t.kind, 0 | 1 | 30);
let old_float = matches!(bt.kind, 0 | 1 | 30);
if new_float && old_float {
if t.kind != bt.kind
|| t.dimensions != bt.dimensions
|| !same_bytes(
&mut new_file,
shards[0].index.summary.data_start + t.offset,
&mut old_file,
base_index.summary.data_start + bt.offset,
t.bytes,
bt.bytes,
)?
{
return Err(format!(
"float tensor {name} differs from the base model; this pack cannot reuse its dense.bin"
)
.into());
}
new_rows.push(fields.clone());
} else if new_float {
if t.kind != 30 {
return Err(
format!("unexpected float type {} for {name}", kind_name(t.kind)).into(),
);
}
let offset: usize = extra
.iter()
.map(|b| b.len() + (64 - b.len() % 64) % 64)
.sum();
let mut bytes = vec![0u8; t.bytes as usize];
new_file.seek(SeekFrom::Start(
shards[0].index.summary.data_start + t.offset,
))?;
new_file.read_exact(&mut bytes)?;
extra.push(bytes);
let mut row = vec![
name.to_owned(),
"3".into(),
"4".into(),
offset.to_string(),
t.bytes.to_string(),
"0".into(),
t.bytes.to_string(),
fields[7].clone(),
fields[8].clone(),
];
row.extend(std::iter::repeat_n("0".to_owned(), 10));
new_rows.push(row);
} else {
let mut row = vec![
name.to_owned(),
fields[1].clone(),
"0".into(),
"0".into(),
"0".into(),
"0".into(),
"0".into(),
fields[7].clone(),
fields[8].clone(),
"8".into(),
"0".into(),
"32".into(),
];
row.extend(std::iter::repeat_n("0".to_owned(), 7));
new_rows.push(row);
}
}
let mut pool = 0u64;
let mut lines = Vec::new();
for row in &mut new_rows {
row[5] = pool.to_string();
pool += align(row[6].parse::<u64>()?)?;
lines.push(row.join(" ") + "\n");
}
write_index(output, shards, pool, &lines)?;
let mut extra_file = File::create(output.join("extra.bin"))?;
for bytes in &extra {
extra_file.write_all(bytes)?;
extra_file.write_all(&vec![0u8; (64 - bytes.len() % 64) % 64])?;
}
extra_file.sync_all()?;
let dense = output.join("dense.bin");
if fs::hard_link(base.join("dense.bin"), &dense).is_err() {
fs::copy(base.join("dense.bin"), &dense)?;
}
write_conversions(
output,
&json!({"schema":1,"tool":"strata-next","compat_bf16":false,
"base":base.to_str().unwrap_or_default(),"tensors":[]}),
)
}
fn same_bytes(
a: &mut File,
a_at: u64,
b: &mut File,
b_at: u64,
a_len: u64,
b_len: u64,
) -> Result<bool> {
if a_len != b_len {
return Ok(false);
}
let mut left = vec![0u8; 1 << 20];
let mut right = vec![0u8; 1 << 20];
let mut done = 0u64;
while done < a_len {
let n = (a_len - done).min(left.len() as u64) as usize;
a.seek(SeekFrom::Start(a_at + done))?;
a.read_exact(&mut left[..n])?;
b.seek(SeekFrom::Start(b_at + done))?;
b.read_exact(&mut right[..n])?;
if left[..n] != right[..n] {
return Ok(false);
}
done += n as u64;
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
/// Numpy (`astype(float16)`) and gguf-py (`BF16.quantize_blocks`) answers for 4096 f32 bit patterns, from
/// `scripts/offline/gen_goldens.py`. The packer's F32 -> F16 / BF16 helpers must match bit for bit.
#[test]
fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
let vectors = include_bytes!("../tests/fixtures/offline/f16_bf16_vectors.golden");
assert_eq!(vectors.len() % 8, 0);
let mut checked = 0;
for record in vectors.as_chunks::<8>().0 {
let bits = u32::from_le_bytes(record[0..4].try_into().unwrap());
let f16 = u16::from_le_bytes(record[4..6].try_into().unwrap());
let bf16 = u16::from_le_bytes(record[6..8].try_into().unwrap());
let value = f32::from_bits(bits);
if value.is_finite() {
// the packer refuses non-finite inputs before rounding; NaN payloads are not compared
assert_eq!(
kar_codec::f32_to_f16_bits(value),
f16,
"f16 of {bits:#010x}"
);
}
assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}");
checked += 1;
}
assert!(checked >= 4000);
}
struct Golden {
header: String,
name: String,
experts: u64,
total: u64,
rows: Vec<Vec<String>>,
}
fn parse_golden(text: &str) -> Golden {
let header = text.lines().next().unwrap().to_owned();
let after = |marker: &str| {
header
.split(marker)
.nth(1)
.unwrap()
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '-')
.next()
.unwrap()
.to_owned()
};
Golden {
name: after("offsets in "),
experts: after("n_expert ").parse().unwrap(),
total: after("total ").parse().unwrap(),
rows: text
.lines()
.skip(1)
.map(|l| l.split(' ').map(str::to_owned).collect())
.collect(),
header,
}
}
/// Rebuild the tensor directories that produce a real layer table, then run the packer's own layout code.
/// Gate/up/down element counts follow from the blob size and the two quantization geometries; the hidden size
/// is the model's 2560.
fn shards_for(golden: &Golden) -> Vec<Shard> {
const HIDDEN: u64 = 2560;
let mut names = vec![golden.name.clone()];
let mut tensors: Vec<Vec<gguf::TensorInfo>> = vec![Vec::new()];
let at = |name: &str, names: &mut Vec<String>, tensors: &mut Vec<Vec<gguf::TensorInfo>>| {
if let Some(i) = names.iter().position(|n| n == name) {
return i;
}
names.push(name.to_owned());
tensors.push(Vec::new());
names.len() - 1
};
for row in &golden.rows {
let layer: u64 = row[0].parse().unwrap();
let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap());
let blob: u64 = row[4].parse().unwrap();
let offsets: Vec<u64> = row[5..8].iter().map(|v| v.parse().unwrap()).collect();
let column = row.get(8).cloned().unwrap_or_default();
let files: Vec<String> = if column.contains(',') {
column.split(',').map(str::to_owned).collect()
} else {
vec![column; 3]
};
let (ge, gb) = gguf::block_geometry(gu).unwrap();
let (de, db) = gguf::block_geometry(d).unwrap();
// blob = 2 * X * gb/ge + X * db/de for X = HIDDEN * FF elements per expert
let numerator = blob * ge * de;
let denominator = 2 * gb * de + db * ge;
assert_eq!(numerator % denominator, 0, "layer {layer}");
let x = numerator / denominator;
assert_eq!(x % HIDDEN, 0);
let ff = x / HIDDEN;
let shard = |i: usize, names: &mut Vec<String>, t: &mut Vec<Vec<gguf::TensorInfo>>| {
if files[i].is_empty() {
0
} else {
at(&files[i], names, t)
}
};
let experts = golden.experts;
let roles = [
("gate", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
("up", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
("down", d, vec![ff, HIDDEN, experts], x / de * db * experts),
];
let router = gguf::TensorInfo {
name: format!("blk.{layer}.ffn_gate_inp.weight"),
dimensions: vec![HIDDEN, experts],
kind: 0,
offset: 0,
bytes: HIDDEN * experts * 4,
};
tensors[0].push(router);
for (i, (role, kind, dimensions, bytes)) in roles.into_iter().enumerate() {
let s = shard(i, &mut names, &mut tensors);
tensors[s].push(gguf::TensorInfo {
name: format!("blk.{layer}.ffn_{role}_exps.weight"),
dimensions,
kind,
offset: offsets[i],
bytes,
});
}
}
names
.into_iter()
.zip(tensors)
.map(|(name, tensors)| Shard {
path: PathBuf::from(name),
index: gguf::TensorIndex {
summary: gguf::Summary {
tensors: tensors.len() as u64,
metadata: 0,
architecture: Some("qwen4exp".into()),
split_no: None,
split_count: None,
split_tensors_count: None,
data_start: 0,
file_size: 0,
types: BTreeMap::new(),
},
tensors,
},
})
.collect()
}
/// The six real per-layer expert tables shipped with Strata (IQ3_S, IQ3_XXS, IQ2_XS, Q2_0 packs, the coder
/// IQ1_M pack, and Swift's IQ2_XS whose layers 13-47 live in the second shard): the Rust layout reproduces
/// every row byte for byte. The v2 files predate the shard column; their header wording differs, their rows
/// and totals do not.
#[test]
fn real_golden_expert_tables_are_reproduced() {
let goldens = [
include_str!("../../engine/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../engine/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../engine/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../engine/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../engine/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../engine/strata/tests/data/native_experts/swift-iq2_xs.txt"),
];
for text in goldens {
let golden = parse_golden(text);
let shards = shards_for(&golden);
let layout = expert_layout(&shards).unwrap();
assert_eq!(layout.n_expert, golden.experts);
assert_eq!(layout.total, golden.total, "{}", golden.name);
let produced = layout.text.lines().skip(1).collect::<Vec<_>>();
let wanted = text.lines().skip(1).collect::<Vec<_>>();
assert_eq!(produced, wanted, "{}", golden.name);
if golden.header.contains("native experts v3")
|| golden.header.contains("native experts v4")
{
assert_eq!(layout.text, text, "{}", golden.name);
}
}
}
}