use std::cell::OnceCell;
use anyhow::{anyhow, ensure, Context, Result};
use mlx_native::ops::tq_hb_verify_tile::{
tq_hb_verify_tile_attention, tq_hb_verify_tile_available, verify_tile_scratch_bytes,
verify_tile_slot_splits, TqHbVerifyLane, TqHbVerifyTileCache, TqHbVerifyTileScratch,
TqHbVerifyTileShape, VERIFY_TILE_ROWS,
};
use mlx_native::{CommandEncoder, DType, KernelRegistry, MlxBuffer, MlxDevice};
use super::decode_pool::pooled_alloc_buffer;
use super::joint_decode_core::JointWindow;
use super::kv_cache::FullAttnKvSlot;
use crate::inference::spec_decode::dflash2::route_profile;
use crate::serve::multi_seq_kv::SlotId;
pub(crate) const QWEN_VERIFY_ATTN_TILE_ENV: &str = "HF2Q_QWEN_VERIFY_ATTN_TILE";
pub(crate) fn enabled() -> bool {
const SWITCH: route_profile::Switch = route_profile::switch(QWEN_VERIFY_ATTN_TILE_ENV);
route_profile::is_one(SWITCH)
}
#[derive(Default)]
pub(crate) struct VerifyTileScratch {
buffers: OnceCell<ScratchBuffers>,
}
struct ScratchBuffers {
queries: MlxBuffer,
partials: MlxBuffer,
statistics: MlxBuffer,
attention: MlxBuffer,
}
fn tile_shape(
n_heads: u32,
n_kv_heads: u32,
head_dim: u32,
max_seq_len: u32,
width: usize,
) -> TqHbVerifyTileShape {
TqHbVerifyTileShape {
n_heads,
n_kv_heads,
head_dim,
kv_capacity: max_seq_len,
codebook_bits: crate::debug::INVESTIGATION_ENV.tq_codebook_bits,
scale: 1.0_f32 / (head_dim as f32).sqrt(),
width: width as u32,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn tq_verify_tile_route(
registry: &mut KernelRegistry,
device: &MlxDevice,
slot: &FullAttnKvSlot,
windows: &[JointWindow],
width: usize,
n_heads: u32,
n_kv_heads: u32,
head_dim: u32,
max_seq_len: u32,
) -> Result<bool> {
let shape = tile_shape(n_heads, n_kv_heads, head_dim, max_seq_len, width);
let refusal = if slot.tq.is_none() || slot.k.is_some() {
Some("the cache is not TQ-only")
} else if !shape.supported() {
Some(
"no kernel for this geometry (needs 8-bit codes, head dim 256, six or eight \
query heads per KV head and a capacity that is a multiple of 32)",
)
} else if !windows.iter().all(|window| {
(1..=VERIFY_TILE_ROWS as usize).contains(&window.rows)
&& slot
.current_len
.get(window.slot.0 as usize)
.is_some_and(|&len| len as usize + window.rows <= max_seq_len as usize)
}) {
Some("a window has more than eight rows or no room in its slot")
} else if !tq_hb_verify_tile_available(registry, device, &shape)
.map_err(|e| anyhow!("probe tiled verify attention: {e}"))?
{
Some("the device lacks the Metal tensor API or the kernels' threadgroup limits")
} else {
None
};
if let Some(reason) = refusal {
static FIRST_REFUSAL: std::sync::Once = std::sync::Once::new();
FIRST_REFUSAL.call_once(|| {
tracing::info!(
reason,
num_heads = n_heads,
num_kv_heads = n_kv_heads,
head_dim,
codebook_bits = shape.codebook_bits,
capacity = max_seq_len,
"Qwen DFlash2 verify keeps the per-row attention chain: tiled TQ attention refused"
);
});
}
Ok(refusal.is_none())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn apply_tq_verify_tile_gated_into(
enc: &mut CommandEncoder,
device: &MlxDevice,
registry: &mut KernelRegistry,
q_rows: &MlxBuffer,
k_rows: &MlxBuffer,
v_rows: &MlxBuffer,
gate_rows: &MlxBuffer,
slot: &mut FullAttnKvSlot,
windows: &[JointWindow],
scratch: &VerifyTileScratch,
width: usize,
n_heads: u32,
n_kv_heads: u32,
head_dim: u32,
max_seq_len: u32,
) -> Result<MlxBuffer> {
ensure!(
tq_verify_tile_route(
registry, device, slot, windows, width, n_heads, n_kv_heads, head_dim, max_seq_len
)?,
"tiled verify attention needs a TQ-only 8-bit slot, a compiled geometry and windows of at most {VERIFY_TILE_ROWS} rows with room"
);
ensure!(
windows.first().is_some_and(|window| window.start == 0),
"tiled verify attention: the first window must start at packed row 0"
);
let shape = tile_shape(n_heads, n_kv_heads, head_dim, max_seq_len, width);
let q_total = (n_heads * head_dim) as usize;
let real: usize = windows.iter().map(|window| window.rows).sum();
ensure!(
q_rows.element_count() >= width * q_total && gate_rows.element_count() >= width * q_total,
"tiled verify attention: Q/gate rows hold fewer than {width} rows of {q_total}"
);
let mut writes: Vec<(SlotId, u32)> = Vec::with_capacity(real);
let mut lanes = Vec::with_capacity(windows.len());
for window in windows {
ensure!(
window.start == writes.len(),
"tiled verify attention: windows must cover the real rows in packed order"
);
let cursor = slot.current_len[window.slot.0 as usize];
writes.extend((0..window.rows as u32).map(|row| (window.slot, cursor + row)));
lanes.push(TqHbVerifyLane {
slot: window.slot.0,
committed: cursor,
rows: window.rows as u32,
first_row: window.start as u32,
});
}
slot.encode_rows_to_tq(
k_rows,
v_rows,
&writes,
n_kv_heads,
head_dim,
max_seq_len,
shape.codebook_bits,
enc,
registry,
device,
)
.context("tiled verify attention K/V encode")?;
crate::inference::stage_profile::boundary(enc, "adr065.kv_write")
.context("profile Qwen joint KV write")?;
let slot_splits = verify_tile_slot_splits(&lanes, max_seq_len);
let sizes = verify_tile_scratch_bytes(&shape, lanes.len(), slot_splits);
let buffers = match scratch.buffers.get() {
Some(buffers) => buffers,
None => {
let alloc = |bytes: usize, dtype: DType, label: &str| {
pooled_alloc_buffer(device, bytes, dtype, vec![bytes / dtype.size_of()])
.map_err(|e| anyhow!("alloc tiled verify attention {label}: {e}"))
};
let buffers = ScratchBuffers {
queries: alloc(sizes.queries, DType::F16, "queries")?,
partials: alloc(sizes.partials, DType::F32, "partials")?,
statistics: alloc(sizes.statistics, DType::F32, "statistics")?,
attention: alloc(sizes.attention, DType::F32, "rotated rows")?,
};
scratch.buffers.get_or_init(|| buffers)
}
};
let gated = pooled_alloc_buffer(
device,
width * q_total * 4,
DType::F32,
vec![width * q_total],
)
.map_err(|e| anyhow!("alloc tiled verify gated attention: {e}"))?;
let tq = slot
.tq
.as_ref()
.ok_or_else(|| anyhow!("tiled verify attention: slot.tq is None"))?;
tq_hb_verify_tile_attention(
enc,
registry,
device,
q_rows,
gate_rows,
&TqHbVerifyTileCache {
k_packed: &tq.k_packed,
k_norms: &tq.k_norms,
v_packed: &tq.v_packed,
v_norms: &tq.v_norms,
},
&gated,
&TqHbVerifyTileScratch {
queries: &buffers.queries,
partials: &buffers.partials,
statistics: &buffers.statistics,
attention: &buffers.attention,
},
&shape,
&lanes,
)
.map_err(|e| anyhow!("tiled verify attention: {e}"))?;
for window in windows {
let end = slot.current_len[window.slot.0 as usize] + window.rows as u32;
slot.commit_written_rows(window.slot.0 as usize, end);
}
static FIRST_TILE: std::sync::Once = std::sync::Once::new();
FIRST_TILE.call_once(|| {
tracing::info!(
lanes = lanes.len(),
rows = real,
width,
num_heads = n_heads,
num_kv_heads = n_kv_heads,
"Qwen DFlash2 verify selected tiled TQ attention"
);
});
Ok(gated)
}