oxillama-runtime 0.1.0

Inference engine — KV cache, sampling, tokenizer bridge
Documentation
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
//! Sampling strategies for next-token selection.
//!
//! Supports greedy, top-k, top-p (nucleus), min-p, temperature scaling,
//! repetition penalty, Mirostat v2, and GBNF grammar-constrained sampling.

pub mod chain;
pub mod grammar;

use std::sync::Arc;

use serde::{Deserialize, Serialize};

use grammar::{apply_grammar_mask, Grammar, GrammarState};

/// Configuration for the sampling strategy.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamplerConfig {
    /// Temperature for logit scaling (1.0 = no scaling, 0.0 = greedy).
    pub temperature: f32,
    /// Top-K: only consider the K most likely tokens (0 = disabled).
    pub top_k: usize,
    /// Top-P (nucleus): only consider tokens with cumulative probability <= p.
    pub top_p: f32,
    /// Min-P: minimum probability threshold relative to the top token.
    pub min_p: f32,
    /// Repetition penalty factor (1.0 = no penalty).
    pub repetition_penalty: f32,
    /// Number of recent tokens to consider for repetition penalty.
    pub repetition_penalty_window: usize,
    /// Random seed for reproducible sampling (None = random).
    pub seed: Option<u64>,
    /// Mirostat mode: 0 = disabled, 2 = Mirostat v2.
    pub mirostat: u8,
    /// Mirostat target surprise (tau). Controls coherence vs diversity.
    /// Lower = more coherent, higher = more diverse. Default: 5.0.
    pub mirostat_tau: f32,
    /// Mirostat learning rate (eta). How fast the algorithm adapts. Default: 0.1.
    pub mirostat_eta: f32,

    /// Optional GBNF grammar for constrained sampling.
    /// Logits for tokens that cannot advance the grammar are set to -∞.
    /// Skipped during serialization (not representable as JSON directly).
    #[serde(skip)]
    pub grammar: Option<Arc<Grammar>>,

    /// Pre-computed vocabulary `(token_id, byte_repr)` table used for grammar masking.
    /// Must be set when `grammar` is `Some`. Build via `TokenizerBridge::vocab_bytes()`.
    #[serde(skip)]
    #[allow(clippy::type_complexity)]
    pub token_vocab: Option<Arc<Vec<(u32, Vec<u8>)>>>,
}

impl Default for SamplerConfig {
    fn default() -> Self {
        Self {
            temperature: 0.7,
            top_k: 40,
            top_p: 0.9,
            min_p: 0.0,
            repetition_penalty: 1.1,
            repetition_penalty_window: 64,
            seed: None,
            mirostat: 0,
            mirostat_tau: 5.0,
            mirostat_eta: 0.1,
            grammar: None,
            token_vocab: None,
        }
    }
}

impl SamplerConfig {
    /// Create a greedy sampling config (always pick the most likely token).
    pub fn greedy() -> Self {
        Self {
            temperature: 0.0,
            top_k: 1,
            top_p: 1.0,
            min_p: 0.0,
            repetition_penalty: 1.0,
            repetition_penalty_window: 0,
            seed: None,
            mirostat: 0,
            mirostat_tau: 5.0,
            mirostat_eta: 0.1,
            grammar: None,
            token_vocab: None,
        }
    }

    /// Create a Mirostat v2 config with the given target surprise.
    pub fn mirostat_v2(tau: f32, eta: f32) -> Self {
        Self {
            temperature: 1.0,
            mirostat: 2,
            mirostat_tau: tau,
            mirostat_eta: eta,
            top_k: 0,
            top_p: 1.0,
            min_p: 0.0,
            repetition_penalty: 1.0,
            repetition_penalty_window: 0,
            seed: None,
            grammar: None,
            token_vocab: None,
        }
    }
}

