inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
use super::{ArgmaxArgs, DSparkRejectArgs, DSparkSpanDesc, SampArgs};
use crate::metal::{Enc, Gpu};
use objc2_metal::{
    MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCreateSystemDefaultDevice, MTLDevice,
};

/// Real compute devices only. A missing device skips the shader tests. GitHub-hosted
/// `macos-latest` returns an Apple Paravirtual device whose compute shaders no-op and
/// leave zero-initialized buffers, which would look like token 0.
fn metal_device_runs_compute() -> bool {
    let Some(dev) = MTLCreateSystemDefaultDevice() else {
        eprintln!("Metal shader regression skipped: no Metal device");
        return false;
    };
    let name = dev.name().to_string();
    if name.contains("Paravirtual") {
        eprintln!("Metal shader regression skipped: {name} does not run compute shaders");
        return false;
    }
    true
}

// Three partitions exercise both stages of the reduction, including a partial final group.
const WIDTH: usize = 2049;
const PARTS: usize = WIDTH.div_ceil(1024);

fn sample_rows(gpu: &Gpu, rows: &[[f32; WIDTH]; 2], temps: [f32; 2], bans: [u32; 2]) -> [u32; 2] {
    sample_rows_never(gpu, rows, temps, bans, u32::MAX)
}

fn sample_rows_never(gpu: &Gpu, rows: &[[f32; WIDTH]; 2], temps: [f32; 2], bans: [u32; 2], never: u32) -> [u32; 2] {
    let score_words = rows.len() * WIDTH;
    let arena = gpu.buffer((score_words + rows.len() * 2 * PARTS) * size_of::<f32>());
    let tokens = gpu.buffer(rows.len() * size_of::<u32>());
    // The buffers are idle and the logits occupy the first score_words words.
    unsafe {
        std::ptr::copy_nonoverlapping(
            rows.as_ptr().cast::<f32>(),
            arena.contents().as_ptr().cast(),
            score_words,
        );
    }

    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(&arena, 0, 2);
    e.buf(&tokens, 0, 6);
    e.pso(&gpu.pso("k_gumbel"));
    for i in 0..rows.len() {
        let args = SampArgs {
            logits_off: (i * WIDTH) as u32,
            n: WIDTH as u32,
            seed_lo: 19,
            seed_hi: 0,
            pos: 3,
            ban_tok: bans[i],
            never_tok: never,
            temp: temps[i],
            softcap: 30.0,
        };
        e.bytes(&args, 5);
        e.dispatch((WIDTH.div_ceil(256), 1, 1), 256);
    }
    e.barrier();
    for (kernel, groups, threads) in [("k_argmax1", PARTS, 1024), ("k_argmax2", 1, 32)] {
        e.pso(&gpu.pso(kernel));
        for i in 0..rows.len() {
            let args = ArgmaxArgs {
                logits_off: (i * WIDTH) as u32,
                n: WIDTH as u32,
                part_off: (score_words + i * 2 * PARTS) as u32,
                nparts: PARTS as u32,
                out_index: i as u32,
                checked: 1,
                never_tok: u32::MAX,
                pad: 0,
            };
            e.bytes(&args, 5);
            e.dispatch((groups, 1, 1), threads);
        }
        e.barrier();
    }
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    assert_eq!(
        cb.status(),
        MTLCommandBufferStatus::Completed,
        "{:?}",
        cb.error()
    );
    // Completion makes both token writes visible to the CPU.
    unsafe { *tokens.contents().as_ptr().cast::<[u32; 2]>() }
}

