use std::borrow::Cow;
use crate::error::{ParserError, Result};
mod gguf;
mod open;
#[cfg(feature = "safetensors")]
mod safetensors;
mod types;
pub use gguf::GgufBackend;
#[cfg(feature = "mmap")]
pub use gguf::GgufMmapBackend;
#[cfg(feature = "mmap")]
pub use open::open_checkpoint_mmap;
pub use open::{AnyCheckpoint, open_checkpoint};
#[cfg(feature = "safetensors")]
pub use safetensors::SafetensorsBackend;
#[cfg(all(feature = "safetensors", feature = "mmap"))]
pub use safetensors::SafetensorsMmapBackend;
pub use types::{
CheckpointFormat, CheckpointMetadata, CheckpointSource, DimOrder, MetadataValue, SourceKind,
TensorDType, TensorInfo, TensorLocation, TensorShape,
};
pub trait Checkpoint: Send + Sync {
fn source(&self) -> &CheckpointSource;
fn format(&self) -> CheckpointFormat {
self.source().format
}
fn tensors(&self) -> &[TensorInfo];
fn tensor(&self, name: &str) -> Option<&TensorInfo> {
let tensors = self.tensors();
tensors
.binary_search_by(|t| t.name.as_str().cmp(name))
.ok()
.map(|index| &tensors[index])
}
fn metadata(&self) -> &CheckpointMetadata;
fn tensor_bytes(&self, name: &str) -> Result<Cow<'_, [u8]>>;
}
#[derive(Debug, Clone)]
pub(crate) struct Catalog {
source: CheckpointSource,
tensors: Vec<TensorInfo>,
metadata: CheckpointMetadata,
}
impl Catalog {
pub(crate) fn new(
source: CheckpointSource,
mut tensors: Vec<TensorInfo>,
metadata: CheckpointMetadata,
) -> Self {
tensors.sort_by(|a, b| a.name.cmp(&b.name));
Self {
source,
tensors,
metadata,
}
}
pub(crate) fn require(&self, name: &str) -> Result<&TensorInfo> {
self.tensors
.binary_search_by(|t| t.name.as_str().cmp(name))
.map(|index| &self.tensors[index])
.map_err(|_| ParserError::MissingTensor {
name: name.to_owned(),
path: self.source.path.display().to_string(),
})
}
pub(crate) fn check_len(&self, info: &TensorInfo, len: usize) -> Result<()> {
if len == info.byte_len {
return Ok(());
}
Err(ParserError::InvalidLayout {
path: self.source.path.display().to_string(),
reason: format!(
"tensor '{}' payload is {len} bytes, inventory says {}",
info.name, info.byte_len
),
})
}
}
macro_rules! delegate_catalog {
() => {
fn source(&self) -> &$crate::checkpoint::CheckpointSource {
&self.catalog.source
}
fn tensors(&self) -> &[$crate::checkpoint::TensorInfo] {
&self.catalog.tensors
}
fn metadata(&self) -> &$crate::checkpoint::CheckpointMetadata {
&self.catalog.metadata
}
};
}
pub(crate) use delegate_catalog;