/// Stateful sampler that maintains PRNG state across calls.
pub struct Sampler {
    config: SamplerConfig,
    rng: Xorshift64,
    /// Mirostat v2 running estimate of surprise (mu).
    /// Initialized to 2 * tau, updated after each sample.
    mirostat_mu: f32,
    /// Current grammar parse state (None when no grammar is configured).
    grammar_state: Option<GrammarState>,
}

impl Sampler {
    /// Create a new sampler with the given config.
    pub fn new(config: SamplerConfig) -> Self {
        let seed = config.seed.unwrap_or_else(|| {
            // Use a time-based seed when no explicit seed is provided.
            // This is deterministic enough for inference; not for crypto.
            let mut s = 0x517cc1b727220a95u64;
            // Mix in some bits from the stack address for entropy
            s ^= (&s as *const u64 as u64).wrapping_mul(0x9e3779b97f4a7c15);
            s ^ s.wrapping_shr(33)
        });
        let mirostat_mu = 2.0 * config.mirostat_tau;
        let grammar_state = config.grammar.as_ref().map(|g| g.initial_state());
        Self {
            config,
            rng: Xorshift64::new(seed),
            mirostat_mu,
            grammar_state,
        }
    }

    /// Sample a token ID from logits.
    pub fn sample(&mut self, logits: &[f32], recent_tokens: &[u32]) -> u32 {
        let token = if self.config.mirostat == 2 {
            self.sample_mirostat_v2(logits, recent_tokens)
        } else {
            sample_with_rng(
                logits,
                &self.config,
                recent_tokens,
                &mut self.rng,
                self.grammar_state.as_ref(),
            )
        };

        // Advance grammar state after token selection.
        // We look up the token bytes in the pre-built vocab table (binary search by id).
        if let Some(state) = &mut self.grammar_state {
            if let Some(vocab) = &self.config.token_vocab {
                if let Ok(idx) = vocab.binary_search_by_key(&token, |&(id, _)| id) {
                    let bytes = vocab[idx].1.clone();
                    // Silently ignore advance errors — the mask will catch a stuck state
                    // on the next step and -inf all invalid tokens.
                    let _ = state.advance(&bytes);
                }
            }
        }

        token
    }

    /// Reset the grammar state to the beginning (use for a new generation).
    pub fn reset_grammar(&mut self) {
        self.grammar_state = self.config.grammar.as_ref().map(|g| g.initial_state());
    }

    /// Returns true when the grammar (if any) is in a valid accepting state.
    pub fn grammar_complete(&self) -> bool {
        self.grammar_state
            .as_ref()
            .is_none_or(GrammarState::is_complete)
    }

