pub mod profile;
use std::cell::RefCell;
use mlx_native::ops::quantized_matmul_id_ggml::IdMmScratch;
use mlx_native::{DType, MlxBuffer, MlxBufferPool, MlxDevice};
thread_local! {
static DECODE_POOL: RefCell<MlxBufferPool> = RefCell::new(MlxBufferPool::new());
static MM_ID_SCRATCH_GATE: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
static MM_ID_SCRATCH_UP: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
static MM_ID_SCRATCH_DOWN: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
}
pub(crate) fn worker_memory_snapshot() -> Result<(&'static str, mlx_native::PoolMemorySnapshot), String> {
if let Some(result) = profile::memory_snapshot_if_selected() {
return result.map(|snapshot| ("growth_limited", snapshot));
}
DECODE_POOL.try_with(|cell| {
let pool = cell.try_borrow().map_err(|_| "legacy pool borrow busy".to_string())?;
pool.memory_snapshot().map(|snapshot| ("legacy", snapshot)).map_err(|error| error.to_string())
}).map_err(|_| "legacy worker TLS unavailable".to_string()).and_then(|r| r)
}
#[inline]
pub fn pooled_alloc_buffer(
device: &MlxDevice,
byte_len: usize,
dtype: DType,
shape: Vec<usize>,
) -> std::result::Result<MlxBuffer, mlx_native::MlxError> {
if let Some(result) = profile::alloc(device, byte_len, dtype, &shape) { return result; }
DECODE_POOL.with(|cell| cell.borrow_mut().alloc(device, byte_len, dtype, shape))
}
pub fn reset_decode_pool() {
if let Err(_error) = checked_reset_decode_pool() { profile::quarantine(); }
}
pub fn checked_reset_decode_pool() -> std::result::Result<(), mlx_native::MlxError> {
if let Some(result) = profile::reset() { return result; }
DECODE_POOL.with(|cell| cell.borrow_mut().reset());
Ok(())
}
pub fn reset_for_prefill_chunk() {
if let Err(_error) = checked_reset_for_prefill_chunk() { profile::quarantine(); }
}
pub fn checked_reset_for_prefill_chunk() -> std::result::Result<(), mlx_native::MlxError> {
checked_reset_decode_pool()
}
#[allow(dead_code)]
pub fn decode_pool_in_use_count() -> usize {
if let Some((issued, _)) = profile::counts() { return issued; }
DECODE_POOL.with(|cell| cell.borrow().in_use_count())
}
#[allow(dead_code)]
pub fn decode_pool_free_count() -> usize {
if let Some((_, free)) = profile::counts() { return free; }
DECODE_POOL.with(|cell| cell.borrow().free_count())
}
#[derive(Debug, Clone, Copy)]
pub enum MmIdSlot {
Gate,
Up,
Down,
}
pub fn with_id_mm_scratch<F, R>(
slot: MmIdSlot,
device: &MlxDevice,
n_experts: u32,
max_n_tokens: u32,
f: F,
) -> std::result::Result<R, mlx_native::MlxError>
where
F: FnOnce(&mut IdMmScratch) -> std::result::Result<R, mlx_native::MlxError>,
{
let cell = match slot {
MmIdSlot::Gate => &MM_ID_SCRATCH_GATE,
MmIdSlot::Up => &MM_ID_SCRATCH_UP,
MmIdSlot::Down => &MM_ID_SCRATCH_DOWN,
};
cell.with(|cell| {
let mut guard = cell.borrow_mut();
let needs_realloc = match guard.as_ref() {
None => true,
Some(scratch) => {
let cap_n_experts = scratch.htpe.element_count() as u32;
let cap_total = scratch.hids.element_count() as u64;
let cap_n_tokens = if cap_n_experts == 0 {
0
} else {
(cap_total / cap_n_experts as u64) as u32
};
n_experts > cap_n_experts || max_n_tokens > cap_n_tokens
}
};
if needs_realloc {
*guard = Some(IdMmScratch::alloc(device, n_experts, max_n_tokens)?);
}
let scratch = guard.as_mut().expect("just allocated");
f(scratch)
})
}
#[allow(dead_code)]
pub fn drop_id_mm_scratch() {
MM_ID_SCRATCH_GATE.with(|cell| *cell.borrow_mut() = None);
MM_ID_SCRATCH_UP.with(|cell| *cell.borrow_mut() = None);
MM_ID_SCRATCH_DOWN.with(|cell| *cell.borrow_mut() = None);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pool_resets_recycle_metal_buffers() {
let device = match MlxDevice::new() {
Ok(d) => d,
Err(_) => return,
};
let ptr_a = {
let buf =
pooled_alloc_buffer(&device, 1024, DType::F32, vec![256]).expect("cycle 1 alloc");
buf.contents_ptr()
};
assert!(decode_pool_in_use_count() >= 1);
reset_decode_pool();
assert_eq!(decode_pool_in_use_count(), 0);
let buf = pooled_alloc_buffer(&device, 1024, DType::F32, vec![256]).expect("cycle 2 alloc");
let ptr_b = buf.contents_ptr();
assert_eq!(
ptr_b, ptr_a,
"thread-local pool must reuse Metal buffer across reset"
);
reset_decode_pool();
}
}