crates/format/text/src/sampling.rs 9.8 KiB 264 lines Raw
1 //! The declared sampling parameters and the draw.2 //!3 //! The values come from the model file and are copied into [`Sampling`] as4 //! they are written there. There is no default: a default would pick a5 //! temperature for a model whose author picked a different one, and a reply6 //! that differs from the model's own sampler is a bug that no caller can see.7 //!8 //! [`Sampler`] is deterministic. The same seed and the same logits give the9 //! same token on every run, which is what a replay of a job needs. The random10 //! source is xorshift64*, written here because a leaf crate may not take a11 //! dependency for 64 bits of state.12 13 use std::collections::HashSet;14 use std::fmt;15 16 use crate::token::Token;17 18 /// The shifts of xorshift64*, in the order that the original applies them.19 const SHIFT_A: u32 = 12;20 /// The second shift of xorshift64*.21 const SHIFT_B: u32 = 25;22 /// The third shift of xorshift64*.23 const SHIFT_C: u32 = 27;24 /// The odd multiplier of xorshift64*. The low bit must stay set or the stream25 /// loses its low bits and the draw becomes uneven.26 const MULTIPLIER: u64 = 0x2545_F491_4F6C_DD1D;27 /// The seed that stands in for zero. Xorshift64* maps zero to zero, so a model28 /// file that leaves the seed at zero would otherwise draw one token forever.29 const SEED_WHEN_ZERO: u64 = 0x9E37_79B9_7F4A_7C15;30 /// The bits of a u64 that form the fraction of an f64. 52 mantissa bits plus31 /// the implicit one, so every draw is exactly representable and has no gap.32 const FRACTION_BITS: u32 = 53;33 34 /// The parameters of one model file.35 #[derive(Clone, Copy, PartialEq, Debug)]36 pub struct Sampling {37     /// Zero is greedy: the highest logit wins and the random source is idle.38     pub temperature: f32,39     /// How many of the highest logits stay in the draw. At least 1.40     pub top_k: u32,41     /// The nucleus: the smallest set of tokens whose mass reaches this. Above42     /// zero and at most 1.43     pub top_p: f32,44     /// The seed of the draw. Two jobs with one seed replay one reply.45     pub seed: u64,46     /// Moves the logit of a token that is already in `recent` down. Above 147     /// makes a repeat less likely; 1 leaves every logit alone.48     pub repetition_penalty: f32,49     /// The most tokens that one job may emit. At least 1.50     pub max_tokens: u32,51 }52 53 impl Sampling {54     /// Checks the parameters before a sampler is built from them.55     ///56     /// A parameter that the model file left out arrives as zero, which is the57     /// reason this check exists: zero is valid for a temperature and invalid58     /// for every other field.59     pub fn validate(&self) -> Result<(), SamplerError> {60         // A non-finite temperature is refused here too: infinity would make61         // every later comparison a tie, and not-a-number would make every62         // comparison false and the cut would keep an arbitrary token.63         if !self.temperature.is_finite() || self.temperature < 0.0 {64             return Err(SamplerError::Temperature(self.temperature));65         }66         if self.top_k == 0 {67             return Err(SamplerError::TopK(self.top_k));68         }69         if self.top_p.is_nan() || self.top_p <= 0.0 || self.top_p > 1.0 {70             return Err(SamplerError::TopP(self.top_p));71         }72         if self.repetition_penalty.is_nan() || self.repetition_penalty <= 0.0 {73             return Err(SamplerError::Repetition(self.repetition_penalty));74         }75         if self.max_tokens == 0 {76             return Err(SamplerError::MaxTokens(self.max_tokens));77         }78         Ok(())79     }80 }81 82 /// The reason a parameter set was refused.83 #[derive(Clone, Copy, PartialEq, Debug)]84 pub enum SamplerError {85     /// The temperature is negative or not finite.86     Temperature(f32),87     /// The top-k count is zero, so no token could survive the cut.88     TopK(u32),89     /// The nucleus mass is outside (0, 1].90     TopP(f32),91     /// The repetition penalty is zero or negative. Zero would erase a logit.92     Repetition(f32),93     /// The token budget is zero, so the job could never answer.94     MaxTokens(u32),95 }96 97 impl fmt::Display for SamplerError {98     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {99         match self {100             SamplerError::Temperature(x) => {101                 write!(f, "temperature {x} is not finite or below zero")102             }103             SamplerError::TopK(k) => write!(f, "top_k {k} keeps no token"),104             SamplerError::TopP(p) => write!(f, "top_p {p} is not in (0, 1]"),105             SamplerError::Repetition(p) => write!(f, "repetition_penalty {p} is not above zero"),106             SamplerError::MaxTokens(n) => write!(f, "max_tokens {n} allows no token"),107         }108     }109 }110 111 impl std::error::Error for SamplerError {}112 113 /// The draw for one job: the parameters and the random state.114 #[derive(Clone, Debug)]115 pub struct Sampler {116     temperature: f32,117     top_k: usize,118     top_p: f32,119     repetition_penalty: f32,120     state: u64,121 }122 123 impl Sampler {124     /// A sampler for one job. The parameters are checked first.125     pub fn new(sampling: &Sampling) -> Result<Sampler, SamplerError> {126         sampling.validate()?;127         Ok(Sampler {128             temperature: sampling.temperature,129             top_k: sampling.top_k as usize,130             top_p: sampling.top_p,131             repetition_penalty: sampling.repetition_penalty,132             state: if sampling.seed == 0 {133                 SEED_WHEN_ZERO134             } else {135                 sampling.seed136             },137         })138     }139 140     /// The logits after the repetition penalty.141     ///142     /// A token that is in `recent` is pushed down before the cut, which is the143     /// only repetition control that a leaf crate can offer: the count of144     /// occurrences lives in the caller. A positive logit is divided and a145     /// negative one multiplied, so the penalty always moves the token down.146     pub fn penalised(&self, logits: &[f32], recent: &[Token]) -> Vec<f32> {147         let mut scores = logits.to_vec();148         let mut seen = HashSet::new();149         for token in recent {150             if !seen.insert(token.0) {151                 continue;152             }153             let Some(score) = scores.get_mut(token.0 as usize) else {154                 continue;155             };156             if *score > 0.0 {157                 *score /= self.repetition_penalty;158             } else {159                 *score *= self.repetition_penalty;160             }161         }162         scores163     }164 165     /// The token that this draw chose, or `None` when there is no logit.166     ///167     /// The order is temperature, repetition penalty, top-k, top-p, then one168     /// weighted draw. A temperature of zero returns the argmax and never169     /// touches the random state, so a greedy job replays exactly.170     pub fn pick(&mut self, logits: &[f32], recent: &[Token]) -> Option<Token> {171         if logits.is_empty() {172             return None;173         }174         let mut scores = self.penalised(logits, recent);175         if self.temperature == 0.0 {176             return argmax(&scores);177         }178         for score in &mut scores {179             *score /= self.temperature;180         }181 182         let mut order: Vec<usize> = (0..scores.len()).collect();183         order.sort_by(|&a, &b| scores[b].total_cmp(&scores[a]).then(a.cmp(&b)));184         // `validate` keeps top_k at 1 or more, so this cut leaves a token.185         order.truncate(self.top_k);186 187         // The nucleus is a mass of probability, so the exponent is taken from188         // the highest kept score. The difference is at most zero and the189         // exponential therefore stays in (0, 1].190         let best = scores[order[0]];191         let mut weights: Vec<f64> = order192             .iter()193             .map(|&index| f64::from(scores[index] - best).exp())194             .collect();195         let total: f64 = weights.iter().sum();196         let mut kept = weights.len();197         let mut running = 0.0;198         for (index, weight) in weights.iter().enumerate() {199             running += weight;200             if running >= total * f64::from(self.top_p) {201                 kept = index + 1;202                 break;203             }204         }205         weights.truncate(kept);206         order.truncate(kept);207 208         let total: f64 = weights.iter().sum();209         if total.is_nan() || total <= 0.0 {210             // Every kept weight underflowed to zero. The highest logit is211             // still the one to answer with.212             return order213                 .first()214                 .and_then(|&index| u32::try_from(index).ok())215                 .map(Token);216         }217         let target = self.unit() * total;218         let mut running = 0.0;219         for (weight, &index) in weights.iter().zip(&order) {220             running += weight;221             if target < running {222                 return u32::try_from(index).ok().map(Token);223             }224         }225         // The sum of the weights can round below the target by one ulp.226         order227             .last()228             .and_then(|&index| u32::try_from(index).ok())229             .map(Token)230     }231 232     /// The next 64 bits of the stream.233     fn next_u64(&mut self) -> u64 {234         let mut x = self.state;235         x ^= x >> SHIFT_A;236         x ^= x << SHIFT_B;237         x ^= x >> SHIFT_C;238         self.state = x;239         x.wrapping_mul(MULTIPLIER)240     }241 242     /// A number in [0, 1).243     fn unit(&mut self) -> f64 {244         let scale = (1u64 << FRACTION_BITS) as f64;245         (self.next_u64() >> (u64::BITS - FRACTION_BITS)) as f64 / scale246     }247 }248 249 /// The index of the highest score. A tie goes to the lower index, so two equal250 /// logits always give the same token. A NaN is not a score and is skipped; a251 /// slice with only NaNs has no token.252 fn argmax(scores: &[f32]) -> Option<Token> {253     let mut best: Option<(usize, f32)> = None;254     for (index, &score) in scores.iter().enumerate() {255         if score.is_nan() {256             continue;257         }258         if best.is_none_or(|(_, highest)| score > highest) {259             best = Some((index, score));260         }261     }262     best.and_then(|(index, _)| u32::try_from(index).ok())263         .map(Token)264 }