    /// Mirostat v2 sampling.
    ///
    /// Adaptively controls the "surprise" of generated tokens to maintain
    /// a target perplexity level (tau). This produces more coherent text
    /// than fixed top-k/top-p by dynamically adjusting the token pool.
    fn sample_mirostat_v2(&mut self, logits: &[f32], recent_tokens: &[u32]) -> u32 {
        if logits.is_empty() {
            return 0;
        }

        let mut processed = logits.to_vec();

        // Step 1: Apply repetition penalty
        apply_repetition_penalty(&mut processed, &self.config, recent_tokens);

        // Step 2: Apply grammar mask — BEFORE temperature and sorting.
        // Grammar masking must happen before any filtering so the constraint
        // is respected even in the greedy case.
        if let (Some(state), Some(vocab)) = (&self.grammar_state, &self.config.token_vocab) {
            apply_grammar_mask(&mut processed, state, vocab.as_ref());
        }

        // Step 3: Apply temperature
        if self.config.temperature > 0.0 && self.config.temperature != 1.0 {
            let inv_temp = 1.0 / self.config.temperature;
            for val in &mut processed {
                *val *= inv_temp;
            }
        }

        // Build sorted candidates with probabilities
        let mut candidates: Vec<(u32, f32)> = processed
            .iter()
            .enumerate()
            .map(|(i, &v)| (i as u32, v))
            .collect();
        candidates
            .sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        // Softmax to get probabilities
        softmax_candidates(&mut candidates);

        // Mirostat v2: filter tokens by surprise threshold
        // surprise(token) = -log2(prob)
        // Keep tokens where surprise <= mu
        let mu = self.mirostat_mu;
        candidates.retain(|&(_, p)| {
            if p <= 0.0 {
                return false;
            }
            let surprise = -p.log2();
            surprise <= mu
        });

        // Fallback: if all tokens filtered, keep the top one
        if candidates.is_empty() {
            let token = argmax(&processed);
            // Still update mu
            let top_prob = softmax_single_max(&processed);
            let surprise = if top_prob > 0.0 {
                -top_prob.log2()
            } else {
                self.config.mirostat_tau
            };
            self.mirostat_mu =
                mu - self.config.mirostat_eta * (surprise - self.config.mirostat_tau);
            return token;
        }

        // Re-normalize
        let total: f32 = candidates.iter().map(|(_, p)| p).sum();
        if total > 0.0 && total != 1.0 {
            for (_, p) in &mut candidates {
                *p /= total;
            }
        }

        // Sample from filtered candidates
        let r = self.rng.next_f32();
        let mut cumulative = 0.0f32;
        let mut selected_idx = candidates[0].0;
        let mut selected_prob = candidates[0].1 * total; // original probability
        for &(idx, prob) in &candidates {
            cumulative += prob;
            if r < cumulative {
                selected_idx = idx;
                selected_prob = prob * total;
                break;
            }
        }

        // Update mu: mu' = mu - eta * (surprise - tau)
        let surprise = if selected_prob > 0.0 {
            -selected_prob.log2()
        } else {
            self.config.mirostat_tau
        };
        self.mirostat_mu = mu - self.config.mirostat_eta * (surprise - self.config.mirostat_tau);

        selected_idx
    }

    /// Get a reference to the config.
    pub fn config(&self) -> &SamplerConfig {
        &self.config
    }
}

/// Sample a token ID from logits using the given configuration.
///
/// This is the stateless variant. Grammar state (if any in config) is ignored
/// because there is no place to persist it between calls. Use [`Sampler`] for
/// grammar-constrained generation.
///
/// # Arguments
/// * `logits` - Raw logits from the model (length = vocab_size).
/// * `config` - Sampling configuration.
/// * `recent_tokens` - Recent token history for repetition penalty.
///
/// # Returns
/// The selected token ID.
pub fn sample(logits: &[f32], config: &SamplerConfig, recent_tokens: &[u32]) -> u32 {
    if logits.is_empty() {
        return 0;
    }

    // For stateless API, create a one-shot RNG. Grammar state is not threaded
    // here — callers needing grammar must use `Sampler`.
    let seed = config.seed.unwrap_or(0xDEADBEEF_CAFEBABE);
    let mut rng = Xorshift64::new(seed);
    sample_with_rng(logits, config, recent_tokens, &mut rng, None)
}

