pub mod accumulator;
pub mod corpus;
pub mod error;
pub mod forward;
pub mod gguf_loader;
pub mod gguf_writer;
pub use accumulator::{Accumulator, AccumulatorRegistry};
pub use corpus::{CorpusBytes, CorpusSource, BAKED_CORPUS_NAMES};
pub use error::ImatrixError;
pub use forward::{
compute_imatrix, intercept_qmatmul_id_with_hint, intercept_qmatmul_with_hint, is_active,
with_collector, ComputeImatrixParams, ImatrixCollector, ImatrixHint,
};
pub use gguf_loader::LoadedImatrix;
pub use gguf_writer::{write_imatrix, write_imatrix_to_path};
#[derive(Debug, Clone)]
pub enum ImatrixProvenance {
LoadedFromFile(std::path::PathBuf),
Computed { corpus_label: String, n_ctx: u32 },
}
impl ImatrixProvenance {
pub fn label(&self) -> String {
match self {
ImatrixProvenance::LoadedFromFile(path) => format!("file:{}", path.display()),
ImatrixProvenance::Computed {
corpus_label,
n_ctx,
} => {
format!("computed[{}@n_ctx={}]", corpus_label, n_ctx)
}
}
}
}
#[derive(Debug)]
pub struct ImatrixData {
pub loaded: LoadedImatrix,
pub provenance: ImatrixProvenance,
}
impl ImatrixData {
pub fn load_from_path(path: &std::path::Path) -> Result<Self, ImatrixError> {
let loaded = LoadedImatrix::load_from_path(path)?;
Ok(ImatrixData {
loaded,
provenance: ImatrixProvenance::LoadedFromFile(path.to_path_buf()),
})
}
pub fn write_gguf(
&self,
path: &std::path::Path,
datasets: &[String],
) -> Result<(), ImatrixError> {
write_imatrix_to_path(
path,
&self.loaded.registry,
datasets,
self.loaded.chunk_count,
self.loaded.chunk_size,
)
}
pub fn tensor_pair_count(&self) -> usize {
self.loaded.tensor_pair_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imatrix_data_round_trip_is_byte_stable() {
let mut reg = AccumulatorRegistry::new();
let acc = reg.register("blk.0.attn_q.weight", 4, 1).unwrap();
acc.absorb_dense(&[1.0, 2.0, 3.0, 4.0]).unwrap();
acc.absorb_dense(&[0.5, 0.5, 0.5, 0.5]).unwrap();
let tmp = tempfile::NamedTempFile::new().unwrap();
write_imatrix_to_path(tmp.path(), ®, &["cdv3".to_string()], 1, 512).unwrap();
let data = ImatrixData::load_from_path(tmp.path()).unwrap();
assert_eq!(data.tensor_pair_count(), 1);
let tmp2 = tempfile::NamedTempFile::new().unwrap();
data.write_gguf(tmp2.path(), &["cdv3".to_string()]).unwrap();
let a = std::fs::read(tmp.path()).unwrap();
let b = std::fs::read(tmp2.path()).unwrap();
assert_eq!(
a,
b,
"imatrix file double-round-trip should be byte-identical \
(a.len={}, b.len={})",
a.len(),
b.len()
);
}
#[test]
fn provenance_labels() {
let from_file =
ImatrixProvenance::LoadedFromFile(std::path::PathBuf::from("/tmp/foo.imatrix.gguf"));
assert!(from_file.label().starts_with("file:"));
let computed = ImatrixProvenance::Computed {
corpus_label: "cdv3".to_string(),
n_ctx: 512,
};
assert!(computed.label().contains("cdv3"));
assert!(computed.label().contains("512"));
}
}