//! Lossless, bounded projection export for offline Keyless conversion. use crate::{gguf, gguf_f32_stream}; use serde::Serialize; use sha2::{Digest, Sha256}; use std::{ fs::{File, OpenOptions}, io::Write, path::Path, }; #[derive(Serialize)] pub struct Export { pub tensor: String, pub dimensions: Vec, pub source_kind: u32, pub source_bytes: u64, pub source_tensor_sha256: String, pub source_fnv1a64: String, pub f32_bytes: u64, pub f32_sha256: String, pub decoder: &'static str, } pub fn export(source: &Path, name: &str, destination: &Path) -> Result { let index = gguf::tensor_index(source).map_err(|e| e.to_string())?; let tensor = index .tensors .iter() .find(|t| t.name == name) .ok_or_else(|| format!("GGUF tensor not found: {name}"))?; let expected = expected_f32_bytes(tensor)?; let offset = index .summary .data_start .checked_add(tensor.offset) .ok_or("tensor offset overflow")?; let mut input = File::open(source).map_err(|e| e.to_string())?; let mut output = create_output(destination)?; let result = stream_export(&mut input, offset, tensor, expected, &mut output); drop(output); if result.is_err() { let _ = std::fs::remove_file(destination); } result } /// The byte count of the tensor decoded to F32, from its dimensions. fn expected_f32_bytes(tensor: &gguf::TensorInfo) -> Result { let elements = tensor .dimensions .iter() .try_fold(1u64, |n, d| n.checked_mul(*d)) .ok_or("tensor element count overflow")?; elements .checked_mul(4) .ok_or_else(|| "F32 byte count overflow".to_owned()) } /// The new, private output file (it must not exist yet). fn create_output(destination: &Path) -> Result { let mut options = OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } options.open(destination).map_err(|e| e.to_string()) } /// Decode the tensor to F32 into `output`, hashing the source and the decoded bytes. fn stream_export( input: &mut File, offset: u64, tensor: &gguf::TensorInfo, expected: u64, output: &mut File, ) -> Result { let mut source_hash = Sha256::new(); let mut decoded_hash = Sha256::new(); let mut source_fnv = 0xcbf29ce484222325u64; let bytes = gguf_f32_stream::visit(input, offset, tensor.kind, tensor.bytes, |raw, f32| { if has_nonfinite(f32) { return Err("projection contains nonfinite values".into()); } source_hash.update(raw); for byte in raw { source_fnv = (source_fnv ^ u64::from(*byte)).wrapping_mul(0x100000001b3); } decoded_hash.update(f32); output.write_all(f32).map_err(|e| e.to_string()) })?; if bytes != expected { return Err("decoded tensor size does not match GGUF dimensions".into()); } output.sync_all().map_err(|e| e.to_string())?; let hashes = (source_hash, decoded_hash, source_fnv); Ok(export_record(tensor, bytes, hashes)) } /// The export description: the source tensor, the decoded byte count and the hashes of both streams. fn export_record( tensor: &gguf::TensorInfo, f32_bytes: u64, hashes: (Sha256, Sha256, u64), ) -> Export { let (source_hash, decoded_hash, source_fnv) = hashes; Export { tensor: tensor.name.clone(), dimensions: tensor.dimensions.clone(), source_kind: tensor.kind, source_bytes: tensor.bytes, source_tensor_sha256: hex::encode(source_hash.finalize()), source_fnv1a64: format!("{source_fnv:016x}"), f32_bytes, f32_sha256: hex::encode(decoded_hash.finalize()), decoder: "strata-next/gguf-f32-stream:ggml-3cf03257", } } fn has_nonfinite(f32: &[u8]) -> bool { f32.as_chunks::<4>() .0 .iter() .any(|bits| !f32::from_le_bytes(*bits).is_finite()) }