mlx-native 0.24.0

Pure-Rust Metal GPU compute library for MLX-compatible inference on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Escrow-backed lifetime witnesses over at most two host pages of file-backed
//! Metal storage. Raw-owner tests do not submit work; commit/reclaim tests use
//! the public submission path and a bounded GPU blit on pool-less Rust threads.
//! Escrow keeps no-copy addresses valid even during assertion unwinding.

use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use memmap2::{Mmap, MmapOptions};

use super::{host_page_size, MlxDevice};
use crate::dtypes::DType;
use crate::encoder::RecordedBinding;

const LOGICAL_BYTES: usize = 4096;
const OFFSET: usize = 64;
static NEXT_FILE: AtomicU64 = AtomicU64::new(0);

struct Fixture {
    file: File,
    path: PathBuf,
    physical_bytes: usize,
}

impl Fixture {
    fn new() -> Self {
        let page = host_page_size().expect("query actual host page size");
        let physical_bytes = (OFFSET + LOGICAL_BYTES).div_ceil(page) * page;
        let sequence = NEXT_FILE.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "mlx-mapped-backing-{}-{sequence}.bin",
            std::process::id()
        ));
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(&path)
            .expect("create private regular mapping fixture");
        file.set_len(physical_bytes as u64)
            .expect("size fixture before mapping");
        Self {
            file,
            path,
            physical_bytes,
        }
    }

    fn mapping(&self) -> Arc<Mmap> {
        // SAFETY: this private, uniquely created regular file is sized before
        // mapping and never modified/truncated by these tests. Fixture remains
        // alive until every mapping/resource owner and the escrow have dropped.
        Arc::new(
            unsafe { MmapOptions::new().len(self.physical_bytes).map(&self.file) }
                .expect("map bounded read-only fixture"),
        )
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

#[derive(Clone, Copy, Debug)]
enum ResidencyMode {
    Default,
    Disabled,
}

fn device(mode: ResidencyMode) -> MlxDevice {
    match mode {
        ResidencyMode::Default => MlxDevice::new().expect("Metal device for bounded lifetime test"),
        // Explicit per-device configuration: do not mutate process-global env
        // flags (which are cached and could race other native tests).
        ResidencyMode::Disabled => {
            let device = metal::Device::system_default().expect("Metal device");
            let queue = device.new_command_queue();
            MlxDevice {
                device,
                queue,
                residency_set: None,
            }
        }
    }
}

/// Declared before every resource owner, so unwind drops those owners before
/// flushing their staged residency removals. No command encoder is created.
struct FlushResidencyOnDrop<'a>(&'a MlxDevice);

impl Drop for FlushResidencyOnDrop<'_> {
    fn drop(&mut self) {
        if let Some(set) = self.0.residency_set() {
            set.flush_pending();
        }
    }
}

fn mapped(device: &MlxDevice, escrow: &Arc<Mmap>) -> crate::MlxBuffer {
    device
        .map_file_buffer(
            Arc::clone(escrow),
            OFFSET,
            LOGICAL_BYTES,
            DType::U8,
            vec![LOGICAL_BYTES],
        )
        .expect("bounded no-copy mapping")
}

