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::quantized_matmul::{quantized_matmul, quantized_matmul_simd, QuantizedMatmulParams};
79pub use ops::quantized_matmul_ggml::{
80    quantized_matmul_ggml, GgmlQuantizedMatmulParams, GgmlType,
81};
82pub use ops::quantized_matmul_id::{quantized_matmul_id, QuantizedMatmulIdParams};
83pub use ops::quantized_matmul_id_ggml::{
84    quantized_matmul_id_ggml, GgmlQuantizedMatmulIdParams,
85};
86
87// Re-export weight loading utilities.
88pub use weight::{
89    load_quantized_weights, safetensors_to_metal_buffer, QuantizationConfig, QuantizedWeight,
90    SafetensorsFile, TensorQuantConfig,
91};
92
93// Re-export metal types that appear in the public API.
94pub use metal::MTLSize;
95pub use metal;
96
97#[cfg(test)]
98#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
99mod tests {
100    use super::*;
101
102    // ---- T10.7: compile-time Send + Sync assertions ----
103    fn _assert_send<T: Send>() {}
104    fn _assert_sync<T: Sync>() {}
105
106    #[allow(dead_code)]
107    fn assert_send_sync() {
108        _assert_send::<MlxDevice>();
109        _assert_sync::<MlxDevice>();
110        _assert_send::<MlxBuffer>();
111        _assert_sync::<MlxBuffer>();
112        _assert_send::<MlxError>();
113        _assert_sync::<MlxError>();
114    }
115
116    // ---- T10.1: device initialization ----
117    #[test]
118    fn test_device_init() {
119        let device = MlxDevice::new().expect("MlxDevice::new() should succeed on Apple Silicon");
120        let name = device.name();
121        assert!(!name.is_empty(), "Device name should not be empty");
122        println!("Metal device: {name}");
123    }
124
125    // ---- T10.2: buffer allocation ----
126    #[test]
127    fn test_buffer_alloc() {
128        let device = MlxDevice::new().expect("device");
129        let shape = vec![2, 3, 4];
130        let byte_len = 2 * 3 * 4 * DType::F32.size_of(); // 96 bytes
131        let buf = device
132            .alloc_buffer(byte_len, DType::F32, shape.clone())
133            .expect("alloc_buffer");
134
135        assert_eq!(buf.dtype(), DType::F32);
136        assert_eq!(buf.shape(), &shape);
137        assert_eq!(buf.byte_len(), byte_len);
138        assert_eq!(buf.element_count(), 24);
139    }
140
141    // ---- T10.3: buffer read/write round-trip ----
142    #[test]
143    fn test_buffer_readwrite() {
144        let device = MlxDevice::new().expect("device");
145        let n = 64;
146        let byte_len = n * std::mem::size_of::<f32>();
147        let mut buf = device
148            .alloc_buffer(byte_len, DType::F32, vec![n])
149            .expect("alloc_buffer");
150
151        // Write known data.
152        {
153            let slice: &mut [f32] = buf.as_mut_slice().expect("as_mut_slice");
154            assert_eq!(slice.len(), n);
155            for (i, val) in slice.iter_mut().enumerate() {
156                *val = i as f32 * 1.5;
157            }
158        }
159
160        // Read back and verify.
161        {
162            let slice: &[f32] = buf.as_slice().expect("as_slice");
163            for (i, &val) in slice.iter().enumerate() {
164                let expected = i as f32 * 1.5;
165                assert!(
166                    (val - expected).abs() < f32::EPSILON,
167                    "Mismatch at index {i}: got {val}, expected {expected}"
168                );
169            }
170        }
171    }
172
173    // ---- T10.4: encoder lifecycle ----
174    #[test]
175    fn test_encoder_lifecycle() {
176        let device = MlxDevice::new().expect("device");
177        let mut enc = device.command_encoder().expect("command_encoder");
178        // Commit an empty command buffer — should succeed (no-op on GPU).
179        enc.commit_and_wait()
180            .expect("commit_and_wait on empty encoder");
181    }
182
183    // ---- T10.5: buffer pool reuse ----
184    #[test]
185    fn test_buffer_pool_reuse() {
186        let device = MlxDevice::new().expect("device");
187        let mut pool = MlxBufferPool::new(&device);
188
189        // Allocate a buffer.
190        let buf1 = pool
191            .alloc(1024, DType::F32, vec![256])
192            .expect("pool alloc 1");
193        let buf1_ptr = buf1.contents_ptr();
194        let buf1_byte_len = buf1.byte_len();
195
196        // Release it back to the pool.
197        pool.release(buf1);
198        assert_eq!(pool.free_count(), 1);
199
200        // Allocate again — should reuse the same Metal buffer.
201        let buf2 = pool
202            .alloc(1024, DType::F32, vec![256])
203            .expect("pool alloc 2");
204        let buf2_ptr = buf2.contents_ptr();
205        let buf2_byte_len = buf2.byte_len();
206
207        assert_eq!(buf1_ptr, buf2_ptr, "Pool should reuse the same Metal buffer");
208        assert_eq!(buf1_byte_len, buf2_byte_len, "Byte lengths should match");
209        assert_eq!(pool.free_count(), 0, "Free list should be empty after reuse");
210    }
211
212    // ---- T10.6: kernel registry caching ----
213    #[test]
214    fn test_kernel_registry_caching() {
215        let device = MlxDevice::new().expect("device");
216        let mut registry = KernelRegistry::new();
217
218        // Register a minimal test kernel.
219        registry.register_source(
220            "test_add",
221            r#"
222            #include <metal_stdlib>
223            using namespace metal;
224            kernel void test_add(
225                device float *a [[buffer(0)]],
226                device float *b [[buffer(1)]],
227                device float *c [[buffer(2)]],
228                uint id [[thread_position_in_grid]]
229            ) {
230                c[id] = a[id] + b[id];
231            }
232            "#,
233        );
234
235        // First call — compiles the shader.
236        assert!(!registry.is_cached("test_add"));
237        let p1 = registry
238            .get_pipeline("test_add", device.metal_device())
239            .expect("get_pipeline first call");
240        let p1_ptr = p1 as *const _;
241        assert!(registry.is_cached("test_add"));
242
243        // Second call — returns cached pipeline.
244        let p2 = registry
245            .get_pipeline("test_add", device.metal_device())
246            .expect("get_pipeline second call");
247        let p2_ptr = p2 as *const _;
248
249        assert_eq!(
250            p1_ptr, p2_ptr,
251            "Second get_pipeline call should return the same cached pipeline"
252        );
253    }
254
255    // ---- Additional: test alloc_buffer with zero length returns error ----
256    #[test]
257    fn test_buffer_alloc_zero_len_error() {
258        let device = MlxDevice::new().expect("device");
259        let result = device.alloc_buffer(0, DType::F32, vec![]);
260        assert!(result.is_err(), "Zero-length allocation should fail");
261        match result {
262            Err(MlxError::InvalidArgument(_)) => {}
263            other => panic!("Expected InvalidArgument, got {:?}", other),
264        }
265    }
266
267    // ---- Additional: test kernel not found ----
268    #[test]
269    fn test_kernel_not_found() {
270        let device = MlxDevice::new().expect("device");
271        let mut registry = KernelRegistry::new();
272        let result = registry.get_pipeline("nonexistent_kernel", device.metal_device());
273        assert!(result.is_err());
274        match result {
275            Err(MlxError::KernelNotFound(name)) => {
276                assert_eq!(name, "nonexistent_kernel");
277            }
278            other => panic!("Expected KernelNotFound, got {:?}", other),
279        }
280    }
281
282    // ---- Additional: test DType properties ----
283    #[test]
284    fn test_dtype_sizes() {
285        assert_eq!(DType::F32.size_of(), 4);
286        assert_eq!(DType::F16.size_of(), 2);
287        assert_eq!(DType::BF16.size_of(), 2);
288        assert_eq!(DType::U8.size_of(), 1);
289        assert_eq!(DType::U16.size_of(), 2);
290        assert_eq!(DType::U32.size_of(), 4);
291        assert_eq!(DType::I32.size_of(), 4);
292    }
293
294    // ---- Additional: test MlxBuffer Debug ----
295    #[test]
296    fn test_buffer_debug() {
297        let device = MlxDevice::new().expect("device");
298        let buf = device
299            .alloc_buffer(64, DType::F16, vec![4, 8])
300            .expect("alloc_buffer");
301        let debug_str = format!("{:?}", buf);
302        assert!(debug_str.contains("MlxBuffer"));
303        assert!(debug_str.contains("F16"));
304        assert!(debug_str.contains("[4, 8]"));
305    }
306
307    // ---- Additional: test MlxError Display ----
308    #[test]
309    fn test_error_display() {
310        let e = MlxError::DeviceNotFound;
311        assert!(format!("{e}").contains("Metal GPU device"));
312
313        let e = MlxError::ShaderCompilationError {
314            name: "foo".into(),
315            message: "syntax error".into(),
316        };
317        assert!(format!("{e}").contains("foo"));
318        assert!(format!("{e}").contains("syntax error"));
319    }
320
321    // ---- Additional: test buffer pool with different sizes ----
322    #[test]
323    fn test_buffer_pool_size_buckets() {
324        let device = MlxDevice::new().expect("device");
325        let mut pool = MlxBufferPool::new(&device);
326
327        // Allocate a 100-byte buffer (rounds to 128-byte bucket).
328        let buf_100 = pool.alloc(100, DType::U8, vec![100]).expect("alloc 100");
329        assert!(
330            buf_100.byte_len() >= 100,
331            "Buffer should be at least 100 bytes"
332        );
333        pool.release(buf_100);
334
335        // Allocate a 128-byte buffer — should reuse the same Metal buffer.
336        let buf_128 = pool.alloc(128, DType::U8, vec![128]).expect("alloc 128");
337        assert!(buf_128.byte_len() >= 128);
338        pool.release(buf_128);
339
340        // Allocate a 200-byte buffer — different bucket (256), fresh allocation.
341        let buf_200 = pool.alloc(200, DType::U8, vec![200]).expect("alloc 200");
342        assert!(buf_200.byte_len() >= 200);
343        pool.release(buf_200);
344
345        assert_eq!(pool.free_count(), 2, "Two different bucket sizes in pool");
346    }
347}