New pure-Rust crate leleka-sampler-ref: Philox draw, penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick, greedy argmax, coupled-draft counter/ring math, penalty_rows, exact-match acceptance, and the request-level SamplingParams validation with the Original's GEN defaults and wire keys. Golden fixtures come from compiling the Original's sampler_parity.cpp host reference (included unmodified) and sampler/coupled_draft headers with clang++ (-ffp-contract=off), plus the verbatim StrataEngine.sampling_keys lifted from server.py. No GPU, no speed or quality claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
556 lines
17 KiB
Rust
556 lines
17 KiB
Rust
//! The sampler chain, in llama.cpp's order, as the Original runs it:
|
|
//!
|
|
//! ```text
|
|
//! penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick
|
|
//! ```
|
|
//!
|
|
//! Source of truth: `engine/strata/src/kernels/cuda/sampler.cu`
|
|
//! (`sampler_greedy_kernel`, `sampler_kernel`, `sampler_one_block_kernel`,
|
|
//! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick`
|
|
//! in `sampler_parity.cpp`. The three sampled kernels of the Original (old,
|
|
//! one-block, split) pick the same token bit for bit; this is that token.
|
|
//!
|
|
//! # Float-ordering assumptions (documented, not hidden)
|
|
//!
|
|
//! * Every `f32` operation is a separate IEEE operation, **no fused
|
|
//! multiply-add**: `count * freq + present_flag * present` is two multiplies
|
|
//! and one add. The oracle fixtures are built with `-ffp-contract=off`.
|
|
//! (`nvcc` fuses by default; build the sampler PTX with `--fmad=false` for
|
|
//! bit-exactness on inputs where it matters - see `original_sampler.cu`.)
|
|
//! * Sums are strictly sequential in list order (`f64`), exactly the Original's
|
|
//! ordered sums; no pairwise or vectorised summation.
|
|
//! * `exp` is `f64::exp` and the min_p threshold uses `f32::ln` (`logf`): the
|
|
//! platform libm, like the Original host reference. Cross-libm results can
|
|
//! differ by 1 ulp; that can only flip a pick when `u` lands within ~1e-16 of
|
|
//! a cumulative boundary, and can flip a cut only on a boundary tie.
|
|
//! * `fmaxf` is `f32::max` (NaN-ignoring). Selected logits are never NaN.
|
|
|
|
use crate::philox::philox_uniform;
|
|
|
|
/// The widest top_k list the Original keeps (`kSelMax` / `KMAX`).
|
|
pub const MAX_SELECT: usize = 64;
|
|
/// serve's `kPenaltyWindowCap`: history rows are capped at this many tokens.
|
|
pub const PENALTY_WINDOW_CAP: usize = 4096;
|
|
|
|
/// `strata::kernels::SamplerParams` (sampler.hpp), field for field.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct SamplerParams {
|
|
/// Sampled path: 1..=63 as given; 0 (off), 64 or more keep the widest list, 64.
|
|
pub top_k: i32,
|
|
/// `>= 1.0` disables the filter.
|
|
pub top_p: f32,
|
|
/// 0 disables; keeps tokens whose logit is at least `l0 + ln(min_p)`.
|
|
pub min_p: f32,
|
|
/// `<= 0` means greedy.
|
|
pub temperature: f32,
|
|
/// top_p keeps at least this many.
|
|
pub min_keep: i32,
|
|
/// 0 disables; the window over the history rows to count occurrences in.
|
|
pub penalty_last_n: i32,
|
|
pub penalty_repeat: f32,
|
|
pub penalty_freq: f32,
|
|
pub penalty_present: f32,
|
|
/// Philox key.
|
|
pub seed: u64,
|
|
/// Absolute draw index of row 0; row `t` draws at `counter + t`.
|
|
pub counter: u64,
|
|
pub greedy: bool,
|
|
}
|
|
|
|
impl Default for SamplerParams {
|
|
/// The C++ member initialisers (`top_k = 20`, `top_p = 0.95`, `temperature = 1.0`...).
|
|
fn default() -> Self {
|
|
Self {
|
|
top_k: 20,
|
|
top_p: 0.95,
|
|
min_p: 0.0,
|
|
temperature: 1.0,
|
|
min_keep: 1,
|
|
penalty_last_n: 0,
|
|
penalty_repeat: 1.0,
|
|
penalty_freq: 0.0,
|
|
penalty_present: 0.0,
|
|
seed: 0,
|
|
counter: 0,
|
|
greedy: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl SamplerParams {
|
|
/// `sample_tokens` takes the argmax path when `greedy || temperature <= 0`.
|
|
pub fn is_greedy(&self) -> bool {
|
|
self.greedy || self.temperature <= 0.0
|
|
}
|
|
}
|
|
|
|
/// Failures the Original reports with `exit(1)` or leaves undefined; this port fails closed.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum SamplerError {
|
|
/// `n_vocab == 0` with rows to sample (the Original silently returns).
|
|
EmptyVocabulary,
|
|
/// `logits.len() != n_tokens * n_vocab`.
|
|
LogitsLength { expected: usize, actual: usize },
|
|
/// `penalty_last_n > 0` without a history (the Original prints and exits).
|
|
HistoryRequired,
|
|
/// `history.len() != n_tokens * history_len`.
|
|
HistoryShape { expected: usize, actual: usize },
|
|
}
|
|
|
|
/// The top_k list in selection order: descending by penalised logit, ties to
|
|
/// the lower token id. A round that finds no finite candidate records the
|
|
/// sentinel `(id 0, -inf)`.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Selection {
|
|
pub ids: Vec<i32>,
|
|
pub logits: Vec<f32>,
|
|
}
|
|
|
|
/// The outcome of the tail (top_p, min_p, temperature, draw).
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Pick {
|
|
pub token: i32,
|
|
/// Index of `token` in the selection list.
|
|
pub index: usize,
|
|
/// Entries that survived top_p and min_p.
|
|
pub n_keep: usize,
|
|
/// Probability of `token` under the final distribution (`kProb` of the
|
|
/// coupled draft; `1.0` when nothing survived).
|
|
pub prob: f32,
|
|
/// The uniform that was drawn.
|
|
pub uniform: f32,
|
|
}
|
|
|
|
/// Top_k request -> list length: 1..=63 as given, anything else 64, never more
|
|
/// than the vocabulary (`sampled_k`).
|
|
pub fn sampled_k(top_k: i32, n_vocab: usize) -> usize {
|
|
let k = if top_k > 0 && (top_k as usize) < MAX_SELECT {
|
|
top_k as usize
|
|
} else {
|
|
MAX_SELECT
|
|
};
|
|
k.min(n_vocab)
|
|
}
|
|
|
|
/// `apply_penalties`: the repeat penalty MULTIPLIES a non-positive logit and
|
|
/// DIVIDES a positive one; the presence term is the boolean `count > 0`.
|
|
pub fn apply_penalties(mut logit: f32, count: i32, p: &SamplerParams) -> f32 {
|
|
if count <= 0 {
|
|
return logit;
|
|
}
|
|
if logit <= 0.0 {
|
|
logit *= p.penalty_repeat;
|
|
} else {
|
|
logit /= p.penalty_repeat;
|
|
}
|
|
let flag: f32 = if count > 0 { 1.0 } else { 0.0 };
|
|
let freq = (count as f32) * p.penalty_freq;
|
|
let present = flag * p.penalty_present;
|
|
logit -= freq + present;
|
|
logit
|
|
}
|
|
|
|
/// The counted window of one history row: its last `min(penalty_last_n,
|
|
/// history_len)` entries (`hrow += history_len - hlen`).
|
|
pub fn penalty_window(history_row: &[i32], penalty_last_n: i32) -> &[i32] {
|
|
let hlen = usize::try_from(penalty_last_n.max(0))
|
|
.unwrap_or(0)
|
|
.min(history_row.len());
|
|
&history_row[history_row.len() - hlen..]
|
|
}
|
|
|
|
/// Penalised logits of a row: each in-vocabulary token occurring `c > 0` times
|
|
/// in `window` goes through [`apply_penalties`] once with count `c`. Ids
|
|
/// outside `[0, n_vocab)` are ignored.
|
|
pub fn penalised_logits(logits: &[f32], window: &[i32], p: &SamplerParams) -> Vec<f32> {
|
|
let mut s = logits.to_vec();
|
|
let mut ids: Vec<usize> = window
|
|
.iter()
|
|
.filter_map(|&h| usize::try_from(h).ok())
|
|
.filter(|&h| h < logits.len())
|
|
.collect();
|
|
ids.sort_unstable();
|
|
let mut i = 0;
|
|
while i < ids.len() {
|
|
let v = ids[i];
|
|
let mut j = i;
|
|
while j < ids.len() && ids[j] == v {
|
|
j += 1;
|
|
}
|
|
s[v] = apply_penalties(logits[v], (j - i) as i32, p);
|
|
i = j;
|
|
}
|
|
s
|
|
}
|
|
|
|
/// The greedy argmax over (already penalised) logits: strict `>` from `-inf`,
|
|
/// so the LOWEST index wins ties, NaN and `-inf` are never picked, and a row
|
|
/// with no candidate answers 0.
|
|
pub fn greedy_pick(scores: &[f32]) -> i32 {
|
|
let mut bv = f32::NEG_INFINITY;
|
|
let mut best = scores.len();
|
|
for (v, &s) in scores.iter().enumerate() {
|
|
if s > bv {
|
|
bv = s;
|
|
best = v;
|
|
}
|
|
}
|
|
if best < scores.len() { best as i32 } else { 0 }
|
|
}
|
|
|
|
/// `k` rounds of "first unpicked maximum" (`mirror_select`). Sentinel rounds
|
|
/// store `(0, -inf)` and mark id 0 taken, as the Original does.
|
|
pub fn select_topk(scores: &[f32], k: usize) -> Selection {
|
|
let n = scores.len();
|
|
let mut taken = vec![false; n];
|
|
let mut ids = Vec::with_capacity(k);
|
|
let mut logits = Vec::with_capacity(k);
|
|
for _ in 0..k {
|
|
let mut best = n;
|
|
let mut bv = f32::NEG_INFINITY;
|
|
for (v, &s) in scores.iter().enumerate() {
|
|
if !taken[v] && s > bv {
|
|
bv = s;
|
|
best = v;
|
|
}
|
|
}
|
|
let id = if best < n { best } else { 0 };
|
|
taken[id] = true;
|
|
ids.push(id as i32);
|
|
logits.push(bv);
|
|
}
|
|
Selection { ids, logits }
|
|
}
|
|
|
|
/// The tail of the chain over a selection list: top_p over the whole list,
|
|
/// then min_p on its survivors, temperature, one Philox draw at `counter`.
|
|
/// `sampled_tail_warp` / `mirror_pick`, instruction for instruction.
|
|
pub fn pick_from_list(sel: &Selection, p: &SamplerParams, counter: u64) -> Pick {
|
|
let k = sel.ids.len();
|
|
let l = &sel.logits;
|
|
let inv_t: f32 = if p.temperature > 0.0 {
|
|
1.0f32 / p.temperature
|
|
} else {
|
|
0.0
|
|
};
|
|
let mut n_keep = k;
|
|
let mut mx = l[0];
|
|
for &x in &l[1..] {
|
|
mx = mx.max(x);
|
|
}
|
|
if p.top_p < 1.0 {
|
|
let mut sum = 0.0f64;
|
|
for &x in l.iter() {
|
|
sum += (f64::from(x) - f64::from(mx)).exp();
|
|
}
|
|
let mut cum = 0.0f64;
|
|
let mut cut = k;
|
|
for (i, &x) in l.iter().enumerate() {
|
|
cum += (f64::from(x) - f64::from(mx)).exp() / sum;
|
|
if cum >= f64::from(p.top_p) {
|
|
cut = i + 1;
|
|
break;
|
|
}
|
|
}
|
|
if (cut as i64) < i64::from(p.min_keep) {
|
|
cut = if i64::from(p.min_keep) < k as i64 {
|
|
p.min_keep as usize
|
|
} else {
|
|
k
|
|
};
|
|
}
|
|
n_keep = cut;
|
|
}
|
|
if p.min_p > 0.0 {
|
|
let thresh = l[0] + p.min_p.ln();
|
|
for (i, &x) in l.iter().enumerate().take(n_keep) {
|
|
if x < thresh {
|
|
n_keep = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
let scaled = |i: usize| l[i] * inv_t;
|
|
let mut smx = scaled(0);
|
|
for i in 1..n_keep {
|
|
smx = smx.max(scaled(i));
|
|
}
|
|
let exps: Vec<f64> = (0..n_keep)
|
|
.map(|i| (f64::from(scaled(i)) - f64::from(smx)).exp())
|
|
.collect();
|
|
let mut sum = 0.0f64;
|
|
for &e in &exps {
|
|
sum += e;
|
|
}
|
|
let u = philox_uniform(p.seed, counter);
|
|
let mut cum = 0.0f64;
|
|
let mut pi = n_keep.saturating_sub(1);
|
|
for (i, &e) in exps.iter().enumerate() {
|
|
cum += e / sum;
|
|
if f64::from(u) < cum {
|
|
pi = i;
|
|
break;
|
|
}
|
|
}
|
|
let prob = if n_keep > 0 {
|
|
(exps[pi] / sum) as f32
|
|
} else {
|
|
1.0
|
|
};
|
|
Pick {
|
|
token: sel.ids[pi],
|
|
index: pi,
|
|
n_keep,
|
|
prob,
|
|
uniform: u,
|
|
}
|
|
}
|
|
|
|
/// One row through the whole chain. `history_row` is that row's history slice
|
|
/// (`history_len` slots, unused ones `-1`, most recent last); pass `&[]` when
|
|
/// no penalties apply. `row` offsets the Philox counter.
|
|
pub fn sample_row(
|
|
logits: &[f32],
|
|
history_row: &[i32],
|
|
p: &SamplerParams,
|
|
row: u64,
|
|
) -> Result<i32, SamplerError> {
|
|
if logits.is_empty() {
|
|
return Err(SamplerError::EmptyVocabulary);
|
|
}
|
|
if p.penalty_last_n > 0 && history_row.is_empty() {
|
|
return Err(SamplerError::HistoryRequired);
|
|
}
|
|
let window = penalty_window(history_row, p.penalty_last_n);
|
|
let scores = penalised_logits(logits, window, p);
|
|
if p.is_greedy() {
|
|
return Ok(greedy_pick(&scores));
|
|
}
|
|
let k = sampled_k(p.top_k, logits.len());
|
|
let sel = select_topk(&scores, k);
|
|
Ok(pick_from_list(&sel, p, p.counter.wrapping_add(row)).token)
|
|
}
|
|
|
|
/// `sample_tokens`: `logits` is `(n_tokens, n_vocab)` row-major; `history` is
|
|
/// `(slice of n_tokens * history_len int32, history_len)` or `None`. Row `t`
|
|
/// draws at counter `p.counter + t`.
|
|
pub fn sample_tokens(
|
|
logits: &[f32],
|
|
n_tokens: usize,
|
|
n_vocab: usize,
|
|
history: Option<(&[i32], usize)>,
|
|
p: &SamplerParams,
|
|
) -> Result<Vec<i32>, SamplerError> {
|
|
if n_tokens == 0 {
|
|
return Ok(Vec::new());
|
|
}
|
|
if n_vocab == 0 {
|
|
return Err(SamplerError::EmptyVocabulary);
|
|
}
|
|
let expected = n_tokens
|
|
.checked_mul(n_vocab)
|
|
.ok_or(SamplerError::LogitsLength {
|
|
expected: usize::MAX,
|
|
actual: logits.len(),
|
|
})?;
|
|
if logits.len() != expected {
|
|
return Err(SamplerError::LogitsLength {
|
|
expected,
|
|
actual: logits.len(),
|
|
});
|
|
}
|
|
let hl = history.map_or(0, |(_, hl)| hl);
|
|
if p.penalty_last_n > 0 && (history.is_none() || hl == 0) {
|
|
return Err(SamplerError::HistoryRequired);
|
|
}
|
|
if let Some((h, hl)) = history
|
|
&& h.len() != n_tokens * hl
|
|
{
|
|
return Err(SamplerError::HistoryShape {
|
|
expected: n_tokens * hl,
|
|
actual: h.len(),
|
|
});
|
|
}
|
|
(0..n_tokens)
|
|
.map(|t| {
|
|
let row = &logits[t * n_vocab..(t + 1) * n_vocab];
|
|
let hist: &[i32] = match history {
|
|
Some((h, hl)) if hl > 0 => &h[t * hl..(t + 1) * hl],
|
|
_ => &[],
|
|
};
|
|
sample_row(row, hist, p, t as u64)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn p() -> SamplerParams {
|
|
SamplerParams {
|
|
seed: 7,
|
|
..SamplerParams::default()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sampled_k_rules() {
|
|
assert_eq!(sampled_k(20, 1000), 20);
|
|
assert_eq!(sampled_k(0, 1000), 64);
|
|
assert_eq!(sampled_k(-5, 1000), 64);
|
|
assert_eq!(sampled_k(63, 1000), 63);
|
|
assert_eq!(sampled_k(64, 1000), 64);
|
|
assert_eq!(sampled_k(65, 1000), 64);
|
|
assert_eq!(sampled_k(20, 8), 8);
|
|
}
|
|
|
|
#[test]
|
|
fn repeat_penalty_multiplies_negative_and_divides_positive() {
|
|
let q = SamplerParams {
|
|
penalty_repeat: 2.0,
|
|
..p()
|
|
};
|
|
assert_eq!(apply_penalties(-3.0, 1, &q), -6.0);
|
|
assert_eq!(apply_penalties(4.0, 1, &q), 2.0);
|
|
assert_eq!(apply_penalties(4.0, 0, &q), 4.0);
|
|
let r = SamplerParams {
|
|
penalty_freq: 0.5,
|
|
penalty_present: 1.5,
|
|
..p()
|
|
};
|
|
// count 3: 3*0.5 + 1*1.5 = 3.0 off the (unchanged) logit
|
|
assert_eq!(apply_penalties(10.0, 3, &r), 7.0);
|
|
}
|
|
|
|
#[test]
|
|
fn greedy_ties_go_to_lowest_index_and_empty_rows_answer_zero() {
|
|
assert_eq!(greedy_pick(&[1.0, 3.0, 3.0, 2.0]), 1);
|
|
assert_eq!(greedy_pick(&[f32::NEG_INFINITY, f32::NAN]), 0);
|
|
assert_eq!(greedy_pick(&[f32::NAN, -1.0]), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn selection_is_descending_with_lowest_id_ties() {
|
|
let s = select_topk(&[1.0, 5.0, 5.0, 2.0, 5.0], 4);
|
|
assert_eq!(s.ids, vec![1, 2, 4, 3]);
|
|
assert_eq!(s.logits, vec![5.0, 5.0, 5.0, 2.0]);
|
|
}
|
|
|
|
#[test]
|
|
fn selection_sentinel_is_id_zero_neg_inf() {
|
|
let s = select_topk(&[f32::NEG_INFINITY, 1.0, f32::NAN], 3);
|
|
assert_eq!(s.ids, vec![1, 0, 0]);
|
|
assert_eq!(s.logits[0], 1.0);
|
|
assert!(s.logits[1] == f32::NEG_INFINITY && s.logits[2] == f32::NEG_INFINITY);
|
|
}
|
|
|
|
#[test]
|
|
fn penalty_window_is_the_tail() {
|
|
let h = [-1, -1, 5, 6, 7];
|
|
assert_eq!(penalty_window(&h, 2), &[6, 7]);
|
|
assert_eq!(penalty_window(&h, 99), &h);
|
|
assert_eq!(penalty_window(&h, 0), &[] as &[i32]);
|
|
assert_eq!(penalty_window(&h, -3), &[] as &[i32]);
|
|
}
|
|
|
|
#[test]
|
|
fn history_is_required_when_penalising() {
|
|
let q = SamplerParams {
|
|
penalty_last_n: 4,
|
|
..p()
|
|
};
|
|
assert_eq!(
|
|
sample_row(&[0.0, 1.0], &[], &q, 0),
|
|
Err(SamplerError::HistoryRequired)
|
|
);
|
|
assert_eq!(
|
|
sample_tokens(&[0.0, 1.0], 1, 2, None, &q),
|
|
Err(SamplerError::HistoryRequired)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn shapes_are_checked() {
|
|
assert_eq!(
|
|
sample_tokens(&[0.0; 5], 2, 3, None, &p()),
|
|
Err(SamplerError::LogitsLength {
|
|
expected: 6,
|
|
actual: 5
|
|
})
|
|
);
|
|
assert_eq!(
|
|
sample_tokens(&[0.0; 6], 2, 3, Some((&[0; 5], 3)), &p()),
|
|
Err(SamplerError::HistoryShape {
|
|
expected: 6,
|
|
actual: 5
|
|
})
|
|
);
|
|
assert_eq!(sample_tokens(&[], 0, 3, None, &p()), Ok(vec![]));
|
|
assert_eq!(
|
|
sample_tokens(&[], 1, 0, None, &p()),
|
|
Err(SamplerError::EmptyVocabulary)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn counter_advances_per_row_and_batch_equals_singles() {
|
|
let vocab = 16;
|
|
let count = 32;
|
|
let logits = vec![0.0f32; count * vocab];
|
|
let q = SamplerParams {
|
|
top_k: 16,
|
|
top_p: 1.0,
|
|
seed: 123,
|
|
counter: (1 << 32) + 7,
|
|
..p()
|
|
};
|
|
let batch = sample_tokens(&logits, count, vocab, None, &q).unwrap();
|
|
let singles: Vec<i32> = (0..count)
|
|
.map(|i| {
|
|
let one = SamplerParams {
|
|
counter: q.counter + i as u64,
|
|
..q
|
|
};
|
|
sample_tokens(&logits[..vocab], 1, vocab, None, &one).unwrap()[0]
|
|
})
|
|
.collect();
|
|
assert_eq!(batch, singles);
|
|
assert!(
|
|
batch.iter().any(|&t| t != batch[0]),
|
|
"uniform logits must vary across draws"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn temperature_zero_or_greedy_flag_is_argmax() {
|
|
let l = [0.0, 2.0, 1.0];
|
|
let q = SamplerParams {
|
|
temperature: 0.0,
|
|
..p()
|
|
};
|
|
assert_eq!(sample_row(&l, &[], &q, 0), Ok(1));
|
|
let g = SamplerParams {
|
|
greedy: true,
|
|
temperature: 1.0,
|
|
..p()
|
|
};
|
|
assert_eq!(sample_row(&l, &[], &g, 0), Ok(1));
|
|
}
|
|
|
|
#[test]
|
|
fn min_p_cuts_a_prefix_of_the_list() {
|
|
let sel = Selection {
|
|
ids: vec![3, 1, 2],
|
|
logits: vec![5.0, 4.9, 0.0],
|
|
};
|
|
let q = SamplerParams {
|
|
top_p: 1.0,
|
|
min_p: 0.5,
|
|
..p()
|
|
};
|
|
let pick = pick_from_list(&sel, &q, 0);
|
|
assert_eq!(pick.n_keep, 2);
|
|
}
|
|
}
|