/// Core sampling implementation with explicit RNG and optional grammar state.
fn sample_with_rng(
    logits: &[f32],
    config: &SamplerConfig,
    recent_tokens: &[u32],
    rng: &mut Xorshift64,
    grammar_state: Option<&GrammarState>,
) -> u32 {
    if logits.is_empty() {
        return 0;
    }

    let mut processed = logits.to_vec();

    // Step 1: Apply repetition penalty
    apply_repetition_penalty(&mut processed, config, recent_tokens);

    // Step 2: Apply grammar mask — BEFORE the greedy shortcut.
    // This ensures grammar constraints are enforced even at temperature=0.
    if let (Some(state), Some(vocab)) = (grammar_state, &config.token_vocab) {
        apply_grammar_mask(&mut processed, state, vocab.as_ref());
    }

    // Step 3: Greedy shortcut (after grammar mask)
    if config.temperature <= 0.0 || config.top_k == 1 {
        return argmax(&processed);
    }

    // Step 4: Temperature scaling
    if config.temperature != 1.0 {
        let inv_temp = 1.0 / config.temperature;
        for val in &mut processed {
            *val *= inv_temp;
        }
    }

    // Step 5: Build sorted (index, logit) candidates
    let mut candidates: Vec<(u32, f32)> = processed
        .iter()
        .enumerate()
        .map(|(i, &v)| (i as u32, v))
        .collect();
    candidates.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    // Step 6: Top-K filtering
    if config.top_k > 0 && config.top_k < candidates.len() {
        candidates.truncate(config.top_k);
    }

    // Step 7: Softmax over remaining candidates
    softmax_candidates(&mut candidates);

    // Step 8: Min-P filtering (remove tokens with prob < min_p * max_prob)
    if config.min_p > 0.0 && !candidates.is_empty() {
        let max_prob = candidates[0].1; // already sorted descending by probability
        let threshold = config.min_p * max_prob;
        candidates.retain(|&(_, p)| p >= threshold);
    }

    // Step 9: Top-P (nucleus) filtering
    if config.top_p < 1.0 && !candidates.is_empty() {
        let mut cumulative = 0.0f32;
        let mut cutoff = candidates.len();
        for (i, &(_, prob)) in candidates.iter().enumerate() {
            cumulative += prob;
            if cumulative >= config.top_p {
                cutoff = i + 1;
                break;
            }
        }
        candidates.truncate(cutoff);
    }

    // Step 10: Re-normalize after filtering
    let total: f32 = candidates.iter().map(|(_, p)| p).sum();
    if total > 0.0 && total != 1.0 {
        for (_, p) in &mut candidates {
            *p /= total;
        }
    }

    // Step 11: Weighted random selection
    if candidates.is_empty() {
        return argmax(&processed);
    }
    if candidates.len() == 1 {
        return candidates[0].0;
    }

    let r = rng.next_f32();
    let mut cumulative = 0.0f32;
    for &(idx, prob) in &candidates {
        cumulative += prob;
        if r < cumulative {
            return idx;
        }
    }

    // Fallback: return last candidate (rounding issues)
    candidates.last().map(|&(idx, _)| idx).unwrap_or(0)
}

/// Apply repetition penalty to logits in-place.
fn apply_repetition_penalty(processed: &mut [f32], config: &SamplerConfig, recent_tokens: &[u32]) {
    if config.repetition_penalty == 1.0 || recent_tokens.is_empty() {
        return;
    }

    let window_start = recent_tokens
        .len()
        .saturating_sub(config.repetition_penalty_window);
    for &token in &recent_tokens[window_start..] {
        let idx = token as usize;
        if idx < processed.len() {
            if processed[idx] > 0.0 {
                processed[idx] /= config.repetition_penalty;
            } else {
                processed[idx] *= config.repetition_penalty;
            }
        }
    }
}

/// Compute softmax over candidates in-place (replaces logits with probabilities).
fn softmax_candidates(candidates: &mut [(u32, f32)]) {
    if candidates.is_empty() {
        return;
    }

    let max_logit = candidates
        .iter()
        .map(|(_, v)| *v)
        .fold(f32::NEG_INFINITY, f32::max);

    let mut sum = 0.0f32;
    for (_, logit) in candidates.iter_mut() {
        *logit = (*logit - max_logit).exp();
        sum += *logit;
    }

    if sum > 0.0 {
        for (_, prob) in candidates.iter_mut() {
            *prob /= sum;
        }
    }
}

/// Compute the softmax probability of the maximum logit (for fallback).
fn softmax_single_max(logits: &[f32]) -> f32 {
    let max_val = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
    let sum: f32 = logits.iter().map(|&v| (v - max_val).exp()).sum();
    if sum > 0.0 {
        1.0 / sum
    } else {
        0.0
    }
}

/// Return the index of the maximum value.
fn argmax(values: &[f32]) -> u32 {
    let mut max_idx = 0u32;
    let mut max_val = f32::NEG_INFINITY;
    for (i, &v) in values.iter().enumerate() {
        if v > max_val {
            max_val = v;
            max_idx = i as u32;
        }
    }
    max_idx
}