fn raw_owner_witness(mode: ResidencyMode, recorded: bool) {
    let fixture = Fixture::new();
    // Escrow is outside every autorelease scope/device/Metal owner. It remains
    // strong even if the required >1 predicate fails on the unfixed source.
    let escrow = fixture.mapping();
    let weak = Arc::downgrade(&escrow);
    assert_eq!(Arc::strong_count(&escrow), 1);
    objc::rc::autoreleasepool(|| {
        let device = device(mode);
        let _flush_on_unwind = FlushResidencyOnDrop(&device);
        eprintln!(
            "mapped backing witness mode={mode:?} actual_residency={} recorded={recorded}",
            device.residency_sets_enabled()
        );
        if recorded {
            let retained = objc::rc::autoreleasepool(|| {
                let buffer = mapped(&device, &escrow);
                let view = buffer.slice_view(32, 64);
                let binding = RecordedBinding::Buffer {
                    metal_buffer: view.metal_buffer().clone(),
                    offset: view.byte_offset(),
                };
                let retained = binding.clone();
                drop(binding);
                drop(view);
                drop(buffer);
                retained
            });
            if let Some(set) = device.residency_set() {
                set.flush_pending();
            }
            let count = Arc::strong_count(&escrow);
            eprintln!("mapped backing recorded-only strong_count={count}");
            assert!(
                count > 1,
                "RecordedBinding must retain mapping independently of escrow; observed {count}"
            );
            drop(retained);
        } else {
            let retained = objc::rc::autoreleasepool(|| {
                let buffer = mapped(&device, &escrow);
                let cloned = buffer.clone();
                let view = cloned.slice_view(32, 64);
                let retained = view.metal_buffer().clone();
                drop(view);
                drop(cloned);
                drop(buffer);
                retained
            });
            if let Some(set) = device.residency_set() {
                set.flush_pending();
            }
            let count = Arc::strong_count(&escrow);
            eprintln!("mapped backing raw-only strong_count={count}");
            assert!(
                count > 1,
                "raw Metal owner must retain mapping independently of escrow; observed {count}"
            );
            drop(retained);
        }
        // The guard flushes removal and device/queue ownership ends before
        // this autorelease pool drains; escrow remains outside the whole scope.
    });
    assert_eq!(
        Arc::strong_count(&escrow),
        1,
        "all resource/registration/autorelease owners must release backing, not leak it"
    );
    drop(escrow);
    assert!(
        weak.upgrade().is_none(),
        "final mapping teardown must occur"
    );
}

#[test]
fn raw_metal_owner_retains_mapping_disabled_residency() {
    raw_owner_witness(ResidencyMode::Disabled, false);
}

#[test]
fn raw_metal_owner_retains_mapping_default_residency() {
    raw_owner_witness(ResidencyMode::Default, false);
}

#[test]
fn recorded_binding_retains_mapping_disabled_residency() {
    raw_owner_witness(ResidencyMode::Disabled, true);
}

#[test]
fn recorded_binding_retains_mapping_default_residency() {
    raw_owner_witness(ResidencyMode::Default, true);
}

#[test]
fn ordinary_clones_and_views_retain_mapping_and_release_it() {
    for mode in [ResidencyMode::Disabled, ResidencyMode::Default] {
        let fixture = Fixture::new();
        let escrow = fixture.mapping();
        let weak = Arc::downgrade(&escrow);
        objc::rc::autoreleasepool(|| {
            let device = device(mode);
            let _flush_on_unwind = FlushResidencyOnDrop(&device);
            let buffer = mapped(&device, &escrow);
            assert_eq!(buffer.data_byte_len(), LOGICAL_BYTES);
            assert_eq!(buffer.byte_len(), fixture.physical_bytes);
            assert_eq!(buffer.byte_offset(), OFFSET as u64);
            assert!(!buffer.is_cpu_writable());
            let cloned = buffer.clone();
            let view = cloned.slice_view(32, 64);
            drop(buffer);
            assert!(Arc::strong_count(&escrow) > 1);
            drop(cloned);
            assert!(Arc::strong_count(&escrow) > 1);
            assert_eq!(view.data_byte_len(), 64);
            assert_eq!(view.byte_len(), fixture.physical_bytes);
            assert_eq!(view.byte_offset(), (OFFSET + 32) as u64);
            drop(view);
        });
        assert_eq!(Arc::strong_count(&escrow), 1);
        drop(escrow);
        assert!(weak.upgrade().is_none());
    }
}

