hf2q 0.1.30

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
//! Caller-owned scratch arena for the FA prefill bridge across all FA
//! layers in a single prefill.
//!
//! # Lifetime contract
//!
//! The arena is allocated ONCE at the top of `forward_gpu_impl` (after
//! `ensure_gpu_cache_primed`, before the per-layer loop) when `seq_len > 1`
//! AND the model has at least one `FullAttn` layer. It is reused across all
//! FA layers in the loop, then dropped at the end of `forward_gpu_impl`
//! AFTER the final encoder `commit_and_wait_labeled` at the output-head.
//!
//! **Why this prevents the iter58b residency-rescission failure mode:**
//! The arena buffers are owned by `forward_gpu_impl` for the entire prefill.
//! They do NOT drop at wrapper return. Therefore:
//!
//! 1. The wrapper's `enc.commit()` returns immediately; the wrapper returns
//!    immediately.
//! 2. Nothing inside the wrapper drops a `device.alloc_buffer` `MlxBuffer`
//!    that is still referenced by an in-flight command buffer.
//! 3. No deferred `removeAllocation:` is staged on the residency set when
//!    the wrapper returns.
//! 4. The next encoder's `commit*` does NOT flush a stale
//!    residency-rescission for buffers still referenced by the wrapper's CB.
//! 5. The iter58b failure mode — where a wrapper-local buffer drop staged a
//!    `removeAllocation:` that was flushed mid-flight by the next CB's
//!    `commit*`, demoting still-referenced pages and producing garbage values
//!    — is structurally unreachable.
//!
//! Caller-owned arena outlives all encoders that reference it; the iter58b
//! residency-rescission failure mode cannot fire because no `MlxBuffer::Drop`
//! runs in the wrapper frame.
//!
//! See ADR-013 P21 Stage 1 for full rationale.

use anyhow::{anyhow, Result};
use mlx_native::{MlxBuffer, MlxDevice};

pub(crate) mod plan;
use plan::FaPrefillPlan;

/// Caller-owned scratch arena for the FA prefill bridge (ops1-4 + ops6-7)
/// across all FA layers in a single prefill.
///
/// Contains seven logical BF16 scratch views backed by five allocations.
/// Q/K/V sequence-major staging shares the Q-sized root: each permutation
/// finishes reading it before the next cast overwrites it. Head-major Q/K/V
/// remain separate. All views retain their roots through the full prefill
/// (no residency-set rescission race — see module-level doc).
///
/// Joint segments also share the F32 attention result. Its consumer finishes
/// before the next queue-ordered segment overwrites it; ordinary callers retain
/// independently allocated results.
pub struct FaPrefillArena {
    /// `[seq, nh, d]` BF16 — shared Q/K/V sequence-major staging root.
    pub q_bf16_seq: MlxBuffer,
    /// `[1, nh, seq, d]` BF16 — Q in head-major layout.
    pub q_bf16_hm: MlxBuffer,
    /// `[seq, nkv, d]` BF16 — tight view of Q staging, after Q permutation.
    pub k_bf16_seq: MlxBuffer,
    /// `[1, nkv, seq, d]` BF16 — K in head-major layout.
    pub k_bf16_hm: MlxBuffer,
    /// `[seq, nkv, d]` BF16 — tight view of Q staging, after K permutation.
    pub v_bf16_seq: MlxBuffer,
    /// `[1, nkv, seq, d]` BF16 — V in head-major layout.
    pub v_bf16_hm: MlxBuffer,
    /// `[1, nh, seq, d]` BF16 — attention output in head-major layout.
    pub out_bf16_hm: MlxBuffer,

    // ── Capacity bookkeeping ─────────────────────────────────────────────
    // The arena is sized for the actual prefill seq_len. Per-layer calls
    // may have the same or shorter seq_len; validate_fits() guards against
    // accidental overrun.
    /// The `seq_capacity` value the arena was allocated for.
    pub seq_capacity: u32,
    /// The `n_heads` value the arena was allocated for.
    pub n_heads: u32,
    /// The `n_kv_heads` value the arena was allocated for.
    pub n_kv_heads: u32,
    /// The `head_dim` value the arena was allocated for.
    pub head_dim: u32,

    /// Route (c) scratch for `HF2Q_QWEN_RESUME_ATTN_FAST`: the TQ-dequant
    /// K/V temps, their BF16 casts and the F32 output, sized for the
    /// prefill's `(seq_len, kv_seq_len)`. Allocated by the first TQ FA
    /// layer and shared by the rest, so it lives through the forward's
    /// terminal wait like the buffers above. Cold history reuses arena K/V.
    pub(crate) resume_tq: Option<super::resume_attn_fast::ResumeTqScratch>,
    /// Joint segments share these roots, never their immutable shapes.
    pub(crate) shared_resume: Option<super::resume_attn_fast::ResumeTqWorkspace>,
    /// Queue-ordered joint result, shaped tightly for this segment.
    pub(crate) shared_output: Option<MlxBuffer>,
}

