mlx-native 0.15.4

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
//! Optional immutable native-mediated requested-root history. Not physical admission.
pub(crate) mod state;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod control_tests;
use crate::{DType, MlxBuffer, MlxDevice, Result};
use state::{fail, Charge, DeviceKey, State};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

/// Caller-selected historical ceilings. No resource drop refunds these limits.
#[derive(Clone, Copy, Debug)]
pub struct RootCreationLimits {
    pub max_attempted_requested_bytes: usize,
    pub max_root_attempts: usize,
    pub max_raw_constructor_attempts: usize,
    pub max_registered_devices: usize,
    pub max_rope_cache_entries: usize,
}
/// Requested history and qualification state; never a physical-memory promise.
#[derive(Clone, Debug)]
pub struct RootCreationSnapshot {
    pub scope: &'static str,
    pub limits: Option<RootCreationLimits>,
    pub covered: bool,
    pub legacy_used: bool,
    pub unknown: Option<&'static str>,
    pub attempted_requested_bytes: usize,
    pub root_attempts: usize,
    pub raw_attempt_reservations: usize,
    pub inflight: usize,
    pub successful_roots: usize,
    pub cache_slot_history: usize,
    pub published_cache_entries: usize,
    pub registered_devices: usize,
    pub denied: usize,
}
/// Informational lineage only; snapshot data cannot mint a creation certificate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RootOriginSnapshot {
    Legacy,
    UnknownImport,
    KnownNative { id: usize, requested_bytes: usize },
}
#[derive(Clone)]
pub(crate) enum Origin {
    Legacy,
    Unknown,
    Known(Arc<Charge>),
}
#[derive(Clone)]
pub(crate) struct KnownRoot {
    metal: metal::Buffer,
    origin: Origin,
}
impl KnownRoot {
    pub(crate) fn metal(&self) -> &metal::Buffer {
        &self.metal
    }
    pub(crate) fn into_parts(self) -> (metal::Buffer, Origin) {
        (self.metal, self.origin)
    }
    pub(crate) fn from_parts(metal: metal::Buffer, origin: Origin) -> Self {
        Self { metal, origin }
    }
    pub(crate) fn check(&self) -> Result<()> {
        global().core.health()?;
        if global().core.installed()? {
            match &self.origin {
                Origin::Known(charge)
                    if self.metal.length() as usize == charge.bytes
                        && !self.metal.contents().is_null()
                        && self.metal.storage_mode() == metal::MTLStorageMode::Shared =>
                {
                    Ok(())
                }
                _ => {
                    global()
                        .core
                        .unknown("unknown origin or invalid returned resource");
                    Err(fail("known native resource required"))
                }
            }
        } else {
            Ok(())
        }
    }
    pub(crate) fn check_device(&self, device: &metal::DeviceRef) -> Result<()> {
        self.check()?;
        if let Origin::Known(charge) = &self.origin {
            if charge.device != device_key(device) {
                return Err(fail("known root device mismatch"));
            }
        }
        Ok(())
    }
    pub(crate) fn snapshot(&self) -> RootOriginSnapshot {
        match &self.origin {
            Origin::Legacy => RootOriginSnapshot::Legacy,
            Origin::Unknown => RootOriginSnapshot::UnknownImport,
            Origin::Known(c) => RootOriginSnapshot::KnownNative {
                id: c.id,
                requested_bytes: c.bytes,
            },
        }
    }
}
pub(crate) struct Core {
    state: Mutex<State>,
    poisoned: AtomicBool,
    // Published only AFTER Fresh->permanently legacy under the state mutex.
    legacy_fast: AtomicBool,
}
impl Default for Core {
    fn default() -> Self {
        Self {
            state: Mutex::new(State::default()),
            poisoned: AtomicBool::new(false),
            legacy_fast: AtomicBool::new(false),
        }
    }
}
impl Core {
    pub(crate) fn lock(&self) -> Result<std::sync::MutexGuard<'_, State>> {
        if self.poisoned.load(Ordering::Acquire) {
            return Err(fail("state poisoned"));
        }
        self.state.lock().map_err(|_| {
            self.poisoned.store(true, Ordering::Release);
            fail("state poisoned")
        })
    }
    pub(crate) fn health(&self) -> Result<()> {
        if self.legacy_fast.load(Ordering::Acquire) {
            return Ok(());
        }
        self.lock()?.health()
    }
    fn installed(&self) -> Result<bool> {
        if self.legacy_fast.load(Ordering::Acquire) {
            return Ok(false);
        }
        Ok(self.lock()?.limits.is_some())
    }
    pub(crate) fn unknown(&self, reason: &'static str) {
        match self.lock() {
            Ok(mut s) => {
                s.unknown.get_or_insert(reason);
            }
            Err(_) => {
                self.poisoned.store(true, Ordering::Release);
            }
        }
    }
    pub(crate) fn create<T>(
        &self,
        key: DeviceKey,
        bytes: usize,
        cache: bool,
        raw: impl FnOnce() -> Result<T>,
    ) -> Result<(T, Origin)> {
        if bytes == 0 {
            return Err(fail("zero creation request"));
        }
        if self.legacy_fast.load(Ordering::Acquire) {
            return raw().map(|value| (value, Origin::Legacy));
        }
        let charge = self.lock()?.reserve(key, bytes, cache)?;
        if charge.is_none() {
            self.legacy_fast.store(true, Ordering::Release);
        }
        // Allocate all certificate metadata BEFORE invoking the raw constructor.
        let origin = charge
            .map(|c| Origin::Known(Arc::new(c)))
            .unwrap_or(Origin::Legacy);
        let mut attempt = Attempt {
            core: self,
            tracked: matches!(origin, Origin::Known(_)),
            closed: false,
        };
        let result = raw();
        // Nonnil/raw success MUST remain Ok, even if diagnostic completion fails:
        // Native55 construct interprets every Err as no resource created.
        attempt.finish(result.is_ok(), false);
        result.map(|value| (value, origin))
    }
}
struct Attempt<'a> {
    core: &'a Core,
    tracked: bool,
    closed: bool,
}
impl Attempt<'_> {
    fn finish(&mut self, success: bool, abandoned: bool) {
        if self.tracked {
            match self.core.lock() {
                Ok(mut s) => s.finish(success, abandoned),
                Err(_) => self.core.poisoned.store(true, Ordering::Release),
            }
        }
        self.closed = true;
    }
}
impl Drop for Attempt<'_> {
    fn drop(&mut self) {
        if !self.closed {
            self.finish(false, true);
        }
    }
}
// A successful raw creation has already committed Native55's local charge.
// Postcreation publication failure poisons coverage without a constructor Err.
pub(crate) struct PublicationGuard<'a> {
    core: &'a Core,
    tracked: bool,
    done: bool,
}
impl<'a> PublicationGuard<'a> {
    fn new(core: &'a Core) -> Self {
        Self {
            core,
            tracked: core.installed().unwrap_or(true),
            done: false,
        }
    }
    pub(crate) fn complete(mut self) {
        self.done = true;
    }
}
impl Drop for PublicationGuard<'_> {
    fn drop(&mut self) {
        if self.tracked && !self.done {
            self.core
                .unknown("postcreation publication failed or unwound");
        }
    }
}
pub(crate) fn publication_guard() -> PublicationGuard<'static> {
    PublicationGuard::new(&global().core)
}

