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

271 lines
11 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};
use crate::weight_source::{BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded};
/// 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 group = u64::from(self.group);
if !self.parameters_valid(group) {
return Err(KarError::Format("invalid KAR nested tensor parameters"));
}
if !self.shape_valid() {
return Err(KarError::Format("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 Err(KarError::Format("KAR padded tensor count mismatch"));
}
let expected = self.expected_layout(group)?;
if !self.layout_matches(&expected) {
return Err(KarError::Format("invalid KAR nested tensor section layout"));
}
Ok(())
}
fn parameters_valid(&self, group: u64) -> bool {
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
}
fn shape_valid(&self) -> bool {
!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)
}
/// Where the pieces of the section must lie, from the sizes this record states.
fn expected_layout(&self, group: u64) -> Result<ExpectedLayout, KarError> {
let scales_bytes =
(self.n_padded / group).checked_mul(2).ok_or(KarError::Format("KAR scale count overflow"))?;
let books_bytes = (1u64 << (u64::from(self.planes_stored) + 2)) - 4;
let plane_words_bytes =
(self.n_padded / 32).checked_mul(4).ok_or(KarError::Format("KAR plane size overflow"))?;
let 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"))?;
Ok(ExpectedLayout { scales_bytes, books_bytes, stride, books_start, planes_start, section_end })
}
fn layout_matches(&self, expected: &ExpectedLayout) -> bool {
let planes = u64::from(self.planes_stored);
self.scales_offset == self.section_offset
&& self.scales_bytes == expected.scales_bytes
&& self.books_offset == expected.books_start
&& self.books_bytes == expected.books_bytes
&& self.planes_offset == expected.planes_start
&& u64::from(self.plane_stride_bytes) == expected.stride
&& self.planes_offset.checked_add(planes * expected.stride).is_some_and(|end| end <= expected.section_end)
}
}
/// The sizes and offsets `KarNestedRecord::validate` derives from a record's own fields.
struct ExpectedLayout {
scales_bytes: u64,
books_bytes: u64,
stride: u64,
books_start: u64,
planes_start: u64,
section_end: u64,
}
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(())
}
}
/// The archive's open descriptor as a port source. Inspection checks structure and CRCs, not the archive digest, so the
/// identity carries no digest and says `Unverified`; the pin lives with the verifier that holds the descriptor.
impl WeightSource for KarInspection {
fn identity(&self) -> WeightIdentity {
WeightIdentity {
sha256: [0; 32],
bytes: self.summary.archive_bytes,
verification: Verification::Unverified,
backing: BackingKind::File,
}
}
fn region(&self, range: std::ops::Range<u64>) -> Result<Region<'_>, WeightError> {
bounded(&range, self.summary.archive_bytes)?;
Ok(Region::Positional { file: &self.file, offset: range.start, len: range.end - range.start })
}
fn live_len(&self) -> Result<u64, WeightError> {
Ok(self.file.metadata()?.len())
}
}
#[cfg(test)]
#[path = "weight_source/kar_inspection_tests.rs"]
mod weight_source_tests;