pub mod arch;
pub mod imatrix_input;
pub mod model_shape;
pub mod policy;
pub mod recipe;
#[cfg(test)]
mod recipe_golden;
#[cfg(test)]
mod recipe_golden_arch;
#[cfg(test)]
mod recipe_golden_qwen35;
use std::collections::BTreeMap;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use clap::Parser;
use frink_gguf::{GgmlType, GgufFile, GgufValue, GgufWriter, TensorPlan};
use rayon::prelude::*;
use arch::QuantArch;
use imatrix_input::{imatrix_for_tensor, imatrix_metadata, load_imatrix};
use model_shape::ModelShape;
use policy::{
allows_quantization, disposition, first_unused_kv_layer, parse_target, unused_kv_type,
Disposition, Target,
};
use recipe::Recipe;
const GGML_QNT_VERSION: u32 = 2;
const ROWS_PER_TASK: usize = 64;
#[derive(Parser, Debug)]
pub struct QuantizeArgs {
pub input: PathBuf,
pub output: Option<PathBuf>,
#[arg(long = "type", default_value = "Q8_0")]
pub ty: String,
#[arg(long)]
pub pure: bool,
#[arg(long)]
pub dry_run: bool,
#[arg(long)]
pub force: bool,
#[arg(long)]
pub imatrix: Option<PathBuf>,
}
pub(crate) struct Planned {
pub(crate) name: String,
pub(crate) shape: Vec<u64>,
source_dtype: GgmlType,
out_dtype: GgmlType,
source_bytes: usize,
out_bytes: usize,
copy_reason: Option<&'static str>,
}
pub fn run(args: QuantizeArgs) -> Result<()> {
let target = parse_target(&args.ty).map_err(|e| anyhow::anyhow!("{e}"))?;
let file =
GgufFile::open(&args.input).with_context(|| format!("opening {}", args.input.display()))?;
if file
.metadata_u64(frink_gguf::sharded::SPLIT_COUNT_KEY)
.is_some_and(|n| n > 1)
{
bail!(
"{} is one shard of a split GGUF. `frink quantize` writes a single file and has no \
--keep-split; merge the shards first, or quantize the unsplit source.",
args.input.display()
);
}
let output = args
.output
.clone()
.unwrap_or_else(|| default_output_path(&args.input, target));
if !args.dry_run {
if output == args.input {
bail!("output would overwrite the input ({})", output.display());
}
if output.exists() && !args.force {
bail!(
"{} already exists (pass --force to overwrite)",
output.display()
);
}
}
let planned = plan(&file, target, args.pure, args.imatrix.is_some())?;
let imatrix = match &args.imatrix {
Some(p) => Some(load_imatrix(p)?),
None => None,
};
let mut metadata: BTreeMap<String, GgufValue> = file
.metadata
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
metadata.insert(
"general.file_type".to_string(),
GgufValue::U32(target.llama_ftype()),
);
metadata.insert(
"general.quantization_version".to_string(),
GgufValue::U32(GGML_QNT_VERSION),
);
if let (Some(im), Some(p)) = (&imatrix, &args.imatrix) {
imatrix_metadata(&mut metadata, im, p);
}
let src_total: u64 = planned.iter().map(|p| p.source_bytes as u64).sum();
let out_total: u64 = planned.iter().map(|p| p.out_bytes as u64).sum();
let n_quantized = planned.iter().filter(|p| p.copy_reason.is_none()).count();
println!(
"quantize: {} -> {}",
args.input.display(),
if args.dry_run {
"(dry run, nothing written)".to_string()
} else {
output.display().to_string()
}
);
println!(" target: {}", target.name());
for (i, p) in planned.iter().enumerate() {
match p.copy_reason {
Some(reason) => println!(
" [{:>4}/{}] {:<44} {:?} {:>10} B copy ({reason})",
i + 1,
planned.len(),
p.name,
p.source_dtype,
p.source_bytes
),
None => println!(
" [{:>4}/{}] {:<44} {:?} {:>10} B -> {:?} {:>10} B",
i + 1,
planned.len(),
p.name,
p.source_dtype,
p.source_bytes,
p.out_dtype,
p.out_bytes
),
}
}
println!(
" {n_quantized}/{} tensors quantized; {:.2} MiB -> {:.2} MiB ({:.2}x)",
planned.len(),
src_total as f64 / (1024.0 * 1024.0),
out_total as f64 / (1024.0 * 1024.0),
src_total as f64 / out_total.max(1) as f64,
);
if args.dry_run {
return Ok(());
}
let plan_entries: Vec<TensorPlan> = planned
.iter()
.map(|p| TensorPlan {
name: p.name.clone(),
shape: p.shape.clone(),
dtype: p.out_dtype,
byte_len: p.out_bytes,
})
.collect();
let out_file =
std::fs::File::create(&output).with_context(|| format!("creating {}", output.display()))?;
let mut writer = GgufWriter::create(
BufWriter::with_capacity(4 << 20, out_file),
&metadata,
plan_entries,
)?;
for p in &planned {
let src = file.tensor_bytes(&p.name)?;
if p.copy_reason.is_some() {
writer.write_tensor(&p.name, src)?;
} else {
let qw = match &imatrix {
Some(im) => imatrix_for_tensor(im, p)?,
None => None,
};
let encoded = encode_tensor(p, src, qw)?;
writer.write_tensor(&p.name, &encoded)?;
}
}
writer.finish()?.into_inner()?;
println!("wrote {}", output.display());
Ok(())
}
fn default_output_path(input: &Path, target: Target) -> PathBuf {
let stem = input
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "ggml-model".to_string());
input.with_file_name(format!("{stem}-{}.gguf", target.name()))
}
fn plan(file: &GgufFile, target: Target, pure: bool, has_imatrix: bool) -> Result<Vec<Planned>> {
let mut out = Vec::with_capacity(file.tensors.len());
let arch_name = file.metadata_str("general.architecture").unwrap_or("");
let arch = QuantArch::from_name(arch_name);
let chosen_types = if pure {
BTreeMap::new()
} else {
let tensors: Vec<(String, Vec<u64>, GgmlType)> = file
.tensors
.iter()
.map(|t| (t.name.clone(), t.shape.clone(), t.dtype))
.collect();
Recipe::resolve_all(
target,
ModelShape::from_header(file)?,
has_imatrix,
&tensors,
|name, shape| allows_quantization(arch, name, shape).is_none(),
)?
};
let key = |suffix: &str| file.metadata_u64(&format!("{arch_name}.{suffix}"));
let unused_kv_from =
first_unused_kv_layer(key("block_count"), key("attention.shared_kv_layers"));
for t in &file.tensors {
let source_bytes = t.byte_len().ok_or_else(|| {
anyhow::anyhow!(
"tensor '{}' has dtype {:?}, whose block layout this build does not know, so it \
cannot even be copied through",
t.name,
t.dtype
)
})?;
let copy_through = |reason: &'static str| Planned {
name: t.name.clone(),
shape: t.shape.clone(),
source_dtype: t.dtype,
out_dtype: t.dtype,
source_bytes,
out_bytes: source_bytes,
copy_reason: Some(reason),
};
if let Some(reason) = allows_quantization(arch, &t.name, &t.shape) {
out.push(copy_through(reason));
continue;
}
let unused_kv = unused_kv_type(&t.name, t.shape[0], unused_kv_from);
let chosen = if let Some(ty) = unused_kv {
ty
} else if pure {
target.ggml_type()
} else {
*chosen_types
.get(&t.name)
.expect("resolve_all and allows_quantization disagree about a tensor")
};
match disposition(t.dtype, chosen) {
Disposition::Copy(reason) => out.push(copy_through(reason)),
Disposition::Quantize(ty) => {
if !matches!(t.dtype, GgmlType::F32 | GgmlType::F16 | GgmlType::BF16) {
bail!(
"tensor '{}' is {:?}. `frink quantize` reads F32/F16/BF16 sources only: \
re-quantizing an already-quantized tensor stacks a second rounding on \
the first, and the result is worse than quantizing the original \
checkpoint once. Convert from the original weights instead.",
t.name,
t.dtype
);
}
if row_encoder(ty).is_none() {
let why = if unused_kv.is_some() {
format!(
"it belongs to a layer that shares an earlier layer's KV cache \
({arch_name}.attention.shared_kv_layers), and llama-quantize writes \
such a tensor as {ty:?} under every target"
)
} else if ty == recipe::Q4_0_IMATRIX_FFN_DOWN_FIRST_EIGHTH {
"llama-quantize --type Q4_0 with an imatrix writes the first eighth of \
the ffn_down layers as Q4_1"
.to_string()
} else {
format!("the {} mix chooses it", target.name())
};
bail!(
"tensor '{}' would be {ty:?}: {why}. frink has no {ty:?} encoder, so it \
stops rather than write a different type than llama-quantize would.",
t.name
);
}
let (block_bytes, block_elems) = ty.block_layout();
let n_cols = t.shape[0] as usize;
if block_elems == 0 || !n_cols.is_multiple_of(block_elems) {
bail!(
"tensor '{}' has {n_cols} columns, which is not a multiple of {:?}'s \
block size ({block_elems}). {}",
t.name,
ty,
target.fallback_note()
);
}
let n_elements = t.element_count().ok_or_else(|| {
anyhow::anyhow!("tensor '{}' declares an unrepresentable shape", t.name)
})?;
out.push(Planned {
name: t.name.clone(),
shape: t.shape.clone(),
source_dtype: t.dtype,
out_dtype: ty,
source_bytes,
out_bytes: n_elements / block_elems * block_bytes,
copy_reason: None,
});
}
}
}
Ok(out)
}
fn encode_tensor(p: &Planned, src: &[u8], imatrix: Option<&[f32]>) -> Result<Vec<u8>> {
let n_cols = p.shape[0] as usize;
let n_rows = (p.shape.iter().product::<u64>() as usize)
.checked_div(n_cols)
.unwrap_or(0);
let ne1 = p.shape.get(1).copied().unwrap_or(1).max(1) as usize;
let src_row_bytes = source_bytes_per_element(p.source_dtype) * n_cols;
let out_row_bytes = p.out_bytes / n_rows.max(1);
let groups: Vec<Vec<u8>> = (0..n_rows)
.collect::<Vec<_>>()
.par_chunks(ROWS_PER_TASK)
.map(|rows| {
let mut buf = Vec::with_capacity(rows.len() * out_row_bytes);
let mut scratch = vec![0f32; n_cols];
for &r in rows {
let row = &src[r * src_row_bytes..(r + 1) * src_row_bytes];
decode_source_row(p.source_dtype, row, &mut scratch)?;
let qw = imatrix.map(|im| {
let mat = r / ne1;
&im[mat * n_cols..(mat + 1) * n_cols]
});
encode_row(p.out_dtype, &scratch, qw, &mut buf)?.ok_or_else(|| {
anyhow::anyhow!(
"tensor '{}' row length {n_cols} is not a whole number of {:?} blocks",
p.name,
p.out_dtype
)
})?;
}
Ok(buf)
})
.collect::<Result<Vec<Vec<u8>>>>()?;
let mut out = Vec::with_capacity(p.out_bytes);
for g in groups {
out.extend_from_slice(&g);
}
debug_assert_eq!(out.len(), p.out_bytes);
Ok(out)
}
pub(crate) type RowEncoder = fn(&[f32], Option<&[f32]>, &mut Vec<u8>) -> Option<()>;
pub(crate) fn row_encoder(ty: GgmlType) -> Option<RowEncoder> {
let enc: RowEncoder = match ty {
GgmlType::Q8_0 => |row, _qw, out| frink_quant::encode_row_q8_0(row, out),
GgmlType::Q4_0 => frink_quant::encode_row_q4_0,
GgmlType::Q4K => frink_quant::encode_row_q4_k,
GgmlType::Q5K => frink_quant::encode_row_q5_k,
GgmlType::Q6K => frink_quant::encode_row_q6_k,
_ => return None,
};
Some(enc)
}
fn encode_row(
ty: GgmlType,
row: &[f32],
qw: Option<&[f32]>,
out: &mut Vec<u8>,
) -> Result<Option<()>> {
let Some(enc) = row_encoder(ty) else {
bail!(
"the plan chose {ty:?} for a tensor and `frink quantize` has no encoder for it. \
This is a bug in the planner, not in the checkpoint: `plan` refuses an unwritable \
type before any byte is written."
);
};
Ok(enc(row, qw, out))
}
fn source_bytes_per_element(dtype: GgmlType) -> usize {
match dtype {
GgmlType::F32 => 4,
GgmlType::F16 | GgmlType::BF16 => 2,
other => unreachable!("source dtype {other:?} reached the encoder"),
}
}
fn decode_source_row(dtype: GgmlType, row: &[u8], out: &mut [f32]) -> Result<()> {
match dtype {
GgmlType::F32 => {
for (o, c) in out.iter_mut().zip(row.as_chunks::<4>().0) {
*o = f32::from_le_bytes(*c);
}
}
GgmlType::F16 => {
for (o, c) in out.iter_mut().zip(row.as_chunks::<2>().0) {
*o = half::f16::from_le_bytes(*c).to_f32();
}
}
GgmlType::BF16 => {
for (o, c) in out.iter_mut().zip(row.as_chunks::<2>().0) {
*o = f32::from_bits(u32::from(u16::from_le_bytes(*c)) << 16);
}
}
other => bail!("source dtype {other:?} reached the encoder"),
}
Ok(())
}
#[cfg(test)]
mod tests;