use super::*;
use crate::inference::kv_slot_rows::read_rows;
use crate::inference::models::qwen35::joint_verify_tests::{synthetic_cfg, synthetic_model, padded_policy};
use crate::inference::models::qwen35::gpu_full_attn::{upload_f32, download_f32};
use crate::inference::models::qwen35::spec_decode::positions_for_range;
use crate::serve::multi_seq_kv::SlotId;
fn allocation_cfg() -> Qwen35Config {
let mut cfg = synthetic_cfg();
cfg.num_hidden_layers = 2;
cfg.layer_types = vec![Qwen35LayerKind::FullAttention, Qwen35LayerKind::LinearAttention];
cfg.num_key_value_heads = 4;
cfg.head_dim = 1;
cfg.mtp_num_hidden_layers = 1;
cfg
}
fn root_ids(cache: &HybridKvCache) -> Vec<usize> {
cache.full_attn.iter().chain(cache.mtp_slot.iter()).flat_map(roots)
.map(|buffer| buffer.as_slice::<u8>().unwrap().as_ptr() as usize).collect()
}
fn rows(cache: &HybridKvCache, lengths: &[[u32; 4]]) -> Vec<Vec<u8>> {
cache.full_attn.iter().chain(cache.mtp_slot.iter()).zip(lengths)
.flat_map(|(block, lengths)| roots(block).into_iter().flat_map(move |buffer| {
lengths.iter().enumerate().map(move |(slot, &length)| {
read_rows(buffer, slot, 4, length as usize, "demand backing regression").unwrap()
})
})).collect()
}
fn plant(cache: &mut HybridKvCache, lengths: &[[u32; 4]]) {
for (layer, (block, lengths)) in cache.full_attn.iter_mut().chain(cache.mtp_slot.iter_mut())
.zip(lengths).enumerate() {
let mut buffers = Vec::new();
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());
for (root, buffer) in buffers.into_iter().enumerate() {
let shape = buffer.shape();
let (heads, capacity, inner) = (shape[1], shape[2], shape[3]);
let row_bytes = inner * buffer.dtype().size_of();
let bytes = buffer.as_mut_slice::<u8>().unwrap();
for (slot, &length) in lengths.iter().enumerate() {
for head in 0..heads {
let start = (slot * heads + head) * capacity * row_bytes;
for (offset, byte) in bytes[start..start + length as usize * row_bytes].iter_mut().enumerate() {
*byte = ((layer * 37 + root * 19 + slot * 43 + head * 11 + offset) % 251) as u8;
}
}
}
}
block.current_len.copy_from_slice(lengths);
block.initialized_len.copy_from_slice(lengths);
}
}
fn snapshot_bytes(snapshot: &HybridKvCacheSnapshot) -> Vec<Vec<u8>> {
let mut buffers: Vec<&MlxBuffer> = snapshot.full_attn_k.iter().flatten()
.chain(snapshot.full_attn_v.iter().flatten()).collect();
for tq in snapshot.full_attn_tq.iter().flatten() {
buffers.extend([&tq.k_packed, &tq.k_norms, &tq.v_packed, &tq.v_norms]);
}
if let Some(mtp) = &snapshot.mtp {
buffers.extend(mtp.k.iter()); buffers.extend(mtp.v.iter());
if let Some(tq) = &mtp.tq { buffers.extend([&tq.k_packed, &tq.k_norms, &tq.v_packed, &tq.v_norms]); }
}
buffers.extend(&snapshot.linear_conv); buffers.extend(&snapshot.linear_recurrent);
buffers.into_iter().map(|buffer| buffer.as_slice::<u8>().unwrap().to_vec()).collect()
}
#[test]
fn demand_backing_growth_math_and_overflow_preserve_full_logical_capacity() {
assert_eq!(initial_rows(0), 0);
assert_eq!(initial_rows(17), 17);
assert_eq!(initial_rows(262144), 16384);
assert_eq!(next_rows(16384, 262144, 16384).unwrap(), 16384);
assert_eq!(next_rows(16384, 262144, 16385).unwrap(), 65536);
assert_eq!(next_rows(65536, 262144, 65537).unwrap(), 262144);
assert_eq!(next_rows(16384, 20000, 16385).unwrap(), 20000);
assert_eq!(next_rows(u32::MAX / 2, u32::MAX, u32::MAX as usize).unwrap(), u32::MAX);
assert!(next_rows(16384, 262144, usize::MAX).is_err());
assert!(next_rows(0, 262144, 1).is_err());
assert!(BufferPlan::new("overflow", DType::F32, vec![usize::MAX, 2], Init::Overwrite).is_err());
}
#[test]
fn demand_backing_four_slots_heads_retained_anchors_mtp_and_snapshots_are_byte_exact() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
for tq in [false, true] {
let mut cache = HybridKvCache::new_with_options(&allocation_cfg(), &device, 262144, 4, tq).unwrap();
assert_eq!((cache.max_seq_len, cache.n_seqs, cache.full_attn_capacity()), (262144, 4, 16384));
assert!(cache.mtp_slot.is_some());
let lengths = [[10, 17, 23, 29], [3, 5, 7, 11]];
plant(&mut cache, &lengths);
let expected = rows(&cache, &lengths);
let snapshot = cache.snapshot_prefix(&device, 2).unwrap();
let images = snapshot_bytes(&snapshot);
let generations = cache.slot_state_generation.clone();
let anchors: Vec<_> = (0..4).map(|slot| cache.snapshot_slot_anchor(SlotId(slot), lengths[0][slot as usize] as usize).unwrap()).collect();
for slot in 0..4 {
cache.truncate_full_attn_to_for_slot(SlotId(slot), 2).unwrap();
cache.truncate_mtp_to_for_slot(SlotId(slot), 1).unwrap();
}
let shallow = cache.snapshot_slot_anchor(SlotId(0), 2).unwrap();
let old_view = cache.full_attn[0].tq.as_ref().map(|tq| tq.k_packed.clone())
.or_else(|| cache.full_attn[0].k.clone()).unwrap();
let old_ids = root_ids(&cache);
let initial_charge = cache.fa_allocation_charge;
cache.ensure_fa_backing(16385).unwrap();
assert_eq!(cache.full_attn_capacity(), 65536);
assert_ne!(old_ids, root_ids(&cache));
assert_eq!(old_view.shape()[2], 16384, "a retained old view still owns its old stride");
assert!(cache.fa_allocation_charge > initial_charge);
assert_eq!(expected, rows(&cache, &lengths));
assert_eq!(cache.slot_state_generation, generations);
for (slot, anchor) in anchors.iter().enumerate() {
let plan = cache.plan_slot_anchor_restore(SlotId(slot as u32), anchor).unwrap();
cache.apply_slot_anchor_restore(plan).unwrap();
}
assert_eq!(snapshot_bytes(&cache.snapshot_prefix(&device, 2).unwrap()), images);
let plan = cache.plan_slot_anchor_restore(SlotId(0), &shallow).unwrap();
cache.apply_slot_anchor_restore(plan).unwrap();
cache.ensure_fa_backing(65537).unwrap();
assert_eq!(cache.full_attn_capacity(), cache.max_seq_len);
assert_eq!(expected, rows(&cache, &lengths));
let plan = cache.plan_slot_anchor_restore(SlotId(0), &anchors[0]).unwrap();
cache.apply_slot_anchor_restore(plan).unwrap();
let ids = root_ids(&cache);
let charge = cache.fa_allocation_charge;
cache.ensure_fa_backing(262144).unwrap();
assert_eq!(root_ids(&cache), ids, "at-capacity fast path never replaces roots");
assert_eq!(cache.fa_allocation_charge, charge);
assert!(cache.ensure_fa_backing(262145).is_err());
assert_eq!(root_ids(&cache), ids);
plant(&mut cache, &[[262144; 4]; 2]);
let mut restored = HybridKvCache::new_with_options(&allocation_cfg(), &device, 262144, 4, tq).unwrap();
for slot in 0..4 {
let full = cache.spill_slot(SlotId(slot)).unwrap();
restored.restore_slot_spill(SlotId(slot), &full).unwrap();
assert!(restored.spill_slot(SlotId(slot)).unwrap().observable_state_eq(&full));
}
assert_eq!(restored.full_attn_capacity(), 262144);
}
}
#[test]
fn demand_backing_failed_attempts_and_grant_refusal_never_publish_or_refund() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
for tq in [false, true] {
let mut cache = HybridKvCache::new_with_options(&allocation_cfg(), &device, 65536, 4, tq).unwrap();
let lengths = [[10, 17, 23, 29], [3, 5, 7, 11]];
plant(&mut cache, &lengths);
let ids = root_ids(&cache);
let bytes = rows(&cache, &lengths);
let initial = cache.fa_allocation_charge;
cache.set_fa_allocation_budget(initial as u64).unwrap();
assert!(cache.ensure_fa_backing(16385).is_err());
assert_eq!(cache.fa_allocation_charge, initial);
cache.set_fa_allocation_budget(0).unwrap();
let mut ordinal = 0;
let result = cache.grow_fa_backing(65536, |plan| {
ordinal += 1;
if ordinal == 2 { anyhow::bail!("injected second replacement allocation failure"); }
plan.allocate(&device)
});
assert!(result.is_err());
assert_eq!(cache.full_attn_capacity(), 16384);
assert_eq!(cache.fa_allocation_charge, initial * 5 - cache.linear_attn.iter().map(|la|
la.conv_state.byte_len() + la.conv_state_scratch.byte_len() + la.recurrent.byte_len() + la.recurrent_scratch.byte_len()
).sum::<usize>() * 4);
assert_eq!(root_ids(&cache), ids);
assert_eq!(rows(&cache, &lengths), bytes);
let failed_charge = cache.fa_allocation_charge;
FAIL_BEFORE_PUBLICATION.with(|point| point.set(true));
assert!(cache.ensure_fa_backing(16385).is_err(), "actual copies complete, then publication is faulted");
assert_eq!(root_ids(&cache), ids);
assert_eq!(rows(&cache, &lengths), bytes);
assert_eq!(cache.full_attn_capacity(), 16384);
assert!(cache.fa_allocation_charge > failed_charge);
let failed_charge = cache.fa_allocation_charge;
cache.ensure_fa_backing(16385).unwrap();
assert!(cache.fa_allocation_charge > failed_charge, "retry cannot refund its abandoned allocation attempt");
assert_eq!(rows(&cache, &lengths), bytes);
}
}
#[test]
fn demand_backing_cursor_only_metadata_does_not_forge_initialized_rows() {
use crate::serve::multi_seq_kv::MultiSeqKvCache;
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
let mut cache = HybridKvCache::new_with_options(&allocation_cfg(), &device, 65536, 4, true).unwrap();
cache.append_for_seq(SlotId(3), 16385).unwrap();
assert_eq!(cache.sequence_len_for_slot(SlotId(3)).unwrap(), 16385);
assert_eq!(cache.full_attn_capacity(), 16384, "cursor-only acknowledgment is not an allocator");
cache.ensure_fa_backing(16385).unwrap();
for block in cache.full_attn.iter().chain(cache.mtp_slot.iter()) {
assert_eq!(block.current_len[3], 16385);
assert_eq!(block.initialized_len, [0; 4], "metadata alone cannot cause unread rows to be copied");
}
}
#[test]
fn demand_backing_spill_and_compact_restore_materialize_before_stride_validation() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
for tq in [false, true] {
let cfg = allocation_cfg();
let mut source = HybridKvCache::new_with_options(&cfg, &device, 65536, 4, tq).unwrap();
source.ensure_fa_backing(16385).unwrap();
let lengths = [[16385, 17, 23, 29], [16385, 5, 7, 11]];
plant(&mut source, &lengths);
let spill = source.spill_slot(SlotId(0)).unwrap();
let mut destination = HybridKvCache::new_with_options(&cfg, &device, 65536, 4, tq).unwrap();
destination.restore_slot_spill(SlotId(3), &spill).unwrap();
assert_eq!(destination.full_attn_capacity(), 65536);
assert!(destination.spill_slot(SlotId(3)).unwrap().observable_state_eq(&spill));
let mut compact = HybridKvCache::new_with_options(&cfg, &device, 65536, 4, tq).unwrap();
let uniform = [[16385; 4], [16385; 4]];
plant(&mut source, &uniform);
let snapshot = source.snapshot_prefix(&device, 16385).unwrap();
compact.restore_from(&snapshot).unwrap();
assert_eq!(snapshot_bytes(&compact.snapshot_prefix(&device, 16385).unwrap()), snapshot_bytes(&snapshot));
}
}
#[test]
fn demand_backing_original_producer_failure_precedes_root_allocation() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
use crate::inference::models::qwen35::encoder_stage::{SubmittedCommands, retain_submitted, FailSubmitted};
let mut cache = HybridKvCache::new_with_options(&allocation_cfg(), &device, 65536, 4, true).unwrap();
let producer = MlxDevice::new().unwrap();
assert_ne!(producer.metal_queue().as_ptr(), device.metal_queue().as_ptr());
cache.bind_fa_producer(&producer).unwrap();
let ids = root_ids(&cache);
let charge = cache.fa_allocation_charge;
let _scope = SubmittedCommands::open(true);
let source = upload_f32(&[3.0, 5.0], &producer).unwrap();
let output = producer.alloc_buffer(8, DType::F32, vec![2]).unwrap();
let mut registry = mlx_native::KernelRegistry::new();
let mut encoder = producer.command_encoder().unwrap();
mlx_native::ops::copy::dispatch_copy_f32(&mut encoder, &mut registry, producer.metal_device(), &source, &output, 0, 0, 2).unwrap();
encoder.commit_labeled("test.fa_growth.producer");
retain_submitted(encoder, "test.fa_growth.producer");
let failure = FailSubmitted::nth("test.fa_growth.producer", 0);
assert!(cache.ensure_fa_backing(16385).is_err());
assert_eq!(failure.seen(), (true, 1));
assert_eq!(cache.fa_allocation_charge, charge);
assert_eq!(root_ids(&cache), ids);
}
#[test]
fn demand_backing_boundary_forward_and_mtp_match_prematerialized_control() {
use crate::inference::models::qwen35::{Qwen35JointOutput, Qwen35JointRow};
use crate::inference::models::qwen35::joint_decode_routes::{JointRouteMode, JointDenseFfnRoute};
use crate::inference::models::qwen35::joint_step_options::JointStepOptions;
use crate::inference::models::qwen35::joint_projection::JointProjectionKernel;
use crate::inference::models::qwen35::forward_gpu::Qwen35JointVerifyLane;
use crate::inference::models::qwen35::mtp::MtpDraftLane;
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
let model = synthetic_model(&device, padded_policy(), true);
model.ensure_gpu_cache_primed().unwrap();
for tq in [false, true] {
for operation in 0..7 {
let mut growing = HybridKvCache::new_with_options(&model.cfg, &device, 16385, 4, tq).unwrap();
let mut control = HybridKvCache::new_with_options(&model.cfg, &device, 16385, 4, tq).unwrap();
control.ensure_fa_backing(16385).unwrap();
for cache in [&mut growing, &mut control] {
for block in cache.full_attn.iter_mut().chain(cache.mtp_slot.iter_mut()) {
if let Some(tq) = block.tq.as_mut() {
for buffer in [&mut tq.k_packed, &mut tq.k_norms, &mut tq.v_packed, &mut tq.v_norms] {
buffer.as_mut_slice::<u8>().unwrap().fill(0);
}
}
for buffer in block.k.iter_mut().chain(block.v.iter_mut()) {
buffer.as_mut_slice::<u8>().unwrap().fill(0);
}
block.current_len.fill(16384);
block.initialized_len.fill(16384);
}
}
let positions = positions_for_range(16384, 1);
let run = |cache: &mut HybridKvCache| -> Vec<u32> {
let logits = match operation {
0 => model.forward_gpu_last_logits(&[11], &positions, cache, SlotId(3)).unwrap(),
1 => return vec![model.forward_gpu_greedy(&[11], &positions, cache, SlotId(3)).unwrap()],
2 => {
let rows = [0, 3].map(|slot| Qwen35JointRow {
slot_id: SlotId(slot), token: 11 + slot, position: 16384,
output: Qwen35JointOutput::Logits,
});
model.forward_gpu_decode_joint_with_options(&rows, cache,
JointRouteMode::PaddedMvExt, JointDenseFfnRoute::SharedWeights,
JointStepOptions::default()).unwrap()
.into_iter().flat_map(|row| row.logits.unwrap()).collect()
}
3 => {
let tokens = [11];
let lanes = [0, 3].map(|slot| Qwen35JointVerifyLane {
slot_id: SlotId(slot), position: 16384, tokens: &tokens,
output: Qwen35JointOutput::Logits,
});
let verified = model.forward_gpu_joint_verify(&lanes, cache,
JointRouteMode::PaddedMvExt, JointDenseFfnRoute::SharedWeights,
JointStepOptions::default()).unwrap();
verified.rows.into_iter().flatten().flat_map(|row| row.logits.unwrap()).collect()
}
_ => return model.with_gpu_cache_mut(|device, registry| {
let width = model.cfg.hidden_size as usize;
let hidden = upload_f32(&vec![0.0; width], device)?;
let mtp = model.mtp.as_ref().unwrap();
match operation {
4 => {
let (logits, _) = mtp.forward_draft_for_token(&hidden, 11, &hidden, cache,
SlotId(3), &positions, device, registry, &model.cfg)?;
Ok(download_f32(&logits)?.into_iter().map(f32::to_bits).collect())
}
5 => {
let lanes = [0, 3].map(|slot| MtpDraftLane {
slot_id: SlotId(slot), prev_hidden: &hidden, token: 11 + slot, position: 16384,
});
let embeds = upload_f32(&vec![0.0; 2 * width], device)?;
Ok(mtp.forward_draft_greedy_batch(&lanes, &embeds, cache, device,
registry, &model.cfg, JointProjectionKernel::Canonical)?
.into_iter().flat_map(|(token, hidden)| {
std::iter::once(token).chain(download_f32(&hidden).unwrap().into_iter().map(f32::to_bits))
}).collect())
}
6 => {
mtp.process_target_batch(&[11], None, &hidden, &hidden, cache,
SlotId(3), &positions, device, registry, &model.cfg,
JointProjectionKernel::Canonical)?;
Ok(Vec::new())
}
_ => unreachable!(),
}
}).unwrap(),
};
logits.into_iter().map(f32::to_bits).collect()
};
assert_eq!(run(&mut growing), run(&mut control), "operation={operation}, TQ={tq}");
assert_eq!(growing.full_attn_capacity(), 16385);
for slot in 0..4 {
assert!(growing.spill_slot(SlotId(slot)).unwrap()
.observable_state_eq(&control.spill_slot(SlotId(slot)).unwrap()),
"all cursor-visible cache bytes must match: operation={operation}, TQ={tq}, slot={slot}");
}
}
}
}