#[test]
fn metal_sampling_validates_each_row_and_preserves_greedy_order() {
    if !metal_device_runs_compute() {
        return;
    }
    // Compile the production sampling region alone so this test also runs on GPUs without tensor ops.
    let all = include_str!("../kernels.metal");
    let start = all.find("// argmax over logits").unwrap();
    let end = all[start..].find("// Adaptive LoopCD-Logits").unwrap();
    let src = format!(
        "#include <metal_stdlib>\nusing namespace metal;\n{}",
        &all[start..start + end]
    );
    let gpu = Gpu::new(&src, &["k_gumbel", "k_argmax1", "k_argmax2"]);

    let mut rows = [[-20.0; WIDTH]; 2];
    let above_twenty = f32::from_bits(20.0_f32.to_bits() + 1);
    rows[0][1] = 21.0; // banned
    rows[0][2] = 20.0;
    rows[0][1025] = above_twenty;
    rows[0][2048] = above_twenty; // tie across workgroups
    rows[1][12] = 20.0;
    for temp in [0.0, 1.25e-38, 1e-6] {
        let tokens = sample_rows(&gpu, &rows, [temp, 0.5], [1, u32::MAX]);
        assert_eq!(tokens, [1025, 12], "temperature {temp}");
    }

    for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
        rows[0][2048] = bad;
        for (temp, ban) in [(0.0, 1), (0.5, 1), (1.25e-38, 2048), (0.5, 2048)] {
            let tokens = sample_rows(&gpu, &rows, [temp, 0.5], [ban, u32::MAX]);
            assert_eq!(
                tokens,
                [u32::MAX, 12],
                "logit {bad}, banned {ban}, temperature {temp}"
            );
        }
    }
    rows[0].fill(f32::NAN);
    let tokens = sample_rows(&gpu, &rows, [1.0, 0.5], [u32::MAX; 2]);
    assert_eq!(tokens, [u32::MAX, 12], "all-NaN row");

    // Standalone (1-row) + batched (2-row) near-zero temperature agreement with CPU `Sampler::sample_next`
    // alongside an ordinary-temperature finite control (`t-audit-engine-sampling-near-zero` & `t-audit-engine-sampling-finite`).
    let mut cpu_tie_row = [-15.0f32; WIDTH];
    cpu_tie_row[513] = 420.0;
    cpu_tie_row[1537] = 425.0; // `30 * tanh(x / 30)` saturates to 30.0 in f32 for both, while raw argmax is 1537!
    let mut finite_ctrl = [-15.0f32; WIDTH];
    finite_ctrl[77] = 25.0;

    for temp in [0.0f32, 1.0e-38, 1.25e-38, 1.0e-6] {
        let mut cpu_sampler = crate::sampler::Sampler::new(temp, 0, 1.0, 30.0, 19);
        let cpu_tok = cpu_sampler.sample_next(&cpu_tie_row).unwrap();
        assert_eq!(cpu_tok, 1537, "CPU near-zero raw argmax at temp={temp}");
        let gpu_pair = sample_rows(&gpu, &[cpu_tie_row, finite_ctrl], [temp, 0.7], [u32::MAX; 2]);
        assert_eq!(gpu_pair[0], cpu_tok, "GPU batched near-zero mismatch at temp={temp}");
        assert_eq!(gpu_pair[1], 77, "finite ordinary-temperature control disturbed at temp={temp}");
    }
}

fn sampling_region_src() -> String {
    let all = include_str!("../kernels.metal");
    let start = all.find("// argmax over logits").unwrap();
    let end = all[start..].find("// Adaptive LoopCD-Logits").unwrap();
    format!("#include <metal_stdlib>\nusing namespace metal;\n{}", &all[start..start + end])
}

/// `k_gumbel` never draws `never_tok` (`<|endoftext|>`), greedy or sampled, even when it has the highest logit
/// and while `ban_tok` masks another token.
#[test]
fn metal_gumbel_never_draws_the_never_token() {
    if !metal_device_runs_compute() {
        return;
    }
    let gpu = Gpu::new(&sampling_region_src(), &["k_gumbel", "k_argmax1", "k_argmax2"]);
    const NEVER: u32 = 1999;
    let mut rows = [[-20.0; WIDTH]; 2];
    for row in &mut rows {
        row[NEVER as usize] = 25.0;
        row[5] = 24.0; // banned on row 0
        row[1500] = 0.0;
    }
    for temp in [0.0, 1e-6, 0.7, 1.0] {
        let tokens = sample_rows_never(&gpu, &rows, [temp, temp], [5, u32::MAX], NEVER);
        assert_eq!(tokens[0], 1500, "row 0, temperature {temp}");
        assert_ne!(tokens[1], NEVER, "row 1, temperature {temp}");
    }
    assert_eq!(sample_rows_never(&gpu, &rows, [0.0, 0.0], [5, u32::MAX], NEVER)[1], 5, "greedy row 1");
    // Control: without the mask the same rows draw it.
    assert_eq!(sample_rows(&gpu, &rows, [0.0, 0.0], [5, u32::MAX]), [NEVER, NEVER]);
}