#[test]
fn rejected_ranges_do_not_retain_mapping() {
    for mode in [ResidencyMode::Disabled, ResidencyMode::Default] {
        let fixture = Fixture::new();
        let escrow = fixture.mapping();
        let weak = Arc::downgrade(&escrow);
        objc::rc::autoreleasepool(|| {
            let device = device(mode);
            for (offset, length) in [(0, 0), (fixture.physical_bytes, 1), (usize::MAX, 2)] {
                let result = device.map_file_buffer(
                    Arc::clone(&escrow),
                    offset,
                    length,
                    DType::U8,
                    vec![length],
                );
                assert!(result.is_err());
                drop(result);
                assert_eq!(Arc::strong_count(&escrow), 1);
            }
        });
        drop(escrow);
        assert!(weak.upgrade().is_none());
    }
}

#[test]
fn nil_constructor_disposes_the_same_backing_capture_without_callback_dependency() {
    let fixture = Fixture::new();
    let escrow = fixture.mapping();
    let weak = Arc::downgrade(&escrow);
    let mut calls = 0;
    objc::rc::autoreleasepool(|| {
        let result = super::mapped_resource_with(
            Arc::clone(&escrow),
            fixture.physical_bytes,
            |_deallocator| {
                calls += 1;
                assert!(
                    Arc::strong_count(&escrow) > 1,
                    "actual production block capture must exist across constructor"
                );
                // Nil creation may never invoke the callback. The very same
                // helper must dispose its local copied block/capture anyway.
                std::ptr::null_mut()
            },
        );
        assert!(matches!(
            result,
            Err(crate::MlxError::BufferAllocationError { .. })
        ));
        drop(result);
    });
    assert_eq!(calls, 1);
    assert_eq!(Arc::strong_count(&escrow), 1);
    drop(escrow);
    assert!(weak.upgrade().is_none());
}

#[test]
fn constructor_unwind_disposes_capture_without_metal_or_payload_access() {
    let fixture = Fixture::new();
    let escrow = fixture.mapping();
    let weak = Arc::downgrade(&escrow);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        super::mapped_resource_with(Arc::clone(&escrow), fixture.physical_bytes, |_| {
            assert!(Arc::strong_count(&escrow) > 1);
            panic!("bounded injected constructor unwind before resource creation");
        })
    }));
    assert!(result.is_err());
    assert_eq!(Arc::strong_count(&escrow), 1);
    drop(escrow);
    assert!(weak.upgrade().is_none());
}

