use anyhow::{anyhow, bail, ensure, Context, Result};
use mlx_native::ops::dflash2_attention_pack::{
dispatch_dflash2_mask_moe_routes, DFlash2MoeRouteMaskParams,
};
use mlx_native::ops::dense_matvec_f32_rows::{
dispatch_dense_matvec_f32_rows, DENSE_MATVEC_F32_ROWS_MAX_ROWS,
};
use mlx_native::ops::dense_mm_f32_f32::{dense_matmul_f32_f32_tensor, DenseMmF32F32Params};
use mlx_native::ops::moe_softmax_topk::dispatch_moe_softmax_topk_simd;
use mlx_native::ops::moe_weighted_reduce::{
dispatch_moe_weighted_reduce, dispatch_moe_weighted_reduce_masked,
};
use mlx_native::ops::quantized_matmul_ggml::{GgmlQuantizedMatmulParams, GgmlType};
use mlx_native::ops::quantized_matmul_id_ggml::{
quantized_matmul_id_ggml_grouped_m8_epilogue,
quantized_matmul_id_ggml_grouped_m8_epilogue_masked, quantized_matmul_id_ggml_mv,
quantized_matmul_id_ggml_mv_masked, quantized_matmul_id_ggml_mv_q4_k_nr2,
quantized_matmul_id_ggml_mv_q4_k_nr2_masked, GgmlQuantizedMatmulIdParams, GroupedM8Epilogue,
GroupedM8Input,
};
use mlx_native::ops::silu_mul::dispatch_silu_mul;
use mlx_native::{CommandEncoder, DType, KernelRegistry, MlxBuffer, MlxDevice};
use super::decode_pool::pooled_alloc_buffer;
use super::execution_dispatch::quantized_matmul_ggml;
use super::ffn::MoeFfnShape;
use super::expert_storage::{ExpertRole, ExpertRoleRef};
use super::gpu_ffn::MoeFfnWeightsGpuQ;
use crate::inference::spec_decode::dflash2::route_profile;
pub(crate) const QWEN_MOE_BATCHED_ENV: &str = "HF2Q_QWEN_MOE_BATCHED";
pub(crate) const QWEN_MOE_STAGED_M8_ENV: &str = "HF2Q_QWEN_MOE_STAGED_M8";
pub(crate) const QWEN_MOE_LIVE_TILES_ENV: &str = "HF2Q_QWEN_MOE_LIVE_TILES";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MoeExpertRoute {
Matvec,
StagedM8,
LiveTiles,
}
impl MoeExpertRoute {
pub(crate) fn label(self) -> &'static str {
match self {
Self::Matvec => "matvec",
Self::StagedM8 => "staged_m8",
Self::LiveTiles => "live_tiles",
}
}
}
pub(crate) fn resolve_moe_expert_route(
batched: bool,
staged_m8: Option<&str>,
live_tiles: Option<&str>,
) -> Result<MoeExpertRoute, String> {
use super::joint_step_options::parse_switch;
let staged = parse_switch(QWEN_MOE_STAGED_M8_ENV, staged_m8)?;
let live = parse_switch(QWEN_MOE_LIVE_TILES_ENV, live_tiles)?;
if staged && !batched {
return Err(format!(
"{QWEN_MOE_STAGED_M8_ENV}=1 requires {QWEN_MOE_BATCHED_ENV}=1"
));
}
if live && !staged {
return Err(format!(
"{QWEN_MOE_LIVE_TILES_ENV}=1 requires {QWEN_MOE_STAGED_M8_ENV}=1"
));
}
Ok(match (staged, live) {
(_, true) => MoeExpertRoute::LiveTiles,
(true, false) => MoeExpertRoute::StagedM8,
(false, false) => MoeExpertRoute::Matvec,
})
}
pub(crate) fn qwen_moe_expert_route() -> Result<MoeExpertRoute> {
const STAGED_M8: route_profile::Switch = route_profile::switch(QWEN_MOE_STAGED_M8_ENV);
const LIVE_TILES: route_profile::Switch = route_profile::switch(QWEN_MOE_LIVE_TILES_ENV);
let batched = qwen_moe_batched_requested();
route_profile::with_value(STAGED_M8, |staged_m8| {
route_profile::with_value(LIVE_TILES, |live_tiles| {
resolve_moe_expert_route(batched, staged_m8, live_tiles)
})
})
.map_err(|error| anyhow::anyhow!("{error}"))
}
pub(crate) const MOE_BATCHED_MAX_ROWS: usize = 32;
pub(crate) fn parse_qwen_moe_batched(raw: Option<&str>) -> Result<bool, String> {
let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
return Ok(false);
};
match raw.to_ascii_lowercase().as_str() {
"1" | "on" | "true" => Ok(true),
"0" | "off" | "false" => Ok(false),
_ => Err(format!(
"{QWEN_MOE_BATCHED_ENV} must be 1/on/true or 0/off/false, got {raw:?}"
)),
}
}
pub(crate) fn qwen_moe_batched_requested() -> bool {
const SWITCH: route_profile::Switch = route_profile::switch(QWEN_MOE_BATCHED_ENV);
route_profile::with_value(SWITCH, parse_qwen_moe_batched).unwrap_or_else(|error| {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(error, fallback = false, "invalid Qwen MoE batched switch");
});
false
})
}
pub(crate) fn native_shared_types_supported(gate_up: GgmlType, down: GgmlType) -> bool {
let exact = |t: GgmlType| matches!(t, GgmlType::Q4_K | GgmlType::Q6_K);
exact(gate_up) && exact(down)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MoeDenseStorage {
Bf16,
Native {
shared_gate_up: GgmlType,
shared_down: GgmlType,
},
}
impl MoeDenseStorage {
pub fn is_native(self) -> bool {
matches!(self, Self::Native { .. })
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum MoeDenseRole {
Router,
SharedGateLogit,
SharedGate,
SharedUp,
SharedDown,
}
impl MoeDenseRole {
pub(crate) fn weight(self, weights: &MoeFfnWeightsGpuQ) -> &MlxBuffer {
match self {
Self::Router => &weights.router,
Self::SharedGateLogit => &weights.shared_gate_inp,
Self::SharedGate => &weights.shared_gate,
Self::SharedUp => &weights.shared_up,
Self::SharedDown => &weights.shared_down,
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_native_dense_proj(
enc: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &MlxDevice,
input: &MlxBuffer,
weights: &MoeFfnWeightsGpuQ,
role: MoeDenseRole,
output: &MlxBuffer,
rows: u32,
in_features: u32,
out_features: u32,
) -> Result<()> {
let MoeDenseStorage::Native {
shared_gate_up,
shared_down,
} = weights.dense_storage
else {
bail!("{role:?}: native projection requested on BF16 MoE storage");
};
let weight = role.weight(weights);
match role {
MoeDenseRole::Router | MoeDenseRole::SharedGateLogit => {
ensure!(
weight.dtype() == DType::F32,
"{role:?}: native router weights must be F32, got {:?}",
weight.dtype()
);
if rows <= DENSE_MATVEC_F32_ROWS_MAX_ROWS {
dispatch_dense_matvec_f32_rows(
enc,
registry,
device,
input,
weight,
output,
rows,
out_features,
in_features,
)
.with_context(|| format!("{role:?} dense_matvec_f32_rows"))
} else {
dense_matmul_f32_f32_tensor(
enc,
registry,
device,
weight,
input,
output,
&DenseMmF32F32Params {
m: rows,
n: out_features,
k: in_features,
src0_batch: 1,
src1_batch: 1,
},
)
.with_context(|| format!("{role:?} dense_matmul_f32_f32_tensor"))
}
}
MoeDenseRole::SharedGate | MoeDenseRole::SharedUp | MoeDenseRole::SharedDown => {
let ggml_type = if matches!(role, MoeDenseRole::SharedDown) {
shared_down
} else {
shared_gate_up
};
quantized_matmul_ggml(
enc,
registry,
device,
input,
weight,
output,
&GgmlQuantizedMatmulParams {
m: rows,
n: out_features,
k: in_features,
ggml_type,
},
)
.map_err(|e| anyhow!("{role:?} quantized_matmul_ggml {ggml_type:?}: {e}"))
}
}
}
#[allow(clippy::too_many_arguments)]
fn dispatch_expert_mv(
enc: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &MlxDevice,
input: &MlxBuffer,
weight: ExpertRoleRef<'_>,
ids: &MlxBuffer,
output: &MlxBuffer,
params: &GgmlQuantizedMatmulIdParams,
tag: &'static str,
layer: usize,
masked: bool,
) -> Result<()> {
if let ExpertRoleRef::Prepared(planes) = weight {
ensure!(!crate::quantize::imatrix::is_active(), "canonical expert storage cannot collect imatrix inputs");
use mlx_native::ops::quantized_matmul_id_ggml as native;
let routing = registry.ggml_routing_policy().copied()
.unwrap_or_else(mlx_native::ggml_routing_policy_from_environment);
let dispatched = match (params.ggml_type, masked) {
(GgmlType::Q4_K, false) => native::quantized_matmul_id_ggml_prepared_mv_q4_k_nr2(
enc, registry, device, input, planes, ids, output, params,
),
(GgmlType::Q4_K, true) => native::quantized_matmul_id_ggml_prepared_mv_q4_k_nr2_masked(
enc, registry, device, input, planes, ids, output, params,
),
(_, false) => native::quantized_matmul_id_ggml_prepared_mv_with_policy(
enc, registry, device, input, planes, ids, output, params, &routing,
),
(_, true) => native::quantized_matmul_id_ggml_prepared_mv_masked_with_policy(
enc, registry, device, input, planes, ids, output, params, &routing,
),
};
return dispatched.map_err(|e| anyhow!("{tag} prepared mul_mv_id: {e}"));
}
let ExpertRoleRef::Ggml(weight) = weight else {
bail!("{tag}: forced expert matvec does not support affine storage");
};
crate::quantize::imatrix::intercept_qmatmul_id_with_hint(
crate::quantize::imatrix::ImatrixHint::Layered { tag, layer },
params.n_tokens as usize,
params.top_k as usize,
params.k as usize,
|| {
if let Err(e) = enc.commit_wait_and_rotate() {
eprintln!(
"[hf2q imatrix moe intercept ({tag})] commit_wait_and_rotate failed: {e}"
);
return None;
}
input.as_slice::<f32>().ok().map(|sl| sl.to_vec())
},
|| ids.as_slice::<u32>().ok().map(|sl| sl.to_vec()),
)
.map_err(|e| anyhow!("imatrix moe intercept ({tag}): {e}"))?;
let dispatched = match (params.ggml_type, masked) {
(GgmlType::Q4_K, false) => quantized_matmul_id_ggml_mv_q4_k_nr2(
enc, registry, device, input, weight, ids, output, params,
),
(GgmlType::Q4_K, true) => quantized_matmul_id_ggml_mv_q4_k_nr2_masked(
enc, registry, device, input, weight, ids, output, params,
),
(_, false) => {
quantized_matmul_id_ggml_mv(enc, registry, device, input, weight, ids, output, params)
}
(_, true) => quantized_matmul_id_ggml_mv_masked(
enc, registry, device, input, weight, ids, output, params,
),
};
dispatched.map_err(|e| anyhow!("{tag} mul_mv_id: {e}"))
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) struct MoeBatchedRouting {
pub ids: MlxBuffer,
pub weights: MlxBuffer,
}
#[derive(Clone, Copy)]
pub(crate) struct DFlash2MoeRouteMask<'a> {
pub verify_rows: &'a MlxBuffer,
pub params: DFlash2MoeRouteMaskParams,
}
pub(super) fn pooled(device: &MlxDevice, elements: usize, dtype: DType, shape: Vec<usize>, label: &str) -> Result<MlxBuffer> {
pooled_alloc_buffer(device, elements * dtype.size_of(), dtype, shape)
.map_err(|e| anyhow!("allocate batched MoE {label}: {e}"))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_moe_ffn_layer_gpu_batched_into(
enc: &mut CommandEncoder,
device: &MlxDevice,
registry: &mut KernelRegistry,
x: &MlxBuffer,
weights: &MoeFfnWeightsGpuQ,
shape: MoeFfnShape,
residual: Option<&MlxBuffer>,
out: &mut MlxBuffer,
rows: u32,
layer_idx: usize,
route_mask: Option<DFlash2MoeRouteMask<'_>>,
) -> Result<MoeBatchedRouting> {
build_moe_ffn_layer_gpu_batched_route_into(
enc,
device,
registry,
x,
weights,
shape,
residual,
out,
rows,
layer_idx,
route_mask,
qwen_moe_expert_route()?,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_moe_ffn_layer_gpu_batched_route_into(
enc: &mut CommandEncoder,
device: &MlxDevice,
registry: &mut KernelRegistry,
x: &MlxBuffer,
weights: &MoeFfnWeightsGpuQ,
shape: MoeFfnShape,
residual: Option<&MlxBuffer>,
out: &mut MlxBuffer,
rows: u32,
layer_idx: usize,
route_mask: Option<DFlash2MoeRouteMask<'_>>,
route: MoeExpertRoute,
) -> Result<MoeBatchedRouting> {
ensure!(
(1..=MOE_BATCHED_MAX_ROWS).contains(&(rows as usize)),
"batched MoE layer {layer_idx} accepts 1..={MOE_BATCHED_MAX_ROWS} rows, got {rows}"
);
ensure!(
weights.dense_storage.is_native(),
"batched MoE layer {layer_idx} requires native router/shared-expert storage"
);
ensure!(
!weights.experts.has_affine(),
"batched MoE layer {layer_idx} does not support DWQ affine expert overlays"
);
if route == MoeExpertRoute::LiveTiles {
return super::moe_live_tiles_fused::build_moe_ffn_layer_live_tiles_into(
enc, device, registry, x, weights, shape, residual, out, rows, layer_idx, route_mask,
);
}
let staged_m8 = route == MoeExpertRoute::StagedM8;
if staged_m8 {
ensure!(
matches!(shape.num_experts_per_tok, 1 | 6 | 8)
&& shape.hidden_size % 64 == 0
&& shape.moe_intermediate_size % 64 == 0
&& matches!(weights.ggml_type_gate_up, GgmlType::Q4_K | GgmlType::Q6_K)
&& matches!(weights.ggml_type_down, GgmlType::Q4_K | GgmlType::Q6_K)
&& !crate::quantize::imatrix::is_active(),
"{QWEN_MOE_STAGED_M8_ENV}=1 requires top-k 1/6/8, \
64-column-aligned Q4_K/Q6_K native expert stacks and no imatrix collector"
);
}
let prepared_m8 = if staged_m8 {
Some(
weights.experts.completed()
.context("staged M8 route requires canonical completed expert planes")?,
)
} else {
None
};
let r = rows as usize;
let h = shape.hidden_size as usize;
let top_k = shape.num_experts_per_tok as usize;
let m_moe = shape.moe_intermediate_size as usize;
let m_sh = shape.shared_intermediate_size as usize;
let ne = shape.num_experts;
ensure!(
x.element_count() >= r * h,
"batched MoE layer {layer_idx}: input has {} values, need {rows} x {h}",
x.element_count()
);
let pairs = r * top_k;
let logits = pooled(
device,
r * ne as usize,
DType::F32,
vec![r, ne as usize],
"router logits",
)?;
let sh_logit = pooled(device, r, DType::F32, vec![r, 1], "shared gate logit")?;
let a_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared gate")?;
let b_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared up")?;
let h_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared swiglu")?;
let y_s = pooled(device, r * h, DType::F32, vec![r, h], "shared down")?;
let ids = pooled(device, pairs, DType::U32, vec![pairs], "expert ids")?;
let routing_weights = pooled(device, pairs, DType::F32, vec![pairs], "routing weights")?;
let gate_all = pooled(
device,
pairs * m_moe,
DType::F32,
vec![pairs, m_moe],
"expert gate",
)?;
let up_all = pooled(
device,
pairs * m_moe,
DType::F32,
vec![pairs, m_moe],
"expert up",
)?;
let h_all = pooled(
device,
pairs * m_moe,
DType::F32,
vec![pairs, m_moe],
"expert swiglu",
)?;
let y_all = pooled(device, pairs * h, DType::F32, vec![pairs, h], "expert down")?;
let gathered_m8 = staged_m8
.then(|| {
let width = h.max(m_moe);
let gathered_rows =
mlx_native::grouped_m8_gathered_rows(rows, shape.num_experts_per_tok, ne)
.map_err(|e| anyhow!("staged M8 gathered rows: {e}"))?;
pooled(
device,
gathered_rows * width,
DType::BF16,
vec![gathered_rows, width],
"staged M8 gathered input",
)
})
.transpose()?;
let mut silu_sh_params = pooled(device, 1, DType::U32, vec![1], "shared swiglu params")?;
let mut silu_params = pooled(device, 1, DType::U32, vec![1], "expert swiglu params")?;
let n_h_s = (r * m_sh) as u32;
let n_h_all = (pairs * m_moe) as u32;
silu_sh_params
.as_mut_slice::<u32>()
.map_err(|e| anyhow!("batched MoE shared swiglu params: {e}"))?[0] = n_h_s;
silu_params
.as_mut_slice::<u32>()
.map_err(|e| anyhow!("batched MoE expert swiglu params: {e}"))?[0] = n_h_all;
let dummy_residual;
let residual_ref = match residual {
Some(buffer) => buffer,
None => {
dummy_residual = pooled(device, 1, DType::F32, vec![1], "dummy residual")?;
&dummy_residual
}
};
let h32 = shape.hidden_size;
let m_sh32 = shape.shared_intermediate_size;
for (role, output, out_features) in [
(MoeDenseRole::Router, &logits, ne),
(MoeDenseRole::SharedGateLogit, &sh_logit, 1),
(MoeDenseRole::SharedGate, &a_s, m_sh32),
(MoeDenseRole::SharedUp, &b_s, m_sh32),
] {
encode_native_dense_proj(
enc,
registry,
device,
x,
weights,
role,
output,
rows,
h32,
out_features,
)
.with_context(|| format!("batched MoE layer {layer_idx}"))?;
}
enc.memory_barrier();
dispatch_moe_softmax_topk_simd(
enc,
registry,
device,
&logits,
&ids,
&routing_weights,
rows,
ne,
shape.num_experts_per_tok,
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} top-k: {e}"))?;
if route_mask.is_some() {
enc.memory_barrier();
}
if let Some(mask) = route_mask {
dispatch_dflash2_mask_moe_routes(
enc,
registry,
device,
mask.verify_rows,
&ids,
&routing_weights,
mask.params,
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} DFlash2 route mask: {e}"))?;
}
dispatch_silu_mul(
enc,
registry,
device.metal_device(),
&a_s,
&b_s,
&h_s,
&silu_sh_params,
n_h_s,
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} shared swiglu: {e}"))?;
enc.memory_barrier();
let gate_params = GgmlQuantizedMatmulIdParams {
n_tokens: rows,
top_k: shape.num_experts_per_tok,
n: shape.moe_intermediate_size,
k: h32,
n_experts: ne,
expert_stride: weights.expert_gate_stride,
ggml_type: weights.ggml_type_gate_up,
};
let up_params = GgmlQuantizedMatmulIdParams {
expert_stride: weights.expert_up_stride,
..gate_params
};
let staged_projection = if route_mask.is_some() {
quantized_matmul_id_ggml_grouped_m8_epilogue_masked
} else {
quantized_matmul_id_ggml_grouped_m8_epilogue
};
if staged_m8 {
super::decode_pool::with_id_mm_scratch(
super::decode_pool::MmIdSlot::Gate,
device,
ne,
rows * shape.num_experts_per_tok,
|scratch| {
let prepared = prepared_m8.expect("validated prepared M8");
staged_projection(
enc,
registry,
device,
x,
gathered_m8.as_ref().expect("allocated staged M8 input"),
&prepared.gate,
&ids,
&gate_all,
None,
scratch,
&gate_params,
false,
false,
false,
GroupedM8Input::F32,
GroupedM8Epilogue::F32,
)?;
staged_projection(
enc,
registry,
device,
x,
gathered_m8.as_ref().expect("allocated staged M8 input"),
&prepared.up,
&ids,
&up_all,
None,
scratch,
&up_params,
false,
true,
true,
GroupedM8Input::F32,
GroupedM8Epilogue::F32,
)
},
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} staged M8 gate/up: {e}"))?;
} else {
dispatch_expert_mv(
enc,
registry,
device,
x,
weights.experts.role(ExpertRole::Gate),
&ids,
&gate_all,
&gate_params,
"ffn_gate_exps",
layer_idx,
route_mask.is_some(),
)?;
dispatch_expert_mv(
enc,
registry,
device,
x,
weights.experts.role(ExpertRole::Up),
&ids,
&up_all,
&up_params,
"ffn_up_exps",
layer_idx,
route_mask.is_some(),
)?;
}
encode_native_dense_proj(
enc,
registry,
device,
&h_s,
weights,
MoeDenseRole::SharedDown,
&y_s,
rows,
m_sh32,
h32,
)
.with_context(|| format!("batched MoE layer {layer_idx}"))?;
enc.memory_barrier();
dispatch_silu_mul(
enc,
registry,
device.metal_device(),
&gate_all,
&up_all,
&h_all,
&silu_params,
n_h_all,
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} expert swiglu: {e}"))?;
enc.memory_barrier();
let down_params = GgmlQuantizedMatmulIdParams {
n_tokens: pairs as u32,
top_k: 1,
n: h32,
k: shape.moe_intermediate_size,
n_experts: ne,
expert_stride: weights.expert_down_stride,
ggml_type: weights.ggml_type_down,
};
if staged_m8 {
let slotted_down_params = GgmlQuantizedMatmulIdParams {
n_tokens: rows,
top_k: shape.num_experts_per_tok,
..down_params
};
super::decode_pool::with_id_mm_scratch(
super::decode_pool::MmIdSlot::Gate,
device,
ne,
rows * shape.num_experts_per_tok,
|scratch| {
staged_projection(
enc,
registry,
device,
&h_all,
gathered_m8.as_ref().expect("allocated staged M8 input"),
&prepared_m8.expect("validated prepared M8").down,
&ids,
&y_all,
None,
scratch,
&slotted_down_params,
true,
true,
false,
GroupedM8Input::F32,
GroupedM8Epilogue::F32,
)
},
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} staged M8 down: {e}"))?;
} else {
dispatch_expert_mv(
enc,
registry,
device,
&h_all,
weights.experts.role(ExpertRole::Down),
&ids,
&y_all,
&down_params,
"ffn_down_exps",
layer_idx,
route_mask.is_some(),
)?;
}
enc.memory_barrier();
let weighted_reduce = if staged_m8 && route_mask.is_some() {
dispatch_moe_weighted_reduce_masked
} else {
dispatch_moe_weighted_reduce
};
weighted_reduce(
enc,
registry,
device,
&routing_weights,
&y_all,
&sh_logit,
&y_s,
residual_ref,
out,
rows,
shape.num_experts_per_tok,
h32,
residual.is_some(),
)
.map_err(|e| anyhow!("batched MoE layer {layer_idx} weighted reduce: {e}"))?;
#[cfg(test)]
retain_routing_for_tests(&logits, &ids, &routing_weights, r, ne as usize, top_k)?;
Ok(MoeBatchedRouting {
ids,
weights: routing_weights,
})
}
#[cfg(test)]
pub(super) fn retain_routing_for_tests(
logits: &MlxBuffer,
ids: &MlxBuffer,
routing_weights: &MlxBuffer,
rows: usize,
experts: usize,
top_k: usize,
) -> Result<()> {
use crate::adr063_invariance::qwen::retain_current;
retain_current("moe_router_logits", logits, vec![rows, experts]).map_err(anyhow::Error::msg)?;
retain_current("moe_router_ids", ids, vec![rows, top_k]).map_err(anyhow::Error::msg)?;
retain_current("moe_router_weights", routing_weights, vec![rows, top_k])
.map_err(anyhow::Error::msg)
}