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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Wired-memory limit — `mlx_set_wired_limit` thin wrapper, recommended
//! working-set query, and the RAII [`WiredLimitGuard`] scope guard (port of
//! mlx-lm's `wired_limit(model, streams=None)` `@contextmanager`).
//!
//! ## References
//! - Python: [`mlx-lm/mlx_lm/generate.py`](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/generate.py)
//! `wired_limit` (lines 230-269) — `@contextmanager` that sets
//! [`mlx_set_wired_limit`](mlxrs_sys::mlx_set_wired_limit) to the device's
//! `max_recommended_working_set_size`, warns on >90% utilization, restores
//! the prior limit on exit after [`Stream::synchronize`](crate::Stream::synchronize).
//! - Swift: [`mlx-swift-lm/.../WiredMemoryPolicies.swift`](https://github.com/ml-explore/mlx-swift-lm/blob/main/Libraries/MLXLMCommon/WiredMemoryPolicies.swift)
//! `recommendedWorkingSetBytes()` (lines 5-12) — the equivalent
//! `GPU.maxRecommendedWorkingSetBytes()` helper consulted by the LM-side
//! policy clamps.
//! - C: [`mlx/c/memory.h`](https://github.com/ml-explore/mlx/blob/main/mlx/c/memory.h)
//! `mlx_set_wired_limit` (out-param returns prior limit; non-zero rc on
//! failure).
//!
//! The wired-memory limit is **process-global**: setting it on one thread
//! affects every subsequent allocation in the process, irrespective of which
//! [`crate::Device`] / [`crate::Stream`] requested it. Use the guard form to
//! ensure the prior value is restored even on early return / panic.
use ;
use crate::;
/// Shared install-state for the process-global wired-memory limit.
///
/// Carried inside the `WIRED_LIMIT_STATE` mutex; populated by the first
/// concurrent [`WiredLimitGuard::install`] in an epoch and cleared by the
/// last live guard's [`Drop`] (refcount → 0).
/// Process-global install-state for [`WiredLimitGuard`].
///
/// A design with NO synchronization on
/// the install/Drop read-modify-restore cycle would let two concurrent guards
/// on different threads interleave their captures and corrupt the
/// process-global `mlx_set_wired_limit` state:
/// ```text
/// T1 install: captures L0 (sets recommended)
/// T2 install: captures recommended (sets recommended; thinks "old" = recommended!)
/// T1 drop: restores L0 (limit = L0)
/// T2 drop: restores recommended (limit = recommended; T1's restore is gone)
/// ```
/// Net effect: process-global limit ends at *recommended*, not the
/// original L0, despite both scopes having "completed cleanly".
///
/// ## Design: refcounted-guard
/// A **single-active-guard** approach (concurrent installs
/// returned `Ok(None)`) would silently lose
/// in-scope protection for the second concurrent install:
/// ```text
/// T1 install → captures L0, sets recommended limit, returns Some(guard)
/// T2 install → sees flag set, returns Ok(None) (NO GUARD)
/// T2 continues memory-sensitive work assuming protection
/// T1 drops → restores L0 (the ORIGINAL, lower limit)
/// T2 still running → now has L0 (UN-PROTECTED) for the rest of its scope
/// ```
/// The flag-check captured *intent* correctly but lost *lifetime* protection
/// for T2. We replace it with **refcounted-guard** semantics:
/// - The first install in an epoch captures the prior limit (`L0`), sets
/// the limit to the recommended value, and creates a [`WiredLimitState`]
/// with `refcount = 1`.
/// - Every concurrent install in the same epoch bumps `refcount` and yields
/// its own `Some(guard)` (NOT `Ok(None)`); the limit stays at recommended
/// for the new guard's full scope.
/// - Every [`Drop`] decrements `refcount`. Only when `refcount` hits 0 does
/// the captured `L0` get restored and the state cleared.
///
/// ## Comparison vs Python `wired_limit` context manager
/// Python's `wired_limit` is a `@contextmanager` that simply saves the prior
/// limit on entry and restores it on exit. Under the GIL, nesting is safe
/// because only one context is active at a time; under genuine concurrency
/// (sub-interpreters, free-threaded Python) the same unsynchronized bug
/// would fire. mlxrs's refcounted design matches Python's *intended
/// semantics* — "stack installs, restore the original at the bottom of the
/// stack" — but enforces them race-free via this mutex. (A single-active-guard
/// design preserves race-freedom at the cost of in-scope protection for
/// the second concurrent install; the refcounted design preserves both.)
///
/// ## Lock-hold discipline
/// The `Mutex` is held ONLY across the install's read-modify-write
/// (acquire → set_wired_limit if first → record state) and the Drop's
/// refcount-and-conditional-restore. It is NOT held during the scope's
/// body, so user code in a `WiredLimitGuard`-scoped region runs
/// unsynchronized — that is the correct behavior (the body shouldn't
/// block on the limit transition).
///
/// The lock is poison-tolerant: a panic mid-install (extremely rare —
/// `set_wired_limit`'s only failure path is the FFI rc) leaves the
/// payload `None` (the install captured nothing), so subsequent installs
/// proceed normally as the start of a new epoch.
static WIRED_LIMIT_STATE: = new;
/// Set the wired-memory limit in bytes, returning the **prior** limit.
///
/// Wraps [`mlx_set_wired_limit`](mlxrs_sys::mlx_set_wired_limit). The mlx-c
/// signature is `int mlx_set_wired_limit(size_t* res, size_t limit)` where
/// `res` receives the prior limit value (mirrors Python's
/// `old = mx.set_wired_limit(new)`).
///
/// **Process-global.** Prefer the RAII [`WiredLimitGuard`] form so the prior
/// limit is restored on early return / panic. Use the raw form only for
/// ad-hoc diagnostics, or when wrapping a longer-lived control structure.
/// The Metal device's recommended working-set size in bytes, if available.
///
/// Mirrors the Swift LM-side helper
/// [`recommendedWorkingSetBytes()`](https://github.com/ml-explore/mlx-swift-lm/blob/main/Libraries/MLXLMCommon/WiredMemoryPolicies.swift),
/// which itself wraps `GPU.maxRecommendedWorkingSetBytes()` from mlx-swift
/// (`Source/MLX/GPU+Metal.swift::DeviceInfo.maxRecommendedWorkingSetSize`).
///
/// Returns `Ok(None)` (gracefully) when the value cannot be obtained — non-
/// Metal builds, a CPU-only mlx, or an mlx-c that does not surface the
/// `max_recommended_working_set_size` key. Returns `Err` only on a genuine
/// FFI failure of [`mlx_device_info_get_size`](mlxrs_sys::mlx_device_info_get_size)
/// for an existing key (a backend rc).
///
/// **Process-global.** The value depends only on the system GPU's
/// `recommendedMaxWorkingSetSize`; mlxrs queries it through the default GPU
/// device's `mlx_device_info` map.
/// RAII scope guard for the wired-memory limit — port of mlx-lm's
/// `wired_limit(model, streams=None)` `@contextmanager`.
///
/// On [`WiredLimitGuard::install`] the prior limit is captured and the limit
/// is set to the device's `max_recommended_working_set_size`. On [`Drop`] the
/// supplied streams (or the default stream if none) are synchronized and the
/// prior limit is restored.
///
/// `install` returns `Ok(None)` ONLY when the wired-limit surface is
/// unavailable on this platform (non-Metal build, CPU-only mlx, or any
/// environment where [`recommended_working_set_bytes`] returns
/// `Ok(None)`). Mirrors the Python helper's `if not mx.metal.is_available():
/// yield` early return.
///
/// ## Concurrency
/// Concurrent installs use **refcounted-guard** semantics:
/// - The first install in an epoch captures the prior limit, sets the
/// limit to recommended, and yields `Ok(Some(guard))`.
/// - Every subsequent install while the first epoch is still live bumps
/// an internal refcount and *also* yields `Ok(Some(guard))`. The limit
/// stays at recommended for the new guard's full scope — its caller
/// gets the protection it asked for.
/// - Each [`Drop`] decrements the refcount. Only when the last guard in
/// the epoch drops does the limit restore to the originally-captured
/// prior value.
///
/// This matches Python's implicit-stacking semantics (Python's GIL hides
/// the race; mlxrs makes it genuinely race-free via the internal mutex).
/// See the crate-private `WIRED_LIMIT_STATE` static's doc-comment for the
/// refcounted design rationale.
///
/// Emits a `[WARNING]` to stderr (via [`eprintln`]) when `model_bytes >
/// 0.9 * max_rec_size`, matching the Python helper's near-OOM warning
/// (mlx-lm `generate.py` lines 248-256).
///
/// ## References
/// - Python: [`mlx-lm/mlx_lm/generate.py`](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/generate.py)
/// `wired_limit` (lines 230-269) and the `Tuner.close()` symmetric pattern
/// (lines 1545-1559).
///
/// ## Usage
///
/// ```rust,ignore
/// use mlxrs::memory::WiredLimitGuard;
///
/// // Caller computes `model_bytes` from their model's parameters (sum of
/// // `Array::nbytes()` over the weight tree) before calling install.
/// let _guard = WiredLimitGuard::install(model_bytes, &[])?;
/// // ... generation loop ...
/// // Guard drops here: synchronizes default stream, restores prior limit.
/// ```