use crate::{MlxCError, MlxStream, error::check_status, raw};
pub fn set_memory_limit(active_memory_limit_bytes: usize) -> Result<usize, MlxCError> {
let mut previous_limit_bytes = 0;
let status =
unsafe { raw::mlx_set_memory_limit(&mut previous_limit_bytes, active_memory_limit_bytes) };
check_status(status, "set the MLX active memory limit")?;
Ok(previous_limit_bytes)
}
pub fn set_cache_limit(allocator_cache_limit_bytes: usize) -> Result<usize, MlxCError> {
let mut previous_limit_bytes = 0;
let status =
unsafe { raw::mlx_set_cache_limit(&mut previous_limit_bytes, allocator_cache_limit_bytes) };
check_status(status, "set the MLX allocator cache memory limit")?;
Ok(previous_limit_bytes)
}
pub fn memory_limit_bytes() -> Result<usize, MlxCError> {
read_metric("read the MLX memory limit", raw::mlx_get_memory_limit)
}
pub fn active_memory_bytes() -> Result<usize, MlxCError> {
read_metric("read MLX active memory", raw::mlx_get_active_memory)
}
pub fn cache_memory_bytes() -> Result<usize, MlxCError> {
read_metric("read MLX allocator-cache memory", raw::mlx_get_cache_memory)
}
pub fn peak_memory_bytes() -> Result<usize, MlxCError> {
read_metric("read MLX peak memory", raw::mlx_get_peak_memory)
}
pub fn reset_peak_memory() -> Result<(), MlxCError> {
let status = unsafe { raw::mlx_reset_peak_memory() };
check_status(status, "reset MLX peak memory")
}
pub fn clear_allocator_cache() -> Result<(), MlxCError> {
let status = unsafe { raw::mlx_clear_cache() };
check_status(status, "clear the MLX allocator cache")
}
pub fn synchronize(stream: &MlxStream) -> Result<(), MlxCError> {
let status = unsafe { raw::mlx_synchronize(stream.raw()) };
check_status(status, "synchronize the MLX GPU stream")
}
fn read_metric(
operation: &'static str,
metric_reader: unsafe extern "C" fn(*mut usize) -> i32,
) -> Result<usize, MlxCError> {
let mut metric_bytes = 0;
let status = unsafe { metric_reader(&mut metric_bytes) };
check_status(status, operation)?;
Ok(metric_bytes)
}