use std::path::Path;
use anyhow::{bail, Context, Result};
use mlx_native::gguf::{GgufFile, MetadataValue};
use crate::inference::glp::{CheckpointIdentity, Compatibility};
use super::reader::{GraftBank, GraftHookPoint};
fn f32_to_bf16_bits(value: f32) -> u16 {
let bits = value.to_bits();
let rounded = bits + 0x7FFF + ((bits >> 16) & 1);
(rounded >> 16) as u16
}
fn is_bf16_representable(value: f32) -> bool {
if !value.is_finite() {
return false;
}
let bits = f32_to_bf16_bits(value);
f32::from_bits(u32::from(bits) << 16).to_bits() == value.to_bits()
}
#[derive(Debug, Clone, PartialEq)]
pub struct CompressedKvShape {
pub arch: String,
pub compress_ratios: Vec<u32>,
pub covered_layers: Vec<u32>,
pub n_kv_heads: u32,
pub head_dim: u32,
pub rope_theta: f32,
pub rotary_dim: u32,
pub context_length: u32,
}
impl CompressedKvShape {
pub fn from_gguf(gguf: &GgufFile) -> Result<Self> {
let arch = gguf
.metadata_string("general.architecture")
.ok_or_else(|| anyhow::anyhow!("model GGUF missing 'general.architecture'"))?
.to_owned();
if arch != "deepseek4" {
bail!(
"graft bind: architecture {arch:?} does not expose the \
compressed_kv graft site in this build (the site is \
DeepSeek-V4 only, ADR-059); refusing to bind"
);
}
let cfg = crate::inference::models::deepseek4::Deepseek4Config::from_gguf(gguf)
.context("graft bind: DeepSeek-V4 model config")?;
let covered_layers: Vec<u32> = cfg
.compress_ratios
.iter()
.enumerate()
.filter(|(_, ratio)| **ratio != 0)
.map(|(layer, _)| layer as u32)
.collect();
anyhow::ensure!(
!covered_layers.is_empty(),
"graft bind: deepseek4 model exposes no compressed layers \
(compress_ratios are all zero); the compressed_kv site has no \
cache medium on this model"
);
Ok(Self {
arch,
compress_ratios: cfg.compress_ratios.clone(),
covered_layers,
n_kv_heads: cfg.num_key_value_heads,
head_dim: cfg.head_dim,
rope_theta: cfg.compress_rope_theta,
rotary_dim: cfg.rope_head_dim,
context_length: cfg.max_position_embeddings,
})
}
}
pub fn validate_compressed_kv_bank_for_model(
bank: &GraftBank,
model: &CompressedKvShape,
) -> Result<()> {
let bank_ratios = bank.compress_ratios.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"graft bind: graft.compress_ratios missing; the compressed_kv \
site requires the per-layer compression schedule parallel to \
the model's"
)
})?;
if bank_ratios.len() != model.compress_ratios.len()
|| bank_ratios
.iter()
.zip(model.compress_ratios.iter())
.any(|(b, m)| b != m)
{
bail!(
"graft bind: graft.compress_ratios [{}] does not match the model's \
per-layer schedule [{}] on {} — the compressed_kv splice reserves \
the leading rows of every covered layer; a divergent schedule is \
a wrong-checkpoint bank",
bank_ratios
.iter()
.map(|r| r.to_string())
.collect::<Vec<_>>()
.join(","),
model
.compress_ratios
.iter()
.map(|r| r.to_string())
.collect::<Vec<_>>()
.join(","),
model.arch
);
}
if bank.n_slots == 0 {
return Ok(());
}
let offenders: Vec<String> = bank
.layers
.keys()
.filter(|layer| {
model
.compress_ratios
.get(**layer as usize)
.is_none_or(|ratio| *ratio == 0)
})
.map(|layer| layer.to_string())
.collect();
if !offenders.is_empty() {
bail!(
"graft bind: bank covers layer(s) [{}] with compress_ratios[layer]==0 \
on {} — those layers own no compressed region (no long-range \
history); the compressed_kv site splices only covered \
(ratio != 0) layers",
offenders.join(", "),
model.arch
);
}
let missing: Vec<String> = model
.covered_layers
.iter()
.filter(|l| !bank.layers.contains_key(l))
.map(|l| l.to_string())
.collect();
if !missing.is_empty() {
bail!(
"graft bind: bank does not cover compressed layer(s) [{}] on {} \
— the compressed_kv site requires complete coverage of every \
covered (ratio != 0) layer (partial-coverage banks are not a \
defined v1 artifact)",
missing.join(", "),
model.arch
);
}
if bank.n_kv_heads != model.n_kv_heads as usize {
bail!(
"graft bind: bank n_kv_heads {} does not match model {}",
bank.n_kv_heads,
model.n_kv_heads
);
}
if model.n_kv_heads != 1 {
bail!(
"graft bind: deepseek4 reports {} KV heads; the compressed_kv \
site is shared-KV MQA (one K==V series) and binds only 1",
model.n_kv_heads
);
}
if bank.head_dim != model.head_dim as usize {
bail!(
"graft bind: bank head_dim {} does not match model {}",
bank.head_dim,
model.head_dim
);
}
let theta_delta = (bank.rope_theta - model.rope_theta).abs();
let theta_scale = bank
.rope_theta
.abs()
.max(model.rope_theta.abs())
.max(f32::EPSILON);
if !(theta_delta <= 1e-6 * theta_scale) {
bail!(
"graft bind: bank rope_theta {} does not match the model's \
compress rope theta {} (checkpoint identity of the \
compressed_kv site)",
bank.rope_theta,
model.rope_theta
);
}
if bank.rotary_dim != model.rotary_dim {
bail!(
"graft bind: bank rotary_dim {} does not match the model's rope \
head dim {} (checkpoint identity of the compressed_kv site)",
bank.rotary_dim,
model.rotary_dim
);
}
let binding_capacity = model
.compress_ratios
.iter()
.zip(model.covered_layers.iter())
.filter(|(ratio, _)| **ratio != 0)
.map(|(ratio, _)| model.context_length / *ratio)
.min()
.unwrap_or(0);
if bank.n_slots as u64 > binding_capacity as u64 {
bail!(
"graft bind: graft n_slots {} exceeds the compressed-region \
capacity {} rows (context {}/max covered ratio) — the graft \
reserves leading rows the real history must not overwrite",
bank.n_slots,
binding_capacity,
model.context_length
);
}
for (layer, kv) in &bank.layers {
for value in kv.k.iter().chain(kv.v.iter()) {
if !is_bf16_representable(*value) {
bail!(
"graft bind: layer {layer} bank value {value} is not \
bf16-representable — the compressed_kv splice encodes \
through the cache's BF16 rows; export bf16-rounded \
values (the #309 to-gguf contract) or the splice is lossy"
);
}
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq)]
pub struct GraftModelShape {
pub arch: String,
pub full_attn_layers: Vec<u32>,
pub n_kv_heads: u32,
pub head_dim: u32,
pub rope_theta: f32,
pub rotary_dim: u32,
pub mrope_interleaved: bool,
}
impl GraftModelShape {
pub fn from_gguf(gguf: &GgufFile) -> Result<Self> {
let arch = gguf
.metadata_string("general.architecture")
.ok_or_else(|| anyhow::anyhow!("model GGUF missing 'general.architecture'"))?
.to_owned();
match arch.as_str() {
"qwen35" | "qwen35moe" => {
let required_u32 = |key: &str| -> Result<u32> {
gguf.metadata_u32(key).with_context(|| {
format!("graft bind: model GGUF missing required key '{key}'")
})
};
let block_count = required_u32(&format!("{arch}.block_count"))?;
let interval = required_u32(&format!("{arch}.full_attention_interval"))?;
let full_attn_layers: Vec<u32> = if interval == 0 {
Vec::new()
} else {
(0..block_count)
.filter(|i| (i + 1) % interval == 0)
.collect()
};
if full_attn_layers.is_empty() {
bail!(
"graft bind: {arch} model exposes no full-attention layers \
(full_attention_interval={interval}); the full_attn_kv site \
has no cache medium on this model"
);
}
Ok(Self {
n_kv_heads: required_u32(&format!("{arch}.attention.head_count_kv"))?,
head_dim: required_u32(&format!("{arch}.attention.key_length"))?,
rope_theta: gguf
.metadata_f32(&format!("{arch}.rope.freq_base"))
.with_context(|| {
format!("graft bind: model GGUF missing '{arch}.rope.freq_base'")
})?,
rotary_dim: required_u32(&format!("{arch}.rope.dimension_count"))?,
mrope_interleaved: true,
arch,
full_attn_layers,
})
}
"gemma4" => {
let required_u32 = |key: &str| -> Result<u32> {
gguf.metadata_u32(key).with_context(|| {
format!("graft bind: model GGUF missing required key '{key}'")
})
};
let block_count = required_u32("gemma4.block_count")?;
let full_attn_layers: Vec<u32> = match gguf
.metadata("gemma4.attention.sliding_window_pattern")
{
Some(MetadataValue::Array(arr)) => {
let pattern: Vec<bool> = arr
.iter()
.filter_map(|v| match v {
MetadataValue::Bool(b) => Some(*b),
_ => None,
})
.collect();
anyhow::ensure!(
pattern.len() == block_count as usize,
"graft bind: gemma4.attention.sliding_window_pattern length {} \
!= block_count {}",
pattern.len(),
block_count
);
(0..block_count)
.filter(|i| !pattern[*i as usize])
.collect()
}
_ => (0..block_count).filter(|i| (i + 1) % 6 == 0).collect(),
};
anyhow::ensure!(
!full_attn_layers.is_empty(),
"graft bind: gemma4 model exposes no full-attention layers; the \
full_attn_kv site has no cache medium on this model"
);
let head_count_kv: Vec<u32> = match gguf
.metadata("gemma4.attention.head_count_kv")
{
Some(MetadataValue::Array(arr)) => {
arr.iter().filter_map(|v| v.as_u32()).collect()
}
Some(other) => bail!(
"graft bind: gemma4.attention.head_count_kv has unexpected \
type {:?}",
std::mem::discriminant(other)
),
None => bail!("graft bind: gemma4.attention.head_count_kv missing"),
};
anyhow::ensure!(
head_count_kv.len() == block_count as usize,
"graft bind: gemma4.attention.head_count_kv length {} != block_count {}",
head_count_kv.len(),
block_count
);
let first_full = full_attn_layers[0] as usize;
let n_kv_heads = head_count_kv[first_full];
anyhow::ensure!(
n_kv_heads > 0,
"graft bind: gemma4 full-attention layer {} reports 0 KV heads",
first_full
);
Ok(Self {
n_kv_heads,
head_dim: required_u32("gemma4.attention.key_length")?,
rope_theta: gguf
.metadata_f32("gemma4.rope.freq_base")
.with_context(|| {
"graft bind: model GGUF missing 'gemma4.rope.freq_base'"
})?,
rotary_dim: required_u32("gemma4.rope.dimension_count")?,
mrope_interleaved: false,
arch,
full_attn_layers,
})
}
other => bail!(
"graft bind: architecture {other:?} does not expose the \
full_attn_kv graft site in this build (staged per ADR-059); \
refusing to bind"
),
}
}
}
pub fn validate_graft_bank_for_model(bank: &GraftBank, model: &GraftModelShape) -> Result<()> {
if bank.hook_point != GraftHookPoint::FullAttnKv {
bail!(
"graft bind: site {:?} is not the full_attn_kv site; this bind \
validates full_attn_kv banks on {} (the compressed_kv site \
validates through CompressedKvShape)",
bank.hook_point.as_str(),
model.arch
);
}
if bank.position_base != 0 {
bail!(
"graft bind: graft.position_base {} is unsupported; the v1 \
splice_prefix contract occupies positions 0..n_slots",
bank.position_base
);
}
if bank.n_slots == 0 {
return Ok(());
}
let offenders: Vec<String> = bank
.layers
.keys()
.filter(|layer| !model.full_attn_layers.contains(layer))
.map(|layer| layer.to_string())
.collect();
if !offenders.is_empty() {
bail!(
"graft bind: bank covers non-full-attention layer(s) [{}] on {} \
(full-attention layers: [{}]); the full_attn_kv site only splices \
full-attention-layer caches",
offenders.join(", "),
model.arch,
model
.full_attn_layers
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>()
.join(", ")
);
}
let missing: Vec<String> = model
.full_attn_layers
.iter()
.filter(|l| !bank.layers.contains_key(l))
.map(|l| l.to_string())
.collect();
if !missing.is_empty() {
bail!(
"graft bind: bank does not cover full-attention layer(s) [{}] on {} \
— the full_attn_kv site requires complete coverage of every \
full-attention layer (partial-coverage banks are not a defined \
v1 artifact)",
missing.join(", "),
model.arch
);
}
if bank.n_kv_heads != model.n_kv_heads as usize {
bail!(
"graft bind: bank n_kv_heads {} does not match model {}",
bank.n_kv_heads, model.n_kv_heads
);
}
if bank.head_dim != model.head_dim as usize {
bail!(
"graft bind: bank head_dim {} does not match model {}",
bank.head_dim, model.head_dim
);
}
let theta_delta = (bank.rope_theta - model.rope_theta).abs();
let theta_scale = bank.rope_theta.abs().max(model.rope_theta.abs()).max(f32::EPSILON);
if !(theta_delta <= 1e-6 * theta_scale) {
bail!(
"graft bind: bank rope_theta {} does not match model {}",
bank.rope_theta, model.rope_theta
);
}
if bank.rotary_dim != model.rotary_dim {
bail!(
"graft bind: bank rotary_dim {} does not match model {}",
bank.rotary_dim, model.rotary_dim
);
}
if bank.mrope_interleaved != model.mrope_interleaved {
bail!(
"graft bind: bank mrope_interleaved {} does not match model {}",
bank.mrope_interleaved, model.mrope_interleaved
);
}
Ok(())
}
pub fn validate_graft_for_model(
graft_path: &Path,
model_path: &Path,
model: &GgufFile,
) -> Result<(GraftBank, Compatibility)> {
let bank = GraftBank::load(graft_path).context("load graft bank")?;
let graft_gguf = GgufFile::open(graft_path).context("open graft GGUF metadata")?;
let compatibility = CheckpointIdentity::from_gguf(&graft_gguf)?
.validate_for(&CheckpointIdentity::for_model_path(model_path, model)?)?;
match bank.hook_point {
GraftHookPoint::FullAttnKv => {
let shape = GraftModelShape::from_gguf(model)?;
validate_graft_bank_for_model(&bank, &shape)?;
}
GraftHookPoint::CompressedKv => {
let shape = CompressedKvShape::from_gguf(model)?;
validate_compressed_kv_bank_for_model(&bank, &shape)?;
}
staged => bail!(
"graft bind: site {:?} is a staged site with no family in this \
build (ADR-059 site matrix); refusing to bind",
staged.as_str()
),
}
Ok((bank, compatibility))
}
#[cfg(test)]
#[path = "compatibility_tests.rs"]
mod tests;