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