struct Global {
    core: Core,
    devices: Mutex<Vec<metal::Device>>,
}
fn global() -> &'static Global {
    static G: OnceLock<Global> = OnceLock::new();
    G.get_or_init(|| Global {
        core: Core::default(),
        devices: Mutex::new(Vec::new()),
    })
}
fn device_key(device: &metal::DeviceRef) -> DeviceKey {
    DeviceKey {
        object: device as *const metal::DeviceRef as usize,
        registry: crate::device::metal_device_registry_id(device),
    }
}
/// Installs only before any native root/heap creation or unknown import.
pub struct NativeRootAuthority;
#[derive(Clone, Copy)]
pub struct RootAuthorityHandle {
    _private: (),
}
impl NativeRootAuthority {
    pub fn install_early(limits: RootCreationLimits) -> Result<RootAuthorityHandle> {
        let g = global();
        let mut devices = g
            .devices
            .lock()
            .map_err(|_| fail("device registry poisoned"))?;
        let mut state = g.core.lock()?;
        if state.limits.is_some() || state.legacy || state.unknown.is_some() {
            return Err(fail(
                "installation requires fresh native creation/import history",
            ));
        }
        if limits.max_registered_devices == 0 {
            return Err(fail("device limit must be nonzero"));
        }
        devices
            .try_reserve_exact(limits.max_registered_devices)
            .map_err(|_| fail("device handle reservation failed"))?;
        state.install(limits)?;
        Ok(RootAuthorityHandle { _private: () })
    }
}
impl RootAuthorityHandle {
    /// Retains the actual device. Different queues share this process history.
    pub fn register_device(&self, device: &MlxDevice) -> Result<()> {
        let g = global();
        let mut owners = g
            .devices
            .lock()
            .map_err(|_| fail("device registry poisoned"))?;
        let key = device_key(device.metal_device());
        // Retain outside the global state lock; publication below is allocation-free.
        let retained = device.metal_device().to_owned();
        let mut s = g.core.lock()?;
        if s.devices.contains(&key) {
            return s.health();
        }
        // Registry capacity was preallocated before installation; no buffer creation.
        s.register(key)?;
        owners.push(retained);
        Ok(())
    }
    pub fn snapshot(&self) -> Result<RootCreationSnapshot> {
        Ok(global().core.lock()?.snapshot())
    }
}
pub(crate) fn import_origin() -> Origin {
    let core = &global().core;
    if core.legacy_fast.load(Ordering::Acquire) {
        return Origin::Legacy;
    }
    match core.lock() {
        Ok(mut s) => {
            s.import();
            if s.limits.is_some() {
                Origin::Unknown
            } else {
                core.legacy_fast.store(true, Ordering::Release);
                Origin::Legacy
            }
        }
        Err(_) => Origin::Unknown,
    }
}
pub(crate) fn require_no_heap() -> Result<()> {
    let core = &global().core;
    if core.legacy_fast.load(Ordering::Acquire) {
        return Ok(());
    }
    let mut state = core.lock()?;
    let result = state.heap();
    if state.limits.is_none() && state.legacy {
        core.legacy_fast.store(true, Ordering::Release);
    }
    result
}

