use anyhow::{anyhow, Context, Result};
use mlx_native::MlxBuffer;
use super::{
copy_slot_region_in, copy_slot_region_out, FullAttnKvSlot, HybridKvCache,
HybridKvSlotAnchor, SlotStateLineage,
};
use crate::inference::kv_slot_rows::{read_rows, write_rows, SlotRows};
use crate::serve::multi_seq_kv::SlotId;
#[cfg_attr(test, derive(PartialEq, Eq))]
struct SpilledAttention {
cursor: u32,
rows: Vec<Vec<u8>>,
}
#[cfg_attr(test, derive(PartialEq, Eq))]
struct SpilledLinear {
pp_flipped: bool,
regions: Vec<Vec<u8>>,
}
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct HybridKvSlotSpill {
lineage: SlotStateLineage,
full_attn: Vec<SpilledAttention>,
mtp: Option<SpilledAttention>,
linear_attn: Vec<SpilledLinear>,
graft_len: u32,
}
pub(crate) struct HybridKvSlotSpillRestorePlan<'cache, 'image> {
cache: &'cache mut HybridKvCache,
spill: &'image HybridKvSlotSpill,
slot_idx: usize,
n_seqs: usize,
}
pub(crate) struct HybridKvSlotSpillRestoreReceipt<'cache, 'image> {
cache: &'cache mut HybridKvCache,
spill: &'image HybridKvSlotSpill,
slot: SlotId,
}
impl HybridKvSlotSpillRestoreReceipt<'_, '_> {
pub(crate) fn rebind_anchor(&self, anchor: &mut HybridKvSlotAnchor) -> Result<()> {
self.spill.validate_anchor(anchor)?;
anchor.lineage = self.cache.slot_state_lineage(self.slot)?;
Ok(())
}
}
impl HybridKvSlotSpill {
fn validate_anchor(&self, anchor: &HybridKvSlotAnchor) -> Result<()> {
anyhow::ensure!(anchor.lineage == self.lineage,
"slot spill: carried anchor source lineage differs");
anyhow::ensure!(anchor.graft_len == self.graft_len,
"slot spill: carried anchor graft identity differs");
anyhow::ensure!(
anchor.full_attn_current_len.len() == self.full_attn.len()
&& anchor.full_attn_current_len.iter().zip(&self.full_attn)
.all(|(&saved, block)| saved <= block.cursor),
"slot spill: carried anchor exceeds copied full-attention rows"
);
match (anchor.mtp_current_len, self.mtp.as_ref()) {
(Some(saved), Some(block)) if saved <= block.cursor => {}
(None, None) => {}
_ => anyhow::bail!("slot spill: carried anchor exceeds copied MTP rows"),
}
Ok(())
}
#[cfg(test)]
pub(crate) fn observable_state_eq(&self, other: &Self) -> bool {
self.full_attn == other.full_attn && self.mtp == other.mtp
&& self.linear_attn == other.linear_attn && self.graft_len == other.graft_len
}
pub(crate) fn validate_logical_token_boundary(&self, tokens: usize) -> Result<()> {
let physical = tokens.checked_add(self.graft_len as usize)
.ok_or_else(|| anyhow!("Qwen spill token cursor overflow"))?;
anyhow::ensure!(self.full_attn.iter().all(|block| block.cursor as usize == physical),
"Qwen spill target cursor does not match its retained token boundary");
Ok(())
}
pub fn total_bytes(&self) -> usize {
let attention = self
.full_attn
.iter()
.chain(self.mtp.iter())
.flat_map(|block| block.rows.iter())
.map(Vec::len);
let linear = self
.linear_attn
.iter()
.flat_map(|layer| layer.regions.iter())
.map(Vec::len);
attention.chain(linear).sum::<usize>() + std::mem::size_of::<SlotStateLineage>()
}
}
fn attention_buffers(block: &FullAttnKvSlot) -> Vec<&MlxBuffer> {
let mut buffers = Vec::with_capacity(6);
if let Some(tq) = &block.tq {
buffers.extend([&tq.k_packed, &tq.k_norms, &tq.v_packed, &tq.v_norms]);
}
buffers.extend(block.k.as_ref());
buffers.extend(block.v.as_ref());
buffers
}
fn attention_buffers_mut(block: &mut FullAttnKvSlot) -> Vec<&mut MlxBuffer> {
let mut buffers = Vec::with_capacity(6);
if let Some(tq) = block.tq.as_mut() {
buffers.extend([
&mut tq.k_packed,
&mut tq.k_norms,
&mut tq.v_packed,
&mut tq.v_norms,
]);
}
buffers.extend(block.k.as_mut());
buffers.extend(block.v.as_mut());
buffers
}
const LINEAR_BUFFER_NAMES: [&str; 4] = [
"conv_state",
"conv_state_scratch",
"recurrent",
"recurrent_scratch",
];
fn linear_buffers(layer: &super::LinearAttnStateSlot) -> [&MlxBuffer; 4] {
[
&layer.conv_state,
&layer.conv_state_scratch,
&layer.recurrent,
&layer.recurrent_scratch,
]
}
fn linear_buffers_mut(layer: &mut super::LinearAttnStateSlot) -> [&mut MlxBuffer; 4] {
[
&mut layer.conv_state,
&mut layer.conv_state_scratch,
&mut layer.recurrent,
&mut layer.recurrent_scratch,
]
}
fn block_cursor(block: &FullAttnKvSlot, slot_idx: usize, name: &str) -> Result<u32> {
block
.current_len
.get(slot_idx)
.copied()
.ok_or_else(|| anyhow!("slot spill ({name}): cursor missing for slot {slot_idx}"))
}
fn spill_attention(
block: &FullAttnKvSlot,
slot_idx: usize,
n_seqs: usize,
name: &str,
) -> Result<SpilledAttention> {
let cursor = block_cursor(block, slot_idx, name)?;
let rows = attention_buffers(block)
.into_iter()
.enumerate()
.map(|(index, buffer)| {
read_rows(
buffer,
slot_idx,
n_seqs,
cursor as usize,
&format!("{name} buffer {index}"),
)
})
.collect::<Result<_>>()?;
Ok(SpilledAttention { cursor, rows })
}
fn attention_spill_bytes(
block: &FullAttnKvSlot,
cursor: u32,
n_seqs: usize,
name: &str,
) -> Result<usize> {
attention_buffers(block)
.into_iter()
.map(|buffer| SlotRows::of(buffer, n_seqs, name)?.spilled_len(cursor as usize, name))
.sum()
}
fn validate_attention(
block: &FullAttnKvSlot,
spilled: &SpilledAttention,
slot_idx: usize,
n_seqs: usize,
name: &str,
) -> Result<()> {
block_cursor(block, slot_idx, name)?;
let buffers = attention_buffers(block);
anyhow::ensure!(
buffers.len() == spilled.rows.len(),
"slot spill ({name}): spill holds {} K/V buffers, cache holds {} (TQ/F32 mode mismatch)",
spilled.rows.len(),
buffers.len()
);
for (index, (buffer, rows)) in buffers.into_iter().zip(&spilled.rows).enumerate() {
let expected =
SlotRows::of(buffer, n_seqs, name)?.spilled_len(spilled.cursor as usize, name)?;
anyhow::ensure!(
rows.len() == expected,
"slot spill ({name} buffer {index}): spilled {} bytes, cache geometry needs {expected}",
rows.len()
);
}
Ok(())
}
fn restore_attention(
block: &mut FullAttnKvSlot,
spilled: &SpilledAttention,
slot_idx: usize,
n_seqs: usize,
name: &str,
) -> Result<()> {
for (index, (buffer, rows)) in attention_buffers_mut(block)
.into_iter()
.zip(&spilled.rows)
.enumerate()
{
write_rows(
rows,
buffer,
slot_idx,
n_seqs,
spilled.cursor as usize,
&format!("{name} buffer {index}"),
)?;
}
block.commit_written_rows(slot_idx, spilled.cursor);
block.initialized_len[slot_idx] = spilled.cursor;
Ok(())
}
impl HybridKvCache {
fn validate_spill_anchors<'a>(
&self, slot: SlotId, anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
) -> Result<()> {
for anchor in anchors {
self.validate_slot_anchor_identity(slot, anchor)?;
self.validate_anchor_restore(
slot, anchor.linear_image.as_ref().context("slot spill: anchor image missing")?,
&anchor.full_attn_current_len, anchor.mtp_current_len,
)?;
anyhow::ensure!(
anchor.full_attn_current_len.iter().zip(&self.full_attn)
.all(|(&saved, block)| saved <= block.current_len[slot.0 as usize]),
"slot spill: carried anchor exceeds the proven live full-attention prefix"
);
anyhow::ensure!(
match (anchor.mtp_current_len, self.mtp_slot.as_ref()) {
(Some(saved), Some(block)) => saved <= block.current_len[slot.0 as usize],
(None, None) => true,
_ => false,
},
"slot spill: carried anchor exceeds the proven live MTP prefix"
);
}
Ok(())
}
fn slot_spill_index(&self, slot: SlotId, operation: &str) -> Result<usize> {
let slot_idx = slot.0 as usize;
anyhow::ensure!(
slot_idx < self.n_seqs as usize,
"{operation}: slot {} outside n_seqs={}",
slot.0,
self.n_seqs
);
anyhow::ensure!(
!self.la_capture_active(),
"{operation}: DeltaNet capture is active; a slot can only move between transactions"
);
Ok(slot_idx)
}
#[cfg(test)]
pub(crate) fn slot_spill_bytes(&self, slot: SlotId) -> Result<usize> {
self.slot_spill_bytes_with_anchors(slot, std::iter::empty())
}
pub(crate) fn slot_spill_bytes_with_anchors<'a>(
&self, slot: SlotId,
anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
) -> Result<usize> {
let slot_idx = self.slot_spill_index(slot, "slot_spill_bytes")?;
let n_seqs = self.n_seqs as usize;
self.validate_spill_anchors(slot, anchors)?;
let mut total = std::mem::size_of::<SlotStateLineage>();
for (layer, block) in self.full_attn.iter().enumerate() {
let cursor = block_cursor(block, slot_idx, "slot_spill_bytes")?;
total += attention_spill_bytes(
block, cursor, n_seqs, &format!("full_attn[{layer}]"))?;
}
if let Some(mtp) = &self.mtp_slot {
let cursor = block_cursor(mtp, slot_idx, "slot_spill_bytes MTP")?;
total += attention_spill_bytes(mtp, cursor, n_seqs, "mtp")?;
}
for (layer, linear) in self.linear_attn.iter().enumerate() {
for (buffer, name) in linear_buffers(linear).into_iter().zip(LINEAR_BUFFER_NAMES) {
anyhow::ensure!(
buffer.byte_len() % n_seqs == 0,
"slot_spill_bytes: linear_attn[{layer}].{name} is not split by slot"
);
total += buffer.byte_len() / n_seqs;
}
}
Ok(total)
}
#[cfg(test)]
pub(crate) fn spill_slot(&self, slot: SlotId) -> Result<HybridKvSlotSpill> {
self.spill_slot_with_anchors(slot, std::iter::empty())
}
pub(crate) fn spill_slot_with_anchors<'a>(
&self, slot: SlotId,
anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
) -> Result<HybridKvSlotSpill> {
let slot_idx = self.slot_spill_index(slot, "spill_slot")?;
let n_seqs = self.n_seqs as usize;
self.validate_spill_anchors(slot, anchors)?;
let full_attn = self
.full_attn
.iter()
.enumerate()
.map(|(layer, block)| {
spill_attention(block, slot_idx, n_seqs, &format!("full_attn[{layer}]"))
})
.collect::<Result<_>>()?;
let mtp = self
.mtp_slot
.as_ref()
.map(|mtp| {
spill_attention(mtp, slot_idx, n_seqs, "mtp")
})
.transpose()?;
let linear_attn = self
.linear_attn
.iter()
.enumerate()
.map(|(layer, linear)| {
let pp_flipped = *linear.pp_flipped.get(slot_idx).ok_or_else(|| {
anyhow!("spill_slot: linear_attn[{layer}] parity missing for slot {slot_idx}")
})?;
let regions = linear_buffers(linear)
.into_iter()
.zip(LINEAR_BUFFER_NAMES)
.map(|(buffer, name)| {
copy_slot_region_out(
buffer,
slot_idx,
n_seqs,
&format!("linear_attn[{layer}].{name}"),
)
})
.collect::<Result<_>>()?;
Ok(SpilledLinear {
pp_flipped,
regions,
})
})
.collect::<Result<_>>()?;
let graft_len = *self
.graft_len
.get(slot_idx)
.ok_or_else(|| anyhow!("spill_slot: graft length missing for slot {slot_idx}"))?;
Ok(HybridKvSlotSpill {
lineage: self.slot_state_lineage(slot)?,
full_attn,
mtp,
linear_attn,
graft_len,
})
}
#[cfg(test)]
pub(crate) fn restore_slot_spill(
&mut self, slot: SlotId, spill: &HybridKvSlotSpill,
) -> Result<()> {
self.plan_slot_spill_restore(slot, spill)?.apply().map(|_| ())
}
pub(crate) fn plan_slot_spill_restore<'cache, 'image>(
&'cache mut self,
slot: SlotId,
spill: &'image HybridKvSlotSpill,
) -> Result<HybridKvSlotSpillRestorePlan<'cache, 'image>> {
let slot_idx = self.slot_spill_index(slot, "restore_slot_spill")?;
let n_seqs = self.n_seqs as usize;
let required = spill.full_attn.iter().chain(spill.mtp.iter())
.map(|block| block.cursor).max().unwrap_or(0);
self.ensure_fa_backing(required as usize)?;
anyhow::ensure!(
spill.full_attn.len() == self.full_attn.len(),
"restore_slot_spill: spill holds {} full-attention layers, cache holds {}",
spill.full_attn.len(),
self.full_attn.len()
);
anyhow::ensure!(
spill.linear_attn.len() == self.linear_attn.len(),
"restore_slot_spill: spill holds {} DeltaNet layers, cache holds {}",
spill.linear_attn.len(),
self.linear_attn.len()
);
for (layer, (block, spilled)) in self.full_attn.iter().zip(&spill.full_attn).enumerate() {
validate_attention(
block,
spilled,
slot_idx,
n_seqs,
&format!("full_attn[{layer}]"),
)?;
}
match (self.mtp_slot.as_ref(), spill.mtp.as_ref()) {
(Some(mtp), Some(spilled)) => {
validate_attention(mtp, spilled, slot_idx, n_seqs, "mtp")?
}
(None, None) => {}
_ => anyhow::bail!("restore_slot_spill: MTP presence differs between spill and cache"),
}
for (layer, (linear, spilled)) in
self.linear_attn.iter().zip(&spill.linear_attn).enumerate()
{
anyhow::ensure!(
slot_idx < linear.pp_flipped.len(),
"restore_slot_spill: linear_attn[{layer}] parity missing for slot {slot_idx}"
);
anyhow::ensure!(
spilled.regions.len() == LINEAR_BUFFER_NAMES.len(),
"restore_slot_spill: linear_attn[{layer}] spill holds {} regions",
spilled.regions.len()
);
for ((buffer, name), region) in linear_buffers(linear)
.into_iter()
.zip(LINEAR_BUFFER_NAMES)
.zip(&spilled.regions)
{
anyhow::ensure!(
buffer.byte_len() % n_seqs == 0 && region.len() == buffer.byte_len() / n_seqs,
"restore_slot_spill: linear_attn[{layer}].{name} spilled {} bytes, slot region is {}",
region.len(),
buffer.byte_len() / n_seqs
);
}
}
anyhow::ensure!(
slot_idx < self.graft_len.len(),
"restore_slot_spill: graft length missing for slot {slot_idx}"
);
Ok(HybridKvSlotSpillRestorePlan { cache: self, spill, slot_idx, n_seqs })
}
}
impl<'cache, 'image> HybridKvSlotSpillRestorePlan<'cache, 'image> {
pub(crate) fn validate_anchor(&self, anchor: &HybridKvSlotAnchor) -> Result<()> {
self.spill.validate_anchor(anchor)?;
anchor.linear_image.as_ref().context("slot spill: anchor image missing")?
.validate_cache_layout(self.cache)
}
pub(crate) fn apply(self) -> Result<HybridKvSlotSpillRestoreReceipt<'cache, 'image>> {
let Self { cache, spill, slot_idx, n_seqs } = self;
cache.advance_slot_state_generation(slot_idx);
for (layer, (block, spilled)) in cache.full_attn.iter_mut().zip(&spill.full_attn).enumerate()
{
restore_attention(
block,
spilled,
slot_idx,
n_seqs,
&format!("full_attn[{layer}]"),
)?;
}
if let (Some(mtp), Some(spilled)) = (cache.mtp_slot.as_mut(), spill.mtp.as_ref()) {
restore_attention(mtp, spilled, slot_idx, n_seqs, "mtp")?;
}
for (layer, (linear, spilled)) in cache
.linear_attn
.iter_mut()
.zip(&spill.linear_attn)
.enumerate()
{
for ((buffer, name), region) in linear_buffers_mut(linear)
.into_iter()
.zip(LINEAR_BUFFER_NAMES)
.zip(&spilled.regions)
{
copy_slot_region_in(
region,
buffer,
slot_idx,
n_seqs,
&format!("linear_attn[{layer}].{name}"),
)?;
}
linear.pp_flipped[slot_idx] = spilled.pp_flipped;
}
cache.graft_len[slot_idx] = spill.graft_len;
Ok(HybridKvSlotSpillRestoreReceipt { cache, spill, slot: SlotId(slot_idx as u32) })
}
}
#[cfg(test)]
#[path = "slot_spill_tests.rs"]
mod tests;