Files
leleka/control-plane/examples/compare-iq3-s.rs
T

72 lines
2.4 KiB
Rust

//! Compare the independent Rust IQ3_S decoder with pinned ggml on real GGUF blocks.
//! The GGUF input stays outside Git; this diagnostic reads only caller-chosen blocks.
use std::{
env,
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
use leleka_control_plane::{ggml_bridge, gguf, iq3_s};
type Failure = Box<dyn std::error::Error>;
const USAGE: &str = "usage: compare-iq3-s FILE.gguf [BLOCKS]";
/// The GGUF path and the number of blocks to compare (1024 by default).
fn parse_args() -> Result<(String, u64), Failure> {
let mut args = env::args().skip(1);
let path = args.next().ok_or(USAGE)?;
let requested: u64 = args.next().unwrap_or_else(|| "1024".into()).parse()?;
if args.next().is_some() || requested == 0 {
return Err(USAGE.into());
}
Ok((path, requested))
}
/// Compares `blocks` consecutive blocks of `source` between the Rust decoder and pinned ggml, bit for bit.
fn compare_blocks(source: &mut File, blocks: u64) -> Result<(), Failure> {
let mut block = [0u8; iq3_s::BLOCK_BYTES];
let mut ggml = [0.0f32; iq3_s::BLOCK_ELEMENTS];
for number in 0..blocks {
source.read_exact(&mut block)?;
let rust = iq3_s::decode_block(&block)?;
ggml_bridge::decode_into(21, &block, &mut ggml)?;
if let Some(position) = rust
.iter()
.zip(&ggml)
.position(|(left, right)| left.to_bits() != right.to_bits())
{
return Err(format!(
"block {number}, value {position}: Rust={:#010x}, ggml={:#010x}",
rust[position].to_bits(),
ggml[position].to_bits()
)
.into());
}
}
Ok(())
}
fn main() -> Result<(), Failure> {
let (path, requested) = parse_args()?;
let path = Path::new(&path);
let index = gguf::tensor_index(path)?;
let tensor = index
.tensors
.iter()
.find(|tensor| tensor.kind == 21)
.ok_or("GGUF has no IQ3_S tensor")?;
let blocks = requested.min(tensor.bytes / iq3_s::BLOCK_BYTES as u64);
let mut source = File::open(path)?;
source.seek(SeekFrom::Start(index.summary.data_start + tensor.offset))?;
compare_blocks(&mut source, blocks)?;
println!(
"{}: {blocks} IQ3_S blocks, {} F32 values bit-identical to pinned ggml",
tensor.name,
blocks * iq3_s::BLOCK_ELEMENTS as u64
);
Ok(())
}