1#![deny(clippy::panic, clippy::unwrap_used, clippy::expect_used)]
41#![allow(unexpected_cfgs)]
45
46#[macro_use]
48mod error;
49mod buffer;
50mod buffer_pool;
51mod device;
52mod dtypes;
53mod encoder;
54mod kernel_registry;
55mod mem_ranges;
56mod residency;
57pub mod gguf;
58pub mod kernel_profile;
59pub mod graph;
60pub mod ops;
61pub mod turboquant;
62pub mod weight;
63
64pub use buffer::MlxBuffer;
66pub use buffer_pool::MlxBufferPool;
67pub use device::MlxDevice;
68pub use dtypes::DType;
69pub use encoder::{
70 auto_barrier_concurrent_count, auto_barrier_count, barrier_count, barrier_total_ns,
71 cmd_buf_count, dispatch_count, reset_counters, sync_count, CapturedNode, CommandEncoder,
72 DispatchKind, KernelArg, RecordedBinding,
73};
74pub use mem_ranges::{BufferRange, MemRangeRole, MemRanges};
75pub use error::{MlxError, Result};
76pub use graph::{ComputeGraph, GraphExecutor, GraphSession, OpKind};
77pub use kernel_registry::KernelRegistry;
78#[doc(hidden)]
84pub use residency::{
85 macos_15_or_newer_for_test, reset_residency_env_cache_for_test,
86 reset_residency_test_counters, residency_allocation_count_for_test,
87 residency_commit_call_count_for_test,
88};
89
90pub use gguf::{GgufFile, MetadataValue, TensorInfo};
92
93pub use ops::dense_mm_bf16::{dense_matmul_bf16_f32_tensor, DenseMmBf16F32Params};
95pub use ops::dense_mm_f16::{dense_matmul_f16_f32_tensor, DenseMmF16F32Params};
96pub use ops::dense_mm_f32_f32::{dense_matmul_f32_f32_tensor, DenseMmF32F32Params};
97pub use ops::quantized_matmul::{quantized_matmul, quantized_matmul_simd, QuantizedMatmulParams};
98pub use ops::quantized_matmul_ggml::{
99 dispatch_mm_for_test, quantized_matmul_ggml, quantized_matmul_mm_tensor_perm021,
100 GgmlQuantizedMatmulParams, GgmlQuantizedMatmulPerm021Params, GgmlType,
101 MM_ROUTING_THRESHOLD,
102};
103pub use ops::quantized_matmul_id::{quantized_matmul_id, QuantizedMatmulIdParams};
104pub use ops::quantized_matmul_id_ggml::{
105 dispatch_id_mm_for_test, quantized_matmul_id_ggml, quantized_matmul_id_ggml_pooled,
106 quantized_matmul_id_swiglu_q4_0,
107 GgmlIdMmDispatchParams, GgmlQuantizedMatmulIdParams, IdMmScratch,
108 MM_ID_ROUTING_THRESHOLD,
109};
110
111pub use weight::{
113 load_quantized_weights, safetensors_to_metal_buffer, QuantizationConfig, QuantizedWeight,
114 SafetensorsFile, TensorQuantConfig,
115};
116
117pub use metal::MTLSize;
119pub use metal;
120
121#[cfg(test)]
122#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
123mod tests {
124 use super::*;
125
126 fn _assert_send<T: Send>() {}
128 fn _assert_sync<T: Sync>() {}
129
130 #[allow(dead_code)]
131 fn assert_send_sync() {
132 _assert_send::<MlxDevice>();
133 _assert_sync::<MlxDevice>();
134 _assert_send::<MlxBuffer>();
135 _assert_sync::<MlxBuffer>();
136 _assert_send::<MlxError>();
137 _assert_sync::<MlxError>();
138 }
139
140 #[test]
142 fn test_device_init() {
143 let device = MlxDevice::new().expect("MlxDevice::new() should succeed on Apple Silicon");
144 let name = device.name();
145 assert!(!name.is_empty(), "Device name should not be empty");
146 println!("Metal device: {name}");
147 }
148
149 #[test]
151 fn test_buffer_alloc() {
152 let device = MlxDevice::new().expect("device");
153 let shape = vec![2, 3, 4];
154 let byte_len = 2 * 3 * 4 * DType::F32.size_of(); let buf = device
156 .alloc_buffer(byte_len, DType::F32, shape.clone())
157 .expect("alloc_buffer");
158
159 assert_eq!(buf.dtype(), DType::F32);
160 assert_eq!(buf.shape(), &shape);
161 assert_eq!(buf.byte_len(), byte_len);
162 assert_eq!(buf.element_count(), 24);
163 }
164
165 #[test]
167 fn test_buffer_readwrite() {
168 let device = MlxDevice::new().expect("device");
169 let n = 64;
170 let byte_len = n * std::mem::size_of::<f32>();
171 let mut buf = device
172 .alloc_buffer(byte_len, DType::F32, vec![n])
173 .expect("alloc_buffer");
174
175 {
177 let slice: &mut [f32] = buf.as_mut_slice().expect("as_mut_slice");
178 assert_eq!(slice.len(), n);
179 for (i, val) in slice.iter_mut().enumerate() {
180 *val = i as f32 * 1.5;
181 }
182 }
183
184 {
186 let slice: &[f32] = buf.as_slice().expect("as_slice");
187 for (i, &val) in slice.iter().enumerate() {
188 let expected = i as f32 * 1.5;
189 assert!(
190 (val - expected).abs() < f32::EPSILON,
191 "Mismatch at index {i}: got {val}, expected {expected}"
192 );
193 }
194 }
195 }
196
197 #[test]
199 fn test_encoder_lifecycle() {
200 let device = MlxDevice::new().expect("device");
201 let mut enc = device.command_encoder().expect("command_encoder");
202 enc.commit_and_wait()
204 .expect("commit_and_wait on empty encoder");
205 }
206
207 #[test]
209 fn test_buffer_pool_reuse() {
210 let device = MlxDevice::new().expect("device");
211 let mut pool = MlxBufferPool::new();
212
213 let buf1 = pool
215 .alloc(&device, 1024, DType::F32, vec![256])
216 .expect("pool alloc 1");
217 let buf1_ptr = buf1.contents_ptr();
218 let buf1_byte_len = buf1.byte_len();
219
220 pool.release(buf1);
222 assert_eq!(pool.free_count(), 1);
223
224 let buf2 = pool
226 .alloc(&device, 1024, DType::F32, vec![256])
227 .expect("pool alloc 2");
228 let buf2_ptr = buf2.contents_ptr();
229 let buf2_byte_len = buf2.byte_len();
230
231 assert_eq!(buf1_ptr, buf2_ptr, "Pool should reuse the same Metal buffer");
232 assert_eq!(buf1_byte_len, buf2_byte_len, "Byte lengths should match");
233 assert_eq!(pool.free_count(), 0, "Free list should be empty after reuse");
234 }
235
236 #[test]
238 fn test_kernel_registry_caching() {
239 let device = MlxDevice::new().expect("device");
240 let mut registry = KernelRegistry::new();
241
242 registry.register_source(
244 "test_add",
245 r#"
246 #include <metal_stdlib>
247 using namespace metal;
248 kernel void test_add(
249 device float *a [[buffer(0)]],
250 device float *b [[buffer(1)]],
251 device float *c [[buffer(2)]],
252 uint id [[thread_position_in_grid]]
253 ) {
254 c[id] = a[id] + b[id];
255 }
256 "#,
257 );
258
259 assert!(!registry.is_cached("test_add"));
261 let p1 = registry
262 .get_pipeline("test_add", device.metal_device())
263 .expect("get_pipeline first call");
264 let p1_ptr = p1 as *const _;
265 assert!(registry.is_cached("test_add"));
266
267 let p2 = registry
269 .get_pipeline("test_add", device.metal_device())
270 .expect("get_pipeline second call");
271 let p2_ptr = p2 as *const _;
272
273 assert_eq!(
274 p1_ptr, p2_ptr,
275 "Second get_pipeline call should return the same cached pipeline"
276 );
277 }
278
279 #[test]
281 fn test_buffer_alloc_zero_len_error() {
282 let device = MlxDevice::new().expect("device");
283 let result = device.alloc_buffer(0, DType::F32, vec![]);
284 assert!(result.is_err(), "Zero-length allocation should fail");
285 match result {
286 Err(MlxError::InvalidArgument(_)) => {}
287 other => panic!("Expected InvalidArgument, got {:?}", other),
288 }
289 }
290
291 #[test]
293 fn test_kernel_not_found() {
294 let device = MlxDevice::new().expect("device");
295 let mut registry = KernelRegistry::new();
296 let result = registry.get_pipeline("nonexistent_kernel", device.metal_device());
297 assert!(result.is_err());
298 match result {
299 Err(MlxError::KernelNotFound(name)) => {
300 assert_eq!(name, "nonexistent_kernel");
301 }
302 other => panic!("Expected KernelNotFound, got {:?}", other),
303 }
304 }
305
306 #[test]
308 fn test_dtype_sizes() {
309 assert_eq!(DType::F32.size_of(), 4);
310 assert_eq!(DType::F16.size_of(), 2);
311 assert_eq!(DType::BF16.size_of(), 2);
312 assert_eq!(DType::U8.size_of(), 1);
313 assert_eq!(DType::U16.size_of(), 2);
314 assert_eq!(DType::U32.size_of(), 4);
315 assert_eq!(DType::I32.size_of(), 4);
316 }
317
318 #[test]
320 fn test_buffer_debug() {
321 let device = MlxDevice::new().expect("device");
322 let buf = device
323 .alloc_buffer(64, DType::F16, vec![4, 8])
324 .expect("alloc_buffer");
325 let debug_str = format!("{:?}", buf);
326 assert!(debug_str.contains("MlxBuffer"));
327 assert!(debug_str.contains("F16"));
328 assert!(debug_str.contains("[4, 8]"));
329 }
330
331 #[test]
333 fn test_error_display() {
334 let e = MlxError::DeviceNotFound;
335 assert!(format!("{e}").contains("Metal GPU device"));
336
337 let e = MlxError::ShaderCompilationError {
338 name: "foo".into(),
339 message: "syntax error".into(),
340 };
341 assert!(format!("{e}").contains("foo"));
342 assert!(format!("{e}").contains("syntax error"));
343 }
344
345 #[test]
347 fn test_buffer_pool_size_buckets() {
348 let device = MlxDevice::new().expect("device");
349 let mut pool = MlxBufferPool::new();
350
351 let buf_100 = pool.alloc(&device, 100, DType::U8, vec![100]).expect("alloc 100");
353 assert!(
354 buf_100.byte_len() >= 100,
355 "Buffer should be at least 100 bytes"
356 );
357 pool.release(buf_100);
358
359 let buf_128 = pool.alloc(&device, 128, DType::U8, vec![128]).expect("alloc 128");
361 assert!(buf_128.byte_len() >= 128);
362 pool.release(buf_128);
363
364 let buf_200 = pool.alloc(&device, 200, DType::U8, vec![200]).expect("alloc 200");
366 assert!(buf_200.byte_len() >= 200);
367 pool.release(buf_200);
368
369 assert_eq!(pool.free_count(), 2, "Two different bucket sizes in pool");
370 }
371}