Files
leleka/control-plane/src/prepare_preview/derived_verification.rs
T

275 lines
9.9 KiB
Rust

//! Read-back of a derived preview archive against its source (header, source identity, tensor sections), and the
//! helpers the preparation shares with it: decoding of source tensors, the provenance file, and file hashing.
use super::{
DerivedIdentity, Digest, File, Path, PathBuf, PreviewKind, Read, Sha256, derived_iq3, derived_mixed, fs, iq3_s,
kar, kar_codec, kar_shard_plan, read_recorded_provenance,
};
fn load_derived_identity(source_path: &Path, kind: PreviewKind) -> Result<DerivedIdentity, String> {
Ok(match kind {
PreviewKind::F32 => return Err("F32 preview does not use derived provenance".into()),
PreviewKind::Iq3 => DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?),
PreviewKind::Mixed => DerivedIdentity::Mixed(derived_mixed::fingerprint(source_path)?),
})
}
fn require_derived_header(
identity: &DerivedIdentity,
summary: &kar::Summary,
source_count: usize,
) -> Result<(), String> {
if summary.source_digest != identity.derived_digest()
|| summary.source_bytes != identity.derived_bytes()
|| summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes())
|| source_count != identity.tensor_count()
{
return Err("KAR header differs from derived F32 source identity".into());
}
Ok(())
}
fn require_derived_source(
identity: &DerivedIdentity,
number: usize,
record: &kar::TensorSource,
) -> Result<(), String> {
let tensor = identity.tensor(number);
let record_bytes = record
.dimensions
.iter()
.try_fold(4u64, |size, dim| size.checked_mul(*dim))
.ok_or("KAR tensor source byte count overflow")?;
if record.name != tensor.name
|| record.dtype != 0
|| &record.digest != tensor.f32_digest
|| record.offset != tensor.offset
|| record_bytes != tensor.bytes
{
return Err(format!(
"{}: KAR tensor source identity mismatch",
tensor.name
));
}
Ok(())
}
pub(super) fn verify_derived(
source_path: &Path,
archive_path: &Path,
kind: PreviewKind,
) -> Result<kar::Summary, String> {
let identity = load_derived_identity(source_path, kind)?;
let (summary, sources) = kar::verify_with_sources(archive_path)?;
require_derived_header(&identity, &summary, sources.len())?;
for (number, record) in sources.iter().enumerate() {
require_derived_source(&identity, number, record)?;
}
let archive_digest = hash_file(archive_path)?;
let recorded = read_recorded_provenance(archive_path)?;
if recorded != provenance_value(&identity, archive_digest) {
return Err("derived preview provenance differs from source or archive".into());
}
Ok(summary)
}
/// Little-endian 16-bit weights: `f16` for kind 1, `bf16` for kind 30.
fn decode_16_bit(kind: u32, raw: &[u8]) -> Vec<f32> {
raw.as_chunks::<2>()
.0
.iter()
.map(|pair| {
let bits = u16::from_le_bytes(*pair);
if kind == 1 {
kar_codec::f16_bits_to_f32(bits)
} else {
f32::from_bits(u32::from(bits) << 16)
}
})
.collect()
}
pub(super) fn decode_source_tensor(
kind: u32,
raw: &[u8],
elements: usize,
) -> Result<Vec<f32>, String> {
let weights = match kind {
0 => raw
.as_chunks::<4>()
.0
.iter()
.map(|chunk| f32::from_le_bytes(*chunk))
.collect(),
1 | 30 => decode_16_bit(kind, raw),
21 => {
let mut values = vec![0.0f32; elements];
iq3_s::decode_into(raw, &mut values)?;
values
}
_ => return Err("unsupported GGUF tensor source kind".into()),
};
if weights.len() != elements {
return Err("decoded GGUF tensor size differs from shape".into());
}
Ok(weights)
}
pub(super) fn provenance_path(destination: &Path) -> Result<PathBuf, String> {
Ok(destination.with_file_name(format!(
"{}.provenance.json",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy()
)))
}
pub(super) fn provenance_value(
identity: &DerivedIdentity,
archive_digest: [u8; 32],
) -> serde_json::Value {
match identity {
DerivedIdentity::Iq3(identity) => iq3_provenance(identity, archive_digest),
DerivedIdentity::Mixed(identity) => mixed_provenance(identity, archive_digest),
}
}
fn iq3_provenance(identity: &derived_iq3::Identity, archive_digest: [u8; 32]) -> serde_json::Value {
serde_json::json!({
"schema": "leleka-api/iq3-preview-provenance-v1",
"derivation": "leleka-api/iq3_s-to-f32-le-v1",
"original_gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"iq3_sha256": hex::encode(tensor.iq3_sha256),
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
})
}
fn mixed_provenance(
identity: &derived_mixed::Identity,
archive_digest: [u8; 32],
) -> serde_json::Value {
serde_json::json!({
"schema": "leleka-api/mixed-preview-provenance-v1",
"derivation": "leleka-api/gguf-mixed-to-f32-le-v1",
"original_gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
})
}
pub(super) fn sharded_provenance_value(
identity: &derived_mixed::ShardedIdentity,
archive_digest: [u8; 32],
) -> serde_json::Value {
serde_json::json!({
"schema": "leleka-api/sharded-preview-provenance-v1",
"derivation": "leleka-api/gguf-shards-to-f32-le-v1",
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"shards": identity.shards.iter().map(|shard| serde_json::json!({
"name": shard.name,
"gguf_sha256": hex::encode(shard.gguf_sha256),
"gguf_bytes": shard.gguf_bytes,
"tensor_count": shard.tensor_count,
})).collect::<Vec<_>>(),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
})
}
pub(super) fn partitioned_provenance(
parts: &[Vec<kar_shard_plan::PartIdentity>],
) -> serde_json::Value {
serde_json::json!(
parts
.iter()
.filter(|group| group.len() > 1)
.map(|group| {
serde_json::json!({
"parent_name": group[0].parent_name,
"parent_dimensions": group[0].parent_dimensions,
"source_kind": group[0].source_kind,
"parts": group.iter().map(|part| serde_json::json!({
"name": part.name,
"dimensions": part.dimensions,
"source_byte_offset": part.source_byte_offset,
"source_bytes": part.source_bytes,
"source_sha256": hex::encode(part.source_sha256),
"derived_offset": part.derived_offset,
"derived_bytes": part.derived_bytes,
"f32_sha256": hex::encode(part.f32_sha256),
})).collect::<Vec<_>>(),
})
})
.collect::<Vec<_>>()
)
}
pub(super) fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
if fs::symlink_metadata(path).is_ok() {
return Err("provenance destination already exists".into());
}
let temporary = path.with_file_name(format!(
"{}.part",
path.file_name()
.ok_or("provenance path has no file name")?
.to_string_lossy()
));
let result = (|| {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.map_err(|error| error.to_string())?;
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
use std::io::Write;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())?;
fs::hard_link(&temporary, path).map_err(|error| error.to_string())?;
Ok(())
})();
let _ = fs::remove_file(&temporary);
result
}
pub(super) fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = source
.read(&mut buffer)
.map_err(|error| error.to_string())?;
if count == 0 {
break;
}
digest.update(&buffer[..count]);
}
Ok(digest.finalize().into())
}