pub(crate) fn shared_with(
    device: &metal::DeviceRef,
    bytes: usize,
    cache: bool,
    raw: impl FnOnce() -> Result<metal::Buffer>,
) -> Result<KnownRoot> {
    global()
        .core
        .create(device_key(device), bytes, cache, raw)
        .map(|(metal, origin)| KnownRoot { metal, origin })
}
pub(crate) fn healthy() -> Result<()> {
    global().core.health()
}
pub(crate) fn cache_published() {
    if global().core.legacy_fast.load(Ordering::Acquire) {
        return;
    }
    match global().core.lock() {
        Ok(mut s) => {
            if s.limits.is_some() {
                s.published_cache = s.published_cache.saturating_add(1);
            }
        }
        Err(_) => global().core.poisoned.store(true, Ordering::Release),
    }
}
/// Exact initialized Shared upload. No kernel, queue creation or conversion.
pub(crate) fn upload_on_device(
    device: &metal::DeviceRef,
    data: &[u8],
    dtype: DType,
    shape: Vec<usize>,
    cache: bool,
) -> Result<MlxBuffer> {
    let expected = shape
        .iter()
        .try_fold(dtype.size_of(), |n, d| n.checked_mul(*d))
        .ok_or_else(|| fail("upload shape byte overflow"))?;
    if expected != data.len() {
        return Err(fail("upload shape/byte mismatch"));
    }
    if data.is_empty() {
        return Err(fail("empty upload"));
    }
    let root = crate::device::new_shared_on_device(device, data.len(), cache)?;
    let publication = publication_guard();
    root.check_device(device)?;
    // Exclusive unpublished root, checked extent and nonnull before CPU write.
    unsafe {
        std::ptr::copy_nonoverlapping(
            data.as_ptr(),
            root.metal().contents().cast::<u8>(),
            data.len(),
        );
    }
    let buffer = MlxBuffer::from_known(root, dtype, shape)?;
    publication.complete();
    Ok(buffer)
}