use super::*;
use super::allocation_plan::{product, BufferPlan, Init};
use mlx_native::metal::foreign_types::ForeignType;
pub(super) const INITIAL_ROWS: u32 = 16_384;
pub(super) fn initial_rows(logical: u32) -> u32 { logical.min(INITIAL_ROWS) }
#[cfg(test)]
thread_local! {
static FAIL_BEFORE_PUBLICATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn next_rows(current: u32, logical: u32, required: usize) -> Result<u32> {
anyhow::ensure!(required <= logical as usize, "FA backing request {required} exceeds logical context {logical}");
anyhow::ensure!(current > 0 && current <= logical, "invalid FA backing capacity {current}/{logical}");
let mut next = current;
while (next as usize) < required {
next = next.checked_mul(4).unwrap_or(logical).min(logical);
}
Ok(next)
}
pub(super) fn copy_rows(src: &MlxBuffer, dst: &mut MlxBuffer, rows: &[u32]) -> Result<()> {
let s = src.shape();
let d = dst.shape();
anyhow::ensure!(s.len() == 4 && d.len() == 4 && s[0] == rows.len()
&& s[0] == d[0] && s[1] == d[1] && s[3] == d[3] && src.dtype() == dst.dtype(),
"FA backing copy geometry mismatch");
let row_bytes = product(&[s[3], src.dtype().size_of()])?;
let src_head = product(&[s[2], row_bytes])?;
let dst_head = product(&[d[2], row_bytes])?;
let src_slot = product(&[s[1], src_head])?;
let dst_slot = product(&[d[1], dst_head])?;
anyhow::ensure!(product(&[s[0], src_slot])? == src.byte_len()
&& product(&[d[0], dst_slot])? == dst.byte_len(), "FA backing copy byte extent mismatch");
anyhow::ensure!(rows.iter().all(|&r| r as usize <= s[2] && r as usize <= d[2]),
"FA initialized rows exceed backing capacity");
let heads = s[1];
let source = src.as_slice::<u8>().context("FA backing copy source")?;
let destination = dst.as_mut_slice::<u8>().context("FA backing copy destination")?;
for (slot, &rows) in rows.iter().enumerate() {
let bytes = rows as usize * row_bytes;
for head in 0..heads {
let from = slot * src_slot + head * src_head;
let to = slot * dst_slot + head * dst_head;
destination[to..to + bytes].copy_from_slice(&source[from..from + bytes]);
}
}
Ok(())
}
fn roots(slot: &FullAttnKvSlot) -> impl Iterator<Item = &MlxBuffer> + Clone {
let roots = if let Some(tq) = &slot.tq {
[Some(&tq.k_packed), Some(&tq.k_norms), Some(&tq.v_packed), Some(&tq.v_norms)]
} else {
[slot.k.as_ref(), slot.v.as_ref(), None, None]
};
roots.into_iter().flatten()
}
fn drain_queue(device: &MlxDevice) -> Result<()> {
device.command_encoder().context("FA growth drain encoder")
.and_then(|mut encoder| encoder.commit_and_wait_labeled("qwen35.fa_backing.growth_drain")
.context("FA growth queue drain"))
}
impl HybridKvCache {
pub(crate) fn full_attn_capacity(&self) -> u32 { self.fa_backing_rows }
pub(crate) fn bind_fa_producer(&mut self, device: &MlxDevice) -> Result<()> {
if let Some(previous) = &self.fa_producer_device {
if previous.metal_queue().as_ptr() == device.metal_queue().as_ptr() {
return Ok(());
}
let settled = super::super::encoder_stage::settle_submitted()
.context("FA queue change original producer drain");
let drained = drain_queue(previous);
settled.and(drained)?;
}
self.fa_producer_device = Some(device.clone());
Ok(())
}
pub(crate) fn set_fa_allocation_budget(&mut self, bytes: u64) -> Result<()> {
let budget = if bytes == 0 { None } else { Some(usize::try_from(bytes)?) };
if let Some(limit) = budget {
anyhow::ensure!(self.fa_allocation_charge <= limit,
"initial cache requested charge exceeds KV grant");
}
self.fa_allocation_budget = budget;
Ok(())
}
pub(crate) fn fa_append_requirement(
&self, slot: crate::serve::multi_seq_kv::SlotId, rows: usize, mtp: bool,
) -> Result<usize> {
anyhow::ensure!(slot.0 < self.n_seqs, "FA append slot {} outside {}", slot.0, self.n_seqs);
let current = if mtp {
*self.mtp_slot.as_ref().context("MTP append requires MTP cache")?
.current_len.get(slot.0 as usize).context("MTP append cursor missing")?
} else {
self.full_attn.first().map_or(0, |layer| layer.current_len[slot.0 as usize])
};
let required = (current as usize).checked_add(rows).context("FA append length overflow")?;
anyhow::ensure!(required <= self.max_seq_len as usize,
"FA append {required} exceeds logical context {}", self.max_seq_len);
Ok(required)
}
pub(crate) fn ensure_fa_append(
&mut self, slot: crate::serve::multi_seq_kv::SlotId, rows: usize, mtp: bool,
) -> Result<()> {
let required = self.fa_append_requirement(slot, rows, mtp)?;
self.ensure_fa_backing(required)
}
pub(crate) fn ensure_fa_backing(&mut self, required: usize) -> Result<()> {
let next = next_rows(self.fa_backing_rows, self.max_seq_len, required)?;
if next == self.fa_backing_rows { return Ok(()); }
let device = self.device.clone();
self.grow_fa_backing(next, |plan| plan.allocate(&device))
}
fn grow_fa_backing(
&mut self, next: u32, mut allocate: impl FnMut(&BufferPlan) -> Result<MlxBuffer>,
) -> Result<()> {
let settled = super::super::encoder_stage::settle_submitted()
.context("FA growth original producer drain");
let drained = drain_queue(&self.device);
let producer = match &self.fa_producer_device {
Some(device) if device.metal_queue().as_ptr() != self.device.metal_queue().as_ptr() =>
drain_queue(device),
_ => Ok(()),
};
settled.and(drained).and(producer)?;
let slots = self.full_attn.iter().chain(self.mtp_slot.iter());
let mut plans = Vec::new();
plans.try_reserve_exact(self.full_attn.len() + usize::from(self.mtp_slot.is_some()))?;
let mut new_bytes = 0usize;
for slot in slots {
let mut descriptors = Vec::new();
descriptors.try_reserve_exact(if slot.tq.is_some() {
4
} else {
usize::from(slot.k.is_some()) + usize::from(slot.v.is_some())
})?;
for root in roots(slot) {
anyhow::ensure!(root.shape().len() == 4 && root.shape()[2] == self.fa_backing_rows as usize,
"FA growth old root stride mismatch");
let mut shape = root.shape().to_vec();
shape[2] = next as usize;
let plan = BufferPlan::new("grow full-attention backing", root.dtype(), shape, Init::Overwrite)?;
new_bytes = new_bytes.checked_add(plan.bytes).context("FA growth aggregate overflow")?;
descriptors.push(plan);
}
plans.push(descriptors);
}
let overlap_charge = self.fa_allocation_charge.checked_add(new_bytes)
.context("FA growth lifetime allocation charge overflow")?;
if let Some(budget) = self.fa_allocation_budget {
anyhow::ensure!(overlap_charge <= budget,
"FA growth lifetime requested charge {overlap_charge} exceeds unchanged KV grant {budget}");
}
let mut replacements = Vec::new();
replacements.try_reserve_exact(plans.len())?;
self.fa_allocation_charge = overlap_charge;
for plan in &plans {
let mut values = Vec::new();
values.try_reserve_exact(plan.len())?;
replacements.push(values);
}
for (plan, values) in plans.iter().zip(&mut replacements) {
for descriptor in plan {
values.push(allocate(descriptor)?);
}
}
for (slot, replacement) in self.full_attn.iter().chain(self.mtp_slot.iter())
.zip(&mut replacements) {
for (old, new) in roots(slot).into_iter().zip(replacement) {
copy_rows(old, new, &slot.initialized_len)?;
}
}
#[cfg(test)]
if FAIL_BEFORE_PUBLICATION.with(|point| point.replace(false)) {
anyhow::bail!("injected FA growth failure after copies before publication");
}
for (slot, replacement) in self.full_attn.iter_mut().chain(self.mtp_slot.iter_mut())
.zip(replacements) {
let mut replacement = replacement.into_iter();
if let Some(tq) = slot.tq.as_mut() {
tq.k_packed = replacement.next().unwrap();
tq.k_norms = replacement.next().unwrap();
tq.v_packed = replacement.next().unwrap();
tq.v_norms = replacement.next().unwrap();
} else {
slot.k = replacement.next();
slot.v = replacement.next();
}
}
self.fa_backing_rows = next;
tracing::info!(backing_rows = next, logical_rows = self.max_seq_len,
requested_lifetime_charge_bytes = overlap_charge,
"Qwen FA backing materialized; requested charge is not measured residency");
Ok(())
}
}
#[cfg(test)]
#[path = "demand_backing_tests.rs"]
mod tests;