/// `k_argmax1` + `k_argmax2` over one row, unchecked as greedy decode and prefill run them.
fn argmax_row(gpu: &Gpu, row: &[f32; WIDTH], never: u32) -> u32 {
    let arena = gpu.buffer((WIDTH + 2 * PARTS) * size_of::<f32>());
    let tokens = gpu.buffer(size_of::<u32>());
    unsafe { std::ptr::copy_nonoverlapping(row.as_ptr(), arena.contents().as_ptr().cast(), WIDTH) };
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(&arena, 0, 2);
    e.buf(&tokens, 0, 6);
    let args = ArgmaxArgs {
        logits_off: 0,
        n: WIDTH as u32,
        part_off: WIDTH as u32,
        nparts: PARTS as u32,
        out_index: 0,
        checked: 0,
        never_tok: never,
        pad: 0,
    };
    for (kernel, groups, threads) in [("k_argmax1", PARTS, 1024), ("k_argmax2", 1, 32)] {
        e.pso(&gpu.pso(kernel));
        e.bytes(&args, 5);
        e.dispatch((groups, 1, 1), threads);
        e.barrier();
    }
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    assert_eq!(cb.status(), MTLCommandBufferStatus::Completed, "{:?}", cb.error());
    unsafe { *tokens.contents().as_ptr().cast::<u32>() }
}

/// The greedy argmax (`k_argmax1`/`k_argmax2`: prefill's first token, pipelined greedy decode) never returns
/// `never_tok`, wherever it sits in the row and whichever partition holds the runner-up.
#[test]
fn metal_argmax_never_returns_the_never_token() {
    if !metal_device_runs_compute() {
        return;
    }
    let gpu = Gpu::new(&sampling_region_src(), &["k_argmax1", "k_argmax2"]);
    for (never, runner_up) in [(1999u32, 5usize), (0, 2048), (2048, 1024), (1023, 1024)] {
        let mut row = [-20.0f32; WIDTH];
        row[never as usize] = 25.0;
        row[runner_up] = 24.0;
        assert_eq!(argmax_row(&gpu, &row, u32::MAX), never, "control: unmasked argmax");
        assert_eq!(argmax_row(&gpu, &row, never), runner_up as u32, "never {never}");
    }
}

/// Unchecked greedy argmax (session prefill and decode, `checked == 0`) must not invent token 0 when
/// every unbanned logit is non-finite. The kernel writes `-1`, which the host reads as `u32::MAX`.
#[test]
fn metal_argmax_empty_row_does_not_emit_token_zero() {
    if !metal_device_runs_compute() {
        return;
    }
    let gpu = Gpu::new(&sampling_region_src(), &["k_argmax1", "k_argmax2"]);
    let absent = u32::MAX;
    let mut finite = [-20.0f32; WIDTH];
    finite[0] = 9.0;
    finite[5] = 1.0;
    assert_eq!(argmax_row(&gpu, &finite, 5), 0, "finite token 0");
    for never in [0u32, 5, 1999] {
        let mut only_never = [f32::NEG_INFINITY; WIDTH];
        only_never[never as usize] = 25.0;
        assert_eq!(argmax_row(&gpu, &only_never, never), absent, "only never {never}");
        let all_inf = [f32::NEG_INFINITY; WIDTH];
        assert_eq!(argmax_row(&gpu, &all_inf, never), absent, "all -inf, never {never}");
        let all_nan = [f32::NAN; WIDTH];
        assert_eq!(argmax_row(&gpu, &all_nan, never), absent, "all NaN, never {never}");
    }
}

