Skip to main content

fuel_tensor/
sampling.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Sampling controls for decode loops (ROADMAP row 133, slice 1: the pure host sampler).
3//!
4//! [`sample_with_params`] picks the next token from one logits row under a [`SamplingParams`] and
5//! the tokens seen so far. It is host-side and deterministic: the same logits, params, history and
6//! RNG state give the same token. With only a positive temperature set it reduces exactly to
7//! [`crate::lazy::sample_logits`] (same RNG stream, same probabilities), which a test pins.
8//!
9//! **Order of operations**, so a caller can predict the result:
10//! 1. penalties on the raw logits, from `history`: repetition (HF form: a seen token's positive
11//!    logit is divided by the penalty, a negative one multiplied), then
12//!    `logit -= frequency * count + presence * (count > 0)`;
13//! 2. `temperature <= 0` or NaN: the argmax of the penalised logits (greedy), lowest index on a tie;
14//! 3. otherwise scale by `1 / temperature`, softmax, then `top_k`, then `top_p` (nucleus: the
15//!    smallest prefix of descending probabilities reaching `top_p`, at least one token), then
16//!    `min_p` (drop tokens below `min_p` times the largest remaining probability), renormalise,
17//!    and draw with [`crate::lazy::sample_multinomial`].
18//!
19//! **Logprobs are of the model's own distribution**: `log_softmax` of the INPUT logits, before
20//! penalties, temperature and filters (vLLM's "raw logprobs"). They describe what the model said,
21//! not what was sampled from, and they do not depend on the sampling controls.
22//!
23//! `history` is whatever the caller wants penalised. OpenAI penalises generated tokens only;
24//! HF's repetition penalty covers the prompt too. The scheduler slice decides which it passes.
25
26use crate::lazy::sample_multinomial;
27use fuel_ir::{Error, Result};
28
29/// Every control for one sampling step. `Default` is greedy with no penalties and no logprobs.
30#[derive(Debug, Clone, PartialEq)]
31pub struct SamplingParams {
32    /// Softmax temperature; `<= 0` or NaN means greedy.
33    pub temperature: f32,
34    /// Keep only the `k` most probable tokens (`k >= 1`).
35    pub top_k: Option<usize>,
36    /// Nucleus mass in `(0, 1]`.
37    pub top_p: Option<f32>,
38    /// Minimum probability relative to the most probable token, in `[0, 1]`.
39    pub min_p: Option<f32>,
40    /// Subtracted once from a token's logit if it appears in the history.
41    pub presence_penalty: f32,
42    /// Subtracted per occurrence of a token in the history.
43    pub frequency_penalty: f32,
44    /// Multiplicative penalty on seen tokens (`> 0`; `1.0` is off).
45    pub repetition_penalty: f32,
46    /// Seeds the caller's RNG state for a new sequence.
47    pub seed: u64,
48    /// Report this many top logprobs (plus the chosen token's); `None` reports none.
49    pub logprobs: Option<usize>,
50}
51
52impl Default for SamplingParams {
53    fn default() -> Self {
54        Self {
55            temperature: 0.0,
56            top_k: None,
57            top_p: None,
58            min_p: None,
59            presence_penalty: 0.0,
60            frequency_penalty: 0.0,
61            repetition_penalty: 1.0,
62            seed: 0,
63            logprobs: None,
64        }
65    }
66}
67
68/// One sampled step.
69#[derive(Debug, Clone, PartialEq)]
70pub struct Sampled {
71    /// The chosen token.
72    pub token: u32,
73    /// Its logprob under the model's own distribution; `None` unless `logprobs` was requested.
74    pub logprob: Option<f32>,
75    /// The `logprobs` most probable tokens, most probable first (lowest index on a tie).
76    pub top_logprobs: Vec<(u32, f32)>,
77}
78
79fn err(msg: String) -> Error {
80    Error::Msg(msg).bt()
81}
82
83impl SamplingParams {
84    /// Check every control against the vocabulary size; the first problem is named.
85    pub fn validate(&self, vocab: usize) -> Result<()> {
86        self.validate_filters()?;
87        self.validate_penalties()?;
88        if let Some(n) = self.logprobs
89            && n > vocab
90        {
91            return Err(err(format!(
92                "SamplingParams: logprobs {n} exceeds the vocabulary size {vocab}"
93            )));
94        }
95        Ok(())
96    }
97
98    fn validate_filters(&self) -> Result<()> {
99        if let Some(0) = self.top_k {
100            return Err(err("SamplingParams: top_k must be >= 1".into()));
101        }
102        if let Some(p) = self.top_p
103            && !(p > 0.0 && p <= 1.0)
104        {
105            return Err(err(format!("SamplingParams: top_p {p} is not in (0, 1]")));
106        }
107        if let Some(p) = self.min_p
108            && !(0.0..=1.0).contains(&p)
109        {
110            return Err(err(format!("SamplingParams: min_p {p} is not in [0, 1]")));
111        }
112        Ok(())
113    }
114
115    fn validate_penalties(&self) -> Result<()> {
116        if !(self.repetition_penalty > 0.0 && self.repetition_penalty.is_finite()) {
117            return Err(err(format!(
118                "SamplingParams: repetition_penalty {} must be finite and > 0",
119                self.repetition_penalty
120            )));
121        }
122        if !self.presence_penalty.is_finite() || !self.frequency_penalty.is_finite() {
123            return Err(err("SamplingParams: penalties must be finite".into()));
124        }
125        Ok(())
126    }
127}
128
129/// Pick the next token. Errors on empty or non-finite logits, a history token outside the
130/// vocabulary, or invalid params; never panics.
131pub fn sample_with_params(
132    logits: &[f32],
133    params: &SamplingParams,
134    history: &[u32],
135    rng_state: &mut u64,
136) -> Result<Sampled> {
137    let vocab = logits.len();
138    if vocab == 0 {
139        return Err(err("sample_with_params: empty logits".into()));
140    }
141    if logits.iter().any(|x| !x.is_finite()) {
142        return Err(err("sample_with_params: non-finite logit".into()));
143    }
144    params.validate(vocab)?;
145
146    let adjusted = apply_penalties(logits, params, history)?;
147    let token = if params.temperature.is_nan() || params.temperature <= 0.0 {
148        argmax(&adjusted)
149    } else {
150        let probs = filtered_probs(&adjusted, params);
151        sample_multinomial(&probs, rng_state)
152    };
153
154    let (logprob, top_logprobs) = match params.logprobs {
155        None => (None, Vec::new()),
156        Some(n) => {
157            let lp = log_softmax(logits);
158            (Some(lp[token as usize]), top_n(&lp, n))
159        }
160    };
161    Ok(Sampled {
162        token,
163        logprob,
164        top_logprobs,
165    })
166}
167
168fn apply_penalties(logits: &[f32], p: &SamplingParams, history: &[u32]) -> Result<Vec<f32>> {
169    let mut counts = vec![0_u32; logits.len()];
170    for t in history {
171        let slot = counts.get_mut(*t as usize).ok_or_else(|| {
172            err(format!(
173                "sample_with_params: history token {t} is outside the vocabulary of {}",
174                logits.len()
175            ))
176        })?;
177        *slot += 1;
178    }
179    Ok(logits
180        .iter()
181        .zip(&counts)
182        .map(|(&l, &c)| {
183            if c == 0 {
184                return l;
185            }
186            let rep = if l > 0.0 {
187                l / p.repetition_penalty
188            } else {
189                l * p.repetition_penalty
190            };
191            rep - p.frequency_penalty * c as f32 - p.presence_penalty
192        })
193        .collect())
194}
195
196fn argmax(x: &[f32]) -> u32 {
197    let mut best = 0;
198    for (i, v) in x.iter().enumerate().skip(1) {
199        if *v > x[best] {
200            best = i;
201        }
202    }
203    best as u32
204}
205
206/// Temperature softmax, then the top_k, top_p and min_p filters, renormalised.
207fn filtered_probs(adjusted: &[f32], p: &SamplingParams) -> Vec<f32> {
208    let mut probs = temperature_softmax(adjusted, p.temperature);
209    if p.top_k.is_none() && p.top_p.is_none() && p.min_p.is_none() {
210        return probs;
211    }
212    // Token order by descending probability, lowest index first on a tie.
213    let mut order: Vec<usize> = (0..probs.len()).collect();
214    order.sort_by(|&a, &b| probs[b].total_cmp(&probs[a]).then(a.cmp(&b)));
215    let keep = kept_count(&probs, &order, p);
216    let kept: std::collections::HashSet<usize> = order.iter().take(keep).copied().collect();
217    let mut total = 0.0_f32;
218    for (i, pr) in probs.iter_mut().enumerate() {
219        if kept.contains(&i) {
220            total += *pr;
221        } else {
222            *pr = 0.0;
223        }
224    }
225    probs.iter_mut().for_each(|pr| *pr /= total);
226    probs
227}
228
229fn temperature_softmax(adjusted: &[f32], temperature: f32) -> Vec<f32> {
230    // Same arithmetic as `sample_logits` so the unfiltered case matches it bit for bit.
231    let inv_temp = 1.0 / temperature;
232    let scaled: Vec<f32> = adjusted.iter().map(|&x| x * inv_temp).collect();
233    let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
234    let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
235    let sum: f32 = exp.iter().sum();
236    exp.iter().map(|&x| x / sum).collect()
237}
238
239/// How many of `order` (most probable first) survive top_k, then top_p, then min_p.
240fn kept_count(probs: &[f32], order: &[usize], p: &SamplingParams) -> usize {
241    let mut keep = order.len();
242    if let Some(k) = p.top_k {
243        keep = keep.min(k);
244    }
245    if let Some(top_p) = p.top_p {
246        keep = keep.min(top_p_count(probs, &order[..keep], top_p));
247    }
248    if let Some(min_p) = p.min_p {
249        let floor = min_p * probs[order[0]];
250        keep = order
251            .iter()
252            .take(keep)
253            .take_while(|&&i| probs[i] >= floor)
254            .count()
255            .max(1);
256    }
257    keep
258}
259
260/// The shortest prefix of `order` whose cumulative probability reaches `top_p` (all of it if never).
261fn top_p_count(probs: &[f32], order: &[usize], top_p: f32) -> usize {
262    let mut cum = 0.0_f32;
263    for (n, &i) in order.iter().enumerate() {
264        cum += probs[i];
265        if cum >= top_p {
266            return n + 1;
267        }
268    }
269    order.len()
270}
271
272fn log_softmax(logits: &[f32]) -> Vec<f32> {
273    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
274    let lse = logits.iter().map(|&x| (x - max).exp()).sum::<f32>().ln() + max;
275    logits.iter().map(|&x| x - lse).collect()
276}
277
278fn top_n(logprobs: &[f32], n: usize) -> Vec<(u32, f32)> {
279    let mut order: Vec<usize> = (0..logprobs.len()).collect();
280    order.sort_by(|&a, &b| logprobs[b].total_cmp(&logprobs[a]).then(a.cmp(&b)));
281    order
282        .into_iter()
283        .take(n)
284        .map(|i| (i as u32, logprobs[i]))
285        .collect()
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::lazy::{SamplingStrategy, sample_logits};
292
293    const L: [f32; 5] = [0.1, 0.2, 0.0, 0.3, 0.15];
294
295    fn p() -> SamplingParams {
296        SamplingParams {
297            temperature: 1.0,
298            ..Default::default()
299        }
300    }
301
302    fn draws(params: &SamplingParams, history: &[u32], n: usize) -> Vec<u32> {
303        let mut rng = 7_u64;
304        (0..n)
305            .map(|_| {
306                sample_with_params(&L, params, history, &mut rng)
307                    .unwrap()
308                    .token
309            })
310            .collect()
311    }
312
313    #[test]
314    fn default_is_greedy_and_reports_no_logprobs() {
315        let s = sample_with_params(&L, &SamplingParams::default(), &[], &mut 0).unwrap();
316        assert_eq!(s.token, 3);
317        assert_eq!((s.logprob, s.top_logprobs.len()), (None, 0));
318    }
319
320    #[test]
321    fn plain_temperature_reduces_to_sample_logits_on_the_same_rng_stream() {
322        let (mut a, mut b) = (42_u64, 42_u64);
323        for _ in 0..50 {
324            let new = sample_with_params(&L, &p(), &[], &mut a).unwrap().token;
325            let old = sample_logits(
326                &L,
327                SamplingStrategy::Temperature {
328                    temp: 1.0,
329                    seed: 42,
330                },
331                &mut b,
332            );
333            assert_eq!(new, old);
334        }
335        assert_eq!(a, b, "both must consume the RNG identically");
336    }
337
338    #[test]
339    fn top_k_confines_the_draws_and_the_unfiltered_control_escapes() {
340        let top2 = SamplingParams {
341            top_k: Some(2),
342            ..p()
343        };
344        assert!(draws(&top2, &[], 200).iter().all(|t| *t == 3 || *t == 1));
345        assert!(draws(&p(), &[], 200).iter().any(|t| *t != 3 && *t != 1));
346        let one = SamplingParams {
347            top_k: Some(1),
348            temperature: 5.0,
349            ..p()
350        };
351        assert!(draws(&one, &[], 50).iter().all(|t| *t == 3));
352    }
353
354    #[test]
355    fn top_p_keeps_the_smallest_prefix_and_always_at_least_one_token() {
356        let tiny = SamplingParams {
357            top_p: Some(0.0001),
358            ..p()
359        };
360        assert!(draws(&tiny, &[], 50).iter().all(|t| *t == 3));
361        // top_p = 1.0 filters nothing: identical draws to the unfiltered sampler.
362        let all = SamplingParams {
363            top_p: Some(1.0),
364            ..p()
365        };
366        assert_eq!(draws(&all, &[], 100), draws(&p(), &[], 100));
367    }
368
369    #[test]
370    fn min_p_one_keeps_only_the_most_probable_and_zero_keeps_all() {
371        let one = SamplingParams {
372            min_p: Some(1.0),
373            ..p()
374        };
375        assert!(draws(&one, &[], 50).iter().all(|t| *t == 3));
376        let zero = SamplingParams {
377            min_p: Some(0.0),
378            ..p()
379        };
380        assert_eq!(draws(&zero, &[], 100), draws(&p(), &[], 100));
381    }
382
383    #[test]
384    fn repetition_penalty_divides_positive_and_multiplies_negative_logits() {
385        let g = |l: &[f32], h: &[u32], rp: f32| {
386            let params = SamplingParams {
387                repetition_penalty: rp,
388                ..Default::default()
389            };
390            sample_with_params(l, &params, h, &mut 0).unwrap().token
391        };
392        assert_eq!(g(&[2.0, 1.9], &[], 2.0), 0);
393        assert_eq!(g(&[2.0, 1.9], &[0], 2.0), 1, "2.0 / 2 = 1.0 < 1.9");
394        assert_eq!(g(&[-1.0, -1.5], &[0], 2.0), 1, "-1.0 * 2 = -2.0 < -1.5");
395    }
396
397    #[test]
398    fn frequency_counts_every_occurrence_and_presence_counts_once() {
399        let run = |f: f32, pr: f32, h: &[u32]| {
400            let params = SamplingParams {
401                frequency_penalty: f,
402                presence_penalty: pr,
403                ..Default::default()
404            };
405            sample_with_params(&[1.0, 0.7], &params, h, &mut 0)
406                .unwrap()
407                .token
408        };
409        assert_eq!(run(0.1, 0.0, &[0]), 0, "1.0 - 0.1 = 0.9 still beats 0.7");
410        assert_eq!(run(0.1, 0.0, &[0, 0, 0, 0]), 1, "1.0 - 0.4 = 0.6 loses");
411        assert_eq!(
412            run(0.0, 0.5, &[0, 0, 0, 0]),
413            1,
414            "presence 0.5 once: 0.5 loses"
415        );
416        assert_eq!(
417            run(0.0, 0.2, &[0, 0, 0, 0]),
418            0,
419            "presence is not multiplied by count"
420        );
421    }
422
423    #[test]
424    fn logprobs_are_the_models_own_distribution_and_ignore_the_controls() {
425        let all = SamplingParams {
426            logprobs: Some(5),
427            top_k: Some(1),
428            repetition_penalty: 3.0,
429            ..p()
430        };
431        let s = sample_with_params(&L, &all, &[3], &mut 1).unwrap();
432        let total: f32 = s.top_logprobs.iter().map(|(_, lp)| lp.exp()).sum();
433        assert!(
434            (total - 1.0).abs() < 1e-5,
435            "full-vocab logprobs sum to {total}"
436        );
437        let order: Vec<u32> = s.top_logprobs.iter().map(|(t, _)| *t).collect();
438        assert_eq!(order, vec![3, 1, 4, 0, 2]);
439        let chosen = s
440            .top_logprobs
441            .iter()
442            .find(|(t, _)| *t == s.token)
443            .unwrap()
444            .1;
445        assert_eq!(s.logprob, Some(chosen));
446        let none = sample_with_params(
447            &L,
448            &SamplingParams {
449                logprobs: Some(5),
450                ..Default::default()
451            },
452            &[],
453            &mut 1,
454        )
455        .unwrap();
456        assert_eq!(
457            none.top_logprobs, s.top_logprobs,
458            "controls must not move logprobs"
459        );
460    }
461
462    #[test]
463    fn same_seed_same_tokens_and_a_different_seed_diverges() {
464        let run = |seed: u64| {
465            let mut rng = seed;
466            (0..64)
467                .map(|_| sample_with_params(&L, &p(), &[], &mut rng).unwrap().token)
468                .collect::<Vec<_>>()
469        };
470        assert_eq!(run(5), run(5));
471        assert_ne!(run(5), run(6));
472    }
473
474    #[test]
475    fn bad_input_is_a_typed_error_not_a_panic() {
476        let d = SamplingParams::default;
477        let bad_params: Vec<SamplingParams> = vec![
478            SamplingParams {
479                top_k: Some(0),
480                ..d()
481            },
482            SamplingParams {
483                top_p: Some(0.0),
484                ..d()
485            },
486            SamplingParams {
487                top_p: Some(1.5),
488                ..d()
489            },
490            SamplingParams {
491                min_p: Some(-0.1),
492                ..d()
493            },
494            SamplingParams {
495                repetition_penalty: 0.0,
496                ..d()
497            },
498            SamplingParams {
499                logprobs: Some(6),
500                ..d()
501            },
502        ];
503        for params in &bad_params {
504            assert!(
505                sample_with_params(&L, params, &[], &mut 0).is_err(),
506                "{params:?}"
507            );
508        }
509        assert!(sample_with_params(&[], &d(), &[], &mut 0).is_err());
510        assert!(sample_with_params(&[1.0, f32::NAN], &d(), &[], &mut 0).is_err());
511        assert!(sample_with_params(&[1.0, 2.0], &d(), &[9], &mut 0).is_err());
512        let ok = SamplingParams {
513            logprobs: Some(5),
514            ..d()
515        };
516        assert!(
517            sample_with_params(&L, &ok, &[], &mut 0).is_ok(),
518            "control: valid input passes"
519        );
520    }
521}