inky-engine 2.0.3

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
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
//! CPU sampler over the GPU logits: softcap -> top-k -> temperature -> top-p -> draw.

pub(crate) fn checked_argmax(logits: &[f32]) -> Result<u32, &'static str> {
    if logits.is_empty() {
        return Err("model returned no logits");
    }
    let mut best = (0u32, f32::NEG_INFINITY);
    for (i, &x) in logits.iter().enumerate() {
        if !x.is_finite() {
            return Err("model returned non-finite logits");
        }
        if x > best.1 {
            best = (i as u32, x);
        }
    }
    Ok(best.0)
}

pub struct Sampler {
    pub temp: f32,
    pub top_k: usize,
    pub top_p: f32,
    pub softcap: f32,
    state: u64,
    cand: Vec<(f32, u32)>,
}

impl Sampler {
    /// `top_k == 0` disables top-k truncation (full-vocab sampling with monotonic `atanh` logit cut).
    pub fn new(temp: f32, top_k: usize, top_p: f32, softcap: f32, seed: u64) -> Sampler {
        Sampler { temp, top_k, top_p, softcap, state: seed ^ 0x9E37_79B9_7F4A_7C15, cand: Vec::with_capacity(256) }
    }

    pub fn greedy(&self) -> bool { self.temp <= 0.0 }

    /// Whether this sampler can use GPU Gumbel-max sampling (`top_k == 0 && top_p >= 1.0`, chadlyb/erisinky).
    pub fn uses_gpu_gumbel(&self) -> bool {
        self.top_k == 0 && self.top_p >= 1.0 && self.temp.is_finite() && self.temp >= 0.0
    }

    fn next_f32(&mut self) -> f32 {
        // splitmix64
        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.state;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^= z >> 31;
        (z >> 40) as f32 / (1u64 << 24) as f32
    }

    /// Draft stream for one request. The mix is `0x85ebca6b`, applied once here, not again per round.
    pub fn draft(temp: f32, top_k: usize, top_p: f32, softcap: f32, request_seed: u64) -> Sampler {
        Sampler::new(temp, top_k, top_p, softcap, request_seed ^ DRAFT_SEED_MIX)
    }

    #[cfg(test)]
    pub fn sample(&mut self, logits: &[f32]) -> u32 {
        self.sample_next(logits).expect("model sampling failed")
    }

