Files
leleka/crates/model-format/src/kar_nested.rs
T

244 lines
9.6 KiB
Rust

//! Section-layout descriptor of one NESTED (bit-plane) KAR-2 directory record.
//!
//! Child module of `kar`: it reads the same already-admitted directory bytes
//! the inspector validated and exposes only the fields a decoder needs. All
//! offsets are archive-absolute. `validate` re-derives the inspector's layout
//! formulas so a descriptor built by hand (tests, a future loader) is held to
//! the identical rules. No payload bytes are read here.
use super::{KarError, KarInspection, RECORD_BYTES, round_up, u16_at, u32_at, u64_at};
/// Nesting order stored in directory byte 45. Only top-down is decodable by
/// the CPU oracle and the CUDA path; bottom-up is legal in the container.
pub const NESTING_TOPDOWN: u8 = 0;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KarNestedRecord {
pub name: String,
pub dimensions: Vec<u64>,
pub n_elements: u64,
pub n_padded: u64,
/// Weights sharing one f16 scale; a multiple of 32 in 32..=1024.
pub group: u32,
/// Bit-planes physically stored for this record.
pub planes_stored: u8,
/// Inclusive dial the producer certifies for this record.
pub planes_min: u8,
pub planes_max: u8,
pub nesting: u8,
pub section_offset: u64,
pub section_bytes: u64,
pub scales_offset: u64,
pub scales_bytes: u64,
pub books_offset: u64,
pub books_bytes: u64,
pub planes_offset: u64,
pub plane_stride_bytes: u32,
}
impl KarNestedRecord {
/// Parse one directory record that the inspector has already admitted.
/// Returns `Ok(None)` for RAW records.
pub(super) fn from_directory(
name: &str,
dimensions: &[u64],
record: &[u8; RECORD_BYTES],
) -> Result<Option<Self>, KarError> {
if record[7] != 0 {
return Ok(None);
}
let parsed = Self {
name: name.to_owned(),
dimensions: dimensions.to_vec(),
n_elements: u64_at(record, 48),
n_padded: u64_at(record, 56),
group: u32::from(u16_at(record, 46)),
planes_stored: record[42],
planes_min: record[43],
planes_max: record[44],
nesting: record[45],
section_offset: u64_at(record, 112),
section_bytes: u64_at(record, 120),
scales_offset: u64_at(record, 64),
scales_bytes: u64_at(record, 72),
books_offset: u64_at(record, 80),
books_bytes: u64_at(record, 88),
planes_offset: u64_at(record, 96),
plane_stride_bytes: u32_at(record, 104),
};
parsed.validate()?;
Ok(Some(parsed))
}
/// Words (32 weights each) of one stored plane.
pub fn plane_words(&self) -> u64 {
self.n_padded / 32
}
/// Re-derive the inspector's nested-section rules. Byte-for-byte the same
/// formulas as `inspect_file`, so hand-built descriptors cannot be looser.
pub fn validate(&self) -> Result<(), KarError> {
let fail = |message: &'static str| Err(KarError::Format(message));
let group = u64::from(self.group);
let planes = u64::from(self.planes_stored);
if group == 0
|| group > 1024
|| !group.is_multiple_of(32)
|| !(1..=16).contains(&self.planes_stored)
|| self.planes_min == 0
|| self.planes_min > self.planes_max
|| self.planes_max > self.planes_stored
|| self.nesting > 1
{
return fail("invalid KAR nested tensor parameters");
}
if self.dimensions.is_empty()
|| self.dimensions.len() > 4
|| self.n_elements == 0
|| self
.dimensions
.iter()
.try_fold(1u64, |acc, dim| acc.checked_mul(*dim))
!= Some(self.n_elements)
{
return fail("KAR tensor element count mismatch");
}
let rounded = self
.n_elements
.div_ceil(group)
.checked_mul(group)
.ok_or(KarError::Format("KAR padded count overflow"))?;
if self.n_padded != rounded {
return fail("KAR padded tensor count mismatch");
}
let expected_scales = (self.n_padded / group)
.checked_mul(2)
.ok_or(KarError::Format("KAR scale count overflow"))?;
let expected_books = (1u64 << (planes + 2)) - 4;
let plane_words_bytes = (self.n_padded / 32)
.checked_mul(4)
.ok_or(KarError::Format("KAR plane size overflow"))?;
let expected_stride =
round_up(plane_words_bytes, 16).ok_or(KarError::Format("KAR plane stride overflow"))?;
let books_start = self
.scales_offset
.checked_add(self.scales_bytes)
.and_then(|value| round_up(value, 16))
.ok_or(KarError::Format("KAR books offset overflow"))?;
let planes_start = self
.books_offset
.checked_add(self.books_bytes)
.and_then(|value| round_up(value, 16))
.ok_or(KarError::Format("KAR planes offset overflow"))?;
let section_end = self
.section_offset
.checked_add(self.section_bytes)
.ok_or(KarError::Format("KAR tensor section overflow"))?;
if self.scales_offset != self.section_offset
|| self.scales_bytes != expected_scales
|| self.books_offset != books_start
|| self.books_bytes != expected_books
|| self.planes_offset != planes_start
|| u64::from(self.plane_stride_bytes) != expected_stride
|| self
.planes_offset
.checked_add(planes * expected_stride)
.is_none_or(|end| end > section_end)
{
return fail("invalid KAR nested tensor section layout");
}
Ok(())
}
}
impl KarInspection {
/// Every NESTED record in directory order. RAW records are skipped.
pub fn nested_records(&self) -> Result<Vec<KarNestedRecord>, KarError> {
let mut records = Vec::new();
records
.try_reserve_exact(self.sources.len())
.map_err(|_| KarError::Allocation)?;
for (index, source) in self.sources.iter().enumerate() {
let record: &[u8; RECORD_BYTES] = self.directory
[index * RECORD_BYTES..(index + 1) * RECORD_BYTES]
.try_into()
.expect("validated directory");
if let Some(nested) =
KarNestedRecord::from_directory(&source.name, &source.dimensions, record)?
{
records.push(nested);
}
}
Ok(records)
}
/// One NESTED record by tensor name.
pub fn nested_record(&self, name: &str) -> Result<KarNestedRecord, KarError> {
let index = self
.sources
.iter()
.position(|source| source.name == name)
.ok_or(KarError::Range("KAR tensor not found"))?;
let record: &[u8; RECORD_BYTES] = self.directory
[index * RECORD_BYTES..(index + 1) * RECORD_BYTES]
.try_into()
.expect("validated directory");
let source = &self.sources[index];
KarNestedRecord::from_directory(&source.name, &source.dimensions, record)?
.ok_or(KarError::Range("KAR tensor is RAW, not NESTED"))
}
}
impl KarInspection {
/// Fused full-archive SHA-256 pin plus every payload CRC-32, over this
/// inspection's own retained descriptor. This is the verification a GPU
/// loader must pass before trusting any window read from this archive.
pub fn verify_archive(&mut self, pin: &[u8; 32]) -> Result<(), KarError> {
let bytes = self.summary.archive_bytes;
self.verify_integrity(bytes, pin)
}
/// Read `out.len()` bytes at an archive-absolute offset from the retained
/// descriptor. The caller keeps the owner-controlled immutability contract
/// of `into_owner_controlled`; the length is rechecked on every call so a
/// truncated or grown file fails closed.
#[cfg(unix)]
pub fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> Result<(), KarError> {
use std::os::unix::fs::FileExt;
let end = offset
.checked_add(out.len() as u64)
.ok_or(KarError::Range("KAR read range overflows"))?;
if end > self.summary.archive_bytes {
return Err(KarError::Range("KAR read range exceeds the archive"));
}
if self.file.metadata().map_err(KarError::Io)?.len() != self.summary.archive_bytes {
return Err(KarError::Integrity("KAR archive length changed"));
}
self.file.read_exact_at(out, offset).map_err(KarError::Io)
}
/// Windows counterpart: `seek_read` carries its own offset (the file position is not used), looped to a full read.
#[cfg(windows)]
pub fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> Result<(), KarError> {
use std::os::windows::fs::FileExt;
let end = offset
.checked_add(out.len() as u64)
.ok_or(KarError::Range("KAR read range overflows"))?;
if end > self.summary.archive_bytes {
return Err(KarError::Range("KAR read range exceeds the archive"));
}
if self.file.metadata().map_err(KarError::Io)?.len() != self.summary.archive_bytes {
return Err(KarError::Integrity("KAR archive length changed"));
}
let mut done = 0;
while done < out.len() {
let n = self.file.seek_read(&mut out[done..], offset + done as u64).map_err(KarError::Io)?;
if n == 0 {
return Err(KarError::Io(std::io::ErrorKind::UnexpectedEof.into()));
}
done += n;
}
Ok(())
}
}