/// Unchecked greedy argmax (`checked == 0`) must also fail closed (`u32::MAX`) when any single logit is
/// `NaN` or `+Inf` alongside finite competitors—including when that fault lands on `never_tok` or comes
/// from `k_loopcd_blend`'s `0x7fc00000` poison value—while still ignoring `-Inf` masks.
#[test]
fn metal_argmax_partial_nan_or_masked_nonfinite_fails_closed() {
    if !metal_device_runs_compute() {
        return;
    }
    let gpu = Gpu::new(&sampling_region_src(), &["k_argmax1", "k_argmax2"]);
    let absent = u32::MAX;
    for never in [0u32, 5, 1999, u32::MAX] {
        for bad_idx in [0usize, 5, 1024, 2048] {
            for bad in [f32::NAN, f32::from_bits(0x7fc0_0000), f32::INFINITY] {
                let mut row = [-20.0f32; WIDTH];
                row[1] = 9.0;
                row[1025] = 8.0;
                row[bad_idx] = bad;
                assert_eq!(
                    argmax_row(&gpu, &row, never),
                    absent,
                    "partial non-finite {bad:?} at {bad_idx} (never={never}) must fail closed"
                );
            }
        }
    }
    let mut masked_row = [-20.0f32; WIDTH];
    masked_row[0] = f32::NEG_INFINITY;
    masked_row[5] = 25.0;
    masked_row[9] = 12.0;
    assert_eq!(argmax_row(&gpu, &masked_row, 5), 9, "-inf mask and never_tok leave finite runner-up");
}

/// One `k_dspark_reject` dispatch over one span (`k` drafts, rows of `n` logits), returning `(n_accepted, emitted)`.
#[allow(clippy::too_many_arguments)]
fn dspark_reject(
    gpu: &Gpu,
    n: usize,
    target: &[f32],
    draft_toks: &[u32],
    draft: &[f32],
    temp: f32,
    seed: u64,
    never: u32,
) -> (usize, Vec<u32>) {
    dspark_reject_x(gpu, n, target, draft_toks, draft, temp, seed, never, false)
}

/// [`dspark_reject`] with the span's one-hot (`INK_PROMPT_LOOKUP`) flag.
#[allow(clippy::too_many_arguments)]
fn dspark_reject_x(
    gpu: &Gpu,
    n: usize,
    target: &[f32],
    draft_toks: &[u32],
    draft: &[f32],
    temp: f32,
    seed: u64,
    never: u32,
    onehot: bool,
) -> (usize, Vec<u32>) {
    let k = draft_toks.len();
    assert_eq!(target.len(), (k + 1) * n);
    let bytes = |v: &[u32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_ne_bytes()).collect() };
    let fbytes = |v: &[f32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_ne_bytes()).collect() };
    let desc = DSparkSpanDesc {
        target_off: 0,
        draft_lg_off: 0,
        draft_tok_off: 0,
        out_off: 0,
        k: k as u32,
        seed_lo: seed as u32,
        seed_hi: (seed >> 32) as u32,
        base_pos: 11,
        ban_tok: u32::MAX,
        temp,
        never_tok: never,
        onehot: u32::from(onehot),
    };
    let args = DSparkRejectArgs {
        n_vocab: n as u32,
        target_stride: n as u32,
        draft_stride: n as u32,
        temp,
        target_softcap: 30.0,
        draft_softcap: 30.0,
        pad0: 0,
        pad1: 0,
    };
    let desc_bytes: &[u8] =
        unsafe { std::slice::from_raw_parts((&raw const desc).cast::<u8>(), size_of::<DSparkSpanDesc>()) };
    let tbuf = gpu.buffer_with(&fbytes(target));
    let dbuf = gpu.buffer_with(desc_bytes);
    let tokbuf = gpu.buffer_with(&bytes(&[draft_toks, &[0]].concat()));
    let dlg = gpu.buffer_with(&fbytes(&[draft, &[0.0]].concat()));
    let out = gpu.buffer_with(&bytes(&vec![0u32; k + 3]));
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.pso(&gpu.pso("k_dspark_reject"));
    e.buf(&tbuf, 0, 2);
    e.bytes(&args, 5);
    e.buf(&dbuf, 0, 6);
    e.buf(&tokbuf, 0, 8);
    e.buf(&dlg, 0, 9);
    e.buf(&out, 0, 10);
    e.dispatch((1, 1, 1), 1024);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    assert_eq!(cb.status(), MTLCommandBufferStatus::Completed, "{:?}", cb.error());
    let raw = unsafe { std::slice::from_raw_parts(out.contents().as_ptr().cast::<u32>(), k + 3) };
    assert_eq!(raw[0], 0, "k_dspark_reject status");
    let acc = raw[1] as usize;
    (acc, raw[2..3 + acc].to_vec())
}