impl FaPrefillArena {
    /// Allocate five BF16 roots and seven logical views for one prefill.
    ///
    /// # Errors
    ///
    /// Returns `Err` if:
    /// - Any dimension is zero (`seq_capacity`, `n_heads`, `n_kv_heads`, or
    ///   `head_dim` equals 0).
    /// - `n_heads % n_kv_heads != 0` (GQA divisibility violated).
    /// - Shape, byte-count, or aggregate requested-payload arithmetic overflows.
    /// - Any `device.alloc_buffer` call fails (out of GPU memory).
    pub fn new(
        device: &MlxDevice,
        seq_capacity: u32,
        n_heads: u32,
        n_kv_heads: u32,
        head_dim: u32,
    ) -> Result<Self> {
        let [q_bf16_seq, q_bf16_hm, k_bf16_seq, k_bf16_hm, v_bf16_seq, v_bf16_hm, out_bf16_hm] =
            FaPrefillPlan::new(seq_capacity, n_heads, n_kv_heads, head_dim)?.into_buffers();
        let q_bf16_seq = q_bf16_seq.allocate(device)?;
        let q_bf16_hm = q_bf16_hm.allocate(device)?;
        let k_bf16_seq = q_bf16_seq
            .slice_view(0, k_bf16_seq.requested_bytes / k_bf16_seq.dtype.size_of())
            .with_shape(k_bf16_seq.shape)
            .map_err(|e| anyhow!("FaPrefillArena K staging view: {e}"))?;
        let k_bf16_hm = k_bf16_hm.allocate(device)?;
        let v_bf16_seq = q_bf16_seq
            .slice_view(0, v_bf16_seq.requested_bytes / v_bf16_seq.dtype.size_of())
            .with_shape(v_bf16_seq.shape)
            .map_err(|e| anyhow!("FaPrefillArena V staging view: {e}"))?;
        let v_bf16_hm = v_bf16_hm.allocate(device)?;
        let out_bf16_hm = out_bf16_hm.allocate(device)?;

        Ok(Self {
            q_bf16_seq,
            q_bf16_hm,
            k_bf16_seq,
            k_bf16_hm,
            v_bf16_seq,
            v_bf16_hm,
            out_bf16_hm,
            seq_capacity,
            n_heads,
            n_kv_heads,
            head_dim,
            resume_tq: None,
            shared_resume: None,
            shared_output: None,
        })
    }

    /// Tight views of one forward-owned workspace for a queue-ordered segment.
    /// Every previous reader must finish before the next segment overwrites it.
    /// The views retain the backing allocations through the terminal drain.
    pub(crate) fn shared_rows(&self, rows: u32) -> Result<Self> {
        self.validate_fits(rows, self.n_heads, self.n_kv_heads, self.head_dim)?;
        let [q_seq, q_hm, k_seq, k_hm, v_seq, v_hm, out_hm] =
            FaPrefillPlan::new(rows, self.n_heads, self.n_kv_heads, self.head_dim)?.into_buffers();
        let view = |buffer: &MlxBuffer, plan: plan::FaBufferPlan| {
            buffer
                .slice_view(0, plan.requested_bytes / plan.dtype.size_of())
                .with_shape(plan.shape)
                .map_err(|e| anyhow!("shared FA workspace {}: {e}", plan.label))
        };
        let shared_output = self.shared_output.as_ref().map(|buffer| {
            buffer
                .slice_view(0, rows as usize * self.n_heads as usize * self.head_dim as usize)
                .with_shape(vec![rows as usize, self.n_heads as usize, self.head_dim as usize])
                .map_err(|e| anyhow!("shared FA output: {e}"))
        }).transpose()?;
        Ok(Self {
            q_bf16_seq: view(&self.q_bf16_seq, q_seq)?,
            q_bf16_hm: view(&self.q_bf16_hm, q_hm)?,
            k_bf16_seq: view(&self.k_bf16_seq, k_seq)?,
            k_bf16_hm: view(&self.k_bf16_hm, k_hm)?,
            v_bf16_seq: view(&self.v_bf16_seq, v_seq)?,
            v_bf16_hm: view(&self.v_bf16_hm, v_hm)?,
            out_bf16_hm: view(&self.out_bf16_hm, out_hm)?,
            seq_capacity: rows,
            n_heads: self.n_heads,
            n_kv_heads: self.n_kv_heads,
            head_dim: self.head_dim,
            resume_tq: None,
            shared_resume: self.shared_resume.clone(),
            shared_output,
        })
    }

