Files
leleka/control-plane/examples/compare-kar-range.rs
T

185 lines
5.9 KiB
Rust

//! Independently decode a bounded KAR range and compare it with GGUF values.
//! The one-tensor GGUF and KAR inputs stay outside Git. This is a CPU diagnostic.
use std::{
env,
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
use leleka_control_plane::{ggml_bridge, gguf, kar};
type Failure = Box<dyn std::error::Error>;
const USAGE: &str = "usage: compare-kar-range FILE.gguf FILE.kar LEVEL START COUNT";
/// The command line: the one-tensor GGUF, the KAR archive, the level and the element range.
struct Args {
source_path: String,
archive_path: String,
level: u8,
start: usize,
count: usize,
}
fn word(args: &mut impl Iterator<Item = String>) -> Result<String, Failure> {
args.next().ok_or_else(|| USAGE.into())
}
fn number<T>(args: &mut impl Iterator<Item = String>) -> Result<T, Failure>
where
T: std::str::FromStr,
T::Err: Into<Failure>,
{
word(args)?.parse().map_err(Into::into)
}
fn parse_args() -> Result<Args, Failure> {
let mut args = env::args().skip(1);
let source_path = word(&mut args)?;
let archive_path = word(&mut args)?;
let level: u8 = number(&mut args)?;
let start: usize = number(&mut args)?;
let count: usize = number(&mut args)?;
if args.next().is_some() || count == 0 || count > 1_000_000 {
return Err(USAGE.into());
}
Ok(Args {
source_path,
archive_path,
level,
start,
count,
})
}
/// `(elements, bytes)` of one block of the supported source kinds.
fn block_geometry(kind: u32) -> Result<(usize, usize), Failure> {
match kind {
20 => Ok((32usize, 18usize)),
21 => Ok((256, 110)),
_ => Err("diagnostic supports IQ4_NL and IQ3_S sources".into()),
}
}
/// The exclusive end of the range, checked against the element count of the tensor.
fn checked_end(tensor: &gguf::TensorInfo, start: usize, count: usize) -> Result<usize, Failure> {
let end = start.checked_add(count).ok_or("GGUF range overflow")?;
let elements = tensor
.dimensions
.iter()
.try_fold(1usize, |n, d| n.checked_mul(usize::try_from(*d).ok()?))
.ok_or("GGUF element count overflow")?;
if end > elements {
return Err("GGUF range exceeds tensor".into());
}
Ok(end)
}
/// The sums the relative L2 error and the maximum absolute error are made of.
#[derive(Default)]
struct ErrorSums {
error: f64,
reference: f64,
maximum_absolute_error: f64,
}
impl ErrorSums {
fn add(&mut self, reference: f64, value: f64) {
let error = (reference - value).abs();
self.error += error * error;
self.reference += reference * reference;
self.maximum_absolute_error = self.maximum_absolute_error.max(error);
}
fn relative_l2(&self) -> f64 {
if self.reference == 0.0 {
self.error.sqrt()
} else {
(self.error / self.reference).sqrt()
}
}
}
/// Decodes the GGUF blocks that cover `start..end` and compares them with the archive's `reconstructed` values.
fn compare_blocks(
source: &mut File,
tensor: &gguf::TensorInfo,
(start, end): (usize, usize),
reconstructed: &[f32],
) -> Result<ErrorSums, Failure> {
let (block_elements, block_bytes) = block_geometry(tensor.kind)?;
let mut block = vec![0u8; block_bytes];
let mut decoded = vec![0.0f32; block_elements];
let mut sums = ErrorSums::default();
for number in start / block_elements..end.div_ceil(block_elements) {
source.read_exact(&mut block)?;
ggml_bridge::decode_into(tensor.kind, &block, &mut decoded)?;
let begin = start.max(number * block_elements);
let finish = end.min((number + 1) * block_elements);
for position in begin..finish {
let reference = f64::from(decoded[position - number * block_elements]);
sums.add(reference, f64::from(reconstructed[position - start]));
}
}
Ok(sums)
}
/// The absolute file offset of the block that holds element `start`.
fn first_block_offset(index: &gguf::TensorIndex, start: usize) -> Result<u64, Failure> {
let tensor = &index.tensors[0];
let (block_elements, block_bytes) = block_geometry(tensor.kind)?;
let first_block_bytes = (start / block_elements)
.checked_mul(block_bytes)
.and_then(|n| u64::try_from(n).ok())
.ok_or("GGUF offset overflow")?;
Ok(index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|n| n.checked_add(first_block_bytes))
.ok_or("GGUF offset overflow")?)
}
fn open_at(path: &Path, offset: u64) -> Result<File, Failure> {
let mut source = File::open(path)?;
source.seek(SeekFrom::Start(offset))?;
Ok(source)
}
fn report(tensor: &gguf::TensorInfo, (level, start, count): (u8, usize, usize), sums: &ErrorSums) {
println!(
concat!(
"{}: {} archived F32 values decoded at level {}, start {}; ",
"relative L2 {:.8}, maximum absolute error {:.8}"
),
tensor.name,
count,
level,
start,
sums.relative_l2(),
sums.maximum_absolute_error
);
}
fn main() -> Result<(), Failure> {
let args = parse_args()?;
let (start, count, level) = (args.start, args.count, args.level);
let source_path = Path::new(&args.source_path);
let index = gguf::tensor_index(source_path)?;
if index.tensors.len() != 1 {
return Err("diagnostic source must contain exactly one tensor".into());
}
let tensor = &index.tensors[0];
block_geometry(tensor.kind)?;
let end = checked_end(tensor, start, count)?;
let archive_path = Path::new(&args.archive_path);
let reconstructed = kar::decode_tensor_range(archive_path, &tensor.name, level, start, count)?;
let absolute = first_block_offset(&index, start)?;
let mut source = open_at(source_path, absolute)?;
let sums = compare_blocks(&mut source, tensor, (start, end), &reconstructed)?;
report(tensor, (level, start, count), &sums);
Ok(())
}