mod device;
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)
}
pub(crate) fn worker_carry_pool_bytes() -> Result<u64, String> {
let native = worker_memory_snapshot()?.1.retained.bytes as u64;
OVERFLOW.try_with(|cell| {
let overflow = cell.try_borrow().map_err(|_| "carry overflow borrow busy".to_string())?;
overflow.iter().try_fold(native, |bytes, root| {
bytes.checked_add(root.byte_len() as u64)
.ok_or_else(|| "carry pool backing capacity overflow".to_string())
})
}).map_err(|_| "carry overflow TLS unavailable".to_string()).and_then(|result| result)
}
#[inline]
#[cfg_attr(test, track_caller)]
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; }
device::bind(device)?;
let bucket = byte_len.max(1).next_power_of_two();
ISSUED_BYTES.with(|issued| issued.set(issued.get() + bucket));
ISSUED_TOTAL.with(|issued| issued.set(issued.get() + bucket as u64));
#[cfg(test)]
{
let site = std::panic::Location::caller();
SCRATCH_TRACE.with(|trace| {
if let Some(trace) = trace.borrow_mut().as_mut() {
trace.push((site.file(), site.line(), byte_len));
}
});
}
if let Some(caps) = CAPS.with(std::cell::Cell::get) {
#[cfg(test)]
CAPPED_FREE_PEAK.with(|peak| {
peak.set(peak.get().max(DECODE_POOL.with(|cell| cell.borrow().free_bytes())))
});
let held = FREE_AT_RESET.with(std::cell::Cell::get)
+ POOLED_SINCE_RESET.with(std::cell::Cell::get);
if held.saturating_add(bucket) > caps.pool {
let buffer = device.alloc_buffer(byte_len, dtype, shape)?;
OVERFLOW.with(|overflow| overflow.borrow_mut().push(buffer.clone()));
return Ok(buffer);
}
}
let buffer = DECODE_POOL.with(|cell| cell.borrow_mut().alloc(device, byte_len, dtype, shape))?;
POOLED_SINCE_RESET.with(|pooled| pooled.set(pooled.get() + bucket));
Ok(buffer)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PoolCaps {
pub(crate) pool: usize,
pub(crate) retained: usize,
}
thread_local! {
static ISSUED_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static ISSUED_TOTAL: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static LAYER_SCRATCH_PEAK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static LAYER_SCRATCH_REPORTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static POOLED_SINCE_RESET: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static FREE_AT_RESET: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static CAPS: std::cell::Cell<Option<PoolCaps>> = const { std::cell::Cell::new(None) };
static CAPS_END_AT_RESET: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static OVERFLOW: RefCell<Vec<MlxBuffer>> = const { RefCell::new(Vec::new()) };
}
#[cfg(test)]
thread_local! {
static SCRATCH_TRACE: RefCell<Option<Vec<(&'static str, u32, usize)>>> =
const { RefCell::new(None) };
}
#[cfg(test)]
pub(crate) fn trace_scratch(on: bool) -> Vec<(&'static str, u32, usize)> {
SCRATCH_TRACE.with(|trace| trace.replace(on.then(Vec::new)).unwrap_or_default())
}
pub(crate) fn issued_bytes() -> usize {
ISSUED_BYTES.with(std::cell::Cell::get)
}
pub(crate) fn issued_total() -> u64 {
ISSUED_TOTAL.with(std::cell::Cell::get)
}
pub(crate) fn note_layer_scratch(bytes: u64, bound: Option<u64>) {
LAYER_SCRATCH_PEAK.with(|peak| peak.set(peak.get().max(bytes)));
if bound.is_some_and(|bound| bytes > bound) && !LAYER_SCRATCH_REPORTED.with(|cell| cell.replace(true)) {
tracing::warn!(
layer_scratch_bytes = bytes,
bound_bytes = bound.unwrap_or_default(),
"Qwen prefill: a layer requested more scratch than the bound derived for its shape"
);
}
}
#[cfg(test)]
pub(crate) fn take_layer_scratch_peak() -> u64 {
LAYER_SCRATCH_PEAK.with(|peak| peak.replace(0))
}
pub(crate) fn cap_pool(caps: Option<PoolCaps>) {
CAPS.with(|cell| cell.set(caps));
CAPS_END_AT_RESET.with(|cell| cell.set(false));
if let Some(caps) = caps {
if !default_pool() {
return;
}
DECODE_POOL.with(|cell| {
let mut pool = cell.borrow_mut();
if pool.free_bytes() > caps.retained {
#[cfg(test)]
let before = (pool.free_bytes(), trim_probe());
pool.clear();
#[cfg(test)]
if let (freed, Some(before)) = before {
let after = trim_probe().unwrap_or(before);
TRIM_SAMPLE.with(|sample| sample.set(Some((freed, before, after))));
}
}
FREE_AT_RESET.with(|free| free.set(pool.free_bytes()));
#[cfg(test)]
CAPPED_FREE_PEAK.with(|peak| peak.set(peak.get().max(pool.free_bytes())));
});
}
}
#[cfg(test)]
thread_local! {
static CAPPED_FREE_PEAK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
thread_local! {
static TRIM_PROBE: std::cell::RefCell<Option<Box<dyn Fn() -> usize>>> =
const { std::cell::RefCell::new(None) };
static TRIM_SAMPLE: std::cell::Cell<Option<(usize, usize, usize)>> =
const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn trim_probe() -> Option<usize> {
TRIM_PROBE.with(|probe| probe.borrow().as_ref().map(|read| read()))
}
#[cfg(test)]
pub(crate) fn set_trim_probe(probe: Option<Box<dyn Fn() -> usize>>) {
TRIM_PROBE.with(|cell| *cell.borrow_mut() = probe);
}
#[cfg(test)]
pub(crate) fn take_trim_sample() -> Option<(usize, usize, usize)> {
TRIM_SAMPLE.with(std::cell::Cell::take)
}
#[cfg(test)]
pub(crate) fn take_capped_free_peak() -> usize {
CAPPED_FREE_PEAK.with(|peak| peak.replace(0))
}
pub(crate) fn end_caps_at_next_reset() {
CAPS_END_AT_RESET.with(|cell| cell.set(CAPS.with(std::cell::Cell::get).is_some()));
}
pub(crate) fn release_overflow() {
OVERFLOW.with(|overflow| overflow.borrow_mut().clear());
}
pub(crate) fn default_pool() -> bool {
!profile::selected()
}
#[cfg(test)]
pub(crate) fn free_bytes() -> usize {
DECODE_POOL.with(|cell| cell.borrow().free_bytes())
}
thread_local! {
static STEP_POOLED_OUTPUTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) struct StepPooledOutputs {
previous: bool,
}
impl StepPooledOutputs {
pub(crate) fn enter(enabled: bool) -> Self {
Self {
previous: STEP_POOLED_OUTPUTS.with(|cell| cell.replace(enabled)),
}
}
}
impl Drop for StepPooledOutputs {
fn drop(&mut self) {
STEP_POOLED_OUTPUTS.with(|cell| cell.set(self.previous));
}
}
pub(crate) fn step_pooled_outputs() -> bool {
STEP_POOLED_OUTPUTS.with(std::cell::Cell::get)
}
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; }
let caps = CAPS.with(std::cell::Cell::get);
DECODE_POOL.with(|cell| {
let mut pool = cell.borrow_mut();
pool.reset();
if caps.is_some_and(|caps| pool.free_bytes() > caps.retained) {
pool.clear();
}
FREE_AT_RESET.with(|free| free.set(pool.free_bytes()));
});
release_overflow();
ISSUED_BYTES.with(|issued| issued.set(0));
POOLED_SINCE_RESET.with(|pooled| pooled.set(0));
if CAPS_END_AT_RESET.with(|cell| cell.replace(false)) {
CAPS.with(|cell| cell.set(None));
}
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) => {
n_experts > scratch.capacity_n_experts()
|| max_n_tokens > scratch.capacity_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 canonical_prepared_products_fit_the_retained_bucket_and_trim_a_larger_prior_scope() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
let source: serde_json::Value = serde_json::from_str(include_str!(
"../../../../tests/fixtures/qwen38/config.json"
)).unwrap();
let cfg = super::super::source_config::qwen35_config_from_authenticated_source(&source).unwrap();
let rows = 2080usize;
let h = cfg.hidden_size as usize;
let q = (cfg.num_attention_heads * cfg.head_dim) as usize;
let z = (cfg.linear_num_value_heads * cfg.linear_value_head_dim) as usize;
let ab = super::super::prepared_projection::alpha_beta_rows(cfg.linear_num_value_heads) as usize;
let largest = [2 * h, 4 * h, 4 * q, 2 * z, 4 * ab,
4 * cfg.linear_num_value_heads as usize,
2 * cfg.intermediate_size.unwrap() as usize]
.into_iter().max().unwrap() * rows;
let caps = super::super::prefill_prepared::prefill_pool_caps();
cap_pool(Some(PoolCaps { pool: 0, retained: 0 }));
checked_reset_decode_pool().unwrap();
cap_pool(None);
let first = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
let second = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
assert_eq!(first.byte_len(), caps.retained, "largest required product fits exactly one retained bucket");
assert!(largest > first.byte_len() / 2, "the next smaller power of two cannot retain it");
drop((first, second));
checked_reset_decode_pool().unwrap();
assert!(free_bytes() > caps.retained, "larger uncapped prior scope really stays warm");
let mut embedding = pooled_alloc_buffer(&device, 4096, DType::F32, vec![1024]).unwrap();
embedding.as_mut_slice::<f32>().unwrap().fill(3.25);
cap_pool(Some(caps));
assert_eq!(free_bytes(), 0, "warm oversized free owners are actually released");
assert_eq!(worker_memory_snapshot().unwrap().1.retained.bytes, embedding.byte_len());
let product = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
assert_eq!(product.byte_len(), caps.retained);
assert!(
issued_bytes() > super::super::prefill_prepared::window_scratch_threshold(),
"this real canonical product plus embedding must trigger an earlier layer wait",
);
assert!(embedding.as_slice::<f32>().unwrap().iter().all(|&x| x == 3.25));
assert_eq!(worker_carry_pool_bytes().unwrap(), (embedding.byte_len() + product.byte_len()) as u64);
drop((embedding, product));
checked_reset_decode_pool().unwrap();
assert_eq!(free_bytes(), 0, "reset also trims a crossing free set");
cap_pool(None);
}
#[test]
fn overflow_roots_and_carry_aliases_survive_queued_success_and_checked_error_drains() {
use super::super::{carry_memory::CarryOwners, encoder_stage};
use mlx_native::ops::copy::dispatch_copy_f32;
use mlx_native::KernelRegistry;
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
cap_pool(Some(PoolCaps { pool: 0, retained: 0 }));
checked_reset_decode_pool().unwrap();
let mut registry = KernelRegistry::new();
for fail in [false, true] {
let submitted = encoder_stage::SubmittedCommands::open(true);
let failure = fail.then(|| encoder_stage::FailSubmitted::nth("test.overflow", 0));
let mut carry = CarryOwners::default();
let mut outputs = Vec::new();
let mut aliases = Vec::new();
let mut expected = Vec::new();
let mut owned_bytes = 0u64;
for count in [99usize, 65] {
let mut root = pooled_alloc_buffer(&device, count * 4, DType::F32, vec![count]).unwrap();
let values: Vec<_> = (0..count).map(|i| (i as f32 + count as f32) * 0.25).collect();
root.as_mut_slice::<f32>().unwrap().copy_from_slice(&values);
let alias = root.slice_view(7 * 4, 11);
assert_eq!(alias.data_byte_len(), 11 * 4);
carry.include(&alias);
carry.include(&root);
owned_bytes += root.byte_len() as u64;
let out = device.alloc_buffer(11 * 4, DType::F32, vec![11]).unwrap();
let mut enc = device.command_encoder().unwrap();
dispatch_copy_f32(
&mut enc, &mut registry, device.metal_device(), &alias, &out, 0, 0, 11,
).unwrap();
enc.commit_labeled("test.overflow");
encoder_stage::retain_submitted(enc, "test.overflow");
drop(root);
aliases.push(alias);
outputs.push(out);
expected.push(values[7..18].to_vec());
}
assert_eq!(worker_carry_pool_bytes().unwrap(), owned_bytes);
assert_eq!(carry.bytes(), owned_bytes, "carry deduplicates aliases at full owning extent");
let drained = encoder_stage::settle_submitted();
assert_eq!(drained.is_err(), fail);
if let Some(point) = &failure {
assert_eq!(point.seen(), (true, 2), "the checked error still settles the later command");
}
for (out, want) in outputs.iter().zip(&expected) {
assert_eq!(out.as_slice::<f32>().unwrap(), want.as_slice());
}
drop(submitted);
assert_eq!(worker_carry_pool_bytes().unwrap(), owned_bytes, "drain alone does not erase owners");
checked_reset_decode_pool().unwrap();
assert_eq!(worker_carry_pool_bytes().unwrap(), 0);
assert_eq!(carry.bytes(), owned_bytes, "escaped aliases stay separately charged after pool reset");
let mut next = pooled_alloc_buffer(&device, 99 * 4, DType::F32, vec![99]).unwrap();
next.as_mut_slice::<f32>().unwrap().fill(-19.0);
assert_eq!(carry.bytes(), owned_bytes);
for (alias, want) in aliases.iter().zip(&expected) {
assert_eq!(alias.as_slice::<f32>().unwrap(), want.as_slice());
}
drop((next, aliases, carry, outputs));
checked_reset_decode_pool().unwrap();
}
cap_pool(None);
}
#[test]
fn carry_pool_census_keeps_full_overflow_roots_without_summing_native_labels() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Ok(device) = MlxDevice::new() else { return };
let previous = OVERFLOW.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
let native = worker_memory_snapshot().unwrap().1.retained.bytes as u64;
let root = device.alloc_buffer(3 * 32 * 4, DType::F32, vec![3, 32]).unwrap();
let bytes = root.byte_len() as u64;
OVERFLOW.with(|cell| cell.borrow_mut().push(root.clone()));
drop(root);
assert_eq!(worker_carry_pool_bytes().unwrap(), native + bytes);
release_overflow();
assert_eq!(worker_carry_pool_bytes().unwrap(), native);
OVERFLOW.with(|cell| *cell.borrow_mut() = previous);
}
#[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();
}
}