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.1213use std::collections::HashSet;14use std::fmt;1516usecrate::token::Token;1718/// The shifts of xorshift64*, in the order that the original applies them.19constSHIFT_A: u32 = 12;20/// The second shift of xorshift64*.21constSHIFT_B: u32 = 25;22/// The third shift of xorshift64*.23constSHIFT_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.26constMULTIPLIER: 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.29constSEED_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.32constFRACTION_BITS: u32 = 53;3334/// The parameters of one model file.35 #[derive(Clone, Copy, PartialEq, Debug)]36pubstructSampling {37/// Zero is greedy: the highest logit wins and the random source is idle.38pub temperature: f32,39/// How many of the highest logits stay in the draw. At least 1.40pub top_k: u32,41/// The nucleus: the smallest set of tokens whose mass reaches this. Above42/// zero and at most 1.43pub top_p: f32,44/// The seed of the draw. Two jobs with one seed replay one reply.45pub 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.48pub repetition_penalty: f32,49/// The most tokens that one job may emit. At least 1.50pub max_tokens: u32,51 }5253implSampling {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.59pubfnvalidate(&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.63if !self.temperature.is_finite() || self.temperature < 0.0 {64returnErr(SamplerError::Temperature(self.temperature));65 }66ifself.top_k == 0 {67returnErr(SamplerError::TopK(self.top_k));68 }69ifself.top_p.is_nan() || self.top_p <= 0.0 || self.top_p > 1.0 {70returnErr(SamplerError::TopP(self.top_p));71 }72ifself.repetition_penalty.is_nan() || self.repetition_penalty <= 0.0 {73returnErr(SamplerError::Repetition(self.repetition_penalty));74 }75ifself.max_tokens == 0 {76returnErr(SamplerError::MaxTokens(self.max_tokens));77 }78Ok(())79 }80 }8182/// The reason a parameter set was refused.83 #[derive(Clone, Copy, PartialEq, Debug)]84pubenumSamplerError {85/// The temperature is negative or not finite.86Temperature(f32),87/// The top-k count is zero, so no token could survive the cut.88TopK(u32),89/// The nucleus mass is outside (0, 1].90TopP(f32),91/// The repetition penalty is zero or negative. Zero would erase a logit.92Repetition(f32),93/// The token budget is zero, so the job could never answer.94MaxTokens(u32),95 }9697impl fmt::DisplayforSamplerError {98fnfmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {99matchself {100SamplerError::Temperature(x) => {101 write!(f, "temperature {x} is not finite or below zero")102 }103SamplerError::TopK(k) => write!(f, "top_k {k} keeps no token"),104SamplerError::TopP(p) => write!(f, "top_p {p} is not in (0, 1]"),105SamplerError::Repetition(p) => write!(f, "repetition_penalty {p} is not above zero"),106SamplerError::MaxTokens(n) => write!(f, "max_tokens {n} allows no token"),107 }108 }109 }110111impl std::error::ErrorforSamplerError {}112113/// The draw for one job: the parameters and the random state.114 #[derive(Clone, Debug)]115pubstructSampler {116 temperature: f32,117 top_k: usize,118 top_p: f32,119 repetition_penalty: f32,120 state: u64,121 }122123implSampler {124/// A sampler for one job. The parameters are checked first.125pubfnnew(sampling: &Sampling) -> Result<Sampler, SamplerError> {126 sampling.validate()?;127Ok(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 {133SEED_WHEN_ZERO134 } else {135 sampling.seed136 },137 })138 }139140/// 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.146pubfnpenalised(&self, logits: &[f32], recent: &[Token]) -> Vec<f32> {147letmut scores = logits.to_vec();148letmut seen = HashSet::new();149for token in recent {150if !seen.insert(token.0) {151continue;152 }153letSome(score) = scores.get_mut(token.0as usize) else {154continue;155 };156if *score > 0.0 {157 *score /= self.repetition_penalty;158 } else {159 *score *= self.repetition_penalty;160 }161 }162 scores163 }164165/// 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.170pubfnpick(&mutself, logits: &[f32], recent: &[Token]) -> Option<Token> {171if logits.is_empty() {172returnNone;173 }174letmut scores = self.penalised(logits, recent);175ifself.temperature == 0.0 {176returnargmax(&scores);177 }178for score in &mut scores {179 *score /= self.temperature;180 }181182letmut 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);186187// 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].190let best = scores[order[0]];191letmut weights: Vec<f64> = order192 .iter()193 .map(|&index| f64::from(scores[index] - best).exp())194 .collect();195let total: f64 = weights.iter().sum();196letmut kept = weights.len();197letmut running = 0.0;198for (index, weight) in weights.iter().enumerate() {199 running += weight;200if running >= total * f64::from(self.top_p) {201 kept = index + 1;202break;203 }204 }205 weights.truncate(kept);206 order.truncate(kept);207208let total: f64 = weights.iter().sum();209if total.is_nan() || total <= 0.0 {210// Every kept weight underflowed to zero. The highest logit is211// still the one to answer with.212return order213 .first()214 .and_then(|&index| u32::try_from(index).ok())215 .map(Token);216 }217let target = self.unit() * total;218letmut running = 0.0;219for (weight, &index) in weights.iter().zip(&order) {220 running += weight;221if target < running {222return 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 }231232/// The next 64 bits of the stream.233fnnext_u64(&mutself) -> u64 {234letmut x = self.state;235 x ^= x >> SHIFT_A;236 x ^= x << SHIFT_B;237 x ^= x >> SHIFT_C;238self.state = x;239 x.wrapping_mul(MULTIPLIER)240 }241242/// A number in [0, 1).243fnunit(&mutself) -> f64 {244let scale = (1u64 << FRACTION_BITS) as f64;245 (self.next_u64() >> (u64::BITS - FRACTION_BITS)) as f64 / scale246 }247 }248249/// 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.252fnargmax(scores: &[f32]) -> Option<Token> {253letmut best: Option<(usize, f32)> = None;254for (index, &score) in scores.iter().enumerate() {255if score.is_nan() {256continue;257 }258if 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 }