use anyhow::{anyhow, Result};
use mlx_native::{DType, MlxBuffer, MlxDevice};
pub struct DenseFfnArena {
pub gate_buf: MlxBuffer,
pub up_buf: MlxBuffer,
pub hidden_buf: MlxBuffer,
pub silu_params_buf: MlxBuffer,
pub down_out_buf: MlxBuffer,
pub seq_capacity: u32,
pub hidden_size: u32,
pub intermediate_size: u32,
}
impl DenseFfnArena {
pub fn new(
device: &MlxDevice,
seq_capacity: u32,
hidden_size: u32,
intermediate_size: u32,
) -> Result<Self> {
if seq_capacity == 0 || hidden_size == 0 || intermediate_size == 0 {
return Err(anyhow!(
"DenseFfnArena::new: zero dim \
seq_capacity={} hidden_size={} intermediate_size={}",
seq_capacity,
hidden_size,
intermediate_size
));
}
let seq = seq_capacity as usize;
let h = hidden_size as usize;
let m = intermediate_size as usize;
let n_h_bytes = seq * m * 4;
let n_out_bytes = seq * h * 4;
let gate_buf = device
.alloc_buffer(n_h_bytes, DType::F32, vec![seq, m])
.map_err(|e| anyhow!("DenseFfnArena alloc gate_buf: {e}"))?;
let up_buf = device
.alloc_buffer(n_h_bytes, DType::F32, vec![seq, m])
.map_err(|e| anyhow!("DenseFfnArena alloc up_buf: {e}"))?;
let hidden_buf = device
.alloc_buffer(n_h_bytes, DType::F32, vec![seq, m])
.map_err(|e| anyhow!("DenseFfnArena alloc hidden_buf: {e}"))?;
let silu_params_buf = device
.alloc_buffer(4, DType::U32, vec![1])
.map_err(|e| anyhow!("DenseFfnArena alloc silu_params_buf: {e}"))?;
let down_out_buf = device
.alloc_buffer(n_out_bytes, DType::F32, vec![seq, h])
.map_err(|e| anyhow!("DenseFfnArena alloc down_out_buf: {e}"))?;
Ok(Self {
gate_buf,
up_buf,
hidden_buf,
silu_params_buf,
down_out_buf,
seq_capacity,
hidden_size,
intermediate_size,
})
}
pub fn validate_fits(
&self,
seq_len: u32,
hidden_size: u32,
intermediate_size: u32,
) -> Result<()> {
if seq_len > self.seq_capacity {
return Err(anyhow!(
"DenseFfnArena::validate_fits: seq_len {} exceeds capacity {}",
seq_len,
self.seq_capacity
));
}
if hidden_size != self.hidden_size || intermediate_size != self.intermediate_size {
return Err(anyhow!(
"DenseFfnArena::validate_fits: shape mismatch — \
arena (hidden_size={}, intermediate_size={}) vs \
call (hidden_size={}, intermediate_size={})",
self.hidden_size,
self.intermediate_size,
hidden_size,
intermediate_size,
));
}
Ok(())
}
}
pub struct MoeFfnArena {
pub ids_buf: MlxBuffer,
pub weights_buf: MlxBuffer,
pub gate_all_buf: MlxBuffer,
pub up_all_buf: MlxBuffer,
pub h_all_buf: MlxBuffer,
pub y_all_buf: MlxBuffer,
pub h_s_buf: MlxBuffer,
pub silu_params_buf: MlxBuffer,
pub silu_sh_params_buf: MlxBuffer,
pub dummy_residual_buf: MlxBuffer,
pub logits_buf: MlxBuffer,
pub sh_logit_buf: MlxBuffer,
pub a_s_buf: MlxBuffer,
pub b_s_buf: MlxBuffer,
pub seq_capacity: u32,
pub hidden_size: u32,
pub num_experts_per_tok: u32,
pub moe_intermediate_size: u32,
pub shared_intermediate_size: u32,
pub num_experts: u32,
}
impl MoeFfnArena {
pub fn new(
device: &MlxDevice,
seq_capacity: u32,
hidden_size: u32,
num_experts_per_tok: u32,
moe_intermediate_size: u32,
shared_intermediate_size: u32,
num_experts: u32,
) -> Result<Self> {
if seq_capacity == 0
|| hidden_size == 0
|| num_experts_per_tok == 0
|| moe_intermediate_size == 0
|| shared_intermediate_size == 0
|| num_experts == 0
{
return Err(anyhow!(
"MoeFfnArena::new: zero dim \
seq_capacity={} hidden_size={} num_experts_per_tok={} \
moe_intermediate_size={} shared_intermediate_size={} \
num_experts={}",
seq_capacity,
hidden_size,
num_experts_per_tok,
moe_intermediate_size,
shared_intermediate_size,
num_experts,
));
}
let seq = seq_capacity as usize;
let h = hidden_size as usize;
let topk = num_experts_per_tok as usize;
let m_moe = moe_intermediate_size as usize;
let m_sh = shared_intermediate_size as usize;
let ne = num_experts as usize;
let total_rows = seq * topk;
let ids_buf = device
.alloc_buffer(total_rows * 4, DType::U32, vec![total_rows])
.map_err(|e| anyhow!("MoeFfnArena alloc ids_buf: {e}"))?;
let weights_buf = device
.alloc_buffer(total_rows * 4, DType::F32, vec![total_rows])
.map_err(|e| anyhow!("MoeFfnArena alloc weights_buf: {e}"))?;
let gate_all_bytes = total_rows * m_moe * 4;
let gate_all_buf = device
.alloc_buffer(gate_all_bytes, DType::F32, vec![total_rows, m_moe])
.map_err(|e| anyhow!("MoeFfnArena alloc gate_all_buf: {e}"))?;
let up_all_buf = device
.alloc_buffer(gate_all_bytes, DType::F32, vec![total_rows, m_moe])
.map_err(|e| anyhow!("MoeFfnArena alloc up_all_buf: {e}"))?;
let h_all_buf = device
.alloc_buffer(gate_all_bytes, DType::F32, vec![total_rows, m_moe])
.map_err(|e| anyhow!("MoeFfnArena alloc h_all_buf: {e}"))?;
let y_all_bytes = total_rows * h * 4;
let y_all_buf = device
.alloc_buffer(y_all_bytes, DType::F32, vec![total_rows, h])
.map_err(|e| anyhow!("MoeFfnArena alloc y_all_buf: {e}"))?;
let h_s_bytes = seq * m_sh * 4;
let h_s_buf = device
.alloc_buffer(h_s_bytes, DType::F32, vec![seq, m_sh])
.map_err(|e| anyhow!("MoeFfnArena alloc h_s_buf: {e}"))?;
let silu_params_buf = device
.alloc_buffer(4, DType::U32, vec![1])
.map_err(|e| anyhow!("MoeFfnArena alloc silu_params_buf: {e}"))?;
let silu_sh_params_buf = device
.alloc_buffer(4, DType::U32, vec![1])
.map_err(|e| anyhow!("MoeFfnArena alloc silu_sh_params_buf: {e}"))?;
let dummy_residual_buf = device
.alloc_buffer(4, DType::F32, vec![1])
.map_err(|e| anyhow!("MoeFfnArena alloc dummy_residual_buf: {e}"))?;
let logits_bytes = seq * ne * 4;
let logits_buf = device
.alloc_buffer(logits_bytes, DType::F32, vec![seq, ne])
.map_err(|e| anyhow!("MoeFfnArena alloc logits_buf: {e}"))?;
let sh_logit_bytes = seq * 4;
let sh_logit_buf = device
.alloc_buffer(sh_logit_bytes, DType::F32, vec![seq, 1])
.map_err(|e| anyhow!("MoeFfnArena alloc sh_logit_buf: {e}"))?;
let a_s_bytes = seq * m_sh * 4;
let a_s_buf = device
.alloc_buffer(a_s_bytes, DType::F32, vec![seq, m_sh])
.map_err(|e| anyhow!("MoeFfnArena alloc a_s_buf: {e}"))?;
let b_s_buf = device
.alloc_buffer(a_s_bytes, DType::F32, vec![seq, m_sh])
.map_err(|e| anyhow!("MoeFfnArena alloc b_s_buf: {e}"))?;
Ok(Self {
ids_buf,
weights_buf,
gate_all_buf,
up_all_buf,
h_all_buf,
y_all_buf,
h_s_buf,
silu_params_buf,
silu_sh_params_buf,
dummy_residual_buf,
logits_buf,
sh_logit_buf,
a_s_buf,
b_s_buf,
seq_capacity,
hidden_size,
num_experts_per_tok,
moe_intermediate_size,
shared_intermediate_size,
num_experts,
})
}
pub fn validate_fits(
&self,
seq_len: u32,
hidden_size: u32,
num_experts_per_tok: u32,
moe_intermediate_size: u32,
shared_intermediate_size: u32,
num_experts: u32,
) -> Result<()> {
if seq_len > self.seq_capacity {
return Err(anyhow!(
"MoeFfnArena::validate_fits: seq_len {} exceeds capacity {}",
seq_len,
self.seq_capacity
));
}
if hidden_size != self.hidden_size
|| num_experts_per_tok != self.num_experts_per_tok
|| moe_intermediate_size != self.moe_intermediate_size
|| shared_intermediate_size != self.shared_intermediate_size
|| num_experts != self.num_experts
{
return Err(anyhow!(
"MoeFfnArena::validate_fits: shape mismatch — \
arena (h={}, topk={}, m_moe={}, m_sh={}, ne={}) vs \
call (h={}, topk={}, m_moe={}, m_sh={}, ne={})",
self.hidden_size,
self.num_experts_per_tok,
self.moe_intermediate_size,
self.shared_intermediate_size,
self.num_experts,
hidden_size,
num_experts_per_tok,
moe_intermediate_size,
shared_intermediate_size,
num_experts,
));
}
Ok(())
}
}
pub struct LayerBoundaryArena {
pub ffn_input_buf: MlxBuffer,
pub ffn_residual_buf: MlxBuffer,
pub seq_capacity: u32,
pub hidden_size: u32,
}
impl LayerBoundaryArena {
pub fn new(device: &MlxDevice, seq_capacity: u32, hidden_size: u32) -> Result<Self> {
if seq_capacity == 0 || hidden_size == 0 {
return Err(anyhow!(
"LayerBoundaryArena::new: zero dim seq_capacity={} hidden_size={}",
seq_capacity,
hidden_size,
));
}
let bytes = (seq_capacity as usize) * (hidden_size as usize) * 4;
let shape = vec![seq_capacity as usize, hidden_size as usize];
let ffn_input_buf = device
.alloc_buffer(bytes, DType::F32, shape.clone())
.map_err(|e| anyhow!("LayerBoundaryArena alloc ffn_input_buf: {e}"))?;
let ffn_residual_buf = device
.alloc_buffer(bytes, DType::F32, shape)
.map_err(|e| anyhow!("LayerBoundaryArena alloc ffn_residual_buf: {e}"))?;
Ok(Self {
ffn_input_buf,
ffn_residual_buf,
seq_capacity,
hidden_size,
})
}
pub fn validate_fits(&self, seq_len: u32, hidden_size: u32) -> Result<()> {
if seq_len > self.seq_capacity {
return Err(anyhow!(
"LayerBoundaryArena::validate_fits: seq_len {} exceeds capacity {}",
seq_len,
self.seq_capacity
));
}
if hidden_size != self.hidden_size {
return Err(anyhow!(
"LayerBoundaryArena::validate_fits: hidden_size {} != arena {}",
hidden_size,
self.hidden_size
));
}
Ok(())
}
}
pub struct DenseFfnOutputRingBuffer {
slot0: MlxBuffer,
slot1: MlxBuffer,
pub seq_capacity: u32,
pub hidden_size: u32,
}
impl DenseFfnOutputRingBuffer {
pub fn new(device: &MlxDevice, seq_capacity: u32, hidden_size: u32) -> Result<Self> {
if seq_capacity == 0 || hidden_size == 0 {
return Err(anyhow!(
"DenseFfnOutputRingBuffer::new: zero dim seq_capacity={} hidden_size={}",
seq_capacity,
hidden_size,
));
}
let bytes = (seq_capacity as usize) * (hidden_size as usize) * 4;
let shape = vec![seq_capacity as usize, hidden_size as usize];
let slot0 = device
.alloc_buffer(bytes, DType::F32, shape.clone())
.map_err(|e| anyhow!("DenseFfnOutputRingBuffer alloc slot0: {e}"))?;
let slot1 = device
.alloc_buffer(bytes, DType::F32, shape)
.map_err(|e| anyhow!("DenseFfnOutputRingBuffer alloc slot1: {e}"))?;
Ok(Self {
slot0,
slot1,
seq_capacity,
hidden_size,
})
}
pub fn validate_fits(&self, seq_len: u32, hidden_size: u32) -> Result<()> {
if seq_len > self.seq_capacity {
return Err(anyhow!(
"DenseFfnOutputRingBuffer::validate_fits: seq_len {} exceeds capacity {}",
seq_len,
self.seq_capacity,
));
}
if hidden_size != self.hidden_size {
return Err(anyhow!(
"DenseFfnOutputRingBuffer::validate_fits: hidden_size {} != ring {}",
hidden_size,
self.hidden_size,
));
}
Ok(())
}
pub fn slot_mut(&mut self, layer_idx: u32) -> &mut MlxBuffer {
if layer_idx % 2 == 0 {
&mut self.slot0
} else {
&mut self.slot1
}
}
pub fn slot_clone(&self, layer_idx: u32) -> MlxBuffer {
if layer_idx % 2 == 0 {
self.slot0.clone()
} else {
self.slot1.clone()
}
}
}
pub struct MoeFfnOutputRingBuffer {
slot0: MlxBuffer,
slot1: MlxBuffer,
pub seq_capacity: u32,
pub hidden_size: u32,
}
impl MoeFfnOutputRingBuffer {
pub fn new(device: &MlxDevice, seq_capacity: u32, hidden_size: u32) -> Result<Self> {
if seq_capacity == 0 || hidden_size == 0 {
return Err(anyhow!(
"MoeFfnOutputRingBuffer::new: zero dim seq_capacity={} hidden_size={}",
seq_capacity,
hidden_size,
));
}
let bytes = (seq_capacity as usize) * (hidden_size as usize) * 4;
let shape = vec![seq_capacity as usize, hidden_size as usize];
let slot0 = device
.alloc_buffer(bytes, DType::F32, shape.clone())
.map_err(|e| anyhow!("MoeFfnOutputRingBuffer alloc slot0: {e}"))?;
let slot1 = device
.alloc_buffer(bytes, DType::F32, shape)
.map_err(|e| anyhow!("MoeFfnOutputRingBuffer alloc slot1: {e}"))?;
Ok(Self {
slot0,
slot1,
seq_capacity,
hidden_size,
})
}
pub fn validate_fits(&self, seq_len: u32, hidden_size: u32) -> Result<()> {
if seq_len > self.seq_capacity {
return Err(anyhow!(
"MoeFfnOutputRingBuffer::validate_fits: seq_len {} exceeds capacity {}",
seq_len,
self.seq_capacity,
));
}
if hidden_size != self.hidden_size {
return Err(anyhow!(
"MoeFfnOutputRingBuffer::validate_fits: hidden_size {} != ring {}",
hidden_size,
self.hidden_size,
));
}
Ok(())
}
pub fn slot_mut(&mut self, layer_idx: u32) -> &mut MlxBuffer {
if layer_idx % 2 == 0 {
&mut self.slot0
} else {
&mut self.slot1
}
}
pub fn slot_clone(&self, layer_idx: u32) -> MlxBuffer {
if layer_idx % 2 == 0 {
self.slot0.clone()
} else {
self.slot1.clone()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn device_or_skip() -> Option<MlxDevice> {
MlxDevice::new().ok()
}
#[test]
fn test_arena_new_qwen36_27b_pp4096() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_arena_new_qwen36_27b_pp4096: skipping — no Metal device");
return;
}
};
let (seq, h, m) = (4096u32, 5120u32, 17408u32);
let arena = DenseFfnArena::new(&device, seq, h, m).expect("arena new pp4096");
assert_eq!(arena.seq_capacity, seq);
assert_eq!(arena.hidden_size, h);
assert_eq!(arena.intermediate_size, m);
let n_h_bytes = (seq as usize) * (m as usize) * 4;
let n_out_bytes = (seq as usize) * (h as usize) * 4;
assert_eq!(arena.gate_buf.byte_len(), n_h_bytes, "gate_buf byte_len");
assert_eq!(arena.up_buf.byte_len(), n_h_bytes, "up_buf byte_len");
assert_eq!(
arena.hidden_buf.byte_len(),
n_h_bytes,
"hidden_buf byte_len"
);
assert_eq!(arena.silu_params_buf.byte_len(), 4, "silu_params byte_len");
assert_eq!(
arena.down_out_buf.byte_len(),
n_out_bytes,
"down_out_buf byte_len"
);
}
#[test]
fn test_arena_new_small_shape() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_arena_new_small_shape: skipping — no Metal device");
return;
}
};
let arena = DenseFfnArena::new(&device, 64, 128, 256).expect("arena new small");
assert_eq!(arena.seq_capacity, 64);
}
#[test]
fn test_arena_new_zero_dim_rejected() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_arena_new_zero_dim_rejected: skipping — no Metal device");
return;
}
};
assert!(DenseFfnArena::new(&device, 0, 128, 256).is_err());
assert!(DenseFfnArena::new(&device, 64, 0, 256).is_err());
assert!(DenseFfnArena::new(&device, 64, 128, 0).is_err());
}
#[test]
fn test_validate_fits_exact_match() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_validate_fits_exact_match: skipping — no Metal device");
return;
}
};
let arena = DenseFfnArena::new(&device, 128, 256, 512).expect("arena new");
assert!(arena.validate_fits(128, 256, 512).is_ok());
assert!(arena.validate_fits(64, 256, 512).is_ok());
}
#[test]
fn test_validate_fits_seq_overrun() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_validate_fits_seq_overrun: skipping — no Metal device");
return;
}
};
let arena = DenseFfnArena::new(&device, 128, 256, 512).expect("arena new");
assert!(arena.validate_fits(256, 256, 512).is_err());
}
#[test]
fn test_validate_fits_shape_mismatch() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_validate_fits_shape_mismatch: skipping — no Metal device");
return;
}
};
let arena = DenseFfnArena::new(&device, 128, 256, 512).expect("arena new");
assert!(arena.validate_fits(128, 128, 512).is_err());
assert!(arena.validate_fits(128, 256, 256).is_err());
}
#[test]
fn test_arena_buffers_zero_initialized() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_arena_buffers_zero_initialized: skipping — no Metal device");
return;
}
};
let arena = DenseFfnArena::new(&device, 64, 128, 256).expect("arena new");
let bufs: [(&MlxBuffer, &str); 3] = [
(&arena.gate_buf, "gate_buf"),
(&arena.up_buf, "up_buf"),
(&arena.hidden_buf, "hidden_buf"),
];
for (buf, name) in &bufs {
let slice = buf
.as_slice::<f32>()
.unwrap_or_else(|e| panic!("{name} as_slice::<f32> failed: {e}"));
let check_len = 16.min(slice.len());
for (i, &v) in slice[..check_len].iter().enumerate() {
assert_eq!(
v, 0.0f32,
"{name}[{i}] = {v} (expected zero from device.alloc_buffer)"
);
}
}
let slice = arena
.silu_params_buf
.as_slice::<u32>()
.expect("silu_params as_slice::<u32>");
assert_eq!(
slice[0], 0u32,
"silu_params[0] should be zero from device.alloc_buffer"
);
}
#[test]
fn test_moe_arena_new_qwen36_35b_pp4096() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_arena_new_qwen36_35b_pp4096: skipping — no Metal device");
return;
}
};
let (seq, h, topk, m_moe, m_sh, ne) = (4096u32, 5120u32, 8u32, 512u32, 512u32, 128u32);
let arena =
MoeFfnArena::new(&device, seq, h, topk, m_moe, m_sh, ne).expect("moe arena new");
assert_eq!(arena.seq_capacity, seq);
assert_eq!(arena.hidden_size, h);
assert_eq!(arena.num_experts_per_tok, topk);
assert_eq!(arena.moe_intermediate_size, m_moe);
assert_eq!(arena.shared_intermediate_size, m_sh);
assert_eq!(arena.num_experts, ne);
let total_rows = (seq as usize) * (topk as usize);
let gate_all_bytes = total_rows * (m_moe as usize) * 4;
let y_all_bytes = total_rows * (h as usize) * 4;
let h_s_bytes = (seq as usize) * (m_sh as usize) * 4;
assert_eq!(
arena.gate_all_buf.byte_len(),
gate_all_bytes,
"gate_all_buf"
);
assert_eq!(arena.up_all_buf.byte_len(), gate_all_bytes, "up_all_buf");
assert_eq!(arena.h_all_buf.byte_len(), gate_all_bytes, "h_all_buf");
assert_eq!(arena.y_all_buf.byte_len(), y_all_bytes, "y_all_buf");
assert_eq!(arena.h_s_buf.byte_len(), h_s_bytes, "h_s_buf");
let logits_bytes = (seq as usize) * (ne as usize) * 4;
let sh_logit_bytes = (seq as usize) * 4;
let a_s_bytes = (seq as usize) * (m_sh as usize) * 4;
assert_eq!(arena.logits_buf.byte_len(), logits_bytes, "logits_buf");
assert_eq!(
arena.sh_logit_buf.byte_len(),
sh_logit_bytes,
"sh_logit_buf"
);
assert_eq!(arena.a_s_buf.byte_len(), a_s_bytes, "a_s_buf");
assert_eq!(arena.b_s_buf.byte_len(), a_s_bytes, "b_s_buf");
}
#[test]
fn test_moe_arena_new_small_shape() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_arena_new_small_shape: skipping — no Metal device");
return;
}
};
let arena = MoeFfnArena::new(&device, 64, 128, 4, 256, 128, 8).expect("moe arena new");
assert_eq!(arena.seq_capacity, 64);
assert_eq!(arena.num_experts, 8);
}
#[test]
fn test_moe_arena_new_zero_dim_rejected() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_arena_new_zero_dim_rejected: skipping — no Metal device");
return;
}
};
assert!(MoeFfnArena::new(&device, 0, 128, 4, 256, 128, 8).is_err());
assert!(MoeFfnArena::new(&device, 64, 0, 4, 256, 128, 8).is_err());
assert!(MoeFfnArena::new(&device, 64, 128, 0, 256, 128, 8).is_err());
assert!(MoeFfnArena::new(&device, 64, 128, 4, 0, 128, 8).is_err());
assert!(MoeFfnArena::new(&device, 64, 128, 4, 256, 0, 8).is_err());
assert!(MoeFfnArena::new(&device, 64, 128, 4, 256, 128, 0).is_err());
}
#[test]
fn test_moe_validate_fits_exact_match() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_validate_fits_exact_match: skipping — no Metal device");
return;
}
};
let arena = MoeFfnArena::new(&device, 128, 256, 4, 512, 256, 16).expect("moe arena new");
assert!(arena.validate_fits(128, 256, 4, 512, 256, 16).is_ok());
assert!(arena.validate_fits(64, 256, 4, 512, 256, 16).is_ok());
}
#[test]
fn test_moe_validate_fits_seq_overrun() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_validate_fits_seq_overrun: skipping — no Metal device");
return;
}
};
let arena = MoeFfnArena::new(&device, 128, 256, 4, 512, 256, 16).expect("moe arena new");
assert!(arena.validate_fits(256, 256, 4, 512, 256, 16).is_err());
}
#[test]
fn test_moe_validate_fits_shape_mismatch() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_validate_fits_shape_mismatch: skipping — no Metal device");
return;
}
};
let arena = MoeFfnArena::new(&device, 128, 256, 4, 512, 256, 16).expect("moe arena new");
assert!(arena.validate_fits(128, 128, 4, 512, 256, 16).is_err());
assert!(arena.validate_fits(128, 256, 8, 512, 256, 16).is_err());
assert!(arena.validate_fits(128, 256, 4, 256, 256, 16).is_err());
assert!(arena.validate_fits(128, 256, 4, 512, 128, 16).is_err());
assert!(arena.validate_fits(128, 256, 4, 512, 256, 32).is_err());
}
#[test]
fn test_layer_boundary_arena_new_apex_shape() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_layer_boundary_arena_new_apex_shape: skipping — no Metal device");
return;
}
};
let (seq, h) = (4096u32, 5120u32);
let arena = LayerBoundaryArena::new(&device, seq, h).expect("new");
assert_eq!(arena.seq_capacity, seq);
assert_eq!(arena.hidden_size, h);
let bytes = (seq as usize) * (h as usize) * 4;
assert_eq!(arena.ffn_input_buf.byte_len(), bytes, "ffn_input_buf");
assert_eq!(arena.ffn_residual_buf.byte_len(), bytes, "ffn_residual_buf");
}
#[test]
fn test_layer_boundary_arena_zero_dim_rejected() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!(
"test_layer_boundary_arena_zero_dim_rejected: skipping — no Metal device"
);
return;
}
};
assert!(LayerBoundaryArena::new(&device, 0, 128).is_err());
assert!(LayerBoundaryArena::new(&device, 128, 0).is_err());
}
#[test]
fn test_layer_boundary_arena_validate_fits() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_layer_boundary_arena_validate_fits: skipping — no Metal device");
return;
}
};
let arena = LayerBoundaryArena::new(&device, 128, 256).expect("new");
assert!(arena.validate_fits(128, 256).is_ok());
assert!(arena.validate_fits(64, 256).is_ok());
assert!(arena.validate_fits(256, 256).is_err()); assert!(arena.validate_fits(128, 128).is_err()); }
#[test]
fn test_layer_boundary_arena_clone_preserves_pointer() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!(
"test_layer_boundary_arena_clone_preserves_pointer: skipping — no Metal device"
);
return;
}
};
let arena = LayerBoundaryArena::new(&device, 64, 128).expect("new");
let original_ptr = arena.ffn_input_buf.contents_ptr();
let cloned = arena.ffn_input_buf.clone();
assert_eq!(
cloned.contents_ptr(),
original_ptr,
"MlxBuffer::clone must preserve the underlying Metal allocation pointer \
(Arc-based)"
);
drop(cloned);
assert_eq!(
arena.ffn_input_buf.contents_ptr(),
original_ptr,
"arena buffer pointer unchanged after clone drop"
);
}
#[test]
fn test_dense_ring_new_apex_shape() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_dense_ring_new_apex_shape: skipping — no Metal device");
return;
}
};
let (seq, h) = (4096u32, 5120u32);
let ring = DenseFfnOutputRingBuffer::new(&device, seq, h).expect("new");
assert_eq!(ring.seq_capacity, seq);
assert_eq!(ring.hidden_size, h);
let bytes = (seq as usize) * (h as usize) * 4;
assert_eq!(ring.slot0.byte_len(), bytes, "slot0 byte_len");
assert_eq!(ring.slot1.byte_len(), bytes, "slot1 byte_len");
}
#[test]
fn test_moe_ring_new_apex_shape() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_ring_new_apex_shape: skipping — no Metal device");
return;
}
};
let (seq, h) = (4096u32, 5120u32);
let ring = MoeFfnOutputRingBuffer::new(&device, seq, h).expect("new");
assert_eq!(ring.seq_capacity, seq);
assert_eq!(ring.hidden_size, h);
let bytes = (seq as usize) * (h as usize) * 4;
assert_eq!(ring.slot0.byte_len(), bytes, "slot0 byte_len");
assert_eq!(ring.slot1.byte_len(), bytes, "slot1 byte_len");
}
#[test]
fn test_ring_new_zero_dim_rejected() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_ring_new_zero_dim_rejected: skipping — no Metal device");
return;
}
};
assert!(DenseFfnOutputRingBuffer::new(&device, 0, 128).is_err());
assert!(DenseFfnOutputRingBuffer::new(&device, 128, 0).is_err());
assert!(MoeFfnOutputRingBuffer::new(&device, 0, 128).is_err());
assert!(MoeFfnOutputRingBuffer::new(&device, 128, 0).is_err());
}
#[test]
fn test_ring_validate_fits() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_ring_validate_fits: skipping — no Metal device");
return;
}
};
let dense = DenseFfnOutputRingBuffer::new(&device, 128, 256).expect("new");
assert!(dense.validate_fits(128, 256).is_ok());
assert!(dense.validate_fits(64, 256).is_ok());
assert!(dense.validate_fits(256, 256).is_err()); assert!(dense.validate_fits(128, 128).is_err());
let moe = MoeFfnOutputRingBuffer::new(&device, 128, 256).expect("new");
assert!(moe.validate_fits(128, 256).is_ok());
assert!(moe.validate_fits(256, 256).is_err());
assert!(moe.validate_fits(128, 128).is_err());
}
#[test]
fn test_dense_ring_slot_rotation() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_dense_ring_slot_rotation: skipping — no Metal device");
return;
}
};
let mut ring = DenseFfnOutputRingBuffer::new(&device, 64, 128).expect("new");
let slot0_ptr = ring.slot_mut(0).contents_ptr();
let slot1_ptr = ring.slot_mut(1).contents_ptr();
assert_ne!(slot0_ptr, slot1_ptr, "slots must be physically distinct");
assert_eq!(ring.slot_mut(2).contents_ptr(), slot0_ptr, "even rotation");
assert_eq!(ring.slot_mut(3).contents_ptr(), slot1_ptr, "odd rotation");
assert_eq!(
ring.slot_mut(64).contents_ptr(),
slot0_ptr,
"high layer wrap"
);
assert_eq!(
ring.slot_mut(65).contents_ptr(),
slot1_ptr,
"high layer wrap"
);
let clone0 = ring.slot_clone(0);
assert_eq!(clone0.contents_ptr(), slot0_ptr, "clone preserves ptr");
let clone2 = ring.slot_clone(2);
assert_eq!(clone2.contents_ptr(), slot0_ptr, "rotation+clone");
}
#[test]
fn test_moe_ring_slot_rotation() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_moe_ring_slot_rotation: skipping — no Metal device");
return;
}
};
let mut ring = MoeFfnOutputRingBuffer::new(&device, 64, 128).expect("new");
let slot0_ptr = ring.slot_mut(0).contents_ptr();
let slot1_ptr = ring.slot_mut(1).contents_ptr();
assert_ne!(slot0_ptr, slot1_ptr);
assert_eq!(ring.slot_mut(2).contents_ptr(), slot0_ptr);
assert_eq!(ring.slot_mut(15).contents_ptr(), slot1_ptr);
let clone15 = ring.slot_clone(15);
assert_eq!(clone15.contents_ptr(), slot1_ptr);
}
#[test]
fn test_dense_ring_clone_outlives_drop() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let device = match device_or_skip() {
Some(d) => d,
None => {
eprintln!("test_dense_ring_clone_outlives_drop: skipping — no Metal device");
return;
}
};
let ring = DenseFfnOutputRingBuffer::new(&device, 64, 128).expect("new");
let original_ptr = ring.slot0.contents_ptr();
let clone = ring.slot_clone(0);
assert_eq!(clone.contents_ptr(), original_ptr);
drop(clone);
assert_eq!(
ring.slot0.contents_ptr(),
original_ptr,
"ring slot0 unchanged after clone drop"
);
}
}