use super::{
config::{DFlash2Config, DFlash2TargetShape},
forward::DFlash2VocabularyHead,
tensors::DFlash2ModelTensors,
workspace::DFlash2Workspace,
};
use crate::{
inference::models::{gemma4::model::MlxModelWeights, qwen35::model::Qwen35Model},
serve::forward_mlx_shared::MlxQWeight,
};
use anyhow::{anyhow, ensure, Context, Result};
use mlx_native::ops::dflash2_attention_pack::{
dispatch_dflash2_mask_rows_f32, DFlash2MaskRowsParams,
};
use mlx_native::ops::repacked_gguf_mm::PreparedGgufWeightPlanes;
use mlx_native::ops::ActivationPrecision;
use mlx_native::{CommandEncoder, GgmlType, KernelRegistry, MlxBuffer, MlxDevice};
#[derive(Clone, Copy)]
pub struct DFlash2TargetCapture<'a> {
pub layer_ids: &'a [usize],
pub output: &'a MlxBuffer,
pub lane_indices: &'a [usize],
pub verify_rows: &'a MlxBuffer,
pub lanes: usize,
pub rows_per_lane: usize,
pub feature_width: usize,
}
pub trait DFlash2TargetFamily {
fn family_name(&self) -> &'static str;
fn target_shape(&self) -> DFlash2TargetShape<'_>;
fn embedding(&self) -> Result<&MlxQWeight>;
fn vocabulary_head(&self) -> Result<&MlxQWeight>;
fn shared_prepared_vocabulary_head(
&self,
_registry: &mut KernelRegistry,
_device: &MlxDevice,
) -> Result<Option<&PreparedGgufWeightPlanes>> {
Ok(None)
}
fn embedding_scale(&self) -> f32;
fn adaptive_verify_budget(&self) -> bool {
false
}
fn target_capture<'a>(
&self,
config: &'a DFlash2Config,
workspace: &'a DFlash2Workspace,
lane_indices: &'a [usize],
) -> Result<DFlash2TargetCapture<'a>> {
ensure!(
workspace.rows_per_lane == config.block_size
&& workspace.max_lanes <= 4
&& config.fc_input_dim()
== config.target_layer_ids.len() * self.target_shape().hidden_size,
"DFlash2 {} target capture geometry does not match its workspace",
self.family_name()
);
Ok(DFlash2TargetCapture {
layer_ids: &config.target_layer_ids,
output: &workspace.captured_target_hidden,
lane_indices,
verify_rows: &workspace.verify_rows,
lanes: workspace.max_lanes,
rows_per_lane: workspace.rows_per_lane,
feature_width: config.fc_input_dim(),
})
}
fn validate(&self, config: &DFlash2Config) -> Result<()> {
config
.validate_target(self.target_shape())
.map_err(anyhow::Error::from)
}
}
pub struct QwenDFlash2Adapter<'a> {
model: &'a Qwen35Model,
}
impl<'a> QwenDFlash2Adapter<'a> {
pub fn new(model: &'a Qwen35Model, config: &DFlash2Config) -> Result<Self> {
let adapter = Self { model };
adapter.validate(config)?;
adapter.embedding()?;
adapter.vocabulary_head()?;
Ok(adapter)
}
}
impl DFlash2TargetFamily for QwenDFlash2Adapter<'_> {
fn family_name(&self) -> &'static str {
"qwen35"
}
fn target_shape(&self) -> DFlash2TargetShape<'_> {
DFlash2TargetShape {
architecture: self.family_name(),
hidden_size: self.model.cfg.hidden_size as usize,
vocab_size: self.model.cfg.vocab_size as usize,
num_hidden_layers: self.model.cfg.num_hidden_layers as usize,
}
}
fn embedding(&self) -> Result<&MlxQWeight> {
self.model
.token_embd_native
.as_ref()
.context("Qwen DFlash2 requires native token_embd.weight")
}
fn vocabulary_head(&self) -> Result<&MlxQWeight> {
self.model
.resolved_native_output_head()?
.map(|(weight, _)| weight)
.context("Qwen DFlash2 requires a native output head")
}
fn shared_prepared_vocabulary_head(
&self,
registry: &mut KernelRegistry,
device: &MlxDevice,
) -> Result<Option<&PreparedGgufWeightPlanes>> {
self.model.shared_prepared_output_head(registry, device)
}
fn embedding_scale(&self) -> f32 {
1.0
}
fn adaptive_verify_budget(&self) -> bool {
self.model.cfg.moe.is_some()
}
}
pub struct GemmaDFlash2Adapter<'a> {
model: &'a MlxModelWeights,
}
impl<'a> GemmaDFlash2Adapter<'a> {
pub fn new(model: &'a MlxModelWeights, config: &DFlash2Config) -> Result<Self> {
let adapter = Self { model };
adapter.validate(config)?;
adapter.embedding()?;
adapter.vocabulary_head()?;
Ok(adapter)
}
}
impl DFlash2TargetFamily for GemmaDFlash2Adapter<'_> {
fn family_name(&self) -> &'static str {
"gemma4"
}
fn target_shape(&self) -> DFlash2TargetShape<'_> {
DFlash2TargetShape {
architecture: self.family_name(),
hidden_size: self.model.hidden_size,
vocab_size: self.model.vocab_size,
num_hidden_layers: self.model.layers.len(),
}
}
fn embedding(&self) -> Result<&MlxQWeight> {
Ok(&self.model.embed_weight)
}
fn vocabulary_head(&self) -> Result<&MlxQWeight> {
Ok(self.model.resolved_lm_head())
}
fn embedding_scale(&self) -> f32 {
(self.model.hidden_size as f32).sqrt()
}
}
fn dispatch_embedding_rows(
encoder: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &MlxDevice,
weight: &MlxQWeight,
token_ids: &mlx_native::MlxBuffer,
output: &mlx_native::MlxBuffer,
rows: usize,
precision: ActivationPrecision,
) -> Result<()> {
ensure!(
weight.affine.is_none(),
"DFlash2 embedding cannot use affine metadata"
);
let vocab_size = weight.info.rows;
let embed_dim = weight.info.cols;
match weight.info.ggml_dtype {
GgmlType::F32 | GgmlType::F16 | GgmlType::BF16 => mlx_native::ops::embedding_dense::embedding_gather_dense_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingDenseParams {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q4_0 => mlx_native::ops::embedding_q4_0::embedding_gather_q4_0_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ4_0Params {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q5_0 => mlx_native::ops::embedding_q5_0::embedding_gather_q5_0_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ5_0Params {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q2_K => mlx_native::ops::embedding_q2_k::embedding_gather_q2_k_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ2KParams {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q4_K => mlx_native::ops::embedding_q4_k::embedding_gather_q4_k_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ4KParams {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q5_K => mlx_native::ops::embedding_kquant::embedding_gather_q5_k_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ5KParams {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q6_K => mlx_native::ops::embedding_kquant::embedding_gather_q6_k_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ6KParams {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
GgmlType::Q8_0 => mlx_native::ops::embedding_q8_0::embedding_gather_q8_0_with_precision(
encoder,
registry,
device,
&weight.buffer,
token_ids,
output,
&mlx_native::EmbeddingQ8_0Params {
vocab_size,
embed_dim,
n_tokens: rows,
},
precision,
)?,
other => return Err(anyhow!("DFlash2 embedding does not support {other:?}")),
}
Ok(())
}
pub fn dispatch_dflash2_input<T: DFlash2TargetFamily>(
tensors: &DFlash2ModelTensors,
encoder: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &MlxDevice,
config: &DFlash2Config,
adapter: &T,
anchors: &[u32],
workspace: &mut DFlash2Workspace,
) -> Result<()> {
if anchors.len() != workspace.max_lanes {
return Err(anyhow!(
"DFlash2 anchor count {} != workspace lanes {}",
anchors.len(),
workspace.max_lanes
));
}
adapter.validate(config)?;
let tokens = workspace.row_tokens.as_mut_slice::<u32>()?;
for (lane, anchor) in anchors.iter().copied().enumerate() {
ensure!(
(anchor as usize) < config.vocab_size,
"DFlash2 anchor {anchor} exceeds vocabulary {}",
config.vocab_size
);
let lane_rows = &mut tokens[lane * config.block_size..(lane + 1) * config.block_size];
lane_rows.fill(config.mask_token_id);
lane_rows[0] = anchor;
}
let embedding = adapter.embedding()?;
ensure!(
embedding.info.cols == config.hidden_size,
"DFlash2 {} embedding width {} != draft hidden {}",
adapter.family_name(),
embedding.info.cols,
config.hidden_size
);
let rows = workspace.max_lanes * config.block_size;
let scale = adapter.embedding_scale();
let precision = if matches!(
&tensors.context_projection, super::tensors::DFlash2Projection::Af4G64 { .. }
) {
ActivationPrecision::Bf16
} else {
ActivationPrecision::F32
};
dispatch_embedding_rows(
encoder,
registry,
device,
embedding,
&workspace.row_tokens,
&workspace.hidden[0],
rows,
if scale == 1.0 { precision } else { ActivationPrecision::F32 },
)?;
encoder.memory_barrier();
if scale != 1.0 {
mlx_native::ops::elementwise::scalar_mul_f32_with_precision(
encoder,
registry,
device.metal_device(),
&workspace.hidden[0],
&workspace.hidden[0],
rows * config.hidden_size,
scale,
precision,
)?;
encoder.memory_barrier();
}
if let Some(mask_embedding) = tensors.mask_embedding.as_ref() {
dispatch_dflash2_mask_rows_f32(
encoder,
registry,
device,
mask_embedding,
&workspace.hidden[0],
DFlash2MaskRowsParams {
lanes: workspace.max_lanes as u32,
rows: config.block_size as u32,
hidden: config.hidden_size as u32,
},
)?;
encoder.memory_barrier();
}
Ok(())
}
pub fn target_vocabulary_head<'a, T: DFlash2TargetFamily>(
adapter: &'a T,
registry: &mut KernelRegistry,
device: &MlxDevice,
reads_prepared_head: bool,
) -> Result<DFlash2VocabularyHead<'a>> {
let weight = adapter.vocabulary_head()?;
if !reads_prepared_head {
return Ok(DFlash2VocabularyHead::Native(weight));
}
Ok(
match adapter.shared_prepared_vocabulary_head(registry, device)? {
Some(prepared) => DFlash2VocabularyHead::SharedPrepared { weight, prepared },
None => DFlash2VocabularyHead::Native(weight),
},
)
}