1use std::collections::BTreeMap;
9use std::fmt;
10use std::path::PathBuf;
11
12use crate::gguf::ggml_type_label;
13
14#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub enum CheckpointFormat {
18 Gguf,
20 Safetensors,
22}
23
24impl CheckpointFormat {
25 pub const fn as_str(self) -> &'static str {
27 match self {
28 Self::Gguf => "gguf",
29 Self::Safetensors => "safetensors",
30 }
31 }
32}
33
34impl fmt::Display for CheckpointFormat {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.write_str(self.as_str())
37 }
38}
39
40#[non_exhaustive]
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum SourceKind {
44 SingleFile,
46 ShardIndex,
48 Directory,
50 InMemory,
52}
53
54impl SourceKind {
55 pub const fn as_str(self) -> &'static str {
57 match self {
58 Self::SingleFile => "single_file",
59 Self::ShardIndex => "shard_index",
60 Self::Directory => "directory",
61 Self::InMemory => "in_memory",
62 }
63 }
64}
65
66impl fmt::Display for SourceKind {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(self.as_str())
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct CheckpointSource {
75 pub format: CheckpointFormat,
77 pub kind: SourceKind,
79 pub path: PathBuf,
82 pub root: PathBuf,
84 pub index_file: Option<String>,
86 pub files: Vec<String>,
88}
89
90#[non_exhaustive]
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum DimOrder {
94 OutermostFirst,
96 InnermostFirst,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Hash)]
108pub struct TensorShape {
109 dims: Vec<usize>,
110 native_order: DimOrder,
111}
112
113impl TensorShape {
114 pub fn outermost_first(dims: Vec<usize>) -> Self {
116 Self {
117 dims,
118 native_order: DimOrder::OutermostFirst,
119 }
120 }
121
122 pub fn from_innermost_first(native: &[usize]) -> Self {
124 Self {
125 dims: native.iter().rev().copied().collect(),
126 native_order: DimOrder::InnermostFirst,
127 }
128 }
129
130 pub fn dims(&self) -> &[usize] {
132 &self.dims
133 }
134
135 pub fn native_order(&self) -> DimOrder {
137 self.native_order
138 }
139
140 pub fn native_dims(&self) -> Vec<usize> {
142 match self.native_order {
143 DimOrder::OutermostFirst => self.dims.clone(),
144 DimOrder::InnermostFirst => self.dims.iter().rev().copied().collect(),
145 }
146 }
147
148 pub fn rank(&self) -> usize {
150 self.dims.len()
151 }
152
153 pub fn element_count(&self) -> Option<usize> {
155 self.dims
156 .iter()
157 .try_fold(1usize, |acc, &d| acc.checked_mul(d))
158 }
159}
160
161#[non_exhaustive]
168#[derive(Debug, Clone, PartialEq, Eq, Hash)]
169pub enum TensorDType {
170 F64,
172 F32,
174 F16,
176 BF16,
178 F8E4M3,
180 F8E5M2,
182 I64,
184 I32,
186 I16,
188 I8,
190 U64,
192 U32,
194 U16,
196 U8,
198 Bool,
200 I4,
202 U4,
204 GgufPacked {
208 ggml_type: u32,
210 },
211 Other(String),
213}
214
215impl TensorDType {
216 pub fn label(&self) -> &str {
218 match self {
219 Self::F64 => "F64",
220 Self::F32 => "F32",
221 Self::F16 => "F16",
222 Self::BF16 => "BF16",
223 Self::F8E4M3 => "F8_E4M3",
224 Self::F8E5M2 => "F8_E5M2",
225 Self::I64 => "I64",
226 Self::I32 => "I32",
227 Self::I16 => "I16",
228 Self::I8 => "I8",
229 Self::U64 => "U64",
230 Self::U32 => "U32",
231 Self::U16 => "U16",
232 Self::U8 => "U8",
233 Self::Bool => "BOOL",
234 Self::I4 => "I4",
235 Self::U4 => "U4",
236 Self::GgufPacked { ggml_type } => ggml_type_label(*ggml_type),
237 Self::Other(label) => label,
238 }
239 }
240
241 pub fn is_packed(&self) -> bool {
243 matches!(self, Self::I4 | Self::U4 | Self::GgufPacked { .. })
244 }
245
246 pub fn element_size(&self) -> Option<usize> {
249 match self {
250 Self::F64 | Self::I64 | Self::U64 => Some(8),
251 Self::F32 | Self::I32 | Self::U32 => Some(4),
252 Self::F16 | Self::BF16 | Self::I16 | Self::U16 => Some(2),
253 Self::F8E4M3 | Self::F8E5M2 | Self::I8 | Self::U8 | Self::Bool => Some(1),
254 Self::I4 | Self::U4 | Self::GgufPacked { .. } | Self::Other(_) => None,
255 }
256 }
257}
258
259impl fmt::Display for TensorDType {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 f.write_str(self.label())
262 }
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Hash)]
267pub struct TensorLocation {
268 pub source: String,
270 pub data_offset: usize,
272 pub file_offset: Option<usize>,
274}
275
276impl TensorLocation {
277 pub fn new(source: impl Into<String>, data_offset: usize, file_offset: Option<usize>) -> Self {
279 Self {
280 source: source.into(),
281 data_offset,
282 file_offset,
283 }
284 }
285}
286
287#[derive(Debug, Clone, PartialEq, Eq, Hash)]
289pub struct TensorInfo {
290 pub name: String,
292 pub dtype: TensorDType,
294 pub native_dtype: String,
297 pub shape: TensorShape,
299 pub byte_len: usize,
301 pub location: TensorLocation,
303}
304
305impl TensorInfo {
306 pub fn new(
309 name: impl Into<String>,
310 dtype: TensorDType,
311 shape: TensorShape,
312 byte_len: usize,
313 location: TensorLocation,
314 ) -> Self {
315 let native_dtype = dtype.label().to_owned();
316 Self {
317 name: name.into(),
318 dtype,
319 native_dtype,
320 shape,
321 byte_len,
322 location,
323 }
324 }
325
326 #[must_use]
328 pub fn with_native_dtype(mut self, native_dtype: impl Into<String>) -> Self {
329 self.native_dtype = native_dtype.into();
330 self
331 }
332}
333
334#[non_exhaustive]
344#[derive(Debug, Clone, PartialEq)]
345pub enum MetadataValue {
346 String(String),
348 UInt(u64),
350 Int(i64),
352 F32(f32),
354 F64(f64),
356}
357
358impl MetadataValue {
359 pub fn as_str(&self) -> Option<&str> {
361 match self {
362 Self::String(s) => Some(s),
363 _ => None,
364 }
365 }
366
367 pub fn as_u64(&self) -> Option<u64> {
369 match *self {
370 Self::UInt(v) => Some(v),
371 Self::Int(v) => u64::try_from(v).ok(),
372 _ => None,
373 }
374 }
375
376 pub fn as_f64(&self) -> Option<f64> {
378 match *self {
379 Self::F32(v) => Some(f64::from(v)),
380 Self::F64(v) => Some(v),
381 Self::UInt(v) => Some(v as f64),
382 Self::Int(v) => Some(v as f64),
383 Self::String(_) => None,
384 }
385 }
386}
387
388impl fmt::Display for MetadataValue {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 match self {
391 Self::String(s) => f.write_str(s),
392 Self::UInt(v) => write!(f, "{v}"),
393 Self::Int(v) => write!(f, "{v}"),
394 Self::F32(v) => write!(f, "{v}"),
395 Self::F64(v) => write!(f, "{v}"),
396 }
397 }
398}
399
400#[derive(Debug, Clone, Default, PartialEq)]
402pub struct CheckpointMetadata {
403 entries: BTreeMap<String, MetadataValue>,
404}
405
406impl CheckpointMetadata {
407 pub fn new() -> Self {
409 Self::default()
410 }
411
412 pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue) {
414 self.entries.insert(key.into(), value);
415 }
416
417 pub fn get(&self, key: &str) -> Option<&MetadataValue> {
419 self.entries.get(key)
420 }
421
422 pub fn len(&self) -> usize {
424 self.entries.len()
425 }
426
427 pub fn is_empty(&self) -> bool {
429 self.entries.is_empty()
430 }
431
432 pub fn keys(&self) -> impl Iterator<Item = &str> {
434 self.entries.keys().map(String::as_str)
435 }
436
437 pub fn iter(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
439 self.entries.iter().map(|(k, v)| (k.as_str(), v))
440 }
441}
442
443impl FromIterator<(String, MetadataValue)> for CheckpointMetadata {
444 fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(iter: I) -> Self {
445 Self {
446 entries: iter.into_iter().collect(),
447 }
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
455 #[test]
456 fn gguf_shape_round_trips_native_order() {
457 let shape = TensorShape::from_innermost_first(&[4096, 32000]);
458 assert_eq!(shape.dims(), &[32000, 4096]);
459 assert_eq!(shape.native_dims(), vec![4096, 32000]);
460 assert_eq!(shape.native_order(), DimOrder::InnermostFirst);
461 assert_eq!(shape.element_count(), Some(4096 * 32000));
462 assert_eq!(
463 TensorShape::outermost_first(vec![]).element_count(),
464 Some(1)
465 );
466 assert_eq!(
467 TensorShape::outermost_first(vec![usize::MAX, 2]).element_count(),
468 None
469 );
470 }
471
472 #[test]
473 fn dtype_labels_and_packing() {
474 let q4k = TensorDType::GgufPacked { ggml_type: 12 };
475 assert_eq!(q4k.label(), "Q4_K");
476 assert!(q4k.is_packed());
477 assert_eq!(q4k.element_size(), None);
478 assert_eq!(TensorDType::BF16.element_size(), Some(2));
479 assert!(TensorDType::I4.is_packed());
480 assert_eq!(TensorDType::Other("C64".into()).label(), "C64");
481 }
482
483 #[test]
484 fn metadata_value_accessors() {
485 assert_eq!(MetadataValue::Int(-1).as_u64(), None);
486 assert_eq!(MetadataValue::Int(7).as_u64(), Some(7));
487 assert_eq!(MetadataValue::F32(0.5).as_f64(), Some(0.5));
488 assert_eq!(MetadataValue::String("x".into()).as_str(), Some("x"));
489 let meta: CheckpointMetadata = [
490 ("b".to_string(), MetadataValue::UInt(2)),
491 ("a".to_string(), MetadataValue::UInt(1)),
492 ]
493 .into_iter()
494 .collect();
495 assert_eq!(meta.keys().collect::<Vec<_>>(), vec!["a", "b"]);
496 }
497}