//! 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 elements = tensor .dimensions .iter() .try_fold(1u64, |n, d| n.checked_mul(*d)) .ok_or("tensor element count overflow")?; let expected = elements.checked_mul(4).ok_or("F32 byte count overflow")?; 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 options = OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let mut output = options.open(destination).map_err(|e| e.to_string())?; let mut source_hash = Sha256::new(); let mut decoded_hash = Sha256::new(); let mut source_fnv = 0xcbf29ce484222325u64; let result = (|| { let bytes = gguf_f32_stream::visit(&mut input, offset, tensor.kind, tensor.bytes, |raw, f32| { if f32 .as_chunks::<4>() .0 .iter() .any(|bits| !f32::from_le_bytes(*bits).is_finite()) { 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())?; Ok(Export { tensor: name.into(), 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: bytes, f32_sha256: hex::encode(decoded_hash.finalize()), decoder: "strata-next/gguf-f32-stream:ggml-3cf03257", }) })(); drop(output); if result.is_err() { let _ = std::fs::remove_file(destination); } result }