Files
leleka/control-plane/src/kar.rs
T

331 lines
11 KiB
Rust

//! Bounded KAR-2 metadata inspector. Payload CRC validation and decoding are separate work.
use std::{
fs::File,
io::Read,
path::{Component, Path},
};
use sha2::{Digest, Sha256};
use crate::{kar_codec, model::Manifest};
use leleka_model_format::kar::KarInspection;
pub use leleka_model_format::kar::KarSummary as Summary;
#[derive(Debug)]
pub struct TensorSource {
pub name: String,
pub dimensions: Vec<u64>,
pub dtype: u8,
pub digest: [u8; 32],
pub offset: u64,
pub section_bytes: u64,
pub storage_class: u8,
pub n_elements: u64,
pub planes_min: u8,
pub planes_max: u8,
pub section_offset: u64,
pub planes_offset: u64,
pub plane_stride_bytes: u32,
}
impl TensorSource {
/// The bytes libkar::kar_reserve stages for this record at the requested
/// level. RAW records have no precision dial and always stage in full.
pub fn gpu_resident_bytes(&self, level: u8) -> Result<u64, String> {
if self.storage_class == 1 {
return Ok(self.section_bytes);
}
if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max {
return Err(format!(
"{}: KAR level {level} is outside its supported dial",
self.name
));
}
self.planes_offset
.checked_sub(self.section_offset)
.and_then(|prefix| {
prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes))
})
.filter(|bytes| *bytes <= self.section_bytes)
.ok_or_else(|| format!("{}: invalid KAR GPU prefix size", self.name))
}
pub fn gpu_decode_bytes(&self) -> Result<u64, String> {
self.n_elements
.checked_mul(4)
.ok_or_else(|| format!("{}: KAR F32 decode size overflow", self.name))
}
/// One-row output size for a geometrically addressable NESTED table.
/// Whether the model can consume only selected rows is a separate question.
pub fn gpu_one_row_decode_bytes(&self) -> Option<u64> {
let row_len = *self.dimensions.first()?;
if self.storage_class == 0
&& self.dimensions.len() >= 2
&& row_len.is_multiple_of(32)
&& row_len <= u32::MAX as u64
&& self.n_elements > row_len
&& self.n_elements.is_multiple_of(row_len)
{
row_len.checked_mul(4)
} else {
None
}
}
}
impl From<leleka_model_format::kar::KarTensorSource> for TensorSource {
fn from(s: leleka_model_format::kar::KarTensorSource) -> Self {
Self {
name: s.name,
dimensions: s.dimensions,
dtype: s.dtype,
digest: s.digest,
offset: s.offset,
section_bytes: s.section_bytes,
storage_class: s.storage_class,
n_elements: s.n_elements,
planes_min: s.planes_min,
planes_max: s.planes_max,
section_offset: s.section_offset,
planes_offset: s.planes_offset,
plane_stride_bytes: s.plane_stride_bytes,
}
}
}
pub(crate) use leleka_model_format::kar::{crc32, crc32_step};
pub struct VerifiedRangeDecoder {
reader: KarInspection,
}
impl VerifiedRangeDecoder {
pub fn open(path: &Path) -> Result<Self, String> {
let mut s = Self::open_previously_verified(path)?;
s.reader.verify_payloads().map_err(|e| e.to_string())?;
Ok(s)
}
pub(crate) fn open_previously_verified(path: &Path) -> Result<Self, String> {
Ok(Self {
reader: KarInspection::inspect(File::open(path).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())?,
})
}
pub fn decode_range(
&mut self,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Result<Vec<f32>, String> {
self.reader
.decode_range(name, level, start, count, kar_codec::decode_range)
.map_err(|e| e.to_string())
}
pub fn element_count(&self, name: &str) -> Result<usize, String> {
let n = self
.reader
.tensor_sources()
.iter()
.find(|s| s.name == name)
.ok_or_else(|| format!("KAR tensor not found: {name}"))?
.n_elements;
usize::try_from(n).map_err(|_| "KAR tensor is too large".into())
}
}
pub fn inspect(path: &Path) -> Result<Summary, String> {
Ok(open_inspection(path)?.summary().clone())
}
pub fn inspect_with_sources(path: &Path) -> Result<(Summary, Vec<TensorSource>), String> {
let reader = open_inspection(path)?;
Ok((
reader.summary().clone(),
reader
.tensor_sources()
.iter()
.cloned()
.map(TensorSource::from)
.collect(),
))
}
pub fn verify(path: &Path) -> Result<Summary, String> {
Ok(verify_with_sources(path)?.0)
}
fn open_inspection(path: &Path) -> Result<KarInspection, String> {
KarInspection::inspect(File::open(path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())
}
pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f32>, String> {
decode_tensor_inner(path, name, level, 0, None)
}
/// Decode at most one million values from an arbitrary offset of a nested
/// tensor. Only the relevant scales and plane words are read into memory.
/// This is a CPU quality oracle, not a serving implementation.
pub fn decode_tensor_range(
path: &Path,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Result<Vec<f32>, String> {
decode_tensor_inner(path, name, level, start, Some(count))
}
/// The row length of a record that the CUDA row gather can read: compressed, divisible by 32, at most a million.
fn gather_row_length(record: &TensorSource) -> Result<usize, String> {
let row_len = usize::try_from(
*record
.dimensions
.first()
.ok_or("KAR tensor has no dimensions")?,
)
.map_err(|_| "KAR row length is too large")?;
if record.storage_class != 0
|| row_len == 0
|| !row_len.is_multiple_of(32)
|| row_len > 1_000_000
{
return Err(
"CUDA row gather requires a compressed record with a row length divisible by 32 \
and at most one million values"
.into(),
);
}
Ok(row_len)
}
/// CPU parity oracle for one CUDA row-gather request. The entire archive is
/// verified before the bounded row is decoded.
pub fn decode_tensor_row(
path: &Path,
name: &str,
level: u8,
row_id: u32,
) -> Result<Vec<f32>, String> {
let (_, records) = inspect_with_sources(path)?;
let record = records
.iter()
.find(|record| record.name == name)
.ok_or_else(|| format!("KAR tensor not found: {name}"))?;
let row_len = gather_row_length(record)?;
let start = (row_id as usize)
.checked_mul(row_len)
.ok_or("KAR row offset overflow")?;
if start
.checked_add(row_len)
.is_none_or(|end| end as u64 > record.n_elements)
{
return Err("KAR row ID exceeds tensor bounds".into());
}
decode_tensor_range(path, name, level, start, row_len)
}
fn decode_tensor_inner(
path: &Path,
name: &str,
level: u8,
start: usize,
count: Option<usize>,
) -> Result<Vec<f32>, String> {
let mut decoder = VerifiedRangeDecoder::open(path)?;
let count = count.map_or_else(|| decoder.element_count(name), Ok)?;
decoder.decode_range(name, level, start, count)
}
pub fn f32_fnv1a64(values: &[f32]) -> u64 {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
pub fn verify_with_sources(path: &Path) -> Result<(Summary, Vec<TensorSource>), String> {
let mut reader = open_inspection(path)?;
reader.verify_payloads().map_err(|e| e.to_string())?;
Ok((
reader.summary().clone(),
reader
.tensor_sources()
.iter()
.cloned()
.map(TensorSource::from)
.collect(),
))
}
fn check_shard_name(name: &str) -> Result<(), String> {
let mut components = Path::new(name).components();
if !matches!(components.next(), Some(Component::Normal(_))) || components.next().is_some() {
return Err("source manifest contains an invalid file name".into());
}
Ok(())
}
/// Opens a manifest shard and checks its length against the manifest.
fn open_shard(entry: &crate::model::ModelFile, source_dir: &Path) -> Result<(File, u64), String> {
let file = File::open(source_dir.join(&entry.name))
.map_err(|error| format!("{}: {error}", entry.name))?;
let size = file.metadata().map_err(|error| error.to_string())?.len();
if size != entry.size {
return Err(format!("{}: source size differs from manifest", entry.name));
}
Ok((file, size))
}
/// Streams a shard into the combined digest and checks its own SHA-256 against the manifest.
fn hash_shard(
file: &mut File,
entry: &crate::model::ModelFile,
buffer: &mut [u8],
combined: &mut Sha256,
) -> Result<(), String> {
let mut individual = Sha256::new();
loop {
let read = file.read(buffer).map_err(|error| error.to_string())?;
if read == 0 {
break;
}
individual.update(&buffer[..read]);
combined.update(&buffer[..read]);
}
if hex::encode(individual.finalize()) != entry.sha256.to_ascii_lowercase() {
return Err(format!(
"{}: source SHA-256 differs from manifest",
entry.name
));
}
Ok(())
}
pub fn verify_source_files(
summary: &Summary,
manifest: &Manifest,
source_dir: &Path,
) -> Result<(), String> {
let mut files = manifest.files.iter().collect::<Vec<_>>();
if files.is_empty() {
return Err("source manifest has no files".into());
}
files.sort_unstable_by(|left, right| left.name.as_bytes().cmp(right.name.as_bytes()));
let mut combined = Sha256::new();
let mut total = 0u64;
let mut buffer = vec![0; 8 * 1024 * 1024];
for entry in files {
check_shard_name(&entry.name)?;
let (mut file, size) = open_shard(entry, source_dir)?;
total = total
.checked_add(size)
.ok_or("source byte count overflow")?;
hash_shard(&mut file, entry, &mut buffer, &mut combined)?;
}
if total != summary.source_bytes || combined.finalize().as_slice() != summary.source_digest {
return Err("KAR source identity differs from verified manifest shards".into());
}
Ok(())
}
#[cfg(test)]
mod tests;