mlx_c_rust/runtime/
memory.rs1use crate::{MlxCError, MlxStream, error::check_status, raw};
8
9pub fn set_memory_limit(active_memory_limit_bytes: usize) -> Result<usize, MlxCError> {
12 let mut previous_limit_bytes = 0;
13 let status =
16 unsafe { raw::mlx_set_memory_limit(&mut previous_limit_bytes, active_memory_limit_bytes) };
17 check_status(status, "set the MLX active memory limit")?;
18 Ok(previous_limit_bytes)
19}
20
21pub fn set_cache_limit(allocator_cache_limit_bytes: usize) -> Result<usize, MlxCError> {
24 let mut previous_limit_bytes = 0;
25 let status =
28 unsafe { raw::mlx_set_cache_limit(&mut previous_limit_bytes, allocator_cache_limit_bytes) };
29 check_status(status, "set the MLX allocator cache memory limit")?;
30 Ok(previous_limit_bytes)
31}
32
33pub fn memory_limit_bytes() -> Result<usize, MlxCError> {
35 read_metric("read the MLX memory limit", raw::mlx_get_memory_limit)
36}
37
38pub fn active_memory_bytes() -> Result<usize, MlxCError> {
40 read_metric("read MLX active memory", raw::mlx_get_active_memory)
41}
42
43pub fn cache_memory_bytes() -> Result<usize, MlxCError> {
45 read_metric("read MLX allocator-cache memory", raw::mlx_get_cache_memory)
46}
47
48pub fn peak_memory_bytes() -> Result<usize, MlxCError> {
50 read_metric("read MLX peak memory", raw::mlx_get_peak_memory)
51}
52
53pub fn reset_peak_memory() -> Result<(), MlxCError> {
55 let status = unsafe { raw::mlx_reset_peak_memory() };
58 check_status(status, "reset MLX peak memory")
59}
60
61pub fn clear_allocator_cache() -> Result<(), MlxCError> {
63 let status = unsafe { raw::mlx_clear_cache() };
66 check_status(status, "clear the MLX allocator cache")
67}
68
69pub fn synchronize(stream: &MlxStream) -> Result<(), MlxCError> {
71 let status = unsafe { raw::mlx_synchronize(stream.raw()) };
73 check_status(status, "synchronize the MLX GPU stream")
74}
75
76fn read_metric(
77 operation: &'static str,
78 metric_reader: unsafe extern "C" fn(*mut usize) -> i32,
79) -> Result<usize, MlxCError> {
80 let mut metric_bytes = 0;
81 let status = unsafe { metric_reader(&mut metric_bytes) };
84 check_status(status, operation)?;
85 Ok(metric_bytes)
86}