use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::marker::PhantomData;
use anyhow::{Context, Result};
use mlx_native::{DType, MlxBuffer, MlxBufferPool, MlxDevice};
const POOL_LIMIT_BYTES: usize = 2 << 30;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Init {
Overwritten,
Zeroed,
}
struct Arena {
pool: MlxBufferPool,
device: Option<MlxDevice>,
limit: usize,
free: HashMap<usize, usize>,
in_use: Vec<usize>,
issued: usize,
active: bool,
undrained: bool,
}
impl Arena {
fn new(limit: usize) -> Self {
Self {
pool: MlxBufferPool::new(),
device: None,
limit,
free: HashMap::new(),
in_use: Vec::new(),
issued: 0,
active: false,
undrained: false,
}
}
fn held_bytes(&self) -> usize {
self.pool.free_bytes().saturating_add(self.issued)
}
fn reserve(&mut self, bucket: usize) -> bool {
match self.free.get_mut(&bucket) {
Some(count) if *count > 0 => *count -= 1,
_ => {
if self.issued.saturating_add(bucket) > self.limit {
return false;
}
if self.held_bytes().saturating_add(bucket) > self.limit {
self.pool.clear();
self.free.clear();
}
}
}
self.in_use.push(bucket);
self.issued += bucket;
true
}
fn recycle(&mut self) {
self.pool.reset();
for bucket in self.in_use.drain(..) {
*self.free.entry(bucket).or_default() += 1;
}
self.issued = 0;
self.undrained = false;
}
}
thread_local! {
static ARENA: RefCell<Arena> = RefCell::new(Arena::new(POOL_LIMIT_BYTES));
}
pub(crate) struct PrefillPoolCycle {
zero_all: bool,
quiescent: Cell<bool>,
_thread_bound: PhantomData<*const ()>,
}
impl PrefillPoolCycle {
pub(crate) fn begin(
device: &MlxDevice,
zero_all: bool,
drain: impl FnOnce() -> Result<()>,
) -> Result<Self> {
let undrained = ARENA.with(|arena| {
let mut arena = arena.borrow_mut();
anyhow::ensure!(!arena.active, "nested Gemma batched-prefill pool cycle");
let changed = arena.device.as_ref().is_some_and(|previous| {
!std::ptr::eq(&**previous.metal_queue(), &**device.metal_queue())
});
if changed {
if arena.undrained {
let encoder = arena
.device
.as_ref()
.expect("a changed queue has a previous owner")
.command_encoder()
.context("create previous Gemma prefill queue drain")?;
crate::inference::native_observation::encoder(encoder)
.commit_and_wait()
.context("drain previous Gemma prefill queue before retiring its arena")?;
}
let limit = arena.limit;
*arena = Arena::new(limit);
}
if arena.device.is_none() {
arena.device = Some(device.clone());
}
Ok(arena.undrained)
})?;
if undrained {
drain().context("drain the queue before recycling unwound Gemma prefill buffers")?;
}
ARENA.with(|arena| {
let mut arena = arena.borrow_mut();
if arena.undrained {
arena.recycle();
}
arena.active = true;
});
Ok(Self {
zero_all,
quiescent: Cell::new(false),
_thread_bound: PhantomData,
})
}
pub(crate) fn alloc(
&self,
device: &MlxDevice,
dtype: DType,
elements: usize,
init: Init,
label: &str,
) -> Result<MlxBuffer> {
let bytes = elements
.checked_mul(dtype.size_of())
.with_context(|| format!("batched alloc {label}: byte size overflow"))?;
let bucket = bytes.checked_next_power_of_two().unwrap_or(usize::MAX);
let fill = self.fill_byte(init);
ARENA.with(|arena| {
let mut arena = arena.borrow_mut();
let mut buffer = if bytes == 0 || !arena.reserve(bucket) {
let buffer = device
.alloc_buffer(bytes, dtype, vec![elements])
.map_err(|e| anyhow::anyhow!("batched alloc {label}: {e}"))?;
if fill.is_none_or(|byte| byte == 0) {
return Ok(buffer);
}
buffer
} else {
match arena
.pool
.alloc_uninitialized(device, bytes, dtype, vec![elements])
{
Ok(buffer) => buffer,
Err(e) => {
arena.in_use.pop();
arena.issued -= bucket;
arena.pool.clear();
arena.free.clear();
anyhow::bail!("batched pooled alloc {label}: {e}");
}
}
};
if let Some(byte) = fill {
buffer
.as_mut_slice::<u8>()
.map_err(|e| anyhow::anyhow!("batched alloc {label} fill: {e}"))?
.fill(byte);
}
Ok(buffer)
})
}
fn fill_byte(&self, init: Init) -> Option<u8> {
if self.zero_all || init == Init::Zeroed {
return Some(0);
}
#[cfg(test)]
if let Some(byte) = TEST_OVERWRITTEN_FILL.with(Cell::get) {
return Some(byte);
}
None
}
pub(crate) fn gpu_quiescent(&self) {
self.quiescent.set(true);
}
}
impl Drop for PrefillPoolCycle {
fn drop(&mut self) {
let quiescent = self.quiescent.get();
ARENA.with(|arena| {
let mut arena = arena.borrow_mut();
arena.active = false;
if quiescent {
arena.recycle();
} else {
arena.undrained = true;
}
});
}
}
#[cfg(test)]
fn set_limit_for_test(limit: usize) {
ARENA.with(|arena| arena.borrow_mut().limit = limit);
}
#[cfg(test)]
fn held_bytes_for_test() -> (usize, usize) {
ARENA.with(|arena| {
let arena = arena.borrow();
let mirrored: usize = arena.free.iter().map(|(bucket, n)| bucket * n).sum();
(arena.held_bytes(), mirrored + arena.issued)
})
}
#[cfg(test)]
thread_local! {
static TEST_OVERWRITTEN_FILL: Cell<Option<u8>> = const { Cell::new(None) };
}
#[cfg(test)]
pub(crate) fn set_overwritten_fill_for_test(byte: Option<u8>) {
TEST_OVERWRITTEN_FILL.with(|fill| fill.set(byte));
}
#[cfg(test)]
#[path = "gemma_prefill_pool_tests.rs"]
mod tests;