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. Selection, not a full vocab sort — the
168/// old double `sort_by` over ~150k probs was ~1ms of pure per-token
169/// overhead (roadmap §3 P0).
170fn apply_top_k(probs: &mut [f32], k: usize) {
171    if k == 0 || k >= probs.len() {
172        return;
173    }
174    let mut sel: Vec<f32> = probs.to_vec();
175    // k-th largest = (k-1)-th index in a descending partition.
176    let (_, kth, _) = sel.select_nth_unstable_by(k - 1, |a, b| {
177        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
178    });
179    let threshold = *kth;
180    for p in probs.iter_mut() {
181        if *p < threshold {
182            *p = 0.0;
183        }
184    }
185}
186
187/// Nucleus: keep the smallest prefix of tokens whose cumulative
188/// probability reaches top_p. Only surviving (non-zero) candidates are
189/// sorted — after top-k that is ≤ k elements, not the whole vocab; the
190/// kept set is marked in-place instead of a per-token HashSet.
191fn apply_top_p(probs: &mut [f32], top_p: f32) {
192    let mut indexed: Vec<(usize, f32)> = probs
193        .iter()
194        .copied()
195        .enumerate()
196        .filter(|&(_, p)| p > 0.0)
197        .collect();
198    indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
199
200    let mut cumsum = 0.0f32;
201    let mut cutoff_idx = indexed.len();
202    for (i, &(_, prob)) in indexed.iter().enumerate() {
203        cumsum += prob;
204        if cumsum >= top_p {
205            cutoff_idx = i + 1;
206            break;
207        }
208    }
209
210    // Zero the dropped tail directly — indices, not membership tests.
211    for &(i, _) in &indexed[cutoff_idx..] {
212        probs[i] = 0.0;
213    }
214}
215
216/// Inverse-CDF sampling with an externally supplied uniform r ∈ [0, 1).
217fn categorical_sample(probs: &[f32], r: f32) -> u32 {
218    let mut cumsum = 0.0f32;
219    for (i, &p) in probs.iter().enumerate() {
220        cumsum += p;
221        if r < cumsum {
222            return i as u32;
223        }
224    }
225    probs.iter().rposition(|&p| p > 0.0).unwrap_or(0) as u32
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn test_argmax() {
234        let logits = vec![0.1, 0.5, 0.3, 0.9, 0.2];
235        assert_eq!(argmax(&logits), 3);
236    }
237
238    #[test]
239    fn test_greedy_sampling() {
240        let logits = vec![1.0, 5.0, 2.0, 3.0];
241        let config = SamplerConfig {
242            temperature: 0.0,
243            ..Default::default()
244        };
245        let mut rng = SplitMix64::new(1);
246        assert_eq!(sample(&logits, &config, &[], &mut rng), 1);
247    }
248
249    #[test]
250    fn test_softmax() {
251        let mut logits = vec![1.0, 2.0, 3.0];
252        softmax_inplace(&mut logits);
253        let sum: f32 = logits.iter().sum();
254        assert!((sum - 1.0).abs() < 1e-5);
255        assert!(logits[2] > logits[1] && logits[1] > logits[0]);
256    }
257
258    #[test]
259    fn test_repetition_penalty() {
260        let mut logits = vec![1.0, 2.0, 3.0, 4.0];
261        apply_repetition_penalty(&mut logits, &[1, 3], 2.0);
262        assert_eq!(logits, vec![1.0, 1.0, 3.0, 2.0]);
263    }
264
265    #[test]
266    fn top_k_keeps_exactly_k() {
267        let mut probs = vec![0.1, 0.4, 0.05, 0.3, 0.15];
268        apply_top_k(&mut probs, 2);
269        let kept = probs.iter().filter(|&&p| p > 0.0).count();
270        assert_eq!(kept, 2, "top-k must keep exactly k (was k+1 in v1)");
271        assert!(probs[1] > 0.0 && probs[3] > 0.0);
272    }
273
274    #[test]
275    fn rng_reaches_full_cdf() {
276        // v1 bug: r < 0.233 always, so the CDF tail was unreachable.
277        // With uniform probs the LAST index must be sampled sometimes.
278        let probs = vec![0.25f32; 4];
279        let mut rng = SplitMix64::new(42);
280        let mut hits = [0usize; 4];
281        for _ in 0..4000 {
282            let i = categorical_sample(&probs, rng.next_f32()) as usize;
283            hits[i] += 1;
284        }
285        for (i, &h) in hits.iter().enumerate() {
286            assert!(h > 700, "index {i} sampled only {h}/4000 — biased RNG");
287        }
288    }
289
290    #[test]
291    fn same_seed_same_sequence() {
292        let logits: Vec<f32> = (0..32).map(|i| (i as f32 * 0.37).sin()).collect();
293        let config = SamplerConfig {
294            temperature: 1.0,
295            seed: Some(7),
296            ..Default::default()
297        };
298        let run = |seed: u64| -> Vec<u32> {
299            let mut rng = SplitMix64::new(seed);
300            (0..16).map(|_| sample(&logits, &config, &[], &mut rng)).collect()
301        };
302        assert_eq!(run(7), run(7), "same seed must reproduce");
303        assert_ne!(run(7), run(8), "different seed must differ");
304    }
305}