use super::*;
fn tmp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"frink-quantize-{}-{}-{:?}",
tag,
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn args(input: &Path, output: &Path, ty: &str) -> QuantizeArgs {
QuantizeArgs {
input: input.to_path_buf(),
output: Some(output.to_path_buf()),
ty: ty.into(),
pure: false,
dry_run: false,
force: true,
imatrix: None,
}
}
fn write_f16_source(path: &Path, n_cols: usize) -> Vec<f32> {
let n = n_cols;
let values: Vec<f32> = (0..n * 2)
.map(|i| ((i as f32) * 0.037).sin() * 0.8)
.collect();
let f16_bytes = |vals: &[f32]| -> Vec<u8> {
vals.iter()
.flat_map(|v| half::f16::from_f32(*v).to_le_bytes())
.collect()
};
let mut metadata = BTreeMap::new();
metadata.insert(
"general.architecture".to_string(),
GgufValue::String("llama".into()),
);
metadata.insert("general.file_type".to_string(), GgufValue::U32(1));
let w = f16_bytes(&values);
let one_d = f16_bytes(&values[..n]);
let norm = f16_bytes(&values);
let gate = f16_bytes(&values);
let head = f16_bytes(&values);
let plan = vec![
TensorPlan {
name: "blk.0.attn_q.weight".into(),
shape: vec![n as u64, 2],
dtype: GgmlType::F16,
byte_len: w.len(),
},
TensorPlan {
name: "blk.0.attn_q.bias".into(),
shape: vec![n as u64],
dtype: GgmlType::F16,
byte_len: one_d.len(),
},
TensorPlan {
name: "blk.0.attn_norm.weight".into(),
shape: vec![n as u64, 2],
dtype: GgmlType::F16,
byte_len: norm.len(),
},
TensorPlan {
name: "blk.0.ffn_gate_inp.weight".into(),
shape: vec![n as u64, 2],
dtype: GgmlType::F16,
byte_len: gate.len(),
},
TensorPlan {
name: "output.weight".into(),
shape: vec![n as u64, 2],
dtype: GgmlType::F16,
byte_len: head.len(),
},
];
let f = std::fs::File::create(path).unwrap();
let mut wr = GgufWriter::create(BufWriter::new(f), &metadata, plan).unwrap();
wr.write_tensor("blk.0.attn_q.weight", &w).unwrap();
wr.write_tensor("blk.0.attn_q.bias", &one_d).unwrap();
wr.write_tensor("blk.0.attn_norm.weight", &norm).unwrap();
wr.write_tensor("blk.0.ffn_gate_inp.weight", &gate).unwrap();
wr.write_tensor("output.weight", &head).unwrap();
wr.finish().unwrap().into_inner().unwrap();
values
}
#[test]
fn an_f16_gguf_round_trips_through_quantize_and_reads_back_as_q8_0() {
let dir = tmp_dir("roundtrip");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
let values = write_f16_source(&src, 64);
run(args(&src, &dst, "Q8_0")).unwrap();
let out = GgufFile::open(&dst).unwrap();
assert_eq!(out.metadata_u64("general.file_type"), Some(7));
assert_eq!(out.metadata_u64("general.quantization_version"), Some(2));
assert_eq!(out.metadata_str("general.architecture"), Some("llama"));
let q = out.find_tensor("blk.0.attn_q.weight").unwrap();
assert_eq!(q.dtype, GgmlType::Q8_0);
assert_eq!(q.shape, vec![64, 2]);
for kept in [
"blk.0.attn_q.bias",
"blk.0.attn_norm.weight",
"blk.0.ffn_gate_inp.weight",
] {
assert_eq!(
out.find_tensor(kept).unwrap().dtype,
GgmlType::F16,
"{kept} should have been kept at source precision"
);
}
let back = frink_quant::dequant_q8_0(out.tensor_bytes("blk.0.attn_q.weight").unwrap()).unwrap();
assert_eq!(back.len(), values.len());
for (i, (&want, &have)) in values.iter().zip(back.iter()).enumerate() {
assert!((want - have).abs() < 0.01, "element {i}: {want} -> {have}");
}
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn the_quantized_tensor_bytes_are_what_the_encoder_produces_for_those_rows() {
let dir = tmp_dir("bytes");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
let values = write_f16_source(&src, 64);
run(args(&src, &dst, "q8_0")).unwrap();
let mut want = Vec::new();
let f16_roundtrip: Vec<f32> = values
.iter()
.map(|v| half::f16::from_f32(*v).to_f32())
.collect();
for row in f16_roundtrip.chunks(64) {
frink_quant::encode_row_q8_0(row, &mut want).unwrap();
}
let out = GgufFile::open(&dst).unwrap();
assert_eq!(out.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn asking_for_a_target_with_no_encoder_refuses_before_touching_the_filesystem() {
let dir = tmp_dir("refuse");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
write_f16_source(&src, 64);
let err = run(args(&src, &dst, "Q3_K_M")).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("cannot WRITE Q3_K_M"), "{msg}");
assert!(msg.contains("Q8_0"), "{msg}");
assert!(!dst.exists(), "a refused run must not leave a file behind");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_already_quantized_source_tensor_is_refused_by_name() {
let dir = tmp_dir("requant");
let src = dir.join("src.gguf");
let bytes = vec![0u8; 144 * 2]; let plan = vec![TensorPlan {
name: "blk.0.attn_q.weight".into(),
shape: vec![256, 2],
dtype: GgmlType::Q4K,
byte_len: bytes.len(),
}];
let f = std::fs::File::create(&src).unwrap();
let mut wr = GgufWriter::create(BufWriter::new(f), &BTreeMap::new(), plan).unwrap();
wr.write_tensor("blk.0.attn_q.weight", &bytes).unwrap();
wr.finish().unwrap().into_inner().unwrap();
let err = run(QuantizeArgs {
dry_run: true,
..args(&src, &dir.join("dst.gguf"), "Q8_0")
})
.unwrap_err();
assert!(
err.to_string().contains("F32/F16/BF16 sources only"),
"{err}"
);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_row_length_that_is_not_a_multiple_of_the_block_size_is_refused() {
let dir = tmp_dir("ragged");
let src = dir.join("src.gguf");
let bytes = vec![0u8; 33 * 2 * 2];
let plan = vec![TensorPlan {
name: "blk.0.attn_q.weight".into(),
shape: vec![33, 2],
dtype: GgmlType::F16,
byte_len: bytes.len(),
}];
let f = std::fs::File::create(&src).unwrap();
let mut wr = GgufWriter::create(BufWriter::new(f), &BTreeMap::new(), plan).unwrap();
wr.write_tensor("blk.0.attn_q.weight", &bytes).unwrap();
wr.finish().unwrap().into_inner().unwrap();
let err = run(QuantizeArgs {
dry_run: true,
..args(&src, &dir.join("dst.gguf"), "Q8_0")
})
.unwrap_err();
assert!(err.to_string().contains("not a multiple of"), "{err}");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_existing_output_is_not_overwritten_without_force() {
let dir = tmp_dir("clobber");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
write_f16_source(&src, 64);
std::fs::write(&dst, b"precious").unwrap();
let err = run(QuantizeArgs {
force: false,
..args(&src, &dst, "Q8_0")
})
.unwrap_err();
assert!(err.to_string().contains("--force"), "{err}");
assert_eq!(std::fs::read(&dst).unwrap(), b"precious");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn the_q4_k_m_mix_promotes_the_output_head_and_pure_does_not() {
let dir = tmp_dir("mix");
let src = dir.join("src.gguf");
write_f16_source(&src, 256);
let mixed = dir.join("mixed.gguf");
run(args(&src, &mixed, "q4_k_m")).unwrap();
let pure = dir.join("pure.gguf");
run(QuantizeArgs {
pure: true,
..args(&src, &pure, "q4_k_m")
})
.unwrap();
let m = GgufFile::open(&mixed).unwrap();
let p = GgufFile::open(&pure).unwrap();
assert_eq!(m.find_tensor("output.weight").unwrap().dtype, GgmlType::Q6K);
assert_eq!(p.find_tensor("output.weight").unwrap().dtype, GgmlType::Q4K);
for f in [&m, &p] {
assert_eq!(
f.find_tensor("blk.0.attn_q.weight").unwrap().dtype,
GgmlType::Q4K
);
}
assert_eq!(m.metadata_u64("general.file_type"), Some(15));
assert_eq!(p.metadata_u64("general.file_type"), Some(15));
assert_ne!(
std::fs::read(&mixed).unwrap(),
std::fs::read(&pure).unwrap()
);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_f16_gguf_round_trips_through_quantize_and_reads_back_as_q4_k() {
let dir = tmp_dir("q4k");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
let values = write_f16_source(&src, 256);
run(QuantizeArgs {
pure: true,
..args(&src, &dst, "q4_k_s")
})
.unwrap();
let out = GgufFile::open(&dst).unwrap();
assert_eq!(out.metadata_u64("general.file_type"), Some(14));
let q = out.find_tensor("blk.0.attn_q.weight").unwrap();
assert_eq!(q.dtype, GgmlType::Q4K);
assert_eq!(q.shape, vec![256, 2]);
for kept in [
"blk.0.attn_q.bias",
"blk.0.attn_norm.weight",
"blk.0.ffn_gate_inp.weight",
] {
assert_eq!(
out.find_tensor(kept).unwrap().dtype,
GgmlType::F16,
"{kept} should have been kept at source precision"
);
}
let mut want = Vec::new();
let f16_roundtrip: Vec<f32> = values
.iter()
.map(|v| half::f16::from_f32(*v).to_f32())
.collect();
for row in f16_roundtrip.chunks(256) {
frink_quant::encode_row_q4_k(row, None, &mut want).unwrap();
}
assert_eq!(out.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_row_too_narrow_for_a_super_block_is_refused_and_names_llama_cpps_fallback() {
let dir = tmp_dir("narrow");
let src = dir.join("src.gguf");
write_f16_source(&src, 64);
let err = run(QuantizeArgs {
pure: true,
dry_run: true,
..args(&src, &dir.join("dst.gguf"), "q4_k_s")
})
.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a multiple of Q4K's block size (256)"),
"{msg}"
);
assert!(msg.contains("Q4_K -> Q5_0"), "{msg}");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_imatrix_reaches_the_encoder_and_is_recorded_in_the_metadata() {
let dir = tmp_dir("imatrix");
let src = dir.join("src.gguf");
let values = write_f16_source(&src, 256);
let im_path = dir.join("im.gguf");
let mut stats = BTreeMap::new();
stats.insert(
"blk.0.attn_q.weight".to_string(),
crate::imatrix::file::Stats {
values: (0..256).map(|i| 1.0 + (i % 7) as f32).collect(),
counts: vec![4],
},
);
crate::imatrix::file::write(
&im_path,
crate::imatrix::file::OutputFormat::Gguf,
&stats,
&["calib.txt".to_string()],
2,
512,
)
.unwrap();
let plain = dir.join("plain.gguf");
run(QuantizeArgs {
pure: true,
..args(&src, &plain, "q4_k_s")
})
.unwrap();
let weighted = dir.join("weighted.gguf");
run(QuantizeArgs {
pure: true,
imatrix: Some(im_path.clone()),
..args(&src, &weighted, "q4_k_s")
})
.unwrap();
let qw: Vec<f32> = (0..256).map(|i| (1.0 + (i % 7) as f32) / 4.0).collect();
let mut want = Vec::new();
for row in values.chunks(256) {
let f16_row: Vec<f32> = row
.iter()
.map(|v| half::f16::from_f32(*v).to_f32())
.collect();
frink_quant::encode_row_q4_k(&f16_row, Some(&qw), &mut want).unwrap();
}
let w = GgufFile::open(&weighted).unwrap();
let p = GgufFile::open(&plain).unwrap();
assert_eq!(w.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
assert_ne!(
w.tensor_bytes("blk.0.attn_q.weight").unwrap(),
p.tensor_bytes("blk.0.attn_q.weight").unwrap()
);
assert_eq!(w.metadata_u64("quantize.imatrix.entries_count"), Some(1));
assert_eq!(w.metadata_u64("quantize.imatrix.chunks_count"), Some(2));
assert_eq!(
w.metadata_str("quantize.imatrix.dataset"),
Some("calib.txt")
);
assert!(p.metadata_str("quantize.imatrix.file").is_none());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn the_default_output_name_carries_the_target_and_sits_beside_the_input() {
assert_eq!(
default_output_path(Path::new("/m/Llama-3.2-1B-F16.gguf"), Target::Q8_0),
PathBuf::from("/m/Llama-3.2-1B-F16-Q8_0.gguf")
);
}
fn shared_kv_file(tag: &str, shared: u32, n_cols: usize, names: &[&str]) -> (PathBuf, Vec<f32>) {
let dir = tmp_dir(&format!("shared-kv-{tag}-{shared}-{n_cols}"));
let path = dir.join("src.gguf");
let mut metadata = BTreeMap::new();
metadata.insert(
"general.architecture".to_string(),
GgufValue::String("llama".into()),
);
metadata.insert("llama.block_count".to_string(), GgufValue::U32(2));
metadata.insert(
"llama.attention.shared_kv_layers".to_string(),
GgufValue::U32(shared),
);
let values: Vec<f32> = (0..n_cols * 2)
.map(|i| ((i as f32) * 0.071).cos() * 0.3)
.collect();
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
let plan_entries = names
.iter()
.map(|n| TensorPlan {
name: (*n).into(),
shape: vec![n_cols as u64, 2],
dtype: GgmlType::F32,
byte_len: bytes.len(),
})
.collect();
let f = std::fs::File::create(&path).unwrap();
let mut wr = GgufWriter::create(BufWriter::new(f), &metadata, plan_entries).unwrap();
for n in names {
wr.write_tensor(n, &bytes).unwrap();
}
wr.finish().unwrap().into_inner().unwrap();
(path, values)
}
const BOTH_LAYERS: [&str; 2] = ["blk.0.attn_k.weight", "blk.1.attn_k.weight"];
#[test]
fn an_unused_kv_tensor_of_a_shared_kv_layer_is_planned_as_q4_0_under_every_target() {
let (path, _) = shared_kv_file("plan", 1, 256, &BOTH_LAYERS);
let file = GgufFile::open(&path).unwrap();
let ty = |planned: &[Planned], name: &str| {
planned.iter().find(|p| p.name == name).unwrap().out_dtype
};
for pure in [false, true] {
for target in Target::ALL {
let planned = plan(&file, *target, pure, false).unwrap();
let unused = planned
.iter()
.find(|p| p.name == "blk.1.attn_k.weight")
.unwrap();
assert_eq!(unused.out_dtype, GgmlType::Q4_0, "{target:?} pure={pure}");
assert_eq!(unused.out_bytes, 2 * 256 / 32 * 18, "{target:?}");
assert_eq!(unused.copy_reason, None, "{target:?}");
assert_eq!(
ty(&planned, "blk.0.attn_k.weight"),
target.ggml_type(),
"{target:?} pure={pure}: the layer with its own KV cache"
);
}
}
let (plain, _) = shared_kv_file("plan", 0, 256, &BOTH_LAYERS);
let planned = plan(
&GgufFile::open(&plain).unwrap(),
Target::Q4_K_M,
false,
false,
)
.unwrap();
assert_eq!(ty(&planned, "blk.1.attn_k.weight"), GgmlType::Q4K);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
std::fs::remove_dir_all(plain.parent().unwrap()).ok();
}
#[test]
fn a_shared_kv_checkpoint_quantizes_and_its_unused_kv_bytes_are_q4_0s() {
let (src, values) = shared_kv_file("run", 1, 256, &BOTH_LAYERS);
let dst = src.with_file_name("dst.gguf");
run(args(&src, &dst, "q4_k_m")).unwrap();
let out = GgufFile::open(&dst).unwrap();
let dtype = |n: &str| out.tensors.iter().find(|t| t.name == n).unwrap().dtype;
assert_eq!(dtype("blk.1.attn_k.weight"), GgmlType::Q4_0);
assert_eq!(dtype("blk.0.attn_k.weight"), GgmlType::Q4K);
let mut want = Vec::new();
for row in values.chunks(256) {
frink_quant::encode_row_q4_0(row, None, &mut want).unwrap();
}
assert_eq!(out.tensor_bytes("blk.1.attn_k.weight").unwrap(), &want[..]);
std::fs::remove_dir_all(src.parent().unwrap()).ok();
}
#[test]
fn an_unused_kv_tensor_llama_quantize_writes_as_f16_is_refused_by_name() {
let (path, _) = shared_kv_file("f16", 1, 48, &["blk.1.attn_k.weight"]);
let Err(err) = plan(&GgufFile::open(&path).unwrap(), Target::Q8_0, true, false) else {
panic!("planned an F16 tensor frink cannot write");
};
let err = err.to_string();
assert!(err.contains("blk.1.attn_k.weight"), "{err}");
assert!(err.contains("F16"), "{err}");
assert!(err.contains("shared_kv_layers"), "{err}");
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_q4_0_target_writes_q4_0_blocks_and_a_q6_k_output_head() {
let dir = tmp_dir("q4_0");
let src = dir.join("src.gguf");
let dst = dir.join("dst.gguf");
let values = write_f16_source(&src, 256);
run(args(&src, &dst, "q4_0")).unwrap();
let out = GgufFile::open(&dst).unwrap();
let dtype = |n: &str| out.tensors.iter().find(|t| t.name == n).unwrap().dtype;
assert_eq!(dtype("blk.0.attn_q.weight"), GgmlType::Q4_0);
assert_eq!(dtype("output.weight"), GgmlType::Q6K);
assert_eq!(out.metadata_u64("general.file_type"), Some(2));
let mut want = Vec::new();
for row in values.chunks(256) {
let f16_row: Vec<f32> = row
.iter()
.map(|v| half::f16::from_f32(*v).to_f32())
.collect();
frink_quant::encode_row_q4_0(&f16_row, None, &mut want).unwrap();
}
assert_eq!(out.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn q4_0_with_an_imatrix_refuses_the_q4_1_ffn_down_by_name() {
let dir = tmp_dir("q4_1");
let path = dir.join("src.gguf");
let mut metadata = BTreeMap::new();
metadata.insert(
"general.architecture".to_string(),
GgufValue::String("llama".into()),
);
metadata.insert("llama.block_count".to_string(), GgufValue::U32(8));
let bytes = vec![0u8; 256 * 2 * 2];
let plan_entries = vec![TensorPlan {
name: "blk.0.ffn_down.weight".into(),
shape: vec![256, 2],
dtype: GgmlType::F16,
byte_len: bytes.len(),
}];
let f = std::fs::File::create(&path).unwrap();
let mut wr = GgufWriter::create(BufWriter::new(f), &metadata, plan_entries).unwrap();
wr.write_tensor("blk.0.ffn_down.weight", &bytes).unwrap();
wr.finish().unwrap().into_inner().unwrap();
let file = GgufFile::open(&path).unwrap();
let Err(err) = plan(&file, Target::Q4_0, false, true) else {
panic!("planned a Q4_1 tensor frink cannot write");
};
let err = err.to_string();
assert!(err.contains("blk.0.ffn_down.weight"), "{err}");
assert!(err.contains("Q4_1"), "{err}");
let planned = plan(&file, Target::Q4_0, false, false).unwrap();
assert_eq!(planned[0].out_dtype, GgmlType::Q4_0);
let planned = plan(&file, Target::Q4_0, true, true).unwrap();
assert_eq!(planned[0].out_dtype, GgmlType::Q4_0);
std::fs::remove_dir_all(&dir).ok();
}