/// Simple xorshift64 PRNG — fast, small, seedable, no dependencies.
struct Xorshift64 {
    state: u64,
}

impl Xorshift64 {
    fn new(seed: u64) -> Self {
        // Ensure non-zero state
        Self {
            state: if seed == 0 { 0x517cc1b727220a95 } else { seed },
        }
    }

    fn next_u64(&mut self) -> u64 {
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.state = x;
        x
    }

    /// Generate a uniform f32 in [0, 1).
    fn next_f32(&mut self) -> f32 {
        (self.next_u64() >> 40) as f32 / (1u64 << 24) as f32
    }
}

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

    #[test]
    fn test_greedy_sampling() {
        let logits = vec![0.1, 0.5, 0.3, 0.8, 0.2];
        let config = SamplerConfig::greedy();
        let token = sample(&logits, &config, &[]);
        assert_eq!(token, 3); // index of 0.8
    }

    #[test]
    fn test_empty_logits() {
        let logits: Vec<f32> = vec![];
        let config = SamplerConfig::greedy();
        let token = sample(&logits, &config, &[]);
        assert_eq!(token, 0);
    }

    #[test]
    fn test_temperature_zero_is_greedy() {
        let logits = vec![1.0, 5.0, 3.0, 2.0];
        let config = SamplerConfig {
            temperature: 0.0,
            ..SamplerConfig::default()
        };
        let token = sample(&logits, &config, &[]);
        assert_eq!(token, 1); // argmax
    }

    #[test]
    fn test_top_k_1_is_greedy() {
        let logits = vec![1.0, 5.0, 3.0, 2.0];
        let config = SamplerConfig {
            temperature: 1.0,
            top_k: 1,
            ..SamplerConfig::default()
        };
        let token = sample(&logits, &config, &[]);
        assert_eq!(token, 1);
    }

    #[test]
    fn test_seeded_determinism() {
        let logits = vec![1.0, 2.0, 3.0, 2.0, 1.0];
        let config = SamplerConfig {
            temperature: 1.0,
            top_k: 0,
            top_p: 1.0,
            min_p: 0.0,
            seed: Some(42),
            ..SamplerConfig::default()
        };

        let mut sampler1 = Sampler::new(config.clone());
        let mut sampler2 = Sampler::new(config);

        // Same seed should produce same sequence
        for _ in 0..10 {
            let t1 = sampler1.sample(&logits, &[]);
            let t2 = sampler2.sample(&logits, &[]);
            assert_eq!(t1, t2, "seeded samplers should produce identical results");
        }
    }

    #[test]
    fn test_top_p_filters_low_prob() {
        // One token has overwhelming probability
        let logits = vec![100.0, 0.0, 0.0, 0.0, 0.0];
        let config = SamplerConfig {
            temperature: 1.0,
            top_k: 0,
            top_p: 0.5,
            min_p: 0.0,
            seed: Some(123),
            ..SamplerConfig::default()
        };

        // With top_p=0.5, only the dominant token should remain
        let token = sample(&logits, &config, &[]);
        assert_eq!(token, 0);
    }

    #[test]
    fn test_repetition_penalty() {
        // Token 1 has highest logit but is in recent history
        let logits = vec![1.0, 5.0, 4.9, 1.0];
        let config = SamplerConfig {
            temperature: 0.0,          // greedy after penalty
            repetition_penalty: 100.0, // severe penalty
            repetition_penalty_window: 64,
            ..SamplerConfig::greedy()
        };

        // Without penalty, token 1 wins
        let token_no_penalty = sample(&logits, &SamplerConfig::greedy(), &[]);
        assert_eq!(token_no_penalty, 1);

        // With penalty on token 1, token 2 (4.9) should win
        let token_with_penalty = sample(&logits, &config, &[1]);
        assert_eq!(token_with_penalty, 2);
    }

    #[test]
    fn test_sampling_distribution() {
        // Verify that with temperature sampling, we don't always pick argmax
        let logits = vec![2.0, 2.0, 2.0, 2.0]; // equal logits
        let config = SamplerConfig {
            temperature: 1.0,
            top_k: 0,
            top_p: 1.0,
            min_p: 0.0,
            seed: Some(999),
            ..SamplerConfig::default()
        };

        let mut sampler = Sampler::new(config);
        let mut counts = [0u32; 4];
        for _ in 0..1000 {
            let t = sampler.sample(&logits, &[]);
            counts[t as usize] += 1;
        }

        // With equal logits, each token should get ~250 hits.
        // Allow generous margin (100-400).
        for (i, &count) in counts.iter().enumerate() {
            assert!(
                count > 100 && count < 400,
                "token {i} got {count} hits (expected ~250 for uniform distribution)"
            );
        }
    }

    #[test]
    fn test_min_p_filtering() {
        // One very likely token and several very unlikely ones
        let logits = vec![10.0, -10.0, -10.0, -10.0];
        let config = SamplerConfig {
            temperature: 1.0,
            top_k: 0,
            top_p: 1.0,
            min_p: 0.1, // require at least 10% of max prob
            seed: Some(42),
            ..SamplerConfig::default()
        };

        // The dominant token should always win after min_p filtering
        let mut sampler = Sampler::new(config);
        for _ in 0..100 {
            assert_eq!(sampler.sample(&logits, &[]), 0);
        }
    }

    #[test]
    fn test_xorshift_range() {
        let mut rng = Xorshift64::new(12345);
        for _ in 0..10000 {
            let v = rng.next_f32();
            assert!((0.0..1.0).contains(&v), "RNG produced {v} outside [0, 1)");
        }
    }

    #[test]
    fn test_mirostat_v2_basic() {
        // Mirostat v2 should produce valid tokens
        let logits = vec![3.0, 2.0, 1.0, 0.5, 0.1, -1.0, -2.0, -5.0];
        let config = SamplerConfig {
            seed: Some(42),
            ..SamplerConfig::mirostat_v2(5.0, 0.1)
        };
        let mut sampler = Sampler::new(config);

        for _ in 0..50 {
            let token = sampler.sample(&logits, &[]);
            assert!((token as usize) < logits.len());
        }
    }

    #[test]
    fn test_mirostat_v2_adapts_mu() {
        let logits = vec![5.0, 0.0, 0.0, 0.0];
        let config = SamplerConfig {
            seed: Some(123),
            ..SamplerConfig::mirostat_v2(3.0, 0.1)
        };
        let mut sampler = Sampler::new(config);
        let initial_mu = sampler.mirostat_mu;

        // After sampling, mu should change
        sampler.sample(&logits, &[]);
        assert!(
            (sampler.mirostat_mu - initial_mu).abs() > 1e-6,
            "mu should adapt after sampling"
        );
    }

    #[test]
    fn test_mirostat_v2_low_tau_prefers_top() {
        // Very low tau = very low target surprise = prefer high-probability tokens
        let logits = vec![10.0, 0.0, 0.0, 0.0, 0.0];
        let config = SamplerConfig {
            seed: Some(42),
            ..SamplerConfig::mirostat_v2(0.5, 0.1) // very low tau
        };
        let mut sampler = Sampler::new(config);

        let mut top_count = 0;
        for _ in 0..100 {
            if sampler.sample(&logits, &[]) == 0 {
                top_count += 1;
            }
        }
        // With tau=0.5, should almost always pick the top token
        assert!(
            top_count > 90,
            "low tau should strongly prefer top token, got {top_count}/100"
        );
    }

    #[test]
    fn test_mirostat_v2_deterministic_with_seed() {
        let logits = vec![2.0, 1.5, 1.0, 0.5];
        let config = SamplerConfig {
            seed: Some(777),
            ..SamplerConfig::mirostat_v2(5.0, 0.1)
        };

        let mut sampler1 = Sampler::new(config.clone());
        let mut sampler2 = Sampler::new(config);

        for _ in 0..20 {
            assert_eq!(
                sampler1.sample(&logits, &[]),
                sampler2.sample(&logits, &[]),
                "same seed should produce same sequence"
            );
        }
    }

    #[test]
    fn test_softmax_candidates_basic() {
        let mut candidates = vec![(0, 0.0f32), (1, 0.0), (2, 0.0)];
        softmax_candidates(&mut candidates);
        // Equal logits → equal probabilities
        for &(_, p) in &candidates {
            assert!((p - 1.0 / 3.0).abs() < 0.01, "expected ~0.333, got {p}");
        }
    }

    // ── Grammar-constrained sampling tests ────────────────────────────────────

    #[test]
    fn test_grammar_constrained_yes_no() {
        let g = Grammar::parse(r#"root ::= "yes" | "no""#).unwrap();
        let state = g.initial_state();
        assert!(state.allows_token(b"yes"));
        assert!(state.allows_token(b"no"));
        assert!(!state.allows_token(b"maybe"));
    }

    #[test]
    fn test_grammar_sampler_masks_logits() {
        // Vocab: 0="maybe", 1="yes", 2="no"
        let vocab: Vec<(u32, Vec<u8>)> = vec![
            (0, b"maybe".to_vec()),
            (1, b"yes".to_vec()),
            (2, b"no".to_vec()),
        ];
        let g = Arc::new(Grammar::parse(r#"root ::= "yes" | "no""#).unwrap());
        let config = SamplerConfig {
            temperature: 0.0, // greedy — must pick grammar-compliant token
            grammar: Some(g),
            token_vocab: Some(Arc::new(vocab)),
            ..SamplerConfig::default()
        };

        // Give "maybe" the highest logit — grammar must mask it away
        let logits = vec![100.0f32, 1.0, 1.0];
        let mut sampler = Sampler::new(config);
        let tok = sampler.sample(&logits, &[]);
        // After masking, only "yes"(1) or "no"(2) remain
        assert!(tok == 1 || tok == 2, "expected yes(1) or no(2), got {tok}");
    }

    #[test]
    fn test_grammar_state_advances_through_sequence() {
        let vocab: Vec<(u32, Vec<u8>)> =
            vec![(0, b"a".to_vec()), (1, b"b".to_vec()), (2, b"c".to_vec())];
        let g = Arc::new(Grammar::parse(r#"root ::= "a" "b""#).unwrap());
        let config = SamplerConfig {
            temperature: 0.0,
            grammar: Some(g),
            token_vocab: Some(Arc::new(vocab)),
            ..SamplerConfig::default()
        };

        // Equal logits — grammar drives selection
        let logits = vec![1.0f32, 0.5, 0.5];
        let mut sampler = Sampler::new(config);

        // First step: only "a" is valid
        let tok1 = sampler.sample(&logits, &[]);
        assert_eq!(tok1, 0, "first token must be 'a' (id=0)");

        // Second step: only "b" is valid
        let tok2 = sampler.sample(&logits, &[0]);
        assert_eq!(tok2, 1, "second token must be 'b' (id=1)");

        assert!(
            sampler.grammar_complete(),
            "grammar should be complete after 'a' + 'b'"
        );
    }

    #[test]
    fn test_grammar_parse_roundtrip() {
        let g = Grammar::parse("root ::= [a-z]+ \":\" [0-9]+").unwrap();
        assert!(!g.rules.is_empty());
        assert_eq!(g.root, "root");
    }

    #[test]
    fn test_grammar_stuck_state_masks_all() {
        // A grammar that requires "x" — advancing with "y" must produce an error
        let g = Arc::new(Grammar::parse(r#"root ::= "x""#).unwrap());
        let mut state = g.initial_state();
        let result = state.advance(b"y");
        assert!(result.is_err(), "advancing with wrong bytes should error");
    }
}