/// `k_dspark_reject` never accepts or emits `never_tok`, greedy or stochastic, whether it is drafted, the target
/// argmax at a draft position, or the target argmax at the bonus position.
#[test]
fn metal_dspark_reject_never_emits_the_never_token() {
    if !metal_device_runs_compute() {
        return;
    }
    let all = include_str!("../kernels.metal");
    let start = all.find("// DSpark speculative rejection sampling").unwrap();
    let end = all[start..].find("// Dynamic WHT-2bit-Sketch").unwrap();
    let src = format!("{}\n{}", sampling_region_src(), &all[start..start + end]);
    let gpu = Gpu::new(&src, &["k_dspark_reject"]);
    const N: usize = 64;
    const NEVER: u32 = 40;
    let row = |hi: u32| -> Vec<f32> {
        let mut r = vec![-20.0f32; N];
        r[NEVER as usize] = 25.0;
        r[hi as usize] = 10.0;
        r
    };
    // Draft position 0: the target and the draft both put almost all mass on NEVER; the bonus row too.
    let target = [row(3), row(9)].concat();
    let draft = row(3);
    for temp in [0.0f32, 1.0] {
        for seed in 0..16u64 {
            // NEVER drafted: rejected, replaced by the best other token.
            let (acc, emitted) = dspark_reject(&gpu, N, &target, &[NEVER], &draft, temp, seed, NEVER);
            assert_eq!(acc, 0, "drafted NEVER, temp {temp} seed {seed}");
            assert_ne!(emitted, [NEVER], "drafted NEVER, temp {temp} seed {seed}");
            if temp == 0.0 {
                assert_eq!(emitted, [3], "greedy replacement");
            }
            // Another token drafted and accepted: the bonus draw skips NEVER.
            let (acc, emitted) = dspark_reject(&gpu, N, &target, &[3], &draft, temp, seed, NEVER);
            assert!(!emitted.contains(&NEVER), "bonus, temp {temp} seed {seed}: {emitted:?}");
            if temp == 0.0 {
                assert_eq!((acc, emitted.as_slice()), (1, &[3, 9][..]), "greedy bonus");
            }
        }
    }
    // Control: without the mask NEVER is accepted.
    assert_eq!(dspark_reject(&gpu, N, &target, &[NEVER], &draft, 0.0, 0, u32::MAX), (1, vec![NEVER, NEVER]));
}

/// `k_dspark_reject` with one-hot drafts (`INK_PROMPT_LOOKUP`, `q = one_hot(d)`): greedy accepts exactly the
/// target argmax chain; stochastic emits tokens distributed as the target `p` whatever is drafted (accept
/// `d` with `p(d)`, else draw from `p` with `d` zeroed). It reads no draft logits: they are NaN here.
#[test]
fn metal_dspark_reject_onehot_drafts_keep_the_target_distribution() {
    if !metal_device_runs_compute() {
        return;
    }
    let all = include_str!("../kernels.metal");
    let start = all.find("// DSpark speculative rejection sampling").unwrap();
    let end = all[start..].find("// Dynamic WHT-2bit-Sketch").unwrap();
    let src = format!("{}\n{}", sampling_region_src(), &all[start..start + end]);
    let gpu = Gpu::new(&src, &["k_dspark_reject"]);
    const N: usize = 64;
    let hot: [(usize, f32); 4] = [(3, 2.0), (9, 1.5), (17, 1.0), (40, 0.2)];
    let mut row = vec![-30.0f32; N];
    for &(i, z) in &hot {
        row[i] = z;
    }
    let target = [row.clone(), row.clone()].concat();
    let nan_draft = vec![f32::NAN; N];
    // Greedy: accept iff the draft is the argmax (3); the bonus is the argmax again.
    assert_eq!(dspark_reject_x(&gpu, N, &target, &[3], &nan_draft, 0.0, 1, u32::MAX, true), (1, vec![3, 3]));
    assert_eq!(dspark_reject_x(&gpu, N, &target, &[9], &nan_draft, 0.0, 1, u32::MAX, true), (0, vec![3]));
    // Stochastic, temp 1: p over the hot tokens (softcap 30 is near-identity at these logits).
    let cap = |z: f32| 30.0 * (z / 30.0).tanh();
    let zs: Vec<f64> = row.iter().map(|&z| f64::from(cap(z))).collect();
    let mx = zs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let ez: Vec<f64> = zs.iter().map(|z| (z - mx).exp()).collect();
    let tot: f64 = ez.iter().sum();
    let p: Vec<f64> = ez.iter().map(|e| e / tot).collect();
    for draft in [3u32, 9, 40, 50] {
        let trials = 4000u64;
        let mut counts = vec![0usize; N];
        for seed in 0..trials {
            let (_, emitted) = dspark_reject_x(
                &gpu,
                N,
                &target,
                &[draft],
                &nan_draft,
                1.0,
                0x5eed_0000_0000 ^ seed.wrapping_mul(0x9e37_79b9_7f4a_7c15),
                u32::MAX,
                true,
            );
            counts[emitted[0] as usize] += 1;
        }
        let tvd: f64 =
            0.5 * counts.iter().zip(&p).map(|(&c, &q)| (c as f64 / trials as f64 - q).abs()).sum::<f64>();
        assert!(tvd < 0.03, "draft {draft}: empirical TVD {tvd:.4} vs target");
        // The planted slip (take the draft unchecked) would emit `draft` every time.
        let share = counts[draft as usize] as f64 / trials as f64;
        assert!((share - p[draft as usize]).abs() < 0.03, "draft {draft}: emitted {share:.3}, p {:.3}", p[draft as usize]);
    }
}

