Files
leleka/control-plane/src/native_model.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

292 lines
9.4 KiB
Rust

//! Config-driven immutable GGUF acquisition, exact preparation and offline reuse.
use crate::{
asset_bundle::{self, AssetBundle},
model, native_pack,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
error::Error,
fs::{self, File, OpenOptions},
io::Read,
path::{Path, PathBuf},
};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
const FILES: &[&str] = &[
"dense.bin",
"index.txt",
"native_experts.txt",
"conversions.json",
"source.json",
"tokenizer/vocab.json",
"tokenizer/merges.txt",
"tokenizer/token_type.json",
"tokenizer/tokenizer.json",
"tokenizer/chat_template.jinja",
];
/// Files only the opt-in `iq_pack.py` modes write (`--compat-bf16`, `--base`, `--experts-bin`). A receipt lists the
/// ones present; the default pack has none.
const OPTIONAL_FILES: &[&str] = &[
"compat-bf16.json",
"extra.bin",
"experts.bin",
"experts.bin.src.json",
];
#[derive(Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuntimeProfile {
Qwen4expFlashNext,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeModel {
pub manifest: PathBuf,
pub source_dir: PathBuf,
pub output: PathBuf,
pub runtime_profile: Option<RuntimeProfile>,
}
impl NativeModel {
pub fn validate(&self, assets: &[AssetBundle]) -> Result<()> {
let mut all = vec![
AssetBundle {
manifest: self.manifest.clone(),
directory: self.source_dir.clone(),
},
AssetBundle {
manifest: self.manifest.clone(),
directory: self.output.clone(),
},
];
all.extend(assets.iter().map(|a| AssetBundle {
manifest: a.manifest.clone(),
directory: a.directory.clone(),
}));
asset_bundle::validate(&all)?;
let directories = all
.iter()
.map(|a| resolved(&a.directory))
.collect::<Result<Vec<_>>>()?;
for (i, directory) in directories.iter().enumerate() {
if directories[..i]
.iter()
.any(|other| directory.starts_with(other) || other.starts_with(directory))
{
return Err("native model directories overlap through filesystem aliases".into());
}
}
// The manifest itself must survive publication and cannot live in a generated tree.
for asset in &all {
let manifest = resolved(&asset.manifest)?;
if directories
.iter()
.any(|directory| manifest.starts_with(directory))
{
return Err("asset manifests must be outside generated directories".into());
}
}
Ok(())
}
pub async fn ensure(&self) -> Result<PathBuf> {
let manifest = model::Manifest::load(&self.manifest).await?;
// Source acquisition uses the existing private resumable stage and lock.
asset_bundle::provision(&[AssetBundle {
manifest: self.manifest.clone(),
directory: self.source_dir.clone(),
}])
.await?;
let primary = native_pack::primary_shard(&manifest, &self.source_dir)?;
if let Some(RuntimeProfile::Qwen4expFlashNext) = self.runtime_profile {
crate::gguf::check_flash_next_profile(&primary)?;
}
let parent = self.output.parent().ok_or("pack directory has no parent")?;
fs::create_dir_all(parent)?;
let mut name = std::ffi::OsString::from(".");
name.push(self.output.file_name().ok_or("pack filename missing")?);
name.push(".native-model-lock");
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let lock = options.open(parent.join(name))?;
if !lock.metadata()?.is_file() {
return Err("native model lock must be a regular file".into());
}
lock.try_lock()
.map_err(|_| "native model preparation is busy; retry when it finishes")?;
match fs::symlink_metadata(&self.output) {
Ok(_) => verify_receipt(&manifest, &self.output)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
native_pack::prepare(&manifest, &self.source_dir, &self.output).await?;
verify_receipt(&manifest, &self.output)?;
}
Err(e) => return Err(e.into()),
}
Ok(primary)
}
}
// Resolve existing ancestors too: a new path beneath a symlink can otherwise
// appear lexically disjoint while writing inside another immutable version.
fn resolved(path: &Path) -> Result<PathBuf> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(fs::canonicalize(path)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
let parent = path.parent().ok_or("path has no existing ancestor")?;
Ok(resolved(parent)?.join(path.file_name().ok_or("path component missing")?))
}
Err(e) => Err(e.into()),
}
}
#[derive(Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct Entry {
size: u64,
sha256: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
schema: u32,
converter: u32,
sources: BTreeMap<String, Entry>,
files: BTreeMap<String, Entry>,
}
fn sources(manifest: &model::Manifest) -> BTreeMap<String, Entry> {
manifest
.files
.iter()
.map(|f| {
(
f.name.clone(),
Entry {
size: f.size,
sha256: f.sha256.to_ascii_lowercase(),
},
)
})
.collect()
}
fn digest(path: &Path) -> Result<Entry> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("pack entries must be regular files".into());
}
let mut file = File::open(path)?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 65536];
let mut size = 0;
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
size += n as u64;
}
Ok(Entry {
size,
sha256: hex::encode(hash.finalize()),
})
}
fn exact_tree(output: &Path, optional: &[&str]) -> Result<()> {
let mut top = vec![
"dense.bin",
"index.txt",
"native_experts.txt",
"conversions.json",
"source.json",
"receipt.json",
"tokenizer",
];
top.extend_from_slice(optional);
for (dir, expected) in [
(output.to_path_buf(), top),
(
output.join("tokenizer"),
vec![
"vocab.json",
"merges.txt",
"token_type.json",
"tokenizer.json",
"chat_template.jinja",
],
),
] {
let md = fs::symlink_metadata(&dir)?;
if !md.is_dir() || md.file_type().is_symlink() {
return Err("pack must contain real directories".into());
}
let mut actual = fs::read_dir(&dir)?
.map(|r| r.map(|e| e.file_name()))
.collect::<std::io::Result<Vec<_>>>()?;
actual.sort();
let mut expected = expected
.into_iter()
.map(std::ffi::OsString::from)
.collect::<Vec<_>>();
expected.sort();
if actual != expected {
return Err("pack file set differs from receipt schema".into());
}
}
Ok(())
}
pub fn write_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> {
let files = FILES
.iter()
.chain(OPTIONAL_FILES.iter().filter(|n| output.join(n).exists()))
.map(|name| Ok((name.to_string(), digest(&output.join(name))?)))
.collect::<Result<BTreeMap<_, _>>>()?;
let receipt = Receipt {
schema: 1,
converter: 1,
sources: sources(manifest),
files,
};
use std::io::Write;
let mut file = File::create(output.join("receipt.json"))?;
file.write_all(&serde_json::to_vec_pretty(&receipt)?)?;
file.sync_all()?;
Ok(())
}
pub fn verify_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> {
let path = output.join("receipt.json");
let md = fs::symlink_metadata(&path)?;
if !md.is_file() || md.file_type().is_symlink() || md.len() > 1_048_576 {
return Err("invalid pack receipt file".into());
}
let r: Receipt = serde_json::from_slice(&fs::read(path)?)?;
let optional = OPTIONAL_FILES
.iter()
.copied()
.filter(|n| r.files.contains_key(*n))
.collect::<Vec<_>>();
if r.schema != 1
|| r.converter != 1
|| r.sources != sources(manifest)
|| r.files.len() != FILES.len() + optional.len()
|| !FILES.iter().all(|n| r.files.contains_key(*n))
{
return Err("native pack receipt does not match pinned sources/converter".into());
}
exact_tree(output, &optional)?;
for name in FILES.iter().chain(optional.iter()) {
if r.files.get(*name) != Some(&digest(&output.join(name))?) {
return Err("native pack checksum mismatch; use a new versioned output".into());
}
}
Ok(())
}