    /// Validate that a per-layer call's shape fits inside the arena's
    /// capacity. The arena is typically sized for the actual prefill
    /// `seq_len`, so equality is the common case.
    ///
    /// # Errors
    ///
    /// Returns `Err` if:
    /// - `seq_len > self.seq_capacity` (would overrun the allocated buffer).
    /// - `n_heads`, `n_kv_heads`, or `head_dim` differ from the recorded
    ///   values (buffers were sized for a different shape).
    pub fn validate_fits(
        &self,
        seq_len: u32,
        n_heads: u32,
        n_kv_heads: u32,
        head_dim: u32,
    ) -> Result<()> {
        if seq_len > self.seq_capacity {
            return Err(anyhow!(
                "FaPrefillArena::validate_fits: seq_len {} exceeds capacity {}",
                seq_len,
                self.seq_capacity
            ));
        }
        if n_heads != self.n_heads || n_kv_heads != self.n_kv_heads || head_dim != self.head_dim {
            return Err(anyhow!(
                "FaPrefillArena::validate_fits: shape mismatch — \
                 arena (n_heads={}, n_kv_heads={}, head_dim={}) vs \
                 call (n_heads={}, n_kv_heads={}, head_dim={})",
                self.n_heads,
                self.n_kv_heads,
                self.head_dim,
                n_heads,
                n_kv_heads,
                head_dim,
            ));
        }
        Ok(())
    }
}

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

    /// Helper: acquire an MlxDevice or skip if no Metal device is available
    /// (e.g. headless CI without GPU).
    fn device_or_skip() -> Option<MlxDevice> {
        MlxDevice::new().ok()
    }

    /// Qwen3.5/3.6 canonical shape at pp=101: seq=101, nh=16, nkv=2, d=256.
    /// Verifies all 7 fields' byte_len() match the A.2 formula and
    /// seq_capacity is recorded correctly.
    #[test]
    fn test_arena_new_qwen35_pp101() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_arena_new_qwen35_pp101: skipping — no Metal device");
                return;
            }
        };
        let (seq, nh, nkv, d) = (101usize, 16usize, 2usize, 256usize);
        let arena = FaPrefillArena::new(&device, seq as u32, nh as u32, nkv as u32, d as u32)
            .expect("arena new pp101");

        assert_eq!(arena.seq_capacity, seq as u32);
        assert_eq!(arena.n_heads, nh as u32);
        assert_eq!(arena.n_kv_heads, nkv as u32);
        assert_eq!(arena.head_dim, d as u32);

        let q_bytes = seq * nh * d * 2;
        let k_bytes = seq * nkv * d * 2;
        assert_eq!(arena.q_bf16_seq.byte_len(), q_bytes, "q_bf16_seq byte_len");
        assert_eq!(arena.q_bf16_hm.byte_len(), q_bytes, "q_bf16_hm byte_len");
        assert_eq!(arena.k_bf16_seq.data_byte_len(), k_bytes, "k_bf16_seq data_byte_len");
        assert_eq!(arena.k_bf16_hm.byte_len(), k_bytes, "k_bf16_hm byte_len");
        assert_eq!(arena.v_bf16_seq.data_byte_len(), k_bytes, "v_bf16_seq data_byte_len");
        assert_eq!(arena.v_bf16_hm.byte_len(), k_bytes, "v_bf16_hm byte_len");
        assert_eq!(
            arena.out_bf16_hm.byte_len(),
            q_bytes,
            "out_bf16_hm byte_len"
        );
    }

    /// Qwen3.5/3.6 canonical shape at pp=4096: verifies no allocation failure
    /// and capacity recorded.
    #[test]
    fn test_arena_new_qwen35_pp4096() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_arena_new_qwen35_pp4096: skipping — no Metal device");
                return;
            }
        };
        let arena = FaPrefillArena::new(&device, 4096, 16, 2, 256).expect("arena new pp4096");
        assert_eq!(arena.seq_capacity, 4096);
    }

    /// Passing seq=0, nh=0, nkv=0, or d=0 each individually must return Err.
    #[test]
    fn test_arena_new_zero_dim_rejected() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_arena_new_zero_dim_rejected: skipping — no Metal device");
                return;
            }
        };
        // seq = 0
        assert!(
            FaPrefillArena::new(&device, 0, 16, 2, 256).is_err(),
            "seq=0 should be rejected"
        );
        // n_heads = 0
        assert!(
            FaPrefillArena::new(&device, 101, 0, 2, 256).is_err(),
            "n_heads=0 should be rejected"
        );
        // n_kv_heads = 0
        assert!(
            FaPrefillArena::new(&device, 101, 16, 0, 256).is_err(),
            "n_kv_heads=0 should be rejected"
        );
        // head_dim = 0
        assert!(
            FaPrefillArena::new(&device, 101, 16, 2, 0).is_err(),
            "head_dim=0 should be rejected"
        );
    }

    /// n_heads=15, n_kv_heads=2 (15 % 2 != 0) must return Err.
    #[test]
    fn test_arena_new_gqa_divisibility_rejected() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_arena_new_gqa_divisibility_rejected: skipping — no Metal device");
                return;
            }
        };
        assert!(
            FaPrefillArena::new(&device, 101, 15, 2, 256).is_err(),
            "n_heads=15, n_kv_heads=2 (15 % 2 != 0) should be rejected"
        );
    }

    /// Arena sized for seq_capacity=128; validate_fits(seq_len=256) returns Err.
    #[test]
    fn test_validate_fits_seq_overrun() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_validate_fits_seq_overrun: skipping — no Metal device");
                return;
            }
        };
        let arena = FaPrefillArena::new(&device, 128, 16, 2, 256).expect("arena new seq128");
        assert!(
            arena.validate_fits(256, 16, 2, 256).is_err(),
            "seq_len=256 > capacity=128 should be rejected"
        );
    }

    /// Arena recorded n_heads=16; validate_fits(n_heads=8) returns Err.
    #[test]
    fn test_validate_fits_shape_mismatch() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_validate_fits_shape_mismatch: skipping — no Metal device");
                return;
            }
        };
        let arena = FaPrefillArena::new(&device, 128, 16, 2, 256).expect("arena new nh16");
        assert!(
            arena.validate_fits(128, 8, 2, 256).is_err(),
            "n_heads=8 vs arena n_heads=16 should be rejected"
        );
        assert!(
            arena.validate_fits(128, 16, 4, 256).is_err(),
            "n_kv_heads=4 vs arena n_kv_heads=2 should be rejected"
        );
        assert!(
            arena.validate_fits(128, 16, 2, 128).is_err(),
            "head_dim=128 vs arena head_dim=256 should be rejected"
        );
    }

    /// Arena recorded (seq=128, nh=16, nkv=2, d=256); validate_fits with
    /// the exact same values returns Ok.
    #[test]
    fn test_validate_fits_exact_match() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_validate_fits_exact_match: skipping — no Metal device");
                return;
            }
        };
        let arena = FaPrefillArena::new(&device, 128, 16, 2, 256).expect("arena new seq128");
        assert!(
            arena.validate_fits(128, 16, 2, 256).is_ok(),
            "exact-match validate_fits should return Ok"
        );
        // seq_len < capacity also Ok
        assert!(
            arena.validate_fits(64, 16, 2, 256).is_ok(),
            "seq_len=64 <= capacity=128 should be Ok"
        );
    }

    /// Verifies that device.alloc_buffer zero-initializes all buffers.
    /// Read the first 16 BF16 (u16) elements of each of the 7 buffers and
    /// assert all are zero. This exercises the ADR-015 iter61a zero-init
    /// guarantee documented in mlx_native/src/device.rs:120-146.
    #[test]
    fn test_arena_buffers_zero_initialized() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match device_or_skip() {
            Some(d) => d,
            None => {
                eprintln!("test_arena_buffers_zero_initialized: skipping — no Metal device");
                return;
            }
        };
        let arena = FaPrefillArena::new(&device, 64, 16, 2, 256).expect("arena new seq64");

        let bufs: [(&MlxBuffer, &str); 7] = [
            (&arena.q_bf16_seq, "q_bf16_seq"),
            (&arena.q_bf16_hm, "q_bf16_hm"),
            (&arena.k_bf16_seq, "k_bf16_seq"),
            (&arena.k_bf16_hm, "k_bf16_hm"),
            (&arena.v_bf16_seq, "v_bf16_seq"),
            (&arena.v_bf16_hm, "v_bf16_hm"),
            (&arena.out_bf16_hm, "out_bf16_hm"),
        ];
        for (buf, name) in &bufs {
            let slice = buf
                .as_slice::<u16>()
                .unwrap_or_else(|e| panic!("{name} as_slice::<u16> failed: {e}"));
            let check_len = 16.min(slice.len());
            for (i, &v) in slice[..check_len].iter().enumerate() {
                assert_eq!(
                    v, 0u16,
                    "{name}[{i}] = {v:#06x} (BF16 0x0000 = +0.0), expected zero"
                );
            }
        }
    }
}