Skip to main content

candle_transformers/generation/
mod.rs

1//! Logit Processing and Sampling
2//!
3//! Functionality for modeling sampling strategies and logits processing in text generation
4//! with support for temperature-based sampling, top-k filtering, nucleus sampling (top-p),
5//! and combinations thereof.
6use candle::{DType, Error, Result, Tensor};
7use rand::{distr::Distribution, SeedableRng};
8
9#[derive(Clone, PartialEq, Debug)]
10pub enum Sampling {
11    ArgMax,
12    All { temperature: f64 },
13    TopK { k: usize, temperature: f64 },
14    TopP { p: f64, temperature: f64 },
15    TopKThenTopP { k: usize, p: f64, temperature: f64 },
16    // Note that the rng is not used for the Gumbel-Softmax sampling.
17    GumbelSoftmax { temperature: f64 },
18}
19
20pub struct LogitsProcessor {
21    rng: rand::rngs::StdRng,
22    sampling: Sampling,
23}
24
25impl LogitsProcessor {
26    pub fn from_sampling(seed: u64, sampling: Sampling) -> Self {
27        let rng = rand::rngs::StdRng::seed_from_u64(seed);
28        Self { rng, sampling }
29    }
30
31    pub fn new(seed: u64, temperature: Option<f64>, top_p: Option<f64>) -> Self {
32        let temperature = temperature.and_then(|v| if v < 1e-7 { None } else { Some(v) });
33        let sampling = match temperature {
34            None => Sampling::ArgMax,
35            Some(temperature) => match top_p {
36                None => Sampling::All { temperature },
37                Some(p) => Sampling::TopP { p, temperature },
38            },
39        };
40        Self::from_sampling(seed, sampling)
41    }
42
43    fn sample_argmax(&mut self, logits: Tensor) -> Result<u32> {
44        logits.argmax(candle::D::Minus1)?.to_scalar::<u32>()
45    }
46
47    fn sample_gumbel_softmax(&mut self, logits: &Tensor, temperature: f64) -> Result<u32> {
48        let sampled = candle_nn::sampling::gumbel_softmax(logits, temperature, candle::D::Minus1)?;
49        sampled.to_scalar::<u32>()
50    }
51
52    fn sample_multinomial(&mut self, prs: &Vec<f32>) -> Result<u32> {
53        let distr = rand::distr::weighted::WeightedIndex::new(prs).map_err(Error::wrap)?;
54        let next_token = distr.sample(&mut self.rng) as u32;
55        Ok(next_token)
56    }
57
58    /// top-p sampling (or "nucleus sampling") samples from the smallest set of tokens that exceed
59    /// probability top_p. This way we never sample tokens that have very low probabilities and are
60    /// less likely to go "off the rails".
61    fn sample_topp(&mut self, prs: &mut Vec<f32>, top_p: f32) -> Result<u32> {
62        let mut argsort_indices = (0..prs.len()).collect::<Vec<_>>();
63
64        // Sort by descending probability.
65        argsort_indices.sort_by(|&i, &j| prs[j].total_cmp(&prs[i]));
66
67        // Clamp smaller probabilities to zero.
68        let mut cumsum = 0.;
69        for index in &argsort_indices {
70            if cumsum >= top_p {
71                prs[*index] = 0.0;
72            } else {
73                cumsum += prs[*index];
74            }
75        }
76        // Sample with clamped probabilities.
77        self.sample_multinomial(prs)
78    }
79
80    // top-k sampling samples from the k tokens with the largest probabilities.
81    fn sample_topk(&mut self, prs: &mut Vec<f32>, top_k: usize) -> Result<u32> {
82        if top_k >= prs.len() {
83            self.sample_multinomial(prs)
84        } else {
85            let mut argsort_indices = (0..prs.len()).collect::<Vec<_>>();
86            let (indices, _, _) =
87                argsort_indices.select_nth_unstable_by(top_k, |&i, &j| prs[j].total_cmp(&prs[i]));
88            let prs = indices.iter().map(|&i| prs[i]).collect::<Vec<_>>();
89            let index = self.sample_multinomial(&prs)?;
90            Ok(indices[index as usize] as u32)
91        }
92    }
93
94    // top-k sampling samples from the k tokens with the largest probabilities.
95    // then top-p sampling.
96    fn sample_topk_topp(&mut self, prs: &mut Vec<f32>, top_k: usize, top_p: f32) -> Result<u32> {
97        if top_k >= prs.len() {
98            self.sample_topp(prs, top_p)
99        } else {
100            let mut argsort_indices = (0..prs.len()).collect::<Vec<_>>();
101            let (indices, _, _) =
102                argsort_indices.select_nth_unstable_by(top_k, |&i, &j| prs[j].total_cmp(&prs[i]));
103            let mut prs = indices.iter().map(|&i| prs[i]).collect::<Vec<_>>();
104            let sum_p = prs.iter().sum::<f32>();
105            let index = if top_p <= 0.0 || top_p >= sum_p {
106                self.sample_multinomial(&prs)?
107            } else {
108                self.sample_topp(&mut prs, top_p)?
109            };
110            Ok(indices[index as usize] as u32)
111        }
112    }
113
114    pub fn sample(&mut self, logits: &Tensor) -> Result<u32> {
115        self.sample_f(logits, |_| {})
116    }
117
118    pub fn sample_f(&mut self, logits: &Tensor, f: impl FnOnce(&mut [f32])) -> Result<u32> {
119        let logits = logits.to_dtype(DType::F32)?;
120        let prs = |temperature: f64| -> Result<Vec<f32>> {
121            let logits = (&logits / temperature)?;
122            let prs = candle_nn::ops::softmax_last_dim(&logits)?;
123            let mut prs = prs.to_vec1()?;
124            f(&mut prs);
125            Ok(prs)
126        };
127
128        let next_token = match &self.sampling {
129            Sampling::ArgMax => self.sample_argmax(logits)?,
130            Sampling::GumbelSoftmax { temperature } => {
131                self.sample_gumbel_softmax(&logits, *temperature)?
132            }
133            Sampling::All { temperature } => {
134                let prs = prs(*temperature)?;
135                self.sample_multinomial(&prs)?
136            }
137            Sampling::TopP { p, temperature } => {
138                let mut prs = prs(*temperature)?;
139                if *p <= 0.0 || *p >= 1.0 {
140                    // simply sample from the predicted probability distribution
141                    self.sample_multinomial(&prs)?
142                } else {
143                    // top-p (nucleus) sampling, clamping the least likely tokens to zero
144                    self.sample_topp(&mut prs, *p as f32)?
145                }
146            }
147            Sampling::TopK { k, temperature } => {
148                let mut prs = prs(*temperature)?;
149                self.sample_topk(&mut prs, *k)?
150            }
151            Sampling::TopKThenTopP { k, p, temperature } => {
152                let mut prs = prs(*temperature)?;
153                self.sample_topk_topp(&mut prs, *k, *p as f32)?
154            }
155        };
156        Ok(next_token)
157    }
158}