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

197 lines
6.9 KiB
Rust

//! The WeightSource port: where the compressed weight bytes of a model come from, and how they are exposed.
//!
//! A model is held once. A source hands out *borrowed* views into its single backing store and has no method that
//! returns an owner of the bytes (no `to_vec`, no `Box<[u8]>`, no `Arc<[u8]>`), so a second in-memory copy cannot be
//! introduced through it by accident. Two kinds of view exist, and a source picks the one its store allows:
//!
//! * [`Region::Resident`]: the store is addressable memory (an owned buffer, a huge-page buffer, a file mapping); the
//! region is a slice of it, the same address on every call.
//! * [`Region::Positional`]: the store is a file or a sealed memfd that is not mapped; the region reads a range into a
//! buffer the *caller* owns (a staging or scratch buffer), bounded by that buffer.
//!
//! A source is opened once per model load and read at load time (verification, binding, staging). Nothing here is on
//! the decode path. Adapters: [`FileWeightSource`] (a file or sealed memfd, positional), the verified GGUF shard
//! (`impl WeightSource for VerifiedGgufFile`), [`ResidentWeightSource`] (a retained or mapped GGUF tensor) and
//! [`MemWeightSource`] (the test double) and `KarInspection` (a KAR archive). [`WeightRange`] lends any source to the
//! KAR level staging (`stage_window`). [`sha256_of`] computes a digest through any of them.
use crate::kar::KarTrust;
use std::{fmt, fs::File, io, ops::Range};
mod digest;
mod file;
mod mem;
mod range;
mod resident;
#[cfg(test)]
mod tests;
pub use digest::sha256_of;
pub use file::FileWeightSource;
pub use mem::MemWeightSource;
pub use range::WeightRange;
pub use resident::ResidentWeightSource;
/// What holds the bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackingKind {
/// An owned heap buffer.
Memory,
/// An owned buffer in a 2 MiB huge-page mapping.
HugePages,
/// A read-only shared mapping of a file: the OS file cache holds the bytes, nothing is committed twice.
MappedFile,
/// An open regular file, read by position.
File,
/// A sealed, unlinked memfd, read by position.
SealedMemfd,
}
/// How the content was vouched for when the source was opened. Mirrors [`KarTrust`] plus the unverified case.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Verification {
Unverified,
FullPass,
Stamp,
AttestedMemfd,
SparseExtents,
}
impl From<KarTrust> for Verification {
fn from(trust: KarTrust) -> Self {
match trust {
KarTrust::FullPass => Self::FullPass,
KarTrust::Stamp => Self::Stamp,
KarTrust::AttestedMemfd => Self::AttestedMemfd,
KarTrust::SparseExtents => Self::SparseExtents,
}
}
}
/// Facts about a source that never need its bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WeightIdentity {
/// SHA-256 the content is declared (or was verified) to have. For a view of one tensor of a verified artifact it
/// is the digest of that artifact.
pub sha256: [u8; 32],
/// Length of the addressable range, in bytes.
pub bytes: u64,
pub verification: Verification,
pub backing: BackingKind,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WeightError {
/// A range or a read outside the source, or a scratch buffer that is empty.
Range,
Io(io::ErrorKind),
}
impl fmt::Display for WeightError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Range => f.write_str("weight range outside the source"),
Self::Io(kind) => write!(f, "weight read failed: {kind:?}"),
}
}
}
impl std::error::Error for WeightError {}
impl From<io::Error> for WeightError {
fn from(error: io::Error) -> Self {
Self::Io(error.kind())
}
}
/// A borrowed view of a range of a source. It never owns bytes.
#[derive(Clone, Copy, Debug)]
pub enum Region<'a> {
Resident(&'a [u8]),
Positional { file: &'a File, offset: u64, len: u64 },
}
impl<'a> Region<'a> {
pub fn len(&self) -> u64 {
match self {
Self::Resident(bytes) => bytes.len() as u64,
Self::Positional { len, .. } => *len,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// The bytes in place, when the store is addressable memory. `None` for a positional region.
pub fn as_slice(&self) -> Option<&'a [u8]> {
match self {
Self::Resident(bytes) => Some(bytes),
Self::Positional { .. } => None,
}
}
/// Fill `out` (the caller's buffer) from `at` bytes into the region.
pub fn read_at(&self, at: u64, out: &mut [u8]) -> Result<(), WeightError> {
let end = at.checked_add(out.len() as u64).ok_or(WeightError::Range)?;
if end > self.len() {
return Err(WeightError::Range);
}
match self {
Self::Resident(bytes) => out.copy_from_slice(&bytes[at as usize..end as usize]),
Self::Positional { file, offset, .. } => file::read_exact_at(file, offset + at, out)?,
}
Ok(())
}
/// Hand the region to `visit` in order: the slice itself when resident, otherwise `scratch`-sized pieces.
pub fn for_each_chunk(&self, scratch: &mut [u8], mut visit: impl FnMut(&[u8])) -> Result<(), WeightError> {
if let Self::Resident(bytes) = self {
visit(bytes);
return Ok(());
}
if scratch.is_empty() && !self.is_empty() {
return Err(WeightError::Range);
}
let mut at = 0u64;
while at < self.len() {
let step = scratch.len().min((self.len() - at) as usize);
self.read_at(at, &mut scratch[..step])?;
visit(&scratch[..step]);
at += step as u64;
}
Ok(())
}
}
/// Where compressed weight bytes come from. Implementors are opened once per load; `region` is cheap and repeatable.
pub trait WeightSource {
fn identity(&self) -> WeightIdentity;
/// A borrowed view of `range`. Repeated calls over the same range see the same bytes at the same address.
fn region(&self, range: Range<u64>) -> Result<Region<'_>, WeightError>;
fn len(&self) -> u64 {
self.identity().bytes
}
fn is_empty(&self) -> bool {
self.len() == 0
}
/// The length the backing store has right now, for a check that it did not grow or shrink after it was opened.
/// A source that cannot change answers with its length.
fn live_len(&self) -> Result<u64, WeightError> {
Ok(self.len())
}
}
/// Check `range` against a length and return it as `usize` bounds.
pub(crate) fn bounded(range: &Range<u64>, len: u64) -> Result<Range<usize>, WeightError> {
if range.start > range.end || range.end > len {
return Err(WeightError::Range);
}
let start = usize::try_from(range.start).map_err(|_| WeightError::Range)?;
let end = usize::try_from(range.end).map_err(|_| WeightError::Range)?;
Ok(start..end)
}