use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use crate::gguf::ggml_type_label;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CheckpointFormat {
Gguf,
Safetensors,
}
impl CheckpointFormat {
pub const fn as_str(self) -> &'static str {
match self {
Self::Gguf => "gguf",
Self::Safetensors => "safetensors",
}
}
}
impl fmt::Display for CheckpointFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SourceKind {
SingleFile,
ShardIndex,
Directory,
InMemory,
}
impl SourceKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::SingleFile => "single_file",
Self::ShardIndex => "shard_index",
Self::Directory => "directory",
Self::InMemory => "in_memory",
}
}
}
impl fmt::Display for SourceKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckpointSource {
pub format: CheckpointFormat,
pub kind: SourceKind,
pub path: PathBuf,
pub root: PathBuf,
pub index_file: Option<String>,
pub files: Vec<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DimOrder {
OutermostFirst,
InnermostFirst,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TensorShape {
dims: Vec<usize>,
native_order: DimOrder,
}
impl TensorShape {
pub fn outermost_first(dims: Vec<usize>) -> Self {
Self {
dims,
native_order: DimOrder::OutermostFirst,
}
}
pub fn from_innermost_first(native: &[usize]) -> Self {
Self {
dims: native.iter().rev().copied().collect(),
native_order: DimOrder::InnermostFirst,
}
}
pub fn dims(&self) -> &[usize] {
&self.dims
}
pub fn native_order(&self) -> DimOrder {
self.native_order
}
pub fn native_dims(&self) -> Vec<usize> {
match self.native_order {
DimOrder::OutermostFirst => self.dims.clone(),
DimOrder::InnermostFirst => self.dims.iter().rev().copied().collect(),
}
}
pub fn rank(&self) -> usize {
self.dims.len()
}
pub fn element_count(&self) -> Option<usize> {
self.dims
.iter()
.try_fold(1usize, |acc, &d| acc.checked_mul(d))
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TensorDType {
F64,
F32,
F16,
BF16,
F8E4M3,
F8E5M2,
I64,
I32,
I16,
I8,
U64,
U32,
U16,
U8,
Bool,
I4,
U4,
GgufPacked {
ggml_type: u32,
},
Other(String),
}
impl TensorDType {
pub fn label(&self) -> &str {
match self {
Self::F64 => "F64",
Self::F32 => "F32",
Self::F16 => "F16",
Self::BF16 => "BF16",
Self::F8E4M3 => "F8_E4M3",
Self::F8E5M2 => "F8_E5M2",
Self::I64 => "I64",
Self::I32 => "I32",
Self::I16 => "I16",
Self::I8 => "I8",
Self::U64 => "U64",
Self::U32 => "U32",
Self::U16 => "U16",
Self::U8 => "U8",
Self::Bool => "BOOL",
Self::I4 => "I4",
Self::U4 => "U4",
Self::GgufPacked { ggml_type } => ggml_type_label(*ggml_type),
Self::Other(label) => label,
}
}
pub fn is_packed(&self) -> bool {
matches!(self, Self::I4 | Self::U4 | Self::GgufPacked { .. })
}
pub fn element_size(&self) -> Option<usize> {
match self {
Self::F64 | Self::I64 | Self::U64 => Some(8),
Self::F32 | Self::I32 | Self::U32 => Some(4),
Self::F16 | Self::BF16 | Self::I16 | Self::U16 => Some(2),
Self::F8E4M3 | Self::F8E5M2 | Self::I8 | Self::U8 | Self::Bool => Some(1),
Self::I4 | Self::U4 | Self::GgufPacked { .. } | Self::Other(_) => None,
}
}
}
impl fmt::Display for TensorDType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.label())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TensorLocation {
pub source: String,
pub data_offset: usize,
pub file_offset: Option<usize>,
}
impl TensorLocation {
pub fn new(source: impl Into<String>, data_offset: usize, file_offset: Option<usize>) -> Self {
Self {
source: source.into(),
data_offset,
file_offset,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TensorInfo {
pub name: String,
pub dtype: TensorDType,
pub native_dtype: String,
pub shape: TensorShape,
pub byte_len: usize,
pub location: TensorLocation,
}
impl TensorInfo {
pub fn new(
name: impl Into<String>,
dtype: TensorDType,
shape: TensorShape,
byte_len: usize,
location: TensorLocation,
) -> Self {
let native_dtype = dtype.label().to_owned();
Self {
name: name.into(),
dtype,
native_dtype,
shape,
byte_len,
location,
}
}
#[must_use]
pub fn with_native_dtype(mut self, native_dtype: impl Into<String>) -> Self {
self.native_dtype = native_dtype.into();
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum MetadataValue {
String(String),
UInt(u64),
Int(i64),
F32(f32),
F64(f64),
}
impl MetadataValue {
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(s) => Some(s),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
Self::UInt(v) => Some(v),
Self::Int(v) => u64::try_from(v).ok(),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match *self {
Self::F32(v) => Some(f64::from(v)),
Self::F64(v) => Some(v),
Self::UInt(v) => Some(v as f64),
Self::Int(v) => Some(v as f64),
Self::String(_) => None,
}
}
}
impl fmt::Display for MetadataValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::String(s) => f.write_str(s),
Self::UInt(v) => write!(f, "{v}"),
Self::Int(v) => write!(f, "{v}"),
Self::F32(v) => write!(f, "{v}"),
Self::F64(v) => write!(f, "{v}"),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CheckpointMetadata {
entries: BTreeMap<String, MetadataValue>,
}
impl CheckpointMetadata {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue) {
self.entries.insert(key.into(), value);
}
pub fn get(&self, key: &str) -> Option<&MetadataValue> {
self.entries.get(key)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.entries.keys().map(String::as_str)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
self.entries.iter().map(|(k, v)| (k.as_str(), v))
}
}
impl FromIterator<(String, MetadataValue)> for CheckpointMetadata {
fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self {
Self {
entries: iter.into_iter().collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gguf_shape_round_trips_native_order() {
let shape = TensorShape::from_innermost_first(&[4096, 32000]);
assert_eq!(shape.dims(), &[32000, 4096]);
assert_eq!(shape.native_dims(), vec![4096, 32000]);
assert_eq!(shape.native_order(), DimOrder::InnermostFirst);
assert_eq!(shape.element_count(), Some(4096 * 32000));
assert_eq!(
TensorShape::outermost_first(vec![]).element_count(),
Some(1)
);
assert_eq!(
TensorShape::outermost_first(vec![usize::MAX, 2]).element_count(),
None
);
}
#[test]
fn dtype_labels_and_packing() {
let q4k = TensorDType::GgufPacked { ggml_type: 12 };
assert_eq!(q4k.label(), "Q4_K");
assert!(q4k.is_packed());
assert_eq!(q4k.element_size(), None);
assert_eq!(TensorDType::BF16.element_size(), Some(2));
assert!(TensorDType::I4.is_packed());
assert_eq!(TensorDType::Other("C64".into()).label(), "C64");
}
#[test]
fn metadata_value_accessors() {
assert_eq!(MetadataValue::Int(-1).as_u64(), None);
assert_eq!(MetadataValue::Int(7).as_u64(), Some(7));
assert_eq!(MetadataValue::F32(0.5).as_f64(), Some(0.5));
assert_eq!(MetadataValue::String("x".into()).as_str(), Some("x"));
let meta: CheckpointMetadata = [
("b".to_string(), MetadataValue::UInt(2)),
("a".to_string(), MetadataValue::UInt(1)),
]
.into_iter()
.collect();
assert_eq!(meta.keys().collect::<Vec<_>>(), vec!["a", "b"]);
}
}