hf2q 0.1.31

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Thread-local arena buffer pool for the qwen35 decode hot path.
//!
//! # Purpose
//!
//! ADR-012 §Optimize / Task #15 — close the MoE dwq46 0.90× decode parity gap
//! vs the peer.  Diagnostic localization (`HF2Q_DECODE_PROFILE=1`) showed
//! the gap is fixed-cost-per-layer not per-byte, and the per-layer cost is
//! dominated by ~1750 `MlxDevice::alloc_buffer()` calls per decode token
//! across the three dispatch helpers (`gpu_delta_net::build_delta_net_layer`,
//! `gpu_ffn::build_moe_ffn_layer_gpu_q`, `gpu_full_attn::build_gated_attn_layer`).
//! Each direct alloc hits Metal's `newBuffer` allocator (5-30 µs each); a
//! per-token arena pool reuses the underlying `metal::Buffer` objects across
//! token boundaries so steady-state allocation cost amortizes to near zero.
//!
//! # Why a thread-local
//!
//! The dispatch helpers are deeply nested (`build_delta_net_layer` calls
//! `apply_pre_norm` calls `dispatch_rms_norm` etc.).  Threading a
//! `&mut MlxBufferPool` parameter through every helper would touch ~62
//! call sites + every signature.  A thread-local pool gives a clean
//! single-line replacement at each `device.alloc_buffer(...)` call site
//! (`pooled_alloc_buffer(device, ...)`) with zero signature thrash.
//!
//! Decode is single-threaded per `feedback_oom_prevention` (one model-loading
//! inference at a time on the M5 Max), so a thread-local is sufficient.
//!
//! # Lifecycle
//!
//! * [`reset_decode_pool`] is called at the top of each
//!   `Qwen35Model::forward_gpu_greedy` call (per token).
//! * Layer dispatches inside the forward call use [`pooled_alloc_buffer`]
//!   in place of `device.alloc_buffer`.
//! * Locally-bound `MlxBuffer` values fall out of scope at function exit;
//!   the pool's ARC clones keep the underlying Metal storage alive.
//! * The next token's `reset_decode_pool` moves all in-use clones back to
//!   the free list, ready for reuse by subsequent allocations.
//!
//! # Caller contract
//!
//! No `MlxBuffer` returned from `pooled_alloc_buffer` may outlive a
//! [`reset_decode_pool`] call from the same thread.  In Rust's ownership
//! model, locally-bound buffers fall out of scope at the end of their
//! lexical block, making the per-decode-token pattern safe by construction
//! provided allocations stay inside `forward_gpu_greedy`'s call tree.

mod device;
pub mod profile;

use std::cell::RefCell;

use mlx_native::ops::quantized_matmul_id_ggml::IdMmScratch;
use mlx_native::{DType, MlxBuffer, MlxBufferPool, MlxDevice};

thread_local! {
    /// Per-thread arena pool.  Initialized lazily by the first
    /// [`pooled_alloc_buffer`] call; reset between decode tokens.
    static DECODE_POOL: RefCell<MlxBufferPool> = RefCell::new(MlxBufferPool::new());

    /// Per-thread cached `IdMmScratch` instances for the three MoE FFN
    /// `quantized_matmul_id_ggml` call slots (W-5b.24).  Each FFN call
    /// site (gate, up, down) gets its own scratch so the three calls
    /// inside the gate+up Phase C concurrent block do NOT race on
    /// htpe/hids writes — the down call lives in Phase E behind a
    /// barrier so any of the three could share with down, but keeping
    /// three distinct scratches mirrors the call structure 1:1 and is
    /// trivially correct.
    ///
    /// Grown on demand via `with_id_mm_scratch_*` helpers.  The first
    /// FFN call of a prefill allocates 6 device buffers (2 per scratch
    /// × 3 scratches); every subsequent FFN call (47 layers × 3 calls
    /// = 141 calls) reuses them.  Net: 286 of 288 per-prefill device
    /// allocs eliminated, matching the W-5b.23 audit's recovery target.
    static MM_ID_SCRATCH_GATE: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
    static MM_ID_SCRATCH_UP: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
    static MM_ID_SCRATCH_DOWN: RefCell<Option<IdMmScratch>> = const { RefCell::new(None) };
}