    /// Sample one model row, or fail the request before consuming an RNG draw.
    pub fn sample_next(&mut self, logits: &[f32]) -> Result<u32, &'static str> {
        self.sample_next_with_ban(logits, None)
    }

    /// Sample one model row with an optional banned token ID (used for hard thinking-budget close),
    /// using a monotonic `atanh` raw-logit cutoff (chadlyb/erisinky) to skip `tanh`/`exp` on tokens
    /// more than 30 nats below the maximum.
    pub fn sample_next_with_ban(&mut self, logits: &[f32], ban: Option<u32>) -> Result<u32, &'static str> {
        self.sample_next_with_ban_and_softcap(logits, ban, self.softcap)
    }

    /// Sample one model row with an optional banned token ID and an explicit per-step `softcap`
    /// override (`0.0` when logits are already post-softcap, e.g. after `k_loopcd_blend`).
    pub fn sample_next_with_ban_and_softcap(
        &mut self,
        logits: &[f32],
        ban: Option<u32>,
        softcap: f32,
    ) -> Result<u32, &'static str> {
        self.sample_next_filtered(logits, ban, softcap, |_| true)
    }

    /// Sample one model row while masking out both `ban` and any token rejected by `allow(token_id)`
    /// (for example, byte-level JSON pushdown grammar constraints during active tool-call spans).
    /// Checks finiteness of all logits first and evaluates `allow` lazily only on record-highs and
    /// candidates within the 30-nat raw-logit cutoff.
    pub fn sample_next_filtered<F: FnMut(u32) -> bool>(
        &mut self,
        logits: &[f32],
        ban: Option<u32>,
        softcap: f32,
        allow: F,
    ) -> Result<u32, &'static str> {
        let total = self.prepare_row_filtered(logits, ban, softcap, allow)?;
        Ok(self.draw_cand(total))
    }

    /// Whether a row can be sampled from the GPU's exact top-[`TOPK_CAND`] list
    /// ([`Self::sample_next_from_topk`]) instead of a serial scan of the whole vocabulary.
    pub fn uses_gpu_topk(&self) -> bool {
        !self.uses_gpu_gumbel() && (1..TOPK_CAND).contains(&self.top_k) && self.temp.is_finite()
    }

    /// Whether a grammar-filtered row can sample from the GPU's exact top-[`TOPK_CAND`] list
    /// ([`Self::sample_next_filtered_from_topk`]). Covers both default `0 < top_k < TOPK_CAND`
    /// rows and greedy rows (`temp < 1e-5`, regardless of `top_k`) that bypass GPU Gumbel while
    /// masked by a tool-call JSON grammar.
    pub fn uses_gpu_topk_filtered(&self) -> bool {
        self.temp.is_finite() && (self.temp < 1e-5 || (1..TOPK_CAND).contains(&self.top_k))
    }

    /// The same draw as [`Self::sample_next_with_ban_and_softcap`] on a row of `n_logits` logits, given
    /// only `top`: that row's first `min(n_logits, TOPK_CAND)` entries in [`cmp_cand`] order (as
    /// `k_topk_cand2` writes them) and whether any logit was non-finite. Needs `top_k < TOPK_CAND`; the one
    /// spare entry stands in for a banned token. `Ok(None)` (no RNG draw) when the list cannot decide the
    /// raw first-index argmax the CPU path uses, which needs a run of exactly equal maxima (`+0.0`/`-0.0`)
    /// longer than the list; the caller then scans the row with the CPU path.
    pub fn sample_next_from_topk(
        &mut self,
        top: &[(f32, u32)],
        n_logits: usize,
        nonfinite: bool,
        ban: Option<u32>,
        softcap: f32,
    ) -> Result<Option<u32>, &'static str> {
        assert!(self.top_k > 0 && self.top_k < TOPK_CAND, "top-k list needs 0 < top_k < {TOPK_CAND}");
        self.sample_next_filtered_from_topk(top, n_logits, nonfinite, ban, softcap, |_| true)
    }

    /// The same draw as [`Self::sample_next_filtered`] on a row of `n_logits` logits, given only `top`
    /// (the first `min(n_logits, TOPK_CAND)` entries in [`cmp_cand`] order) and whether any logit was
    /// non-finite. Evaluates `allow(token_id)` only over the at-most-[`TOPK_CAND`] unbanned entries and
    /// returns `Ok(None)` (consuming no RNG draw) whenever unseen vocabulary entries could alter the
    /// exact filtered top-`k`/top-`p` distribution or greedy first-index tie-break; the caller then
    /// falls back to [`Self::sample_next_filtered`] on the full row.
    pub fn sample_next_filtered_from_topk<F: FnMut(u32) -> bool>(
        &mut self,
        top: &[(f32, u32)],
        n_logits: usize,
        nonfinite: bool,
        ban: Option<u32>,
        softcap: f32,
        mut allow: F,
    ) -> Result<Option<u32>, &'static str> {
        if n_logits == 0 { return Err("model returned no logits"); }
        if !self.temp.is_finite() { return Err("invalid sampling temperature"); }
        assert!(
            self.temp < 1e-5 || (1..TOPK_CAND).contains(&self.top_k),
            "top-k list needs greedy temp < 1e-5 or 0 < top_k < {TOPK_CAND}"
        );
        if nonfinite { return Err("model returned non-finite logits"); }
        if top.len() != n_logits.min(TOPK_CAND) || !top.windows(2).all(|w| cmp_cand(&w[0], &w[1]).is_lt()) {
            return Err("GPU top-k candidate list is malformed");
        }
        let has_unseen = n_logits > top.len();
        self.cand.clear();
        let mut best: Option<(f32, u32)> = None;
        for &(val, tok) in top {
            if Some(tok) == ban || !allow(tok) {
                continue;
            }
            match &mut best {
                None => best = Some((val, tok)),
                // First index of the numeric maximum, matching `prepare_row_filtered`'s strict `>`.
                Some((bv, bt)) if val == *bv && tok < *bt => *bt = tok,
                _ => {}
            }
            self.cand.push((val, tok));
        }
        let Some((best_val, best_tok)) = best else {
            return if has_unseen { Ok(None) } else { Err("no sampling candidates") };
        };
        let unseen_max_tie = has_unseen && top.last().is_some_and(|c| c.0 == best_val);
        let Some(raw_cut) = self.raw_cut(best_val, softcap)? else {
            self.cand.clear();
            if unseen_max_tie { return Ok(None); }
            self.cand.push((1.0, best_tok));
            return Ok(Some(best_tok));
        };
        self.cand.retain(|c| c.0 >= raw_cut);
        // Because `top` holds the smallest `top.len()` entries under `cmp_cand`, every unseen token `u`
        // satisfies `cmp_cand(top.last(), u) < 0` and therefore `u.0 <= top.last().0`.
        // - If `self.cand.len() >= self.top_k`, no unseen token can enter the top-`top_k` set.
        // - If `top.last().0 < raw_cut`, no unseen token can pass `x >= raw_cut`.
        // Only when unseen tokens can pass `raw_cut` AND fewer than `self.top_k` allowed candidates
        // survived (or `cand` is empty with an unseen max tie) must we defer to the full CPU scan.
        if self.cand.is_empty() && unseen_max_tie {
            return Ok(None);
        }
        if has_unseen && self.cand.len() < self.top_k {
            if let Some(&(top_last, _)) = top.last() {
                if top_last >= raw_cut {
                    // Dominant top-1 nucleus shortcut: at structural JSON positions (`{`, `:`, `,`, `}`,
                    // tool/property names), typically 1..10 tokens in `top` pass `allow` (`< top_k`),
                    // while `top[64]` is still above the 30-nat `raw_cut`. Even if all `missing`
                    // remaining `top_k` slots were filled with unseen allowed tokens at `top_last`,
                    // if `cand[0]` alone strictly exceeds `top_p`, `finish_row` is guaranteed to
                    // truncate `cand` to `[cand[0]]` (`keep = 1`) and `draw_cand` consumes one RNG
                    // step and returns `cand[0].1` for every possible uniform draw.
                    if !self.cand.is_empty() && !unseen_max_tie && self.top_p < 1.0 {
                        let c = softcap;
                        let t = self.temp;
                        let capped = |x: f32| if c > 0.0 { c * (x / c).tanh() } else { x };
                        let max_cap = capped(best_val);
                        let scaled_max = max_cap / t;
                        let exp_c = |raw: f32| -> f32 {
                            let x = capped(raw);
                            let centered = if scaled_max.is_finite() {
                                x / t - scaled_max
                            } else {
                                (x - max_cap) / t
                            };
                            centered.exp()
                        };
                        let w0 = exp_c(self.cand[0].0);
                        let mut w_known = 0.0f64;
                        for &(v, _) in &self.cand {
                            w_known += f64::from(exp_c(v));
                        }
                        let missing = self.top_k - self.cand.len();
                        let w_tail = (missing as f64) * f64::from(exp_c(top_last));
                        let sum_upper = (w_known + w_tail) * (1.0 + 128.0 * f64::from(f32::EPSILON));
                        if w0 == 1.0 && sum_upper.is_finite() && (1.0f64 / sum_upper) > f64::from(self.top_p) {
                            let tok0 = self.cand[0].1;
                            if self.temp >= 1e-5 {
                                let _ = self.next_f32();
                            }
                            self.cand.clear();
                            self.cand.push((1.0, tok0));
                            return Ok(Some(tok0));
                        }
                    }
                    self.cand.clear();
                    return Ok(None);
                }
            }
        }
        let total = self.finish_row(best_val, best_tok, softcap)?;
        Ok(Some(self.draw_cand(total)))
    }

    fn draw_cand(&mut self, total: f32) -> u32 {
        if self.temp < 1e-5 { return self.cand[0].1; }
        let mut r = self.next_f32() * total;
        let mut last = self.cand[0].1;
        for &(mass, token) in &self.cand {
            if mass == 0.0 { continue; }
            last = token;
            r -= mass;
            if r <= 0.0 { return token; }
        }
        last
    }

    /// Fill `cand` with the masses used for a draw and return their total after the top-p cut.
    /// Both ordinary draws and speculative rejection need the exact same token support.
    fn prepare_row(&mut self, logits: &[f32], ban: Option<u32>, softcap: f32) -> Result<f32, &'static str> {
        self.prepare_row_filtered(logits, ban, softcap, |_| true)
    }

    fn prepare_row_filtered<F: FnMut(u32) -> bool>(
        &mut self,
        logits: &[f32],
        ban: Option<u32>,
        softcap: f32,
        mut allow: F,
    ) -> Result<f32, &'static str> {
        if logits.is_empty() { return Err("model returned no logits"); }
        if !self.temp.is_finite() { return Err("invalid sampling temperature"); }
        let mut best: Option<(f32, u32)> = None;
        for (i, &x) in logits.iter().enumerate() {
            if !x.is_finite() { return Err("model returned non-finite logits"); }
            let tok = i as u32;
            if Some(tok) == ban { continue; }
            if best.is_none_or(|(b, _)| x > b) && allow(tok) {
                best = Some((x, tok));
            }
        }
        let Some((best_val, best_tok)) = best else { return Err("no sampling candidates") };
        self.cand.clear();
        let Some(raw_cut) = self.raw_cut(best_val, softcap)? else {
            self.cand.push((1.0, best_tok));
            return Ok(1.0);
        };
        for (i, &x) in logits.iter().enumerate() {
            let tok = i as u32;
            if Some(tok) != ban && x >= raw_cut && (tok == best_tok || allow(tok)) {
                self.cand.push((x, tok));
            }
        }
        self.finish_row(best_val, best_tok, softcap)
    }

    /// The raw-logit cutoff below the row maximum `best_val`, or `None` for a greedy (near-zero) temperature.
    fn raw_cut(&self, best_val: f32, softcap: f32) -> Result<Option<f32>, &'static str> {
        if self.temp < 1e-5 { return Ok(None); }
        if !softcap.is_finite() || !self.top_p.is_finite() {
            return Err("invalid sampling parameters");
        }
        let c = softcap;
        let t = self.temp;
        let max_cap = if c > 0.0 { c * (best_val / c).tanh() } else { best_val };
        let scaled_max = max_cap / t;
        // Monotonic raw-logit cutoff: tokens >30 nats below max carry < e^-30 (< f32::EPSILON) weight.
        let raw_cut = if scaled_max.is_finite() {
            let y = t * (scaled_max - 30.0);
            let rc = if c <= 0.0 {
                y
            } else if y <= -c {
                f32::NEG_INFINITY
            } else {
                c * (y / c).atanh()
            };
            if rc.is_finite() { rc - 1e-3 * rc.abs() - 1e-3 } else { f32::NEG_INFINITY }
        } else {
            f32::NEG_INFINITY
        };
        Ok(Some(raw_cut))
    }

    /// From the raw candidates above the cutoff in `cand` (any order): top-k, softmax, top-p.
    fn finish_row(&mut self, best_val: f32, best_tok: u32, softcap: f32) -> Result<f32, &'static str> {
        let c = softcap;
        let t = self.temp;
        let capped = |x: f32| if c > 0.0 { c * (x / c).tanh() } else { x };
        let max_cap = capped(best_val);
        let scaled_max = max_cap / t;
        if self.cand.is_empty() {
            self.cand.push((best_val, best_tok));
        }
        truncate_and_sort_top_k(&mut self.cand, self.top_k);
        let mut sum = 0.0;
        for (mass, _) in &mut self.cand {
            let x = capped(*mass);
            let centered = if scaled_max.is_finite() { x / t - scaled_max } else { (x - max_cap) / t };
            *mass = centered.exp();
            sum += *mass;
        }
        if !sum.is_finite() || sum <= 0.0 { return Err("model returned invalid sampling probabilities"); }
        let mut total = 0.0;
        let mut keep = self.cand.len();
        for (i, (mass, _)) in self.cand.iter_mut().enumerate() {
            *mass /= sum;
            total += *mass;
            if total >= self.top_p {
                keep = i + 1;
                break;
            }
        }
        self.cand.truncate(keep);
        Ok(total)
    }

    /// One drafted position. Given the actual drafted token `draft_tok` drawn from `q`, accept with
    /// `min(1, p/q)`, else draw `norm(max(0, p-q))`. Every uniform comes from this sampler.
    /// `temp <= 0` does not belong here.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn reject_one(&mut self, draft_tok: u32, target: &[f32], draft: &[f32]) -> u32 {
        self.reject_at(draft_tok, target, draft, None).0
    }

    /// One verify round on the probabilistic path. `draft_tokens` are the actual drafted tokens
    /// fed into the target forward pass; `target_rows` is those draft positions plus the bonus row.
    /// A rejection stops the round. The bonus draw, when every draft is accepted, uses this same
    /// stream. One call is one round: it is not reseeded per emitted token.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn verify_round(&mut self, draft_tokens: &[u32], target_rows: &[&[f32]], draft_rows: &[&[f32]]) -> Vec<u32> {
        self.verify_round_with_ban(draft_tokens, target_rows, draft_rows, None)
    }

    /// Same as [`Self::verify_round`], while masking an optional `ban` token to zero target mass
    /// (for hard thinking-budget enforcement, matching 1-token decode and GPU `k_dspark_reject`).
    pub fn verify_round_with_ban(
        &mut self,
        draft_tokens: &[u32],
        target_rows: &[&[f32]],
        draft_rows: &[&[f32]],
        ban: Option<u32>,
    ) -> Vec<u32> {
        assert!(self.temp > 0.0, "greedy does not reject");
        assert_eq!(draft_tokens.len(), draft_rows.len(), "one draft token per draft row");
        assert_eq!(target_rows.len(), draft_rows.len() + 1, "one target row per draft token, plus the bonus");
        let mut out = Vec::with_capacity(target_rows.len());
        for i in 0..draft_rows.len() {
            let (tok, accepted) = self.reject_at(draft_tokens[i], target_rows[i], draft_rows[i], ban);
            out.push(tok);
            if !accepted { return out; }
        }
        out.push(self.sample_next_with_ban(target_rows[draft_rows.len()], ban).expect("model sampling failed"));
        out
    }

    fn reject_at(&mut self, draft_tok: u32, target: &[f32], draft: &[f32], ban: Option<u32>) -> (u32, bool) {
        assert!(self.temp > 0.0, "greedy does not reject");
        let masses = self.masses(target, draft, ban);
        let x = draft_tok;
        let px = prob_of(&masses, x, true);
        let qx = prob_of(&masses, x, false);
        // p >= q accepts without a draw; the uniform is only the case that can reject
        let accept = qx > 0.0 && (px >= qx || self.next_f32() < px / qx);
        if accept { return (x, true); }
        let mut resid: Vec<(u32, f32)> = Vec::new();
        for m in &masses {
            let r = m.p - m.q;
            if r > 0.0 { resid.push((m.token, r)); }
        }
        if resid.is_empty() {
            let p: Vec<(u32, f32)> = masses.iter().filter(|m| m.p > 0.0).map(|m| (m.token, m.p)).collect();
            return (self.draw_dist(&p), false);
        }
        (self.draw_dist(&resid), false)
    }

    fn draw_dist(&mut self, dist: &[(u32, f32)]) -> u32 {
        let Some(&(last_tok, _)) = dist.last() else { return 0 };
        let total: f32 = dist.iter().map(|d| d.1).sum();
        let mut r = self.next_f32() * total;
        for &(tok, p) in dist {
            r -= p;
            if r <= 0.0 { return tok; }
        }
        last_tok
    }

    /// p and q on the union of the surviving target and draft candidates, ordered by token ID.
    fn masses(&mut self, target: &[f32], draft: &[f32], ban: Option<u32>) -> Vec<Mass> {
        let mut by_token = std::collections::BTreeMap::new();
        let target_total = self.prepare_row(target, ban, self.softcap).expect("invalid target sampling row");
        for &(weight, token) in &self.cand {
            if weight > 0.0 {
                by_token.insert(token, Mass { token, p: weight / target_total, q: 0.0 });
            }
        }
        let draft_total = self.prepare_row(draft, None, self.softcap).expect("invalid draft sampling row");
        for &(weight, token) in &self.cand {
            if weight > 0.0 {
                by_token.entry(token).or_insert(Mass { token, p: 0.0, q: 0.0 }).q = weight / draft_total;
            }
        }
        by_token.into_values().collect()
    }
}

