Skip to main content

mlx_native/
lib.rs

1//! # mlx-native
2//!
3//! Pure-Rust Metal GPU compute library for MLX-compatible inference on Apple
4//! Silicon.
5//!
6//! This crate provides a thin, safe wrapper around Apple's Metal framework
7//! focused on compute shader dispatch for neural network inference.  It is
8//! designed to be the GPU backend for the `hf2q` inference engine.
9//!
10//! ## Key Types
11//!
12//! | Type | Purpose |
13//! |------|---------|
14//! | [`MlxDevice`]       | Metal device + command queue (entry point) |
15//! | [`CommandEncoder`]   | Batched compute command submission |
16//! | [`MlxBuffer`]        | Typed Metal buffer with shape/dtype metadata |
17//! | [`MlxBufferPool`]    | Arena allocator with power-of-two bucketing |
18//! | [`KernelRegistry`]   | Lazy MSL compilation + pipeline cache |
19//! | [`DType`]            | Element data type enum |
20//! | [`MlxError`]         | Unified error type (never panics) |
21//!
22//! ## Quick Start
23//!
24//! ```ignore
25//! use mlx_native::{MlxDevice, DType};
26//!
27//! let device = MlxDevice::new()?;
28//! let buf = device.alloc_buffer(1024, DType::F32, vec![256])?;
29//! let encoder = device.command_encoder()?;
30//! ```
31//!
32//! ## Design Principles
33//!
34//! * **No panics** — all public APIs return `Result<T, MlxError>`.
35//! * **Zero-copy** — `StorageModeShared` buffers on Apple Silicon unified memory.
36//! * **Thread-safe** — `MlxDevice` and `MlxBuffer` are `Send + Sync`.
37//! * **Lazy compilation** — MSL shaders compiled on first use, then cached.
38
39// Enforce the no-panic policy at compile time.
40#![deny(clippy::panic, clippy::unwrap_used, clippy::expect_used)]
41// The `objc` crate's `msg_send!` macro internally checks `cfg(feature = "cargo-clippy")`
42// which triggers unexpected_cfgs warnings. Suppress at crate level since we can't
43// control the macro expansion site.
44#![allow(unexpected_cfgs)]
45
46// ---- internal modules ----
47#[macro_use]
48mod error;
49mod buffer;
50mod buffer_pool;
51mod device;
52mod dtypes;
53mod encoder;
54mod kernel_registry;
55pub mod gguf;
56pub mod graph;
57pub mod ops;
58pub mod turboquant;
59pub mod weight;
60
61// ---- public re-exports ----
62pub use buffer::MlxBuffer;
63pub use buffer_pool::MlxBufferPool;
64pub use device::MlxDevice;
65pub use dtypes::DType;
66pub use encoder::{
67    dispatch_count, reset_counters, sync_count, CapturedNode, CommandEncoder, DispatchKind,
68    RecordedBinding,
69};
70pub use error::{MlxError, Result};
71pub use graph::{ComputeGraph, GraphExecutor, GraphSession, OpKind};
72pub use kernel_registry::KernelRegistry;
73
74// Re-export GGUF parser.
75pub use gguf::{GgufFile, MetadataValue, TensorInfo};
76
77// Re-export ops.
78pub use ops::dense_mm_bf16::{dense_matmul_bf16_f32_tensor, DenseMmBf16F32Params};
79pub use ops::dense_mm_f32_f32::{dense_matmul_f32_f32_tensor, DenseMmF32F32Params};
80pub use ops::quantized_matmul::{quantized_matmul, quantized_matmul_simd, QuantizedMatmulParams};
81pub use ops::quantized_matmul_ggml::{
82    dispatch_mm_for_test, quantized_matmul_ggml, quantized_matmul_mm_tensor_perm021,
83    GgmlQuantizedMatmulParams, GgmlQuantizedMatmulPerm021Params, GgmlType,
84    MM_ROUTING_THRESHOLD,
85};
86pub use ops::quantized_matmul_id::{quantized_matmul_id, QuantizedMatmulIdParams};
87pub use ops::quantized_matmul_id_ggml::{
88    dispatch_id_mm_for_test, quantized_matmul_id_ggml, quantized_matmul_id_ggml_pooled,
89    GgmlIdMmDispatchParams, GgmlQuantizedMatmulIdParams, IdMmScratch,
90    MM_ID_ROUTING_THRESHOLD,
91};
92
93// Re-export weight loading utilities.
94pub use weight::{
95    load_quantized_weights, safetensors_to_metal_buffer, QuantizationConfig, QuantizedWeight,
96    SafetensorsFile, TensorQuantConfig,
97};
98
99// Re-export metal types that appear in the public API.
100pub use metal::MTLSize;
101pub use metal;
102
103#[cfg(test)]
104#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
105mod tests {
106    use super::*;
107
108    // ---- T10.7: compile-time Send + Sync assertions ----
109    fn _assert_send<T: Send>() {}
110    fn _assert_sync<T: Sync>() {}
111
112    #[allow(dead_code)]
113    fn assert_send_sync() {
114        _assert_send::<MlxDevice>();
115        _assert_sync::<MlxDevice>();
116        _assert_send::<MlxBuffer>();
117        _assert_sync::<MlxBuffer>();
118        _assert_send::<MlxError>();
119        _assert_sync::<MlxError>();
120    }
121
122    // ---- T10.1: device initialization ----
123    #[test]
124    fn test_device_init() {
125        let device = MlxDevice::new().expect("MlxDevice::new() should succeed on Apple Silicon");
126        let name = device.name();
127        assert!(!name.is_empty(), "Device name should not be empty");
128        println!("Metal device: {name}");
129    }
130
131    // ---- T10.2: buffer allocation ----
132    #[test]
133    fn test_buffer_alloc() {
134        let device = MlxDevice::new().expect("device");
135        let shape = vec![2, 3, 4];
136        let byte_len = 2 * 3 * 4 * DType::F32.size_of(); // 96 bytes
137        let buf = device
138            .alloc_buffer(byte_len, DType::F32, shape.clone())
139            .expect("alloc_buffer");
140
141        assert_eq!(buf.dtype(), DType::F32);
142        assert_eq!(buf.shape(), &shape);
143        assert_eq!(buf.byte_len(), byte_len);
144        assert_eq!(buf.element_count(), 24);
145    }
146
147    // ---- T10.3: buffer read/write round-trip ----
148    #[test]
149    fn test_buffer_readwrite() {
150        let device = MlxDevice::new().expect("device");
151        let n = 64;
152        let byte_len = n * std::mem::size_of::<f32>();
153        let mut buf = device
154            .alloc_buffer(byte_len, DType::F32, vec![n])
155            .expect("alloc_buffer");
156
157        // Write known data.
158        {
159            let slice: &mut [f32] = buf.as_mut_slice().expect("as_mut_slice");
160            assert_eq!(slice.len(), n);
161            for (i, val) in slice.iter_mut().enumerate() {
162                *val = i as f32 * 1.5;
163            }
164        }
165
166        // Read back and verify.
167        {
168            let slice: &[f32] = buf.as_slice().expect("as_slice");
169            for (i, &val) in slice.iter().enumerate() {
170                let expected = i as f32 * 1.5;
171                assert!(
172                    (val - expected).abs() < f32::EPSILON,
173                    "Mismatch at index {i}: got {val}, expected {expected}"
174                );
175            }
176        }
177    }
178
179    // ---- T10.4: encoder lifecycle ----
180    #[test]
181    fn test_encoder_lifecycle() {
182        let device = MlxDevice::new().expect("device");
183        let mut enc = device.command_encoder().expect("command_encoder");
184        // Commit an empty command buffer — should succeed (no-op on GPU).
185        enc.commit_and_wait()
186            .expect("commit_and_wait on empty encoder");
187    }
188
189    // ---- T10.5: buffer pool reuse ----
190    #[test]
191    fn test_buffer_pool_reuse() {
192        let device = MlxDevice::new().expect("device");
193        let mut pool = MlxBufferPool::new(&device);
194
195        // Allocate a buffer.
196        let buf1 = pool
197            .alloc(1024, DType::F32, vec![256])
198            .expect("pool alloc 1");
199        let buf1_ptr = buf1.contents_ptr();
200        let buf1_byte_len = buf1.byte_len();
201
202        // Release it back to the pool.
203        pool.release(buf1);
204        assert_eq!(pool.free_count(), 1);
205
206        // Allocate again — should reuse the same Metal buffer.
207        let buf2 = pool
208            .alloc(1024, DType::F32, vec![256])
209            .expect("pool alloc 2");
210        let buf2_ptr = buf2.contents_ptr();
211        let buf2_byte_len = buf2.byte_len();
212
213        assert_eq!(buf1_ptr, buf2_ptr, "Pool should reuse the same Metal buffer");
214        assert_eq!(buf1_byte_len, buf2_byte_len, "Byte lengths should match");
215        assert_eq!(pool.free_count(), 0, "Free list should be empty after reuse");
216    }
217
218    // ---- T10.6: kernel registry caching ----
219    #[test]
220    fn test_kernel_registry_caching() {
221        let device = MlxDevice::new().expect("device");
222        let mut registry = KernelRegistry::new();
223
224        // Register a minimal test kernel.
225        registry.register_source(
226            "test_add",
227            r#"
228            #include <metal_stdlib>
229            using namespace metal;
230            kernel void test_add(
231                device float *a [[buffer(0)]],
232                device float *b [[buffer(1)]],
233                device float *c [[buffer(2)]],
234                uint id [[thread_position_in_grid]]
235            ) {
236                c[id] = a[id] + b[id];
237            }
238            "#,
239        );
240
241        // First call — compiles the shader.
242        assert!(!registry.is_cached("test_add"));
243        let p1 = registry
244            .get_pipeline("test_add", device.metal_device())
245            .expect("get_pipeline first call");
246        let p1_ptr = p1 as *const _;
247        assert!(registry.is_cached("test_add"));
248
249        // Second call — returns cached pipeline.
250        let p2 = registry
251            .get_pipeline("test_add", device.metal_device())
252            .expect("get_pipeline second call");
253        let p2_ptr = p2 as *const _;
254
255        assert_eq!(
256            p1_ptr, p2_ptr,
257            "Second get_pipeline call should return the same cached pipeline"
258        );
259    }
260
261    // ---- Additional: test alloc_buffer with zero length returns error ----
262    #[test]
263    fn test_buffer_alloc_zero_len_error() {
264        let device = MlxDevice::new().expect("device");
265        let result = device.alloc_buffer(0, DType::F32, vec![]);
266        assert!(result.is_err(), "Zero-length allocation should fail");
267        match result {
268            Err(MlxError::InvalidArgument(_)) => {}
269            other => panic!("Expected InvalidArgument, got {:?}", other),
270        }
271    }
272
273    // ---- Additional: test kernel not found ----
274    #[test]
275    fn test_kernel_not_found() {
276        let device = MlxDevice::new().expect("device");
277        let mut registry = KernelRegistry::new();
278        let result = registry.get_pipeline("nonexistent_kernel", device.metal_device());
279        assert!(result.is_err());
280        match result {
281            Err(MlxError::KernelNotFound(name)) => {
282                assert_eq!(name, "nonexistent_kernel");
283            }
284            other => panic!("Expected KernelNotFound, got {:?}", other),
285        }
286    }
287
288    // ---- Additional: test DType properties ----
289    #[test]
290    fn test_dtype_sizes() {
291        assert_eq!(DType::F32.size_of(), 4);
292        assert_eq!(DType::F16.size_of(), 2);
293        assert_eq!(DType::BF16.size_of(), 2);
294        assert_eq!(DType::U8.size_of(), 1);
295        assert_eq!(DType::U16.size_of(), 2);
296        assert_eq!(DType::U32.size_of(), 4);
297        assert_eq!(DType::I32.size_of(), 4);
298    }
299
300    // ---- Additional: test MlxBuffer Debug ----
301    #[test]
302    fn test_buffer_debug() {
303        let device = MlxDevice::new().expect("device");
304        let buf = device
305            .alloc_buffer(64, DType::F16, vec![4, 8])
306            .expect("alloc_buffer");
307        let debug_str = format!("{:?}", buf);
308        assert!(debug_str.contains("MlxBuffer"));
309        assert!(debug_str.contains("F16"));
310        assert!(debug_str.contains("[4, 8]"));
311    }
312
313    // ---- Additional: test MlxError Display ----
314    #[test]
315    fn test_error_display() {
316        let e = MlxError::DeviceNotFound;
317        assert!(format!("{e}").contains("Metal GPU device"));
318
319        let e = MlxError::ShaderCompilationError {
320            name: "foo".into(),
321            message: "syntax error".into(),
322        };
323        assert!(format!("{e}").contains("foo"));
324        assert!(format!("{e}").contains("syntax error"));
325    }
326
327    // ---- Additional: test buffer pool with different sizes ----
328    #[test]
329    fn test_buffer_pool_size_buckets() {
330        let device = MlxDevice::new().expect("device");
331        let mut pool = MlxBufferPool::new(&device);
332
333        // Allocate a 100-byte buffer (rounds to 128-byte bucket).
334        let buf_100 = pool.alloc(100, DType::U8, vec![100]).expect("alloc 100");
335        assert!(
336            buf_100.byte_len() >= 100,
337            "Buffer should be at least 100 bytes"
338        );
339        pool.release(buf_100);
340
341        // Allocate a 128-byte buffer — should reuse the same Metal buffer.
342        let buf_128 = pool.alloc(128, DType::U8, vec![128]).expect("alloc 128");
343        assert!(buf_128.byte_len() >= 128);
344        pool.release(buf_128);
345
346        // Allocate a 200-byte buffer — different bucket (256), fresh allocation.
347        let buf_200 = pool.alloc(200, DType::U8, vec![200]).expect("alloc 200");
348        assert!(buf_200.byte_len() >= 200);
349        pool.release(buf_200);
350
351        assert_eq!(pool.free_count(), 2, "Two different bucket sizes in pool");
352    }
353}