/// Owning-worker only. The serving publisher verifies its worker registration first.
/// This does not reset, allocate Metal buffers, wait, or mutate profile health.
pub(crate) fn worker_memory_snapshot() -> Result<(&'static str, mlx_native::PoolMemorySnapshot), String> {
    if let Some(result) = profile::memory_snapshot_if_selected() {
        return result.map(|snapshot| ("growth_limited", snapshot));
    }
    DECODE_POOL.try_with(|cell| {
        let pool = cell.try_borrow().map_err(|_| "legacy pool borrow busy".to_string())?;
        pool.memory_snapshot().map(|snapshot| ("legacy", snapshot)).map_err(|error| error.to_string())
    }).map_err(|_| "legacy worker TLS unavailable".to_string()).and_then(|r| r)
}

/// Carry/catch-up's prior pool owner, including direct spillover held until
/// reset. `OVERFLOW` is disjoint from the native pool: the capped branch below
/// makes a fresh device allocation, retains it, and returns BEFORE pool.alloc.
/// Native free/issued/residency labels already overlap inside `retained`.
pub(crate) fn worker_carry_pool_bytes() -> Result<u64, String> {
    let native = worker_memory_snapshot()?.1.retained.bytes as u64;
    OVERFLOW.try_with(|cell| {
        let overflow = cell.try_borrow().map_err(|_| "carry overflow borrow busy".to_string())?;
        overflow.iter().try_fold(native, |bytes, root| {
            bytes.checked_add(root.byte_len() as u64)
                .ok_or_else(|| "carry pool backing capacity overflow".to_string())
        })
    }).map_err(|_| "carry overflow TLS unavailable".to_string()).and_then(|result| result)
}

/// Allocate from the thread-local decode pool.
///
/// API-compatible with `MlxDevice::alloc_buffer` so call sites in the
/// dispatch helpers can be edited mechanically.
#[inline]
#[cfg_attr(test, track_caller)]
pub fn pooled_alloc_buffer(
    device: &MlxDevice,
    byte_len: usize,
    dtype: DType,
    shape: Vec<usize>,
) -> std::result::Result<MlxBuffer, mlx_native::MlxError> {
    if let Some(result) = profile::alloc(device, byte_len, dtype, &shape) { return result; }
    device::bind(device)?;
    // The pool hands out the power-of-two bucket the request rounds up to.
    let bucket = byte_len.max(1).next_power_of_two();
    ISSUED_BYTES.with(|issued| issued.set(issued.get() + bucket));
    ISSUED_TOTAL.with(|issued| issued.set(issued.get() + bucket as u64));
    #[cfg(test)]
    {
        let site = std::panic::Location::caller();
        SCRATCH_TRACE.with(|trace| {
            if let Some(trace) = trace.borrow_mut().as_mut() {
                trace.push((site.file(), site.line(), byte_len));
            }
        });
    }
    if let Some(caps) = CAPS.with(std::cell::Cell::get) {
        #[cfg(test)]
        CAPPED_FREE_PEAK.with(|peak| {
            peak.set(peak.get().max(DECODE_POOL.with(|cell| cell.borrow().free_bytes())))
        });
        // Before the allocation: what the pool held free at its last reset
        // plus what it has handed out since bounds what it holds now (a
        // reused buffer counts as if it were new). A request that could
        // take the pool over its cap is served outside it.
        let held = FREE_AT_RESET.with(std::cell::Cell::get)
            + POOLED_SINCE_RESET.with(std::cell::Cell::get);
        if held.saturating_add(bucket) > caps.pool {
            let buffer = device.alloc_buffer(byte_len, dtype, shape)?;
            OVERFLOW.with(|overflow| overflow.borrow_mut().push(buffer.clone()));
            return Ok(buffer);
        }
    }
    let buffer = DECODE_POOL.with(|cell| cell.borrow_mut().alloc(device, byte_len, dtype, shape))?;
    POOLED_SINCE_RESET.with(|pooled| pooled.set(pooled.get() + bucket));
    Ok(buffer)
}

/// The caps a forward puts on this thread's pool ([`cap_pool`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PoolCaps {
    /// What the pool may hold at any time: checked before every allocation.
    pub(crate) pool: usize,
    /// Free bytes above which a reset releases the pool's free buffers.
    pub(crate) retained: usize,
}