/// Runs `k_topk_cand1` then `k_topk_cand2` over `rows` in one encoder, as `Engine::encode_topk_spans` does,
/// and returns each row's decoded `(nonfinite, candidates)`.
fn topk_rows(gpu: &Gpu, rows: &[Vec<f32>]) -> Vec<(bool, Vec<(f32, u32)>)> {
    let width = rows.iter().map(Vec::len).max().unwrap();
    let words = super::topk_row_words(width);
    let tk = rows.len() * width;
    let arena = gpu.buffer((tk + rows.len() * words) * 4);
    let a = arena.contents().as_ptr().cast::<f32>();
    for (r, row) in rows.iter().enumerate() {
        // The buffer is idle; row r occupies [r * width, r * width + row.len()).
        unsafe { std::ptr::copy_nonoverlapping(row.as_ptr(), a.add(r * width), row.len()) };
    }
    let args = |r: usize| {
        let n = rows[r].len();
        let nchunks = n.div_ceil(super::TOPK_CHUNK);
        let base = tk + r * words;
        (
            super::TopkCandArgs {
                logits_off: (r * width) as u32,
                n: n as u32,
                nchunks: nchunks as u32,
                part_off: base as u32,
                out_off: (base + nchunks * super::TOPK_ROW) as u32,
                pad: [0; 3],
            },
            nchunks,
        )
    };
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(&arena, 0, 2);
    e.pso(&gpu.pso("k_topk_cand1"));
    for r in 0..rows.len() {
        let (args, nchunks) = args(r);
        e.bytes(&args, 5);
        e.dispatch((nchunks, 1, 1), 256);
    }
    e.barrier();
    e.pso(&gpu.pso("k_topk_cand2"));
    for r in 0..rows.len() {
        let (args, nchunks) = args(r);
        e.bytes(&args, 5);
        e.dispatch((1, 1, 1), nchunks.div_ceil(32) * 32);
    }
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    assert_eq!(cb.status(), MTLCommandBufferStatus::Completed, "{:?}", cb.error());
    (0..rows.len())
        .map(|r| {
            let (args, _) = args(r);
            // Completion makes the merged rows visible to the CPU.
            let out = unsafe {
                std::slice::from_raw_parts(a.cast::<u32>().add(args.out_off as usize), super::TOPK_ROW)
            };
            crate::sampler::decode_topk_row(out)
        })
        .collect()
}