/// Mixed into the request seed once, for the draft sampler only.
pub const DRAFT_SEED_MIX: u64 = 0x85ebca6b;

/// Entries in a GPU top-k candidate row (`TK_C` in `k_topk_cand1`/`k_topk_cand2`): `top_k <= 64` plus one
/// for a banned token.
pub const TOPK_CAND: usize = 65;

/// What `k_topk_cand2` must write for `row`: the finite logits in `cmp_cand` order, first `TOPK_CAND` of
/// them, and whether any logit was non-finite (`metal_topk_candidates_match_cpu_reference` checks the GPU).
#[cfg(test)]
pub(crate) fn topk_reference(row: &[f32]) -> (bool, Vec<(f32, u32)>) {
    let mut all: Vec<(f32, u32)> =
        row.iter().enumerate().filter(|(_, x)| x.is_finite()).map(|(i, &x)| (x, i as u32)).collect();
    let bad = all.len() < row.len();
    all.sort_by(cmp_cand);
    all.truncate(TOPK_CAND);
    (bad, all)
}

/// Decode a `k_topk_cand2` row (`[bad, (key, id) x TOPK_CAND]`) into `(nonfinite, entries)`, dropping the
/// empty tail. The key is the logit's bits mapped so unsigned order is `f32::total_cmp`.
pub fn decode_topk_row(row: &[u32]) -> (bool, Vec<(f32, u32)>) {
    assert!(row.len() > 2 * TOPK_CAND, "top-k row has {} words", row.len());
    let mut out = Vec::with_capacity(TOPK_CAND);
    for &[key, id] in row[1..1 + 2 * TOPK_CAND].as_chunks::<2>().0 {
        if key == 0 { break; }
        let bits = if key & 0x8000_0000 != 0 { key ^ 0x8000_0000 } else { !key };
        out.push((f32::from_bits(bits), id));
    }
    (row[0] != 0, out)
}

struct Mass { token: u32, p: f32, q: f32 }
#[inline]
fn cmp_cand(a: &(f32, u32), b: &(f32, u32)) -> std::cmp::Ordering {
    b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))
}

fn truncate_and_sort_top_k(cand: &mut Vec<(f32, u32)>, top_k: usize) {
    if top_k > 0 && cand.len() > top_k {
        cand.select_nth_unstable_by(top_k - 1, cmp_cand);
        cand.truncate(top_k);
    }
    cand.sort_unstable_by(cmp_cand);
}
fn prob_of(masses: &[Mass], token: u32, target_side: bool) -> f32 {
    match masses.iter().find(|m| m.token == token) {
        Some(m) => if target_side { m.p } else { m.q },
        None => 0.0,
    }
}

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

    const SOFTCAP: f32 = 20.0;
    const TEMP: f32 = 1.0;
    const TOP_P: f32 = 0.8;
    const K: usize = 64;

    #[test]
    fn invalid_logits_fail_in_greedy_and_sampled_modes() {
        for temp in [0.0, TEMP] {
            let mut sampler = Sampler::new(temp, 2, TOP_P, SOFTCAP, 1);
            let before = sampler.state;
            for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
                // The invalid logit can be inside or outside the top-k candidates.
                assert!(sampler.sample_next(&[bad, 2.0, 1.0]).is_err());
                assert!(sampler.sample_next(&[2.0, 1.0, bad]).is_err());
            }
            assert!(sampler.sample_next(&[]).is_err());
            assert_eq!(sampler.state, before);
            assert!(sampler.sample_next(&[2.0, 2.0, 1.0]).is_ok());
        }
        let mut greedy = Sampler::new(0.0, 2, TOP_P, SOFTCAP, 1);
        assert_eq!(greedy.sample_next(&[1.0, 2.0, 2.0]), Ok(1));
    }

    #[test]
    fn small_positive_temperature_does_not_overflow_probabilities() {
        let mut sampler = Sampler::new(f32::from_bits(1), 3, 1.0, 0.0, 1);
        assert_eq!(sampler.sample_next(&[1.0, f32::MAX, -f32::MAX]), Ok(1));
        assert_eq!(sampler.sample_next(&[-f32::MAX, -2.0, -1.0]), Ok(2));
    }

    /// Target argmax is token 100, outside the draft's top-64. Token 0 is in the draft's top-64
    /// and outside the target's. Token 150 is in neither.
    fn logits() -> (Vec<f32>, Vec<f32>) {
        let mut target = vec![-50.0f32; 200];
        let mut draft = vec![-50.0f32; 200];
        for (i, d) in draft.iter_mut().enumerate().take(64) { *d = 6.0 - i as f32 * 0.01; }
        target[100] = 5.0;
        for (i, t) in target.iter_mut().enumerate().take(73).skip(10) { *t = 4.0 - (i as f32 - 10.0) * 0.01; }
        (target, draft)
    }

    /// The order this step uses: top-k on the raw logits, then softcap, then divide by temperature, then top-p.
    /// The other side's tokens are not in the softmax.
    fn expected_side(logits: &[f32], k: usize, softcap: f32, temp: f32, top_p: f32) -> Vec<(u32, f32)> {
        let mut order: Vec<u32> = (0..logits.len() as u32).collect();
        order.sort_by(|&a, &b| logits[b as usize].total_cmp(&logits[a as usize]).then(a.cmp(&b)));
        order.truncate(k.min(logits.len()));
        let scaled: Vec<f32> = order.iter().map(|&i| {
            let x = logits[i as usize];
            (if softcap > 0.0 { softcap * (x / softcap).tanh() } else { x }) / temp
        }).collect();
        let m = scaled[0];
        let mut pr: Vec<f32> = scaled.iter().map(|&x| (x - m).exp()).collect();
        let sum: f32 = pr.iter().sum();
        for v in pr.iter_mut() { *v /= sum; }
        let mut cum = 0.0;
        let mut n = pr.len();
        for (i, &v) in pr.iter().enumerate() {
            cum += v;
            if cum >= top_p { n = i + 1; break; }
        }
        let total: f32 = pr[..n].iter().sum();
        order.into_iter().zip(pr).take(n).filter(|&(_, p)| p > 0.0).map(|(t, p)| (t, p / total)).collect()
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    fn residual_emits_target_argmax_outside_draft_top64_softcap_after_topk() {
        let (target, draft) = logits();
        let argmax = target.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).unwrap().0 as u32;
        assert_eq!(argmax, 100, "the synthetic target argmax is the token outside the draft top-64");
        let mut draft_order: Vec<usize> = (0..draft.len()).collect();
        draft_order.sort_by(|&a, &b| draft[b].total_cmp(&draft[a]));
        assert!(!draft_order[..K].contains(&(argmax as usize)), "argmax must sit outside the draft top-64");
        assert!(draft_order[..K].contains(&0), "token 0 is in the draft top-64");
        let mut target_order: Vec<usize> = (0..target.len()).collect();
        target_order.sort_by(|&a, &b| target[b].total_cmp(&target[a]));
        assert!(!target_order[..K].contains(&0), "token 0 is outside the target top-64");
        assert!(!target_order[..K].contains(&150) && !draft_order[..K].contains(&150), "150 is in neither top-64");

        let mut sampler = Sampler::new(TEMP, K, TOP_P, SOFTCAP, 1);
        let masses = sampler.masses(&target, &draft, None);
        let exp_p = expected_side(&target, K, SOFTCAP, TEMP, TOP_P);
        let exp_q = expected_side(&draft, K, SOFTCAP, TEMP, TOP_P);
        assert!(exp_p.len() < K && exp_q.len() < K, "top-p cuts both sides on this draw");
        let p_of = |tok: u32| masses.iter().find(|m| m.token == tok).map(|m| m.p).unwrap_or(0.0);
        let q_of = |tok: u32| masses.iter().find(|m| m.token == tok).map(|m| m.q).unwrap_or(0.0);
        for &(tok, p) in &exp_p { assert!((p_of(tok) - p).abs() < 1e-6, "p({tok})"); }
        for &(tok, q) in &exp_q { assert!((q_of(tok) - q).abs() < 1e-6, "q({tok})"); }
        assert!(masses.iter().all(|m| exp_p.iter().any(|e| e.0 == m.token) || m.p == 0.0));
        assert!(masses.iter().all(|m| exp_q.iter().any(|e| e.0 == m.token) || m.q == 0.0));
        assert_eq!(q_of(argmax), 0.0, "a token the draft dropped has q=0 and is not renormed away");
        assert!(p_of(argmax) > 0.02, "the target keeps its argmax");
        assert_eq!(p_of(0), 0.0, "a token the target dropped has p=0");
        assert!(q_of(0) > 0.0, "the draft keeps token 0 through top-p");
        assert!(masses.iter().all(|m| m.token != 150), "a token in neither top-64 is not in the support");
        let p_sum: f32 = masses.iter().map(|m| m.p).sum();
        let q_sum: f32 = masses.iter().map(|m| m.q).sum();
        assert!((p_sum - 1.0).abs() < 1e-5 && (q_sum - 1.0).abs() < 1e-5);
        let p_where_q_zero: f32 = masses.iter().filter(|m| m.q == 0.0).map(|m| m.p).sum();
        assert!(p_where_q_zero > 0.02, "zeros on q do not drop the target-only mass");
        let p_where_q_pos: f32 = masses.iter().filter(|m| m.q > 0.0).map(|m| m.p).sum();
        assert!((p_where_q_zero + p_where_q_pos - 1.0).abs() < 1e-5);

        let n = 30_000u32;
        let mut counts = vec![0u32; target.len()];
        let mut draft_rng = Sampler::draft(TEMP, K, TOP_P, SOFTCAP, 0x51E3_0001);
        let mut rng = Sampler::draft(TEMP, K, TOP_P, SOFTCAP, 0x51E3_0003);
        for _ in 0..n {
            let x = draft_rng.sample(&draft);
            counts[rng.reject_one(x, &target, &draft) as usize] += 1;
        }
        assert!(counts[argmax as usize] > 0, "the residual draw can emit the target argmax");
        assert_eq!(counts[0], 0, "p=0 is not emitted, including a draft token the target dropped");
        assert_eq!(counts[150], 0, "outside the union is not emitted");
        let mut max_abs = 0.0f32;
        for &(tok, p) in &exp_p {
            let freq = counts[tok as usize] as f32 / n as f32;
            max_abs = max_abs.max((freq - p).abs());
        }
        for (tok, &c) in counts.iter().enumerate() {
            if c > 0 { assert!(exp_p.iter().any(|e| e.0 == tok as u32), "emitted {tok} is not in p"); }
        }
        assert!(max_abs < 0.012, "emitted distribution max |freq-p| {max_abs} over {n} draws");
    }

    #[test]
    fn verify_round_evaluates_supplied_draft_tokens_not_cpu_redraw() {
        let (target, draft) = logits();
        // Token 0 has p=0, q>0: must ALWAYS reject regardless of RNG and emit from target residual.
        let mut s1 = Sampler::new(TEMP, K, TOP_P, SOFTCAP, 0x1234);
        let out = s1.verify_round(&[0, 10], &[&target, &target, &target], &[&draft, &draft]);
        assert_eq!(out.len(), 1, "rejection on the first drafted token stops the round");
        assert_ne!(out[0], 0, "p(0)==0 must never be accepted");

        // Identical target & draft: p == q > 0 for drafted tokens 10 and 11, so BOTH exact drafted tokens
        // are accepted without consuming an acceptance uniform, followed by the bonus sample.
        let mut s2 = Sampler::new(TEMP, K, TOP_P, SOFTCAP, 0x5678);
        let out2 = s2.verify_round(&[10, 11], &[&target, &target, &target], &[&target, &target]);
        assert_eq!(out2.len(), 3);
        assert_eq!(&out2[..2], &[10, 11], "accepted tokens must be the exact supplied draft_tokens");
    }

    #[test]
    fn reject_one_respects_the_same_tied_top_k_cutoff_as_the_draft_sampler() {
        let target = [0.0, 0.0, 1.0];
        let draft = [1.0, 1.0, 1.0];
        let mut draw = Sampler::draft(1.0, 2, 1.0, 0.0, 23);
        let mut verify = Sampler::new(1.0, 2, 1.0, 0.0, 43);
        let mut direct = Sampler::new(1.0, 2, 1.0, 0.0, 43);
        let mut seen_verified = [false; 3];
        let mut seen_direct = [false; 3];
        for _ in 0..256 {
            let token = draw.sample(&draft);
            seen_verified[verify.reject_one(token, &target, &draft) as usize] = true;
            seen_direct[direct.sample(&target) as usize] = true;
        }
        assert_eq!(seen_direct, [true, false, true]);
        assert_eq!(seen_verified, seen_direct);
    }

    #[test]
    fn reject_one_uses_first_raw_argmax_at_near_zero_temperature() {
        // All three target logits saturate after softcap. The raw maximum is tied at 0 and 2.
        let target = [61.0, 60.0, 61.0];
        let draft = [0.0, 2.0, 1.0];
        let mut draw = Sampler::draft(1e-6, 3, 1.0, 1.0, 23);
        let mut verify = Sampler::new(1e-6, 3, 1.0, 1.0, 43);
        assert_eq!(draw.sample(&target), 0);
        for _ in 0..64 {
            let token = draw.sample(&draft);
            assert_eq!(token, 1);
            assert_eq!(verify.reject_one(token, &target, &draft), 0);
        }
    }

    #[test]
    fn tiny_temperature_never_panics_in_sample_or_verify_round() {
        let (target, draft) = logits();
        for temp in [1e-37_f32, f32::from_bits(1)] {
            let mut s = Sampler::new(temp, 8, 0.9, SOFTCAP, 7);
            assert_eq!(s.sample_next(&target), Ok(100));
            // draft argmax is 0 (where p=0), so verify_round rejects and draws from target argmax (100) without panicking.
            let out = s.verify_round(&[0], &[&target, &target], &[&draft]);
            assert_eq!(out, vec![100]);
            // identical rows accept the argmax draft token and emit the argmax bonus token.
            let out_same = s.verify_round(&[100], &[&target, &target], &[&target]);
            assert_eq!(out_same, vec![100, 100]);
        }
    }

    #[test]
    fn draft_sampler_mixed_once_per_request_not_reseeded_per_round() {
        let seed = 0xA11C_E5EDu64;
        let mut draft = Sampler::draft(TEMP, K, TOP_P, SOFTCAP, seed);
        let mixed = Sampler::new(TEMP, K, TOP_P, SOFTCAP, seed ^ DRAFT_SEED_MIX);
        assert_eq!(draft.state, mixed.state, "the mix is 0x85ebca6b, once");
        let target = Sampler::new(TEMP, K, TOP_P, SOFTCAP, seed);
        assert_ne!(draft.state, target.state, "the draft stream is not the stream that emits tokens");

        let (tg, dr) = logits();
        let target_state = target.state;
        let _ = draft.reject_one(0, &tg, &dr);
        assert_eq!(target.state, target_state, "rejection draws do not advance the emit stream");

        // identical logits: p == q, so the supplied draft tokens are accepted and one round emits the drafts plus the bonus
        let row = tg.clone();
        let drafted = [100u32, 10];
        let mut round = Sampler::draft(0.7, 8, 1.0, SOFTCAP, seed);
        let before = round.state;
        let out = round.verify_round(&drafted, &[&row, &row, &row], &[&row, &row]);
        assert_eq!(out.len(), 3, "one round may emit more than one token");
        assert_eq!(&out[..2], &drafted);
        assert_ne!(round.state, before);
        let mut continued = Sampler::draft(0.7, 8, 1.0, SOFTCAP, seed);
        let _ = continued.verify_round(&drafted, &[&row, &row, &row], &[&row, &row]);
        let after_first = continued.state;
        let second = continued.verify_round(&drafted, &[&row, &row, &row], &[&row, &row]);
        let mut reseeded = Sampler::draft(0.7, 8, 1.0, SOFTCAP, seed);
        let repeated = reseeded.verify_round(&drafted, &[&row, &row, &row], &[&row, &row]);
        assert_eq!(repeated, out, "the same request seed repeats the first round");
        assert_ne!(second, repeated, "the next round continues; it is not a reseed");
        assert_ne!(continued.state, after_first);
    }

    #[test]
    fn atanh_cutoff_and_ban_mask_preserve_distribution_and_support_full_vocab() {
        // Full-vocab (top_k = 0, top_p = 1.0) with softcap and deep tail logits
        let mut logits = vec![-100.0f32; 2048];
        logits[5] = 10.0;
        logits[42] = 9.5;
        logits[99] = 9.0;
        let mut s = Sampler::new(1.0, 0, 1.0, 20.0, 12345);
        assert!(s.uses_gpu_gumbel());
        assert!(!Sampler::new(1.0, 64, 0.95, 20.0, 12345).uses_gpu_gumbel());

        // Banning the top logit (5) must never emit token 5 in greedy or stochastic mode.
        let mut greedy = Sampler::new(0.0, 0, 1.0, 20.0, 1);
        assert_eq!(greedy.sample_next_with_ban(&logits, None), Ok(5));
        assert_eq!(greedy.sample_next_with_ban(&logits, Some(5)), Ok(42));
        for _ in 0..200 {
            let tok = s.sample_next_with_ban(&logits, Some(5)).unwrap();
            assert_ne!(tok, 5, "banned token must never be sampled");
            assert!(matches!(tok, 42 | 99), "atanh cutoff drops -100 tail cleanly, got {tok}");
        }
        // Banning the only candidate fails cleanly.
        assert!(greedy.sample_next_with_ban(&[1.0], Some(0)).is_err());
    }

    #[test]
    fn softcap_override_zero_matches_raw_softcapped_sampling() {
        let raw = [12.0f32, 11.2, 10.5, 4.0, -8.0, -30.0];
        let c = 20.0f32;
        let pre_capped: Vec<f32> = raw.iter().map(|&x| c * (x / c).tanh()).collect();
        let mut s_raw = Sampler::new(0.8, 4, 0.9, c, 0xCAFE_BABE);
        let mut s_pre = Sampler::new(0.8, 4, 0.9, c, 0xCAFE_BABE);
        for _ in 0..100 {
            let t1 = s_raw.sample_next_with_ban(&raw, Some(3)).unwrap();
            let t2 = s_pre.sample_next_with_ban_and_softcap(&pre_capped, Some(3), 0.0).unwrap();
            assert_eq!(t1, t2, "zero softcap override on pre-softcapped logits must match raw softcapped draw");
        }
    }

    #[test]
    fn top_k_selection_matches_full_sort_and_sampling_across_1000_rows() {
        fn full_sort_ref(cand: &[(f32, u32)], top_k: usize) -> Vec<(f32, u32)> {
            let mut out = cand.to_vec();
            out.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
            if top_k > 0 && out.len() > top_k {
                out.truncate(top_k);
            }
            out
        }

        fn sample_full_sort_ref(logits: &[f32], temp: f32, top_k: usize, top_p: f32, softcap: f32, state: &mut u64) -> u32 {
            let best_val = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
            let best_tok = logits.iter().position(|&x| x == best_val).unwrap() as u32;
            let capped = |x: f32| if softcap > 0.0 { softcap * (x / softcap).tanh() } else { x };
            let max_cap = capped(best_val);
            let scaled_max = max_cap / temp;
            let raw_cut = {
                let y = temp * (scaled_max - 30.0);
                let rc = if softcap <= 0.0 { y } else if y <= -softcap { f32::NEG_INFINITY } else { softcap * (y / softcap).atanh() };
                if rc.is_finite() { rc - 1e-3 * rc.abs() - 1e-3 } else { f32::NEG_INFINITY }
            };
            let mut cand: Vec<(f32, u32)> = logits.iter().enumerate()
                .filter(|&(_, &x)| x >= raw_cut)
                .map(|(i, &x)| (x, i as u32))
                .collect();
            if cand.is_empty() { cand.push((best_val, best_tok)); }
            cand = full_sort_ref(&cand, top_k);
            let mut p: Vec<f32> = cand.iter().map(|&(x, _)| (capped(x) / temp - scaled_max).exp()).collect();
            let sum: f32 = p.iter().sum();
            for v in &mut p { *v /= sum; }
            let mut cum = 0.0;
            let mut n = p.len();
            for (i, &v) in p.iter().enumerate() { cum += v; if cum >= top_p { n = i + 1; break; } }
            let total: f32 = p[..n].iter().sum();
            *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = *state;
            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 r = ((z >> 40) as f32 / (1u64 << 24) as f32) * total;
            let mut last = 0;
            for (i, &mass) in p[..n].iter().enumerate() {
                if mass == 0.0 { continue; }
                last = i;
                r -= mass;
                if r <= 0.0 { return cand[i].1; }
            }
            cand[last].1
        }

        let mut rng = 0xD1CE_5EED_1234_5678u64;
        let mut next_u64 = || {
            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 ks = [0usize, 1, 2, 7, 16, 64, 128, 300];
        for row_idx in 0..1_000usize {
            let vocab = 64 + (row_idx % 257);
            let mut row = Vec::with_capacity(vocab);
            for i in 0..vocab {
                let u = next_u64();
                let x = if row_idx % 5 == 0 {
                    // Heavy multi-way exact ties right across top_k boundaries (including -0.0 vs +0.0).
                    match u % 8 {
                        0 => -0.0f32,
                        1 => 0.0f32,
                        b => (b as f32) * 0.5,
                    }
                } else {
                    (((u & 0xFFFF) as f32) / 2048.0) - 16.0 + ((i % 7) as f32) * 0.25
                };
                row.push(x);
            }
            let top_k = ks[row_idx % ks.len()];
            let cand_in: Vec<(f32, u32)> = row.iter().enumerate().map(|(i, &x)| (x, i as u32)).collect();
            let mut got = cand_in.clone();
            truncate_and_sort_top_k(&mut got, top_k);
            let want = full_sort_ref(&cand_in, top_k);
            assert_eq!(got.len(), want.len(), "row {row_idx} k={top_k} len");
            for ((gx, gt), (wx, wt)) in got.iter().zip(&want) {
                assert_eq!((gx.to_bits(), *gt), (wx.to_bits(), *wt), "row {row_idx} k={top_k} order mismatch");
            }

            let seed = 0x1000_0000u64 + row_idx as u64;
            let temp = if row_idx % 3 == 0 { 0.7 } else { 1.1 };
            let top_p = if row_idx % 4 == 0 { 1.0 } else { 0.9 };
            let softcap = if row_idx % 2 == 0 { 20.0 } else { 0.0 };
            let mut sampler = Sampler::new(temp, top_k, top_p, softcap, seed);
            let mut ref_state = seed ^ 0x9E37_79B9_7F4A_7C15;
            let got_tok = sampler.sample_next(&row).unwrap();
            let want_tok = sample_full_sort_ref(&row, temp, top_k, top_p, softcap, &mut ref_state);
            assert_eq!(got_tok, want_tok, "row {row_idx} sampled token mismatch");
            assert_eq!(sampler.state, ref_state, "row {row_idx} RNG state mismatch");
        }
    }

    #[test]
    fn topk_list_sampling_matches_full_row_cpu_sampling_draw_for_draw() {
        let mut rng = 0x7A11_5EED_0000_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 vocabs = [1usize, 2, 3, 40, 64, 65, 66, 130, 1000];
        let (mut sampled, mut fallbacks) = (0usize, 0usize);
        for row_idx in 0..6000usize {
            let n = vocabs[row_idx % vocabs.len()];
            let style = (row_idx / vocabs.len()) % 4;
            let row: Vec<f32> = (0..n)
                .map(|i| {
                    let u = next();
                    match style {
                        // Exact ties across the top-k and top-p boundaries, +0.0 against -0.0.
                        0 => [0.0, -0.0, 0.0, -0.0, 3.0, 3.0, 1.5, -2.0][(u % 8) as usize],
                        1 => (((u & 0xFFFF) as f32) / 2048.0) - 16.0 + ((i % 7) as f32) * 0.25,
                        // One spike far above a flat floor (the 30-nat cut leaves fewer than k candidates).
                        2 => if u % 97 == 0 { 80.0 } else { -40.0 + (u % 3) as f32 },
                        _ => if u % 13 == 0 { f32::MIN } else { ((u % 5) as f32) * 7.5 },
                    }
                })
                .collect();
            let top_k = [1usize, 2, 7, 16, 63, 64][row_idx % 6];
            let top_p = [0.5f32, 0.9, 0.95, 1.0][(row_idx / 6) % 4];
            let temp = [0.0f32, 1e-6, 0.7, 1.1, 1e-5][(row_idx / 24) % 5];
            let softcap = [0.0f32, 20.0, 30.0][row_idx % 3];
            let ban = match row_idx % 5 {
                0 => None,
                1 => row.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map(|(i, _)| i as u32),
                _ => Some((next() % (n as u64 + 3)) as u32),
            };
            let seed = 0xABCD_0000 + row_idx as u64;
            let mut cpu = Sampler::new(temp, top_k, top_p, softcap, seed);
            let mut gpu = Sampler::new(temp, top_k, top_p, softcap, seed);
            assert!(gpu.uses_gpu_topk());
            let (bad, top) = topk_reference(&row);
            let want = cpu.sample_next_with_ban_and_softcap(&row, ban, softcap);
            match gpu.sample_next_from_topk(&top, n, bad, ban, softcap) {
                Ok(Some(tok)) => {
                    sampled += 1;
                    assert_eq!(Ok(tok), want, "row {row_idx} n={n} k={top_k} p={top_p} t={temp} ban={ban:?}");
                }
                Ok(None) => {
                    fallbacks += 1;
                    assert_eq!(gpu.state, seed ^ 0x9E37_79B9_7F4A_7C15, "row {row_idx}: fallback drew");
                    assert_eq!(gpu.sample_next_with_ban_and_softcap(&row, ban, softcap), want, "row {row_idx}");
                }
                Err(e) => assert_eq!(Err(e), want, "row {row_idx} error"),
            }
            assert_eq!(gpu.state, cpu.state, "row {row_idx} RNG state");
            assert_eq!(gpu.next_f32().to_bits(), cpu.next_f32().to_bits(), "row {row_idx} next draw");
        }
        assert!(sampled > 5000, "only {sampled} rows sampled from the list ({fallbacks} fallbacks)");

        // Non-finite logits fail exactly as the full scan does, before any draw.
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let mut row = vec![1.0f32; 200];
            row[150] = bad;
            let (nf, top) = topk_reference(&row);
            assert!(nf && top.len() == TOPK_CAND);
            let mut s = Sampler::new(0.8, 64, 0.95, 30.0, 9);
            let before = s.state;
            assert_eq!(s.sample_next_from_topk(&top, 200, nf, None, 30.0), Err("model returned non-finite logits"));
            assert_eq!(s.sample_next_with_ban_and_softcap(&row, None, 30.0), Err("model returned non-finite logits"));
            assert_eq!(s.state, before);
        }

        // Greedy over a run of exact maxima longer than the list: -0.0 at token 0 is the CPU's first
        // argmax but sorts after every +0.0, so the list cannot decide it and must hand back the row.
        let mut row = vec![0.0f32; 100];
        row[0] = -0.0;
        let (nf, top) = topk_reference(&row);
        let mut s = Sampler::new(0.0, 64, 0.95, 30.0, 9);
        assert_eq!(s.sample_next_from_topk(&top, 100, nf, None, 30.0), Ok(None));
        assert_eq!(s.sample_next_with_ban_and_softcap(&row, None, 30.0), Ok(0));
        // Same row sampled: the top-k support is the first 64 by total order, which the list holds.
        let mut a = Sampler::new(1.0, 64, 0.95, 30.0, 9);
        let mut b = Sampler::new(1.0, 64, 0.95, 30.0, 9);
        assert_eq!(a.sample_next_from_topk(&top, 100, nf, None, 30.0).unwrap(), b.sample_next(&row).ok());

        // A truncated or reordered list fails the request loudly.
        let mut s = Sampler::new(1.0, 64, 0.95, 30.0, 9);
        let (_, mut top) = topk_reference(&(0..100).map(|i| i as f32).collect::<Vec<_>>());
        top.swap(0, 1);
        assert_eq!(s.sample_next_from_topk(&top, 100, false, None, 30.0), Err("GPU top-k candidate list is malformed"));
        assert_eq!(s.sample_next_from_topk(&top[..10], 100, false, None, 30.0), Err("GPU top-k candidate list is malformed"));
        assert!(!Sampler::new(1.0, 0, 0.95, 30.0, 9).uses_gpu_topk());
        assert!(!Sampler::new(1.0, 65, 0.95, 30.0, 9).uses_gpu_topk());
        assert!(!Sampler::new(1.0, 0, 1.0, 30.0, 9).uses_gpu_topk());
    }

    #[test]
    fn sample_next_filtered_from_topk_matches_cpu_filtered_scan_bit_for_bit() {
        let mut rng = 0x5EED_CAFE_1234_5678u64;
        let mut next_u64 = || {
            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 fast_hits = 0usize;
        let mut fallbacks = 0usize;
        for row_idx in 0..600usize {
            let n = match row_idx % 8 {
                0 => 1,
                1 => 17,
                2 => TOPK_CAND,
                3 => TOPK_CAND + 1,
                _ => 80 + (next_u64() as usize % 320),
            };
            let mut row = Vec::with_capacity(n);
            let pattern = row_idx % 6;
            for i in 0..n {
                let v = match pattern {
                    // Steep peak so raw_cut rejects unseen tokens even with 1 allowed survivor.
                    0 => if i == (row_idx * 7) % n { 45.0 } else { -10.0 + ((next_u64() % 100) as f32) * 0.01 },
                    // Flat ties with +/-0.0.
                    1 => if next_u64() % 2 == 0 { 0.0 } else { -0.0 },
                    // Quantized buckets with many ties across the top-65 boundary.
                    2 => ((next_u64() % 7) as i32 - 3) as f32 * 0.5,
                    // Wide dynamic range.
                    3 => ((next_u64() % 4000) as f32 - 2000.0) * 0.025,
                    // Tight cluster near 0 (all pass raw_cut).
                    4 => ((next_u64() % 50) as f32) * 0.001,
                    // Descending with periodic spikes.
                    _ => -(i as f32) * 0.05 + if i % 19 == 0 { 8.0 } else { 0.0 },
                };
                row.push(v);
            }
            let (bad, top) = topk_reference(&row);
            let temp = [0.0f32, 1e-6, 0.2, 0.7, 1.0, 2.0][row_idx % 6];
            let top_k = if temp < 1e-5 && row_idx % 12 == 0 {
                0 // exercise greedy top_k=0 filtered fast path
            } else {
                [1usize, 2, 4, 8, 16, 64][(row_idx / 6) % 6]
            };
            let top_p = [0.1f32, 0.95, 1.0][(row_idx / 3) % 3];
            let softcap = if row_idx % 2 == 0 { 30.0 } else { 0.0 };
            let ban = match row_idx % 4 {
                0 => None,
                1 => Some(0),
                2 => Some(top[0].1),
                _ => Some((n - 1) as u32),
            };
            let mask_mode = row_idx % 7;
            let mask_salt = next_u64();
            let allow = |tok: u32| -> bool {
                match mask_mode {
                    0 => true,
                    1 => false,
                    2 => ((u64::from(tok).wrapping_mul(0x9E37_79B9) ^ mask_salt) % 10) < 9, // ~90% pass
                    3 => ((u64::from(tok).wrapping_mul(0x9E37_79B9) ^ mask_salt) % 2) == 0, // ~50% pass
                    4 => ((u64::from(tok).wrapping_mul(0x9E37_79B9) ^ mask_salt) % 16) == 0, // ~6% pass
                    5 => tok == top[top.len() / 2].1, // exactly 1 allowed token inside top
                    _ => !top.iter().any(|c| c.1 == tok), // 0 allowed in top, unseen allowed
                }
            };

            let seed = next_u64();
            let mut cpu = Sampler::new(temp, top_k, top_p, softcap, seed);
            let mut gpu = Sampler::new(temp, top_k, top_p, softcap, seed);
            assert!(gpu.uses_gpu_topk_filtered());
            let want = cpu.sample_next_filtered(&row, ban, softcap, allow);
            let state_before = gpu.state;
            match gpu.sample_next_filtered_from_topk(&top, n, bad, ban, softcap, allow) {
                Ok(Some(tok)) => {
                    fast_hits += 1;
                    assert_eq!(Ok(tok), want, "fast-path mismatch row={row_idx} n={n} k={top_k} t={temp} mask={mask_mode}");
                    assert_eq!(gpu.state, cpu.state, "RNG drift on fast path row={row_idx}");
                }
                Ok(None) => {
                    fallbacks += 1;
                    assert_eq!(gpu.state, state_before, "fallback must not consume RNG row={row_idx}");
                    let got = gpu.sample_next_filtered(&row, ban, softcap, allow);
                    assert_eq!(got, want, "fallback mismatch row={row_idx}");
                    assert_eq!(gpu.state, cpu.state, "RNG drift after fallback row={row_idx}");
                }
                Err(e) => {
                    assert_eq!(Err(e), want, "error mismatch row={row_idx}");
                    assert_eq!(gpu.state, state_before, "error must not consume RNG row={row_idx}");
                }
            }
        }
        assert!(fast_hits > 150, "expected substantial GPU top-k filtered hits, got {fast_hits}");
        assert!(fallbacks > 50, "expected fallback coverage too, got {fallbacks}");

        // Explicit steep-peak single-survivor check: top_k=64, only 1 token in top-65 is allowed,
        // but top.last().0 is far below raw_cut -> MUST resolve on GPU fast path WITHOUT fallback!
        let mut steep = vec![-50.0f32; 200];
        steep[137] = 10.0;
        let (nf, top) = topk_reference(&steep);
        let mut s_gpu = Sampler::new(0.8, 64, 0.95, 0.0, 42);
        let mut s_cpu = Sampler::new(0.8, 64, 0.95, 0.0, 42);
        let res = s_gpu.sample_next_filtered_from_topk(&top, 200, nf, None, 0.0, |id| id == 137);
        assert_eq!(res, Ok(Some(137)), "single confident allowed token must not trigger full CPU scan");
        assert_eq!(s_cpu.sample_next_filtered(&steep, None, 0.0, |id| id == 137), Ok(137));
        assert_eq!(s_gpu.state, s_cpu.state);

        // Explicit < top_k with unseen tokens ABOVE raw_cut -> MUST fall back (not drop unseen tokens!).
        let flat = vec![1.0f32; 200];
        let (nf, top) = topk_reference(&flat);
        let mut s_fb = Sampler::new(1.0, 10, 0.95, 0.0, 99);
        let before = s_fb.state;
        // Only 3 of the 65 entries pass allow, while unseen tokens also have logit 1.0 >= raw_cut.
        let fb = s_fb.sample_next_filtered_from_topk(&top, 200, nf, None, 0.0, |id| !(3..100).contains(&id));
        assert_eq!(fb, Ok(None), "must fall back when < top_k survive and unseen tokens pass raw_cut");
        assert_eq!(s_fb.state, before, "fallback must not consume RNG");

        // Greedy with top_k=0 and -0.0 unseen tie -> falls back cleanly; without tie -> fast path.
        let mut z = vec![0.0f32; 100];
        z[0] = -0.0;
        let (nf, top) = topk_reference(&z);
        let mut g0 = Sampler::new(0.0, 0, 1.0, 30.0, 7);
        assert!(g0.uses_gpu_topk_filtered());
        assert_eq!(g0.sample_next_filtered_from_topk(&top, 100, nf, None, 30.0, |_| true), Ok(None));
        assert_eq!(g0.sample_next_filtered(&z, None, 30.0, |_| true), Ok(0));
        // If token 77 strictly leads, greedy top_k=0 resolves on fast path!
        z[77] = 1.5;
        let (nf2, top2) = topk_reference(&z);
        assert_eq!(g0.sample_next_filtered_from_topk(&top2, 100, nf2, None, 30.0, |id| id == 77), Ok(Some(77)));
    }

    #[test]
    fn gpu_topk_tool_call_json_generation_matches_cpu_filtered_token_for_token() {
        use crate::json_grammar::{GrammarLimits, ToolCallGrammar, ToolCatalog, VocabBytes};

        const END_TOK: u32 = 0;
        const MSG_MODEL: u32 = 1;
        const C_TOOL: u32 = 2;
        const C_TEXT: u32 = 3;
        const C_THINK: u32 = 4;
        const END_SAMP: u32 = 5;
        const EOS: u32 = 6;

        // 128-token synthetic vocab (> TOPK_CAND=65) so unseen tokens always exist.
        let mut entries: Vec<Option<&[u8]>> = vec![
            None, None, None, None, None, None, None,
            Some(b"{"), Some(b"}"), Some(b"["), Some(b"]"), Some(b":"), Some(b","), Some(b"\""),
            Some(b" "), Some(b"\n"), Some(b"name"), Some(b"args"), Some(b"search"), Some(b"query"),
            Some(b"limit"), Some(b"true"), Some(b"false"), Some(b"null"), Some(b"0"), Some(b"1"),
            Some(b"42"), Some(b"-5"), Some(b"hello"), Some(b"world"), Some(b"\\n"), Some(b"\\\""),
            Some(b"a\"b"), Some(b"\x00"), Some(b"\"name\":\"search\""), Some(b",\"args\":{"),
        ];
        let fillers: Vec<Vec<u8>> = (0..96u8).map(|i| vec![b'a' + (i % 26), b'0' + (i % 10)]).collect();
        for f in &fillers {
            entries.push(Some(f.as_slice()));
        }
        let vocab = VocabBytes::from_test_entries(&entries);
        let n = entries.len();
        assert!(n > TOPK_CAND);

        let req = serde_json::json!({
            "tools": [{
                "type": "function",
                "function": {
                    "name": "search",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "query": { "type": "string" },
                            "limit": { "type": "integer" }
                        },
                        "required": ["query", "limit"],
                        "additionalProperties": false
                    }
                }
            }]
        });
        let catalog = ToolCatalog::from_request(&req).expect("catalog");
        let limits = GrammarLimits::adversarial_test();

        let mut rng = 0xD00D_F00D_1234_ABCDu64;
        let mut next_u64 = || {
            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 fast_steps = 0usize;
        let mut total_steps = 0usize;
        for trial in 0..20usize {
            let temp = [0.0f32, 0.7, 1.0, 1.2][trial % 4];
            let top_k = if temp == 0.0 && trial % 8 == 0 { 0 } else { 64 };
            let seed = 0x1000 + trial as u64;
            let mut s_cpu = Sampler::new(temp, top_k, 0.95, 30.0, seed);
            let mut s_gpu = Sampler::new(temp, top_k, 0.95, 30.0, seed);
            let mut g_cpu = ToolCallGrammar::new(catalog.clone()).with_limits(limits);
            let mut g_gpu = ToolCallGrammar::new(catalog.clone()).with_limits(limits);
            for tok in [MSG_MODEL, 18, C_TOOL] {
                g_cpu.observe_token(tok, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
                g_gpu.observe_token(tok, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
            }
            assert!(g_cpu.is_in_json() && g_gpu.is_in_json());

            for step in 0..64usize {
                if !g_cpu.is_in_json() {
                    break;
                }
                // Mix peaked (confident model) and noisy logits.
                let mut logits = vec![-25.0f32; n];
                let peaked = step % 2 == 0;
                for (i, x) in logits.iter_mut().enumerate() {
                    *x = if peaked {
                        -25.0 + ((next_u64() % 100) as f32) * 0.02
                    } else {
                        ((next_u64() % 400) as f32 - 200.0) * 0.05
                    };
                    if peaked && i < 36 && g_cpu.allows_token(i as u32, &vocab, END_TOK) {
                        *x = 12.0 + ((next_u64() % 50) as f32) * 0.05;
                    }
                }
                let (nf, top) = topk_reference(&logits);
                let tok_cpu = s_cpu
                    .sample_next_filtered(&logits, None, 30.0, |id| g_cpu.allows_token(id, &vocab, END_TOK))
                    .expect("cpu filtered sample");
                let tok_gpu = match s_gpu
                    .sample_next_filtered_from_topk(&top, n, nf, None, 30.0, |id| g_gpu.allows_token(id, &vocab, END_TOK))
                    .expect("gpu topk filtered sample")
                {
                    Some(t) => {
                        fast_steps += 1;
                        t
                    }
                    None => s_gpu
                        .sample_next_filtered(&logits, None, 30.0, |id| g_gpu.allows_token(id, &vocab, END_TOK))
                        .expect("gpu fallback sample"),
                };
                total_steps += 1;
                assert_eq!(tok_gpu, tok_cpu, "trial {trial} step {step}: token mismatch");
                assert_eq!(s_gpu.state, s_cpu.state, "trial {trial} step {step}: RNG mismatch");
                g_cpu.observe_token(tok_cpu, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
                g_gpu.observe_token(tok_gpu, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
            }
        }
        assert!(total_steps > 100);
        assert!(fast_steps * 2 > total_steps, "expected >50% GPU fast-path hits, got {fast_steps}/{total_steps}");
    }

    #[test]
    fn decode_topk_row_inverts_the_kernel_key() {
        let key = |x: f32| { let b = x.to_bits(); if b & 0x8000_0000 != 0 { !b } else { b | 0x8000_0000 } };
        let vals = [3.5f32, 0.0, -0.0, -1.0, f32::MIN, f32::MAX, f32::from_bits(1), -f32::from_bits(1)];
        let mut row = vec![0u32; 1 + 2 * TOPK_CAND];
        row[0] = 1;
        for (j, v) in vals.iter().enumerate() {
            row[1 + 2 * j] = key(*v);
            row[2 + 2 * j] = j as u32 + 10;
        }
        let (bad, got) = decode_topk_row(&row);
        assert!(bad);
        assert_eq!(got.len(), vals.len());
        for (j, (g, v)) in got.iter().zip(vals).enumerate() {
            assert_eq!((g.0.to_bits(), g.1), (v.to_bits(), j as u32 + 10));
        }
        // Unsigned key order is total_cmp order.
        for a in vals { for b in vals { assert_eq!(key(a).cmp(&key(b)), a.total_cmp(&b), "{a} vs {b}"); } }
    }

    #[test]
    fn checked_sampling_rejects_invalid_rows_without_advancing_rng() {
        let mut sampler = Sampler::new(0.5, 64, 1.0, 0.0, 7);
        let before = sampler.state;
        for row in [
            &[][..],
            &[1.0, f32::NAN],
            &[f32::INFINITY, 2.0],
            &[2.0, f32::NEG_INFINITY],
        ] {
            assert!(checked_argmax(row).is_err());
            assert!(sampler.sample_next(row).is_err());
            assert_eq!(sampler.state, before);
        }
        assert_eq!(checked_argmax(&[0.0, 2.0, 2.0]), Ok(1));
        assert!(sampler.sample_next(&[1.0, 2.0]).is_ok());
    }

    #[test]
    fn speculative_verification_matches_direct_sampling_at_topk_ties_and_controls() {
        const DRAWS: usize = 10_000;
        // 1. Tied top_k=3 boundary: token 1 leads (1.5), tokens 2, 3, 4, 5 tie at 0.9.
        //    Shared `(logit_desc, token_id_asc)` ordering must admit {1, 2, 3} and assign
        //    strictly zero probability to tokens 0, 4, and 5 in BOTH direct sampling and
        //    draft + verify_round, even when the draft model heavily favors tokens 4 and 5!
        let target_tied = [0.2f32, 1.5, 0.9, 0.9, 0.9, 0.9];
        let draft_adversarial = [0.1f32, 0.4, 0.5, 0.6, 2.4, 2.3];
        let mut direct_tied = [0usize; 6];
        let mut spec_tied = [0usize; 6];
        let mut direct_s = Sampler::new(0.8, 3, 1.0, SOFTCAP, 0xA11C_5EED);
        let mut draft_s = Sampler::draft(0.8, 6, 1.0, SOFTCAP, 0xB0BB_5EED);
        let mut verify_s = Sampler::new(0.8, 3, 1.0, SOFTCAP, 0xB0BB_5EED);
        for _ in 0..DRAWS {
            let d = direct_s.sample_next(&target_tied).unwrap() as usize;
            direct_tied[d] += 1;
            let proposed = draft_s.sample_next(&draft_adversarial).unwrap();
            let accepted = verify_s.verify_round(
                &[proposed],
                &[&target_tied, &target_tied],
                &[&draft_adversarial],
            );
            spec_tied[accepted[0] as usize] += 1;
        }
        for excluded in [0usize, 4, 5] {
            assert_eq!(direct_tied[excluded], 0, "direct sampled excluded tied token {excluded}");
            assert_eq!(spec_tied[excluded], 0, "speculative verify sampled excluded tied token {excluded}");
        }
        assert!(direct_tied[2] > 1_000 && direct_tied[3] > 1_000);
        for tok in 0..6 {
            let p_dir = direct_tied[tok] as f64 / DRAWS as f64;
            let p_spec = spec_tied[tok] as f64 / DRAWS as f64;
            assert!(
                (p_dir - p_spec).abs() < 0.025,
                "tied histogram mismatch at token {tok}: direct={p_dir:.4} vs spec={p_spec:.4}"
            );
        }

        // 2. Untied top_k=3 control across 10,000 draws.
        let target_untied = [0.2f32, 1.5, 1.1, 0.8, 0.4, 0.1];
        let mut direct_untied = [0usize; 6];
        let mut spec_untied = [0usize; 6];
        for _ in 0..DRAWS {
            direct_untied[direct_s.sample_next(&target_untied).unwrap() as usize] += 1;
            let proposed = draft_s.sample_next(&draft_adversarial).unwrap();
            let accepted = verify_s.verify_round(
                &[proposed],
                &[&target_untied, &target_untied],
                &[&draft_adversarial],
            );
            spec_untied[accepted[0] as usize] += 1;
        }
        for excluded in [0usize, 4, 5] {
            assert_eq!(direct_untied[excluded], 0);
            assert_eq!(spec_untied[excluded], 0);
        }
        for tok in 0..6 {
            let p_dir = direct_untied[tok] as f64 / DRAWS as f64;
            let p_spec = spec_untied[tok] as f64 / DRAWS as f64;
            assert!(
                (p_dir - p_spec).abs() < 0.025,
                "untied histogram mismatch at token {tok}: direct={p_dir:.4} vs spec={p_spec:.4}"
            );
        }

        // 3. Zero-temperature & near-zero temperature controls on tied and untied rows:
        //    lowest token ID wins deterministically across direct sampling, greedy verify, and near-zero verify_round.
        let mut z_direct = Sampler::new(0.0, 3, 1.0, SOFTCAP, 42);
        let mut nz_verify = Sampler::new(1e-6, 3, 1.0, SOFTCAP, 99);
        for (row, want_winner) in [
            (&[0.0f32, 2.0, 2.0, 2.0][..], 1u32),
            (&[0.0f32, 1.0, 3.0, 2.0][..], 2u32),
        ] {
            assert_eq!(checked_argmax(row), Ok(want_winner));
            assert_eq!(z_direct.sample_next(row), Ok(want_winner));
            for cand_draft in 0..4u32 {
                let g = crate::scheduler::accept_greedy(&[cand_draft], &[want_winner, want_winner], &[]);
                assert_eq!(g.emitted[0], want_winner);
                let out = nz_verify.verify_round(&[cand_draft], &[row, row], &[row]);
                assert_eq!(out[0], want_winner);
            }
        }
    }

    #[test]
    fn verify_round_with_ban_rejects_banned_draft_and_never_emits_banned_token() {
        let mut s = Sampler::new(1.0, 64, 0.95, 30.0, 777);
        // Token 2 (banned) overwhelmingly dominates both target and draft rows.
        let target = [1.0f32, 2.0, 20.0, 1.5];
        let draft = [1.0f32, 2.0, 20.0, 1.5];
        for _ in 0..200 {
            // Case A: drafter proposes the banned token 2 -> must reject and draw from {0, 1, 3}.
            let out_rej = s.verify_round_with_ban(&[2], &[&target, &target], &[&draft], Some(2));
            assert_eq!(out_rej.len(), 1);
            assert_ne!(out_rej[0], 2, "banned token must never be accepted or sampled in residual");

            // Case B: drafter proposes an allowed token 1 that is accepted -> bonus draw must also respect ban=Some(2).
            let target_bonus_ban = [0.0f32, 10.0, 25.0, 0.0];
            let draft_accept = [0.0f32, 10.0, 0.0, 0.0];
            let out_acc = s.verify_round_with_ban(&[1], &[&target_bonus_ban, &target], &[&draft_accept], Some(2));
            assert!(out_acc.iter().all(|&tok| tok != 2), "banned token must never be emitted in bonus draw: {out_acc:?}");
        }
    }
}