fn commit_drop_reclaim_witness(mode: ResidencyMode, gpu_read: bool) {
    // Deliberately no outer autoreleasepool: a consumer's Rust loading/worker
    // thread is not required to install one around native API calls.
    std::thread::spawn(move || {
        let fixture = Fixture::new();
        let expected: [u8; LOGICAL_BYTES] = std::array::from_fn(|i| (i % 251) as u8);
        std::os::unix::fs::FileExt::write_all_at(&fixture.file, &expected, OFFSET as u64)
            .expect("initialize private mapped GPU sentinel");
        let escrow = fixture.mapping();
        let weak = Arc::downgrade(&escrow);
        let loading_device = device(mode);
        let set_dropped = loading_device
            .residency_set()
            .and_then(|set| set.drop_notification_for_test());
        let buffer = mapped(&loading_device, &escrow);
        // Match a surviving loading-thread weight pool. Self-registered
        // storage owns membership; registration must not extend its lifetime.
        let mut registration_pool = crate::MlxBufferPool::new();
        registration_pool
            .register_existing(&loading_device, &buffer)
            .unwrap();
        let binding = RecordedBinding::Buffer {
            metal_buffer: buffer.metal_buffer().clone(),
            offset: buffer.byte_offset(),
        };

        // This device has never encoded a resource. Exactly one empty public
        // commit publishes the mapped allocation's pending residency membership.
        let mut loading_encoder = loading_device.command_encoder().unwrap();
        loading_encoder.commit_and_wait().unwrap();
        drop(loading_encoder);
        drop(loading_device);

        if gpu_read {
            let consumer = device(mode);
            let output = consumer
                .alloc_buffer(LOGICAL_BYTES, DType::U8, vec![LOGICAL_BYTES])
                .unwrap();
            let mut encoder = consumer.command_encoder().unwrap();
            encoder
                .blit_copy_bytes(&buffer, 0, &output, 0, LOGICAL_BYTES as u64)
                .unwrap();
            // Metal's retained command owns the mapping independently of its
            // logical wrapper; RecordedBinding is another independent owner.
            drop(buffer);
            assert!(Arc::strong_count(&escrow) > 1);
            encoder.commit_and_wait().unwrap();
            assert_eq!(
                output.as_logical_slice::<u8>().unwrap(),
                expected,
                "the private file must survive the GPU read"
            );
            drop(encoder);
            drop(output);
            drop(consumer);
        } else {
            drop(buffer);
        }

        // No explicit residency owner or removal flush: the final buffer
        // storage must retire its own set after the loading device has gone.
        assert!(
            Arc::strong_count(&escrow) > 1,
            "recorded Metal owner must still retain its no-copy backing"
        );
        drop(binding);
        if let Some(set_dropped) = set_dropped {
            // An event, not a sleep/RSS plateau: the heartbeat can briefly
            // borrow the last set Arc. Require that owner's actual teardown.
            set_dropped
                .recv_timeout(std::time::Duration::from_secs(5))
                .expect("final residency owner must finish teardown");
        }
        assert_eq!(
            Arc::strong_count(&escrow),
            1,
            "completed commands and final residency teardown must release mapped backing"
        );
        drop(registration_pool);
        drop(escrow);
        assert!(weak.upgrade().is_none());
    })
    .join()
    .expect("pool-less consumer commit/drop/reclaim witness");
}

#[test]
fn empty_loading_commit_then_drop_reclaims_mapping_without_ambient_pool() {
    for mode in [ResidencyMode::Disabled, ResidencyMode::Default] {
        commit_drop_reclaim_witness(mode, false);
    }
}

#[test]
fn loading_commit_then_gpu_read_and_drop_reclaims_mapping_without_ambient_pool() {
    assert!(
        !crate::command_buffer_uses_unretained_references(),
        "this lifetime witness requires Metal's default retained command owners"
    );
    for mode in [ResidencyMode::Disabled, ResidencyMode::Default] {
        commit_drop_reclaim_witness(mode, true);
    }
}

#[test]
fn registration_pool_preserves_live_device_binding_and_rebinds_after_retirement() {
    let fixture = Fixture::new();
    let escrow = fixture.mapping();
    let first = device(ResidencyMode::Default);
    let second = device(ResidencyMode::Default);
    let tracks_residency = first.residency_sets_enabled();
    let first_dropped = first
        .residency_set()
        .and_then(|set| set.drop_notification_for_test());
    let first_buffer = mapped(&first, &escrow);
    let second_buffer = mapped(&second, &escrow);
    let mut pool = crate::MlxBufferPool::new();
    pool.register_existing(&first, &first_buffer).unwrap();
    assert_eq!(
        pool.register_existing(&second, &second_buffer).is_err(),
        tracks_residency,
        "a live registration-only binding must reject another set"
    );
    assert_eq!(
        pool.alloc(&second, 64, DType::U8, vec![64]).is_err(),
        tracks_residency,
        "pool-owned allocations must honor a live registration-only binding"
    );
    drop(first_buffer);
    drop(first);
    if let Some(first_dropped) = first_dropped {
        first_dropped
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("registration-only pool must not own the old set");
    }
    pool.register_existing(&second, &second_buffer).unwrap();
    let pooled = pool.alloc(&second, 64, DType::U8, vec![64]).unwrap();
    let third = device(ResidencyMode::Default);
    let third_buffer = mapped(&third, &escrow);
    assert_eq!(
        pool.register_existing(&third, &third_buffer).is_err(),
        tracks_residency,
        "the pool-owned binding must still reject another set"
    );
    drop(pooled);
}