use anyhow::{anyhow, ensure, Context, Result};
use mlx_native::metal::MTLSize;
use mlx_native::ops::argmax::dispatch_argmax_f32;
use mlx_native::ops::encode_helpers::{as_bytes, encode_with_args, KernelArg};
use mlx_native::{CommandEncoder, DType, KernelRegistry, MlxBuffer, MlxDevice};
use super::decode_pool::pooled_alloc_buffer;
use super::joint_decode_core::JointWindow;
use crate::serve::sampler_pure::{apply_repetition_penalty, sample_greedy};
pub(crate) const DECISION_SLOTS: usize = 64;
const SHADER: &str = include_str!("shaders/verify_decision.metal");
const GATHER: &str = "qwen_verify_decision_gather";
const MASK: &str = "qwen_verify_decision_mask";
const UNUSED: u32 = u32::MAX;
const MASKED: f32 = f32::MIN;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Params {
rows: u32,
vocab: u32,
slots: u32,
row_token_count: u32,
}
pub(super) struct EncodedDecisions {
history_tokens: MlxBuffer,
history_logits: MlxBuffer,
outside_tokens: MlxBuffer,
outside_logits: MlxBuffer,
decided: Vec<bool>,
}
#[allow(clippy::too_many_arguments)]
pub(super) fn encode(
enc: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &MlxDevice,
logits: &MlxBuffer,
windows: &[JointWindow],
histories: &[Option<&[u32]>],
row_tokens: &MlxBuffer,
rows: usize,
vocab: usize,
) -> Result<EncodedDecisions> {
ensure!(
histories.len() == windows.len(),
"Qwen verify decisions: {} histories for {} windows",
histories.len(),
windows.len()
);
ensure!(
logits.dtype() == DType::F32
&& logits.element_count() >= rows * vocab
&& row_tokens.dtype() == DType::U32
&& u32::try_from(rows * vocab).is_ok(),
"Qwen verify decisions: logits {:?} x {} or row tokens {:?} do not fit {rows} rows of {vocab}",
logits.dtype(),
logits.element_count(),
row_tokens.dtype()
);
let mut table = vec![UNUSED; 4 * rows];
let mut base = Vec::new();
let mut decided = vec![false; rows];
for (window, history) in windows.iter().zip(histories) {
let Some(history) = history else {
continue;
};
ensure!(
history.len() <= DECISION_SLOTS && window.start + window.rows <= rows,
"Qwen verify decisions: a history of {} tokens or a window past row {rows}",
history.len()
);
ensure!(
window.start + window.rows <= row_tokens.element_count(),
"Qwen verify decisions: the row tokens end inside a window"
);
let offset = base.len() as u32;
base.extend_from_slice(history);
for r in 0..window.rows {
let row = window.start + r;
table[4 * row..4 * row + 4].copy_from_slice(&[
window.start as u32,
r as u32,
offset,
history.len() as u32,
]);
decided[row] = true;
}
}
base.push(UNUSED);
let words = |values: &[u32], what: &str| -> Result<MlxBuffer> {
let mut buffer = pooled_alloc_buffer(
device,
std::mem::size_of_val(values),
DType::U32,
vec![values.len()],
)
.map_err(|e| anyhow!("allocate Qwen verify decision {what}: {e}"))?;
buffer
.as_mut_slice::<u32>()
.map_err(|e| anyhow!("{e}"))?
.copy_from_slice(values);
Ok(buffer)
};
let table = words(&table, "row table")?;
let base = words(&base, "base histories")?;
let slots = rows * DECISION_SLOTS;
let scratch = |dtype: DType, elements: usize, what: &str| {
pooled_alloc_buffer(device, elements * 4, dtype, vec![elements])
.map_err(|e| anyhow!("allocate Qwen verify decision {what}: {e}"))
};
let history_tokens = scratch(DType::U32, slots, "history tokens")?;
let history_logits = scratch(DType::F32, slots, "history logits")?;
let outside_tokens = scratch(DType::U32, rows, "argmax tokens")?;
let outside_logits = scratch(DType::F32, rows, "argmax logits")?;
let params = Params {
rows: rows as u32,
vocab: vocab as u32,
slots: DECISION_SLOTS as u32,
row_token_count: u32::try_from(row_tokens.element_count())
.context("Qwen verify decisions: row token count")?,
};
let grid = MTLSize::new(DECISION_SLOTS as u64, rows as u64, 1);
let group = MTLSize::new(DECISION_SLOTS as u64, 1, 1);
registry.register_source(GATHER, SHADER);
registry.register_source(MASK, SHADER);
let gather = registry
.get_pipeline(GATHER, device.metal_device())
.context("Qwen verify decision gather pipeline")?;
ensure!(
gather.max_total_threads_per_threadgroup() >= DECISION_SLOTS as u64,
"Qwen verify decision kernels need {DECISION_SLOTS} threads per threadgroup"
);
encode_with_args(
enc,
gather,
&[
(0, KernelArg::Buffer(logits)),
(1, KernelArg::Buffer(&table)),
(2, KernelArg::Buffer(&base)),
(3, KernelArg::Buffer(row_tokens)),
(4, KernelArg::Buffer(&history_tokens)),
(5, KernelArg::Buffer(&history_logits)),
(6, KernelArg::Bytes(as_bytes(¶ms))),
],
grid,
group,
);
enc.memory_barrier();
let mask = registry
.get_pipeline(MASK, device.metal_device())
.context("Qwen verify decision mask pipeline")?;
ensure!(
mask.max_total_threads_per_threadgroup() >= DECISION_SLOTS as u64,
"Qwen verify decision kernels need {DECISION_SLOTS} threads per threadgroup"
);
encode_with_args(
enc,
mask,
&[
(0, KernelArg::Buffer(logits)),
(1, KernelArg::Buffer(&history_tokens)),
(2, KernelArg::Bytes(as_bytes(¶ms))),
],
grid,
group,
);
enc.memory_barrier();
let argmax_params = words(&[vocab as u32], "argmax params")?;
for row in (0..rows).filter(|&row| decided[row]) {
let view = logits
.slice_view((row * vocab * 4) as u64, vocab)
.with_shape(vec![1, vocab])
.map_err(|e| anyhow!("shape Qwen verify decision row {row}: {e}"))?;
dispatch_argmax_f32(
enc,
registry,
device.metal_device(),
&view,
&outside_tokens.slice_view((row * 4) as u64, 1),
&outside_logits.slice_view((row * 4) as u64, 1),
&argmax_params,
vocab as u32,
)
.with_context(|| format!("Qwen verify decision argmax row {row}"))?;
}
Ok(EncodedDecisions {
history_tokens,
history_logits,
outside_tokens,
outside_logits,
decided,
})
}
impl EncodedDecisions {
pub(super) fn read(
&self,
row: usize,
logits_row: MlxBuffer,
) -> Result<Option<JointRowDecision>> {
if !self.decided.get(row).copied().unwrap_or(false) {
return Ok(None);
}
let slots = row * DECISION_SLOTS..(row + 1) * DECISION_SLOTS;
let tokens = &self
.history_tokens
.as_slice::<u32>()
.map_err(|e| anyhow!("read Qwen verify decision history tokens: {e}"))?[slots.clone()];
let logits = &self
.history_logits
.as_slice::<f32>()
.map_err(|e| anyhow!("read Qwen verify decision history logits: {e}"))?[slots];
let mut decision = JointRowDecision {
outside_token: self
.outside_tokens
.as_slice::<u32>()
.map_err(|e| anyhow!("read Qwen verify decision argmax tokens: {e}"))?[row],
outside_logit: self
.outside_logits
.as_slice::<f32>()
.map_err(|e| anyhow!("read Qwen verify decision argmax logits: {e}"))?[row],
history_tokens: [UNUSED; DECISION_SLOTS],
history_logits: [0.0; DECISION_SLOTS],
history_len: tokens.iter().take_while(|&&token| token != UNUSED).count(),
row: logits_row,
};
decision.history_tokens.copy_from_slice(tokens);
decision.history_logits.copy_from_slice(logits);
Ok(Some(decision))
}
}
pub(crate) struct JointRowDecision {
outside_token: u32,
outside_logit: f32,
history_tokens: [u32; DECISION_SLOTS],
history_logits: [f32; DECISION_SLOTS],
history_len: usize,
row: MlxBuffer,
}
impl JointRowDecision {
pub(crate) fn greedy_token(&self, history: &[u32], penalty: f64) -> Option<u32> {
const CANDIDATES: usize = DECISION_SLOTS + 1;
const POSITIONS: [u32; CANDIDATES] = {
let mut positions = [0; CANDIDATES];
let mut index = 0;
while index < CANDIDATES {
positions[index] = index as u32;
index += 1;
}
positions
};
let vocab = self.row.element_count();
let (history_tokens, history_logits) = self.history();
if history_tokens != history
|| self.outside_token as usize >= vocab
|| !self.outside_logit.is_finite()
|| self.outside_logit <= MASKED
{
return None;
}
let mut tokens = [0_u32; CANDIDATES];
let mut logits = [0.0_f32; CANDIDATES];
let mut count = 0;
for (&token, &logit) in history_tokens.iter().zip(history_logits) {
if token as usize >= vocab || !logit.is_finite() || token == self.outside_token {
return None;
}
let at = tokens[..count].partition_point(|&earlier| earlier < token);
if at < count && tokens[at] == token {
continue;
}
tokens.copy_within(at..count, at + 1);
logits.copy_within(at..count, at + 1);
tokens[at] = token;
logits[at] = logit;
count += 1;
}
if penalty != 1.0 && !history.is_empty() {
apply_repetition_penalty(&mut logits[..count], &POSITIONS[..count], penalty);
}
let at = tokens[..count].partition_point(|&token| token < self.outside_token);
tokens.copy_within(at..count, at + 1);
logits.copy_within(at..count, at + 1);
tokens[at] = self.outside_token;
logits[at] = self.outside_logit;
count += 1;
if logits[..count].iter().any(|logit| logit.is_nan()) {
return None;
}
Some(tokens[sample_greedy(&logits[..count]) as usize])
}
pub(crate) fn history(&self) -> (&[u32], &[f32]) {
(
&self.history_tokens[..self.history_len],
&self.history_logits[..self.history_len],
)
}
pub(crate) fn logits(&self) -> Result<Vec<f32>> {
let mut logits = self
.row
.as_slice::<f32>()
.map_err(|e| anyhow!("read Qwen verify decision row: {e}"))?
.to_vec();
self.restore(&mut logits);
Ok(logits)
}
pub(super) fn restore(&self, logits: &mut [f32]) {
let (tokens, raw) = self.history();
for (&token, &logit) in tokens.iter().zip(raw) {
if let Some(slot) = logits.get_mut(token as usize) {
*slot = logit;
}
}
}
#[cfg(test)]
pub(crate) fn for_test(
outside: (u32, f32),
history_tokens: &[u32],
history_logits: &[f32],
row: MlxBuffer,
) -> Self {
let mut decision = Self {
outside_token: outside.0,
outside_logit: outside.1,
history_tokens: [UNUSED; DECISION_SLOTS],
history_logits: [0.0; DECISION_SLOTS],
history_len: history_tokens.len(),
row,
};
decision.history_tokens[..history_tokens.len()].copy_from_slice(history_tokens);
decision.history_logits[..history_logits.len()].copy_from_slice(history_logits);
decision
}
}
#[cfg(test)]
pub(crate) fn candidates_for_test(
device: &MlxDevice,
registry: &mut KernelRegistry,
vocab: usize,
windows: &[(usize, usize)],
histories: &[Option<&[u32]>],
row_tokens: &[u32],
logits: &[f32],
) -> Vec<Option<JointRowDecision>> {
super::decode_pool::checked_reset_decode_pool().unwrap();
let windows = windows
.iter()
.enumerate()
.map(|(slot, &(start, rows))| JointWindow {
slot: crate::serve::multi_seq_kv::SlotId(slot as u32),
start,
rows,
})
.collect::<Vec<_>>();
let rows = windows
.iter()
.map(|window| window.start + window.rows)
.max()
.unwrap();
let width = logits.len() / vocab;
let mut tile = device
.alloc_buffer(logits.len() * 4, DType::F32, vec![width, vocab])
.unwrap();
tile.as_mut_slice::<f32>().unwrap().copy_from_slice(logits);
let mut tokens = device
.alloc_buffer(row_tokens.len() * 4, DType::U32, vec![row_tokens.len()])
.unwrap();
tokens
.as_mut_slice::<u32>()
.unwrap()
.copy_from_slice(row_tokens);
let mut enc = device.command_encoder().unwrap();
let encoded = encode(
&mut enc, registry, device, &tile, &windows, histories, &tokens, rows, vocab,
)
.unwrap();
enc.commit_and_wait().unwrap();
(0..rows)
.map(|row| {
let view = tile
.slice_view((row * vocab * 4) as u64, vocab)
.with_shape(vec![1, vocab])
.unwrap();
encoded.read(row, view).unwrap()
})
.collect()
}
#[cfg(test)]
#[path = "verify_decision_tests.rs"]
mod tests;