/// Functional (needs a Metal GPU; skipped without one): the GPU top-65 lists equal the CPU's
/// `cmp_cand` order bit for bit, including +0.0/-0.0 and exact ties across chunk and threadgroup
/// boundaries, rows shorter than the list, and non-finite logits; and the tokens drawn from them equal
/// the full-row CPU sampler's for the same seeds.
#[test]
fn metal_topk_candidates_match_cpu_reference() {
    if !metal_device_runs_compute() {
        return;
    }
    let all = include_str!("../kernels.metal");
    let start = all.find("// argmax over logits").unwrap();
    let end = all[start..].find("// Adaptive LoopCD-Logits").unwrap();
    let src = format!("#include <metal_stdlib>\nusing namespace metal;\n{}", &all[start..start + end]);
    let gpu = Gpu::new(&src, &["k_topk_cand1", "k_topk_cand2"]);

    let mut rng = 0x5EED_70B6_4000_0001u64;
    let mut next = || {
        rng = rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = rng;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    };
    let mut rows: Vec<Vec<f32>> = Vec::new();
    for (k, n) in [1usize, 2, 64, 65, 66, 255, 2047, 2048, 2049, 4097, 20000, 201_088].into_iter().enumerate() {
        for style in 0..4 {
            rows.push(
                (0..n)
                    .map(|i| {
                        let u = next();
                        match style {
                            0 => [0.0, -0.0, 7.0, 7.0, -3.0, 0.0, -0.0, 1.0][(u % 8) as usize],
                            1 => ((u & 0xFFFFF) as f32) / 4096.0 - 128.0,
                            // Every logit equal except a few: winners decided by token id alone.
                            2 => if u % 1009 == 0 { 2.0 } else { 1.5 },
                            _ => f32::from_bits(((u as u32) & 0x807f_ffff) | (((k as u32 * 7 + i as u32) % 254 + 1) << 23)),
                        }
                    })
                    .collect(),
            );
        }
    }
    // Non-finite logits at chunk edges and in the last partial chunk.
    for (pos, bad) in [(0usize, f32::NAN), (2047, f32::INFINITY), (2048, f32::NEG_INFINITY), (201_087, f32::NAN)] {
        let mut row: Vec<f32> = (0..201_088).map(|i| (i % 977) as f32 * 0.01).collect();
        row[pos] = bad;
        rows.push(row);
    }
    // Subnormals of both signs and -0.0 at the top of the row: their order rests on bits a fast-math float load
    // could flush (Emma Gemini's review), so the kernel loads raw uint.
    for n in [100usize, 4097] {
        let row: Vec<f32> = (0..n)
            .map(|i| match (next() % 6) as u32 {
                0 => -0.0,
                1 => 0.0,
                2 => f32::from_bits(1 + (i as u32 % 0x7f_ffff)),
                3 => -f32::from_bits(1 + (i as u32 % 0x7f_ffff)),
                4 => f32::from_bits(1),
                _ => -1e-30,
            })
            .collect();
        rows.push(row);
    }
    let mut allbad = vec![f32::NAN; 3000];
    allbad[5] = f32::INFINITY;
    rows.push(allbad);

    let got = topk_rows(&gpu, &rows);
    for (r, (row, (gbad, gtop))) in rows.iter().zip(&got).enumerate() {
        let (wbad, wtop) = crate::sampler::topk_reference(row);
        assert_eq!(*gbad, wbad, "row {r} (n={}) nonfinite flag", row.len());
        if wbad {
            continue; // the request fails on the flag; the list is not read
        }
        let g: Vec<(u32, u32)> = gtop.iter().map(|c| (c.0.to_bits(), c.1)).collect();
        let w: Vec<(u32, u32)> = wtop.iter().map(|c| (c.0.to_bits(), c.1)).collect();
        assert_eq!(g, w, "row {r} (n={}) candidates", row.len());
        for (t, (temp, top_k, top_p)) in [(0.0f32, 64usize, 0.95f32), (1.0, 64, 0.95), (0.7, 7, 0.5), (1.3, 1, 1.0)]
            .into_iter()
            .enumerate()
        {
            let ban = (t % 2 == 1).then(|| wtop[0].1);
            let seed = 77 + (r * 4 + t) as u64;
            let mut cpu = crate::sampler::Sampler::new(temp, top_k, top_p, 30.0, seed);
            let mut gpu_s = crate::sampler::Sampler::new(temp, top_k, top_p, 30.0, seed);
            let want = cpu.sample_next_with_ban_and_softcap(row, ban, 30.0);
            let have = match gpu_s.sample_next_from_topk(gtop, row.len(), *gbad, ban, 30.0) {
                Ok(None) => gpu_s.sample_next_with_ban_and_softcap(row, ban, 30.0),
                other => other.map(|t| t.unwrap()),
            };
            assert_eq!(have, want, "row {r} (n={}) temp {temp} k {top_k} p {top_p} ban {ban:?}", row.len());
        }
    }
}