thread_local! {
    /// Bucket bytes handed out since the last reset, by the pool or outside
    /// it.
    static ISSUED_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// Bucket bytes handed out by this thread, ever (never reset).
    static ISSUED_TOTAL: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// The largest scratch one layer has requested since the last
    /// [`take_layer_scratch_peak`], and whether a layer over its bound was
    /// reported already.
    static LAYER_SCRATCH_PEAK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    static LAYER_SCRATCH_REPORTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// The pool's part of [`ISSUED_BYTES`].
    static POOLED_SINCE_RESET: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// Free bytes the pool held after its last reset or, later, when caps
    /// were put on it.
    static FREE_AT_RESET: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// The caps in force, and whether they end with the next reset.
    static CAPS: std::cell::Cell<Option<PoolCaps>> = const { std::cell::Cell::new(None) };
    static CAPS_END_AT_RESET: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// Buffers served outside the pool since the last reset. They are held
    /// like pooled ones, so a command buffer still in flight keeps its
    /// operands, and are released (not recycled) at the reset.
    static OVERFLOW: RefCell<Vec<MlxBuffer>> = const { RefCell::new(Vec::new()) };
}

#[cfg(test)]
thread_local! {
    /// Test trace of the scratch requests: (file, line, bytes requested).
    static SCRATCH_TRACE: RefCell<Option<Vec<(&'static str, u32, usize)>>> =
        const { RefCell::new(None) };
}

/// Start (`true`) or stop a trace of this thread's scratch requests and
/// return what was traced so far.
#[cfg(test)]
pub(crate) fn trace_scratch(on: bool) -> Vec<(&'static str, u32, usize)> {
    SCRATCH_TRACE.with(|trace| trace.replace(on.then(Vec::new)).unwrap_or_default())
}

/// Bucket bytes of scratch this thread has out since its pool's last reset:
/// handed out by the pool or served outside it.
pub(crate) fn issued_bytes() -> usize {
    ISSUED_BYTES.with(std::cell::Cell::get)
}

/// Bucket bytes of scratch this thread has requested so far (monotone).
pub(crate) fn issued_total() -> u64 {
    ISSUED_TOTAL.with(std::cell::Cell::get)
}

/// Record that one layer of a forward requested `bytes` of scratch, against
/// the bound derived for the forward's shape (`None`: no bound applies). A
/// layer over its bound ran on a route the derivation does not cover: it is
/// reported once per thread, the forward is not affected.
pub(crate) fn note_layer_scratch(bytes: u64, bound: Option<u64>) {
    LAYER_SCRATCH_PEAK.with(|peak| peak.set(peak.get().max(bytes)));
    if bound.is_some_and(|bound| bytes > bound) && !LAYER_SCRATCH_REPORTED.with(|cell| cell.replace(true)) {
        tracing::warn!(
            layer_scratch_bytes = bytes,
            bound_bytes = bound.unwrap_or_default(),
            "Qwen prefill: a layer requested more scratch than the bound derived for its shape"
        );
    }
}

/// The largest scratch one layer has requested since the last call.
#[cfg(test)]
pub(crate) fn take_layer_scratch_peak() -> u64 {
    LAYER_SCRATCH_PEAK.with(|peak| peak.replace(0))
}

/// Put `caps` on this thread's pool from now on (`None`: no caps, the
/// default).
///
/// The pool reuses a free buffer only in the exact bucket a request rounds
/// up to and never shrinks on its own, so forwards of varying sizes, and
/// forwards that skip host waits, grow it without bound. Under caps:
/// - before every allocation, a request that could take the pool over
///   `caps.pool` is served by a plain device buffer instead, held until the
///   next reset and released there, so the pool never holds more than
///   `caps.pool` bytes;
/// - a reset releases the pool's free buffers when they exceed
///   `caps.retained`. A reset follows a drained queue and the last use of
///   every issued buffer, so the free buffers have no user.
/// Released and outside buffers are allocated again when needed: that costs
/// allocation time, never memory.
///
/// Putting caps on a pool that earlier, uncapped forwards left warm trims
/// it at once: its free buffers are released when they exceed
/// `caps.retained`, before the first capped allocation, so the hard cap
/// holds from the first window on. The free buffers are those the
/// forward's own initial reset took back (a reset follows a drained queue
/// and the last use of every issued buffer); what the forward has issued
/// since (its embedding) is in use and is not touched. The release takes
/// effect immediately (the pool removes them from the residency set and
/// commits the set); no command buffer is needed for it.
pub(crate) fn cap_pool(caps: Option<PoolCaps>) {
    CAPS.with(|cell| cell.set(caps));
    CAPS_END_AT_RESET.with(|cell| cell.set(false));
    if let Some(caps) = caps {
        if !default_pool() {
            return;
        }
        DECODE_POOL.with(|cell| {
            let mut pool = cell.borrow_mut();
            if pool.free_bytes() > caps.retained {
                #[cfg(test)]
                let before = (pool.free_bytes(), trim_probe());
                pool.clear();
                #[cfg(test)]
                if let (freed, Some(before)) = before {
                    let after = trim_probe().unwrap_or(before);
                    TRIM_SAMPLE.with(|sample| sample.set(Some((freed, before, after))));
                }
            }
            // What the pool holds now is this plus what is in use, which is
            // exactly what it has handed out since its reset.
            FREE_AT_RESET.with(|free| free.set(pool.free_bytes()));
            #[cfg(test)]
            CAPPED_FREE_PEAK.with(|peak| peak.set(peak.get().max(pool.free_bytes())));
        });
    }
}

#[cfg(test)]
thread_local! {
    /// The most free bytes the pool held at a capped allocation or at a cap
    /// activation since the last [`take_capped_free_peak`].
    static CAPPED_FREE_PEAK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
thread_local! {
    /// A test's reading of the device's allocated bytes.
    static TRIM_PROBE: std::cell::RefCell<Option<Box<dyn Fn() -> usize>>> =
        const { std::cell::RefCell::new(None) };
    /// `(free bytes released, probe before, probe after)` of the last trim
    /// at a cap activation with a probe set.
    static TRIM_SAMPLE: std::cell::Cell<Option<(usize, usize, usize)>> =
        const { std::cell::Cell::new(None) };
}

#[cfg(test)]
fn trim_probe() -> Option<usize> {
    TRIM_PROBE.with(|probe| probe.borrow().as_ref().map(|read| read()))
}

/// Sample `probe` immediately before and after the release of a warm pool
/// at a cap activation on this thread.
#[cfg(test)]
pub(crate) fn set_trim_probe(probe: Option<Box<dyn Fn() -> usize>>) {
    TRIM_PROBE.with(|cell| *cell.borrow_mut() = probe);
}

/// `(free bytes released, probe before, probe after)` of the last trim at a
/// cap activation since the last call.
#[cfg(test)]
pub(crate) fn take_trim_sample() -> Option<(usize, usize, usize)> {
    TRIM_SAMPLE.with(std::cell::Cell::take)
}

/// The most free bytes this thread's pool held while caps were in force
/// (sampled when the caps were put on and at every capped allocation) since
/// the last call.
#[cfg(test)]
pub(crate) fn take_capped_free_peak() -> usize {
    CAPPED_FREE_PEAK.with(|peak| peak.replace(0))
}

/// The caps of [`cap_pool`] apply through one more reset and then end. A
/// forward calls this when it returns: the reset that takes its last
/// buffers back is the next forward's or the next decode step's.
pub(crate) fn end_caps_at_next_reset() {
    CAPS_END_AT_RESET.with(|cell| cell.set(CAPS.with(std::cell::Cell::get).is_some()));
}

/// Release the pool's owners of buffers served outside it, after a checked
/// drain of every submitted command (including the error path). This is not
/// evidence that a backing was freed: any escaped carry/parent alias keeps
/// its full backing charge in carry_memory, independently of this census.
pub(crate) fn release_overflow() {
    OVERFLOW.with(|overflow| overflow.borrow_mut().clear());
}

/// Whether this thread's pool is the default one (not the growth-limited
/// investigation profile, which has its own quota and no release).
pub(crate) fn default_pool() -> bool {
    !profile::selected()
}

/// Free bytes this thread's default pool holds.
#[cfg(test)]
pub(crate) fn free_bytes() -> usize {
    DECODE_POOL.with(|cell| cell.borrow().free_bytes())
}

thread_local! {
    /// Whether multi-row layer outputs come from this pool (see
    /// [`StepPooledOutputs`]).
    static STEP_POOLED_OUTPUTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// While alive, the multi-row (`seq > 1`) layer outputs that otherwise use
/// `MlxDevice::alloc_buffer` (dense FFN `down_out` / residual sum, attention
/// projection and Q/gate outputs) come from this pool instead.
///
/// Those outputs are fresh device allocations because a prefill chunk resets
/// this pool between layers while a layer's output becomes the next layer's
/// input. A joint decode step resets the pool only at its start, after the
/// previous step drained, so inside its layer loop pooled outputs live long
/// enough. Every such output is fully written by its producing kernel, so the
/// arithmetic is unchanged (Class A); only the per-step Metal allocation,
/// zero-fill and residency-set churn go away.
pub(crate) struct StepPooledOutputs {
    previous: bool,
}

impl StepPooledOutputs {
    /// Open the scope when `enabled`; a disabled scope changes nothing.
    pub(crate) fn enter(enabled: bool) -> Self {
        Self {
            previous: STEP_POOLED_OUTPUTS.with(|cell| cell.replace(enabled)),
        }
    }
}

impl Drop for StepPooledOutputs {
    fn drop(&mut self) {
        STEP_POOLED_OUTPUTS.with(|cell| cell.set(self.previous));
    }
}

/// Whether a [`StepPooledOutputs`] scope is open on this thread.
pub(crate) fn step_pooled_outputs() -> bool {
    STEP_POOLED_OUTPUTS.with(std::cell::Cell::get)
}

/// Reset the thread-local decode pool — moves every buffer handed out
/// since the last reset back to the free list.
///
/// **Caller contract:** no `MlxBuffer` returned by [`pooled_alloc_buffer`]
/// since the previous reset may still be in scope on this thread.  Calling
/// `reset_decode_pool` while a buffer is still referenced is a soundness
/// hole — the pool may re-issue the same Metal storage to a future
/// allocation, causing aliasing.
pub fn reset_decode_pool() {
    // Legacy/test compatibility entry. Production uses the checked form.
    if let Err(_error) = checked_reset_decode_pool() { profile::quarantine(); }
}

/// Caller guarantees no future issued-buffer access AND a successful drain.
pub fn checked_reset_decode_pool() -> std::result::Result<(), mlx_native::MlxError> {
    if let Some(result) = profile::reset() { return result; }
    let caps = CAPS.with(std::cell::Cell::get);
    DECODE_POOL.with(|cell| {
        let mut pool = cell.borrow_mut();
        pool.reset();
        if caps.is_some_and(|caps| pool.free_bytes() > caps.retained) {
            pool.clear();
        }
        FREE_AT_RESET.with(|free| free.set(pool.free_bytes()));
    });
    release_overflow();
    ISSUED_BYTES.with(|issued| issued.set(0));
    POOLED_SINCE_RESET.with(|pooled| pooled.set(0));
    if CAPS_END_AT_RESET.with(|cell| cell.replace(false)) {
        CAPS.with(|cell| cell.set(None));
    }
    Ok(())
}

/// Reset the thread-local pool at a per-prefill-layer boundary.
///
/// Bytewise identical to [`reset_decode_pool`]; the separate name documents
/// a distinct lifecycle: called between prefill layer iterations in
/// `forward_gpu_impl` after every layer has issued its
/// [`mlx_native::CommandEncoder::commit_and_wait`] (so all in-flight Metal
/// work referencing the layer-scoped scratches has drained), recycling the
/// dense-Q FFN scratches, attention pre-norm/per-head-norm/imrope scratches,
/// and DeltaNet apply_proj scratches before the next layer's allocations.
///
/// # Caller contract (W-5b.15)
///
/// At call time **no pool-allocated `MlxBuffer` may have an outstanding ARC
/// clone whose underlying Metal storage matches a power-of-two bucket the
/// next layer's [`pooled_alloc_buffer`] calls will request**.  In particular:
///
/// * The cross-layer `hidden` buffer (the residual stream consumed by the
///   next layer's attention) **must not** be pool-allocated.  Production
///   path: `embed_tokens_gpu` returns a `device.alloc_buffer` for the first
///   layer, and the dense-Q FFN's pooled `_into` variant (W-5b.15) writes
///   its FINAL output (the buffer that becomes the next `hidden`) to a
///   `device.alloc_buffer` — internal scratches stay pooled.
/// * Same-layer locals (`attn_out`, `q_normed`, FFN gate/up/hidden scratches,
///   etc.) are bound only inside the loop body and are dropped at the closing
///   brace before this reset fires from the *next* iteration's top.
///
/// At chunk-prefill working set (Qwen3.6-27B, seq_len=4096, h=5120, m=17408)
/// without per-layer reset, the dense-Q FFN's 5 pooled scratches alone
/// accumulate ~1 GB / dense layer × 33 dense layers ≈ 33 GB cumulative
/// before layer 33, overrunning Metal's residency-set quota and producing
/// "GPU command buffer completed with error status" — the W-5b.14
/// architectural-limit failure.  The per-layer reset closes this lifecycle
/// gap so dense-Q `_into` can use the pool unconditionally and capture the
/// W-5b.13 audit's projected ~30–40% allocation-churn savings.
pub fn reset_for_prefill_chunk() {
    if let Err(_error) = checked_reset_for_prefill_chunk() { profile::quarantine(); }
}

/// Successful K drain plus no future accesses to issued scratch are required.
pub fn checked_reset_for_prefill_chunk() -> std::result::Result<(), mlx_native::MlxError> {
    checked_reset_decode_pool()
}

/// Diagnostic accessor: number of buffers currently in-use (alloc'd but
/// not yet reset).  Surfaced for the `HF2Q_DECODE_PROFILE` instrumentation.
#[allow(dead_code)]
pub fn decode_pool_in_use_count() -> usize {
    if let Some((issued, _)) = profile::counts() { return issued; }
    DECODE_POOL.with(|cell| cell.borrow().in_use_count())
}

/// Diagnostic accessor: number of buffers currently in the free list.
#[allow(dead_code)]
pub fn decode_pool_free_count() -> usize {
    if let Some((_, free)) = profile::counts() { return free; }
    DECODE_POOL.with(|cell| cell.borrow().free_count())
}

/// Slot identifier for the three MoE FFN `quantized_matmul_id_ggml` call
/// sites: gate, up, and down.  Each slot gets its own thread-local
/// `IdMmScratch` so concurrent dispatches (gate+up in Phase C) do not
/// race on the scratch's htpe/hids buffers.
#[derive(Debug, Clone, Copy)]
pub enum MmIdSlot {
    Gate,
    Up,
    Down,
}

/// Run a closure with a mutable reference to the slot's thread-local
/// `IdMmScratch`, lazily growing the cached scratch if its capacity is
/// less than the requested `(n_experts, max_n_tokens)` pair.
///
/// W-5b.24 wire-up support — replaces 6 per-FFN-call device allocations
/// with 0 (after the first call) by amortising scratch ownership across
/// every FFN call in the prefill.
///
/// On capacity miss the cached scratch is dropped (its underlying Metal
/// buffers freed) and a new larger one is allocated; subsequent calls
/// at the same or smaller size hit the cache.
///
/// # Errors
///
/// Returns `MlxError` if `IdMmScratch::alloc` fails on cache miss.
pub fn with_id_mm_scratch<F, R>(
    slot: MmIdSlot,
    device: &MlxDevice,
    n_experts: u32,
    max_n_tokens: u32,
    f: F,
) -> std::result::Result<R, mlx_native::MlxError>
where
    F: FnOnce(&mut IdMmScratch) -> std::result::Result<R, mlx_native::MlxError>,
{
    let cell = match slot {
        MmIdSlot::Gate => &MM_ID_SCRATCH_GATE,
        MmIdSlot::Up => &MM_ID_SCRATCH_UP,
        MmIdSlot::Down => &MM_ID_SCRATCH_DOWN,
    };
    cell.with(|cell| {
        let mut guard = cell.borrow_mut();
        // Reallocate when the cached scratch's constructor bounds (its
        // capacity accessors) do not cover this call.
        let needs_realloc = match guard.as_ref() {
            None => true,
            Some(scratch) => {
                n_experts > scratch.capacity_n_experts()
                    || max_n_tokens > scratch.capacity_n_tokens()
            }
        };
        if needs_realloc {
            *guard = Some(IdMmScratch::alloc(device, n_experts, max_n_tokens)?);
        }
        let scratch = guard.as_mut().expect("just allocated");
        f(scratch)
    })
}

/// Drop all cached `IdMmScratch` slots for the current thread.
///
/// Used by the `forensic A/B` test path to force a re-allocation
/// between LEGACY and NEW runs so neither path benefits from a warm
/// scratch left behind by the other.  Production paths do not call
/// this; the scratches survive across prefills and decode tokens, with
/// per-allocation cost amortising to zero.
#[allow(dead_code)]
pub fn drop_id_mm_scratch() {
    MM_ID_SCRATCH_GATE.with(|cell| *cell.borrow_mut() = None);
    MM_ID_SCRATCH_UP.with(|cell| *cell.borrow_mut() = None);
    MM_ID_SCRATCH_DOWN.with(|cell| *cell.borrow_mut() = None);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn canonical_prepared_products_fit_the_retained_bucket_and_trim_a_larger_prior_scope() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let Ok(device) = MlxDevice::new() else { return };
        let source: serde_json::Value = serde_json::from_str(include_str!(
            "../../../../tests/fixtures/qwen38/config.json"
        )).unwrap();
        let cfg = super::super::source_config::qwen35_config_from_authenticated_source(&source).unwrap();
        let rows = 2080usize;
        let h = cfg.hidden_size as usize;
        let q = (cfg.num_attention_heads * cfg.head_dim) as usize;
        let z = (cfg.linear_num_value_heads * cfg.linear_value_head_dim) as usize;
        let ab = super::super::prepared_projection::alpha_beta_rows(cfg.linear_num_value_heads) as usize;
        // Remaining actual pooled products. FA Q/gate and gated BF16 now
        // borrow forward arenas; dense FFN's hidden BF16 copy is largest.
        let largest = [2 * h, 4 * h, 4 * q, 2 * z, 4 * ab,
            4 * cfg.linear_num_value_heads as usize,
            2 * cfg.intermediate_size.unwrap() as usize]
            .into_iter().max().unwrap() * rows;
        let caps = super::super::prefill_prepared::prefill_pool_caps();
        cap_pool(Some(PoolCaps { pool: 0, retained: 0 }));
        checked_reset_decode_pool().unwrap();
        cap_pool(None);
        let first = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
        let second = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
        assert_eq!(first.byte_len(), caps.retained, "largest required product fits exactly one retained bucket");
        assert!(largest > first.byte_len() / 2, "the next smaller power of two cannot retain it");
        drop((first, second));
        checked_reset_decode_pool().unwrap();
        assert!(free_bytes() > caps.retained, "larger uncapped prior scope really stays warm");

        // Like forward_gpu, issue the embedding before activating caps.
        // Trimming must release only free roots, never that live operand.
        let mut embedding = pooled_alloc_buffer(&device, 4096, DType::F32, vec![1024]).unwrap();
        embedding.as_mut_slice::<f32>().unwrap().fill(3.25);
        cap_pool(Some(caps));
        assert_eq!(free_bytes(), 0, "warm oversized free owners are actually released");
        assert_eq!(worker_memory_snapshot().unwrap().1.retained.bytes, embedding.byte_len());
        let product = pooled_alloc_buffer(&device, largest, DType::U8, vec![largest]).unwrap();
        assert_eq!(product.byte_len(), caps.retained);
        assert!(
            issued_bytes() > super::super::prefill_prepared::window_scratch_threshold(),
            "this real canonical product plus embedding must trigger an earlier layer wait",
        );
        assert!(embedding.as_slice::<f32>().unwrap().iter().all(|&x| x == 3.25));
        assert_eq!(worker_carry_pool_bytes().unwrap(), (embedding.byte_len() + product.byte_len()) as u64);
        drop((embedding, product));
        checked_reset_decode_pool().unwrap();
        assert_eq!(free_bytes(), 0, "reset also trims a crossing free set");
        cap_pool(None);
    }

    #[test]
    fn overflow_roots_and_carry_aliases_survive_queued_success_and_checked_error_drains() {
        use super::super::{carry_memory::CarryOwners, encoder_stage};
        use mlx_native::ops::copy::dispatch_copy_f32;
        use mlx_native::KernelRegistry;

        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let Ok(device) = MlxDevice::new() else { return };
        cap_pool(Some(PoolCaps { pool: 0, retained: 0 }));
        checked_reset_decode_pool().unwrap();
        let mut registry = KernelRegistry::new();
        for fail in [false, true] {
            let submitted = encoder_stage::SubmittedCommands::open(true);
            let failure = fail.then(|| encoder_stage::FailSubmitted::nth("test.overflow", 0));
            let mut carry = CarryOwners::default();
            let mut outputs = Vec::new();
            let mut aliases = Vec::new();
            let mut expected = Vec::new();
            let mut owned_bytes = 0u64;
            for count in [99usize, 65] {
                let mut root = pooled_alloc_buffer(&device, count * 4, DType::F32, vec![count]).unwrap();
                let values: Vec<_> = (0..count).map(|i| (i as f32 + count as f32) * 0.25).collect();
                root.as_mut_slice::<f32>().unwrap().copy_from_slice(&values);
                let alias = root.slice_view(7 * 4, 11);
                assert_eq!(alias.data_byte_len(), 11 * 4);
                carry.include(&alias);
                carry.include(&root);
                owned_bytes += root.byte_len() as u64;
                let out = device.alloc_buffer(11 * 4, DType::F32, vec![11]).unwrap();
                let mut enc = device.command_encoder().unwrap();
                dispatch_copy_f32(
                    &mut enc, &mut registry, device.metal_device(), &alias, &out, 0, 0, 11,
                ).unwrap();
                enc.commit_labeled("test.overflow");
                encoder_stage::retain_submitted(enc, "test.overflow");
                drop(root);
                aliases.push(alias);
                outputs.push(out);
                expected.push(values[7..18].to_vec());
            }
            // OVERFLOW owns full plain roots while commands are queued;
            // small logical aliases never shrink the charged backing.
            assert_eq!(worker_carry_pool_bytes().unwrap(), owned_bytes);
            assert_eq!(carry.bytes(), owned_bytes, "carry deduplicates aliases at full owning extent");
            let drained = encoder_stage::settle_submitted();
            assert_eq!(drained.is_err(), fail);
            if let Some(point) = &failure {
                assert_eq!(point.seen(), (true, 2), "the checked error still settles the later command");
            }
            for (out, want) in outputs.iter().zip(&expected) {
                assert_eq!(out.as_slice::<f32>().unwrap(), want.as_slice());
            }
            drop(submitted);
            assert_eq!(worker_carry_pool_bytes().unwrap(), owned_bytes, "drain alone does not erase owners");
            checked_reset_decode_pool().unwrap();
            assert_eq!(worker_carry_pool_bytes().unwrap(), 0);
            assert_eq!(carry.bytes(), owned_bytes, "escaped aliases stay separately charged after pool reset");
            // A later allocation must not overwrite a separately-owned
            // overflow backing: plain spill roots are never recycled.
            let mut next = pooled_alloc_buffer(&device, 99 * 4, DType::F32, vec![99]).unwrap();
            next.as_mut_slice::<f32>().unwrap().fill(-19.0);
            assert_eq!(carry.bytes(), owned_bytes);
            for (alias, want) in aliases.iter().zip(&expected) {
                assert_eq!(alias.as_slice::<f32>().unwrap(), want.as_slice());
            }
            drop((next, aliases, carry, outputs));
            checked_reset_decode_pool().unwrap();
        }
        cap_pool(None);
    }

    #[test]
    fn carry_pool_census_keeps_full_overflow_roots_without_summing_native_labels() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let Ok(device) = MlxDevice::new() else { return };
        // Exercise the real direct-overflow owner without changing pool caps
        // or allocating a multi-GiB crossing request merely to reach it.
        let previous = OVERFLOW.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
        let native = worker_memory_snapshot().unwrap().1.retained.bytes as u64;
        let root = device.alloc_buffer(3 * 32 * 4, DType::F32, vec![3, 32]).unwrap();
        let bytes = root.byte_len() as u64;
        OVERFLOW.with(|cell| cell.borrow_mut().push(root.clone()));
        drop(root);
        assert_eq!(worker_carry_pool_bytes().unwrap(), native + bytes);
        release_overflow();
        assert_eq!(worker_carry_pool_bytes().unwrap(), native);
        OVERFLOW.with(|cell| *cell.borrow_mut() = previous);
    }

    #[test]
    fn pool_resets_recycle_metal_buffers() {
        // Skip the GPU-touching part of this test if no Metal device is
        // available (CI builders, headless Linux).  The test merely
        // exercises pool lifecycle; the device is still required because
        // the first alloc must successfully create a Metal buffer.
        let device = match MlxDevice::new() {
            Ok(d) => d,
            Err(_) => return,
        };

        // Cycle 1: alloc, locals drop, reset.
        let ptr_a = {
            let buf =
                pooled_alloc_buffer(&device, 1024, DType::F32, vec![256]).expect("cycle 1 alloc");
            buf.contents_ptr()
        };
        assert!(decode_pool_in_use_count() >= 1);

        reset_decode_pool();
        assert_eq!(decode_pool_in_use_count(), 0);

        // Cycle 2: same bucket size must reuse the cycle-1 metal buffer.
        let buf = pooled_alloc_buffer(&device, 1024, DType::F32, vec![256]).expect("cycle 2 alloc");
        let ptr_b = buf.contents_ptr();
        assert_eq!(
            ptr_b, ptr_a,
            "thread-local pool must reuse Metal buffer across reset"
        );

        reset_decode_pool();
    }
}