hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
//! Logical context admission is independent of the physical FA row stride.
//! Growth copies initialized high waters, not merely the current anchor cursor.
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)
}

/// Both roots have [slots, heads, capacity, inner] layout; only capacity may
/// differ. Every byte offset and extent is checked before reading either root.
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 {
    /// Kernel offsets/strides use this, never the logical admission limit.
    pub(crate) fn full_attn_capacity(&self) -> u32 { self.fa_backing_rows }
    /// Bind the real execution queue before encoding writes. A queue change
    /// drains the previous producer before forgetting its handle. Ordinary
    /// decode only compares queue identities; it clones/allocates nothing.
    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(())
    }


    /// Bind the unchanged aggregate worker grant, never a per-slot fraction.
    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<()> {
        // Normal decode has no allocations, copies, command submissions or drain.
        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<()> {
        // Check original owned statuses, then both allocation and execution
        // queues. These can be distinct MlxDevice::new command queues.
        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)?;

        // Prepare every descriptor and reserve every result container before the
        // first allocation. The old roots, outstanding views and commands remain
        // owners throughout preparation/copy. No root or stride is published yet.
        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())?;
        // Reserve the entire attempt before any fallible allocation or copy.
        // An abandoned attempt remains conservatively charged, with no refund.
        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");
        }
        // Infallible publication only after every allocation and copy succeeds.
        // Dispatch graphs bind the roots afresh each call; no persistent KV view
        // lives in ForwardGpuCache/DecodeBuffers. External old views stay charged
        // by the lifetime ledger, never credited as released here.
        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;