Skip to main content

cortiq_engine/
sampler.rs

1//! Token sampling — temperature, top-p, top-k, min-p, repetition penalty.
2//!
3//! Randomness comes from an explicit SplitMix64 PRNG carried by the
4//! caller: reproducible with a seed, unbiased across the whole CDF
5//! (the v1 `subsec_nanos` source could never pick past ~23% of it).
6
7use serde::{Deserialize, Serialize};
8
9/// SplitMix64 — tiny, fast, statistically solid for sampling.
10#[derive(Debug, Clone)]
11pub struct SplitMix64 {
12    state: u64,
13}
14
15impl SplitMix64 {
16    pub fn new(seed: u64) -> Self {
17        Self { state: seed }
18    }
19
20    /// Seed from OS entropy (address-space + time mix) when none given.
21    pub fn from_entropy() -> Self {
22        let t = std::time::SystemTime::now()
23            .duration_since(std::time::UNIX_EPOCH)
24            .unwrap_or_default();
25        let addr = Box::into_raw(Box::new(0u8)) as u64;
26        // SAFETY: pointer came from Box::into_raw just above.
27        unsafe { drop(Box::from_raw(addr as *mut u8)) };
28        Self::new(t.as_nanos() as u64 ^ addr.rotate_left(17) ^ 0x9E3779B97F4A7C15)
29    }
30
31    #[inline]
32    pub fn next_u64(&mut self) -> u64 {
33        self.state = self.state.wrapping_add(0x9E3779B97F4A7C15);
34        let mut z = self.state;
35        z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
36        z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
37        z ^ (z >> 31)
38    }
39
40    /// Uniform f32 in [0, 1).
41    #[inline]
42    pub fn next_f32(&mut self) -> f32 {
43        (self.next_u64() >> 40) as f32 / (1u64 << 24) as f32
44    }
45}
46
47/// Sampling configuration.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct SamplerConfig {
50    pub temperature: f32,
51    pub top_p: f32,
52    pub top_k: u32,
53    pub repetition_penalty: f32,
54    pub min_p: f32,
55    /// Fixed seed for reproducible generation (None = entropy).
56    #[serde(default)]
57    pub seed: Option<u64>,
58}
59
60impl Default for SamplerConfig {
61    fn default() -> Self {
62        Self {
63            temperature: 0.7,
64            top_p: 0.9,
65            top_k: 40,
66            repetition_penalty: 1.1,
67            min_p: 0.05,
68            seed: None,
69        }
70    }
71}
72
73/// Sample next token from logits. Chain order is fixed:
74/// rep-penalty → temperature → softmax → min-p → top-k → top-p → sample.
75pub fn sample(
76    logits: &[f32],
77    config: &SamplerConfig,
78    past_tokens: &[u32],
79    rng: &mut SplitMix64,
80) -> u32 {
81    let mut probs = logits.to_vec();
82
83    if config.repetition_penalty != 1.0 {
84        apply_repetition_penalty(&mut probs, past_tokens, config.repetition_penalty);
85    }
86
87    if config.temperature < 1e-6 {
88        return argmax(&probs); // greedy
89    }
90    if config.temperature != 1.0 {
91        for p in probs.iter_mut() {
92            *p /= config.temperature;
93        }
94    }
95
96    softmax_inplace(&mut probs);
97
98    if config.min_p > 0.0 {
99        let max_prob = probs.iter().cloned().fold(0.0f32, f32::max);
100        let threshold = max_prob * config.min_p;
101        for p in probs.iter_mut() {
102            if *p < threshold {
103                *p = 0.0;
104            }
105        }
106    }
107
108    if config.top_k > 0 && (config.top_k as usize) < probs.len() {
109        apply_top_k(&mut probs, config.top_k as usize);
110    }
111
112    if config.top_p < 1.0 && config.top_p > 0.0 {
113        apply_top_p(&mut probs, config.top_p);
114    }
115
116    let sum: f32 = probs.iter().sum();
117    if sum > 0.0 {
118        for p in probs.iter_mut() {
119            *p /= sum;
120        }
121    } else {
122        // Everything filtered out — fall back to greedy over original logits.
123        return argmax(logits);
124    }
125
126    categorical_sample(&probs, rng.next_f32())
127}
128
129/// Greedy: index of the maximum value.
130pub fn argmax(values: &[f32]) -> u32 {
131    values
132        .iter()
133        .enumerate()
134        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
135        .map(|(i, _)| i as u32)
136        .unwrap_or(0)
137}
138
139fn softmax_inplace(logits: &mut [f32]) {
140    let max_val = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
141    let mut sum = 0.0f32;
142    for v in logits.iter_mut() {
143        *v = (*v - max_val).exp();
144        sum += *v;
145    }
146    if sum > 0.0 {
147        for v in logits.iter_mut() {
148            *v /= sum;
149        }
150    }
151}
152
153fn apply_repetition_penalty(logits: &mut [f32], past_tokens: &[u32], penalty: f32) {
154    for &tok in past_tokens {
155        let idx = tok as usize;
156        if idx < logits.len() {
157            if logits[idx] > 0.0 {
158                logits[idx] /= penalty;
159            } else {
160                logits[idx] *= penalty;
161            }
162        }
163    }
164}
165
166/// Keep the k highest-probability tokens (plus exact ties at the
167/// threshold), zero the rest.
168fn apply_top_k(probs: &mut [f32], k: usize) {
169    if k == 0 || k >= probs.len() {
170        return;
171    }
172    let mut sorted: Vec<f32> = probs.to_vec();
173    sorted.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
174    let threshold = sorted[k - 1];
175    for p in probs.iter_mut() {
176        if *p < threshold {
177            *p = 0.0;
178        }
179    }
180}
181
182/// Nucleus: keep the smallest prefix of tokens whose cumulative
183/// probability reaches top_p.
184fn apply_top_p(probs: &mut [f32], top_p: f32) {
185    let mut indexed: Vec<(usize, f32)> = probs.iter().copied().enumerate().collect();
186    indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
187
188    let mut cumsum = 0.0f32;
189    let mut cutoff_idx = indexed.len();
190    for (i, &(_, prob)) in indexed.iter().enumerate() {
191        cumsum += prob;
192        if cumsum >= top_p {
193            cutoff_idx = i + 1;
194            break;
195        }
196    }
197
198    let kept: std::collections::HashSet<usize> =
199        indexed[..cutoff_idx].iter().map(|&(i, _)| i).collect();
200    for (i, p) in probs.iter_mut().enumerate() {
201        if !kept.contains(&i) {
202            *p = 0.0;
203        }
204    }
205}
206
207/// Inverse-CDF sampling with an externally supplied uniform r ∈ [0, 1).
208fn categorical_sample(probs: &[f32], r: f32) -> u32 {
209    let mut cumsum = 0.0f32;
210    for (i, &p) in probs.iter().enumerate() {
211        cumsum += p;
212        if r < cumsum {
213            return i as u32;
214        }
215    }
216    probs.iter().rposition(|&p| p > 0.0).unwrap_or(0) as u32
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn test_argmax() {
225        let logits = vec![0.1, 0.5, 0.3, 0.9, 0.2];
226        assert_eq!(argmax(&logits), 3);
227    }
228
229    #[test]
230    fn test_greedy_sampling() {
231        let logits = vec![1.0, 5.0, 2.0, 3.0];
232        let config = SamplerConfig {
233            temperature: 0.0,
234            ..Default::default()
235        };
236        let mut rng = SplitMix64::new(1);
237        assert_eq!(sample(&logits, &config, &[], &mut rng), 1);
238    }
239
240    #[test]
241    fn test_softmax() {
242        let mut logits = vec![1.0, 2.0, 3.0];
243        softmax_inplace(&mut logits);
244        let sum: f32 = logits.iter().sum();
245        assert!((sum - 1.0).abs() < 1e-5);
246        assert!(logits[2] > logits[1] && logits[1] > logits[0]);
247    }
248
249    #[test]
250    fn test_repetition_penalty() {
251        let mut logits = vec![1.0, 2.0, 3.0, 4.0];
252        apply_repetition_penalty(&mut logits, &[1, 3], 2.0);
253        assert_eq!(logits, vec![1.0, 1.0, 3.0, 2.0]);
254    }
255
256    #[test]
257    fn top_k_keeps_exactly_k() {
258        let mut probs = vec![0.1, 0.4, 0.05, 0.3, 0.15];
259        apply_top_k(&mut probs, 2);
260        let kept = probs.iter().filter(|&&p| p > 0.0).count();
261        assert_eq!(kept, 2, "top-k must keep exactly k (was k+1 in v1)");
262        assert!(probs[1] > 0.0 && probs[3] > 0.0);
263    }
264
265    #[test]
266    fn rng_reaches_full_cdf() {
267        // v1 bug: r < 0.233 always, so the CDF tail was unreachable.
268        // With uniform probs the LAST index must be sampled sometimes.
269        let probs = vec![0.25f32; 4];
270        let mut rng = SplitMix64::new(42);
271        let mut hits = [0usize; 4];
272        for _ in 0..4000 {
273            let i = categorical_sample(&probs, rng.next_f32()) as usize;
274            hits[i] += 1;
275        }
276        for (i, &h) in hits.iter().enumerate() {
277            assert!(h > 700, "index {i} sampled only {h}/4000 — biased RNG");
278        }
279    }
280
281    #[test]
282    fn same_seed_same_sequence() {
283        let logits: Vec<f32> = (0..32).map(|i| (i as f32 * 0.37).sin()).collect();
284        let config = SamplerConfig {
285            temperature: 1.0,
286            seed: Some(7),
287            ..Default::default()
288        };
289        let run = |seed: u64| -> Vec<u32> {
290            let mut rng = SplitMix64::new(seed);
291            (0..16).map(|_| sample(&logits, &config, &[], &mut rng)).collect()
292        };
293        assert_eq!(run(7), run(7), "same seed must reproduce");
294        assert_ne!(run(7), run(8), "different seed must differ");
295    }
296}