inky-engine 0.1.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple Silicon M5 Macs (Metal 4)
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
//! CPU sampler over the GPU logits: softcap -> top-k -> temperature -> top-p -> draw.

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)
    }

    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> {
        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"); }
            if Some(i as u32) == ban { continue; }
            if best.is_none_or(|(b, _)| x > b) { best = Some((x, i as u32)); }
        }
        let Some((best_val, best_tok)) = best else { return Err("no sampling candidates") };
        if self.greedy() || self.temp < 1e-5 {
            return Ok(best_tok);
        }
        if !self.softcap.is_finite() || !self.top_p.is_finite() {
            return Err("invalid sampling parameters");
        }
        let c = self.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;
        // 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
        };
        self.cand.clear();
        for (i, &x) in logits.iter().enumerate() {
            if Some(i as u32) != ban && x >= raw_cut {
                self.cand.push((x, i as u32));
            }
        }
        if self.cand.is_empty() {
            self.cand.push((best_val, best_tok));
        }
        self.cand.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
        if self.top_k > 0 && self.cand.len() > self.top_k {
            self.cand.truncate(self.top_k);
        }
        let mut p: Vec<f32> = self.cand.iter().map(|&(x, _)| {
            let x = capped(x);
            let centered = if scaled_max.is_finite() { x / t - scaled_max } else { (x - max_cap) / t };
            centered.exp()
        }).collect();
        let sum: f32 = p.iter().sum();
        if !sum.is_finite() || sum <= 0.0 { return Err("model returned invalid sampling probabilities"); }
        for v in p.iter_mut() { *v /= sum; }
        // top-p cut
        let mut cum = 0.0;
        let mut n = p.len();
        for (i, &v) in p.iter().enumerate() { cum += v; if cum >= self.top_p { n = i + 1; break; } }
        let total: f32 = p[..n].iter().sum();
        let mut r = self.next_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 Ok(self.cand[i].1); }
        }
        Ok(self.cand[last].1)
    }

    /// 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).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> {
        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]);
            out.push(tok);
            if !accepted { return out; }
        }
        out.push(self.sample(target_rows[draft_rows.len()]));
        out
    }

    fn reject_at(&mut self, draft_tok: u32, target: &[f32], draft: &[f32]) -> (u32, bool) {
        assert!(self.temp > 0.0, "greedy does not reject");
        let masses = self.masses(target, draft);
        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 {
        assert!(!dist.is_empty(), "empty sampling distribution");
        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; }
        }
        dist[dist.len() - 1].0
    }

    /// p and q on the union of the two top-k sets, after softcap-after-top-k, `/temp`, and top-p.
    /// A token the other side alone kept is present with a zero. Neither side is renormalized for that zero.
    fn masses(&self, target: &[f32], draft: &[f32]) -> Vec<Mass> {
        let k = if self.top_k == 0 { target.len().max(draft.len()) } else { self.top_k };
        let mut target_kept = Vec::new();
        let mut draft_kept = Vec::new();
        select_top_k(target, k.min(target.len()), &mut target_kept).expect("invalid target sampling row");
        select_top_k(draft, k.min(draft.len()), &mut draft_kept).expect("invalid draft sampling row");
        let draft_ids: Vec<u32> = draft_kept.iter().map(|c| c.1).collect();
        let target_ids: Vec<u32> = target_kept.iter().map(|c| c.1).collect();
        // zeros of the other side sit on the support, after this side's own top-k, and do not enter its softmax
        let p_rows = side_probs(&mut target_kept, &draft_ids, self.softcap, self.temp, self.top_p);
        let q_rows = side_probs(&mut draft_kept, &target_ids, self.softcap, self.temp, self.top_p);
        let mut by_token: Vec<Mass> = Vec::new();
        for (tok, pr) in p_rows {
            match by_token.iter_mut().find(|m| m.token == tok) {
                Some(m) => m.p = pr,
                None => by_token.push(Mass { token: tok, p: pr, q: 0.0 }),
            }
        }
        for (tok, pr) in q_rows {
            match by_token.iter_mut().find(|m| m.token == tok) {
                Some(m) => m.q = pr,
                None => by_token.push(Mass { token: tok, p: 0.0, q: pr }),
            }
        }
        by_token.sort_by_key(|m| m.token);
        by_token
    }
}

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

struct Mass { token: u32, p: f32, q: f32 }

fn select_top_k(logits: &[f32], k: usize, cand: &mut Vec<(f32, u32)>) -> Result<(), &'static str> {
    if k == 0 { return Err("no sampling candidates"); }
    cand.clear();
    let mut floor = 0;
    for (i, &x) in logits.iter().enumerate() {
        if !x.is_finite() { return Err("model returned non-finite logits"); }
        if cand.len() < k {
            let j = cand.len();
            cand.push((x, i as u32));
            if x < cand[floor].0 { floor = j; }
        } else if x > cand[floor].0 {
            cand[floor] = (x, i as u32);
            floor = 0;
            for j in 1..k {
                if cand[j].0 < cand[floor].0 { floor = j; }
            }
        }
    }
    Ok(())
}

/// Softcap after the top-k cut, then `/temp`, then the same top-p. `zeros` are the other side's
/// top-k tokens: they extend the support with probability 0 and are not in the softmax.
fn side_probs(cand: &mut Vec<(f32, u32)>, zeros: &[u32], softcap: f32, temp: f32, top_p: f32) -> Vec<(u32, f32)> {
    if cand.is_empty() { return Vec::new(); }
    cand.sort_by(|a, b| b.0.total_cmp(&a.0));
    let capped = |x: f32| if softcap > 0.0 { softcap * (x / softcap).tanh() } else { x };
    let max = capped(cand[0].0);
    let scaled_max = max / temp;
    let mut pr: Vec<f32> = cand.iter().map(|&(x, _)| {
        let x = capped(x);
        if temp < 1e-5 {
            if x == max { 1.0 } else { 0.0 }
        } else {
            let centered = if scaled_max.is_finite() { x / temp - scaled_max } else { (x - max) / temp };
            centered.exp()
        }
    }).collect();
    let sum: f32 = pr.iter().sum();
    for v in pr.iter_mut() { *v /= sum; }
    let mut rows: Vec<(u32, f32)> = cand.iter().zip(pr).map(|(&(_, tok), p)| (tok, p)).collect();
    for &tok in zeros {
        if !rows.iter().any(|r| r.0 == tok) { rows.push((tok, 0.0)); }
    }
    let mut cum = 0.0;
    let mut n = rows.len();
    for (i, &(_, v)) in rows.iter().enumerate() {
        cum += v;
        if cum >= top_p { n = i + 1; break; }
    }
    let total: f32 = rows[..n].iter().map(|r| r.1).sum();
    let mut out = Vec::with_capacity(n);
    if total > 0.0 {
        for (tok, p) in rows.into_iter().take(n) {
            if p > 0.0 { out.push((tok, p / total)); }
        }
    }
    out
}

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 in 0..64 { draft[i] = 6.0 - i as f32 * 0.01; }
        target[100] = 5.0;
        for i in 10..73 { target[i] = 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]
    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 sampler = Sampler::new(TEMP, K, TOP_P, SOFTCAP, 1);
        let masses = sampler.masses(&target, &draft);
        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 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());
    }
}