Files
leleka/crates/sampler-ref/tests/serve_loop.rs
T

388 lines
13 KiB
Rust

//! The serve loop under sampling on a toy model: speculative decoding with coupled draft sampling must produce the
//! SAME token stream as plain sampled decoding, whatever the window sizes, drafts and acceptance pattern
//! (`coupled_draft.hpp`: "the output is a function of the seed alone, whatever the drafts are").
//!
//! The toy target is a hash of the last three tokens; the draft is the target plus noise (`noise = 0`: the draft
//! equals the target, so a coupled draft - same chain, same history, same uniform - is always accepted). Both loops
//! use only the library under test: `ServeSampling` for request parameters, window staging, history and acceptance,
//! `chain::sample_row` as the verifier's head, `coupled::coupled_draft_sample` as the drafter. The plain loop is the
//! Original's non-speculative decode: counter = sequence index of the fed token, history = the last `h` tokens
//! including the fed one.
use leleka_sampler_ref::{
chain::{SamplerParams, sample_row},
coupled::{COUPLED_HIST_CAP, coupled_draft_cell, coupled_draft_sample},
serve::{ServeSampling, settle_window, window_rows},
};
const V: usize = 48;
const EOS: i64 = 47;
fn mix(mut x: u64) -> u64 {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
fn unit(x: u64) -> f32 {
(mix(x) >> 40) as f32 / (1u64 << 24) as f32
}
/// Logits after the context `ctx`: a few strong tokens depend on the last three tokens, the rest is a long tail.
fn target_logits(ctx: &[i32]) -> Vec<f32> {
let key = ctx
.iter()
.rev()
.take(3)
.fold(7u64, |k, &t| mix(k ^ (t as u64 + 1)));
(0..V as u64)
.map(|i| {
let r = unit(key ^ (i * 0x1_0000_0001));
let strong = if r > 0.85 { 4.0 } else { 0.0 };
r * 3.0 + strong - 1.5
})
.collect()
}
fn draft_logits(ctx: &[i32], cell: i64, noise: f32) -> Vec<f32> {
let mut logits = target_logits(ctx);
for (i, l) in logits.iter_mut().enumerate() {
*l += noise * (unit(mix(cell as u64) ^ i as u64) - 0.5);
}
logits
}
fn last_n(ctx: &[i32], h: usize) -> Vec<i32> {
let take = h.min(ctx.len());
let mut row = vec![-1; h - take];
row.extend_from_slice(&ctx[ctx.len() - take..]);
row
}
/// Plain sampled decode of `n` tokens (stops after an end-of-turn token).
fn plain(sampling: &ServeSampling, prompt: &[i32], n: usize) -> Vec<i32> {
let mut ctx = prompt.to_vec();
let mut out = Vec::new();
while out.len() < n {
let fed = ctx.len() as u64 - 1;
let mut p = *sampling.params();
p.counter = fed;
let history = if sampling.hist_n() > 0 {
last_n(&ctx, sampling.hist_n())
} else {
Vec::new()
};
let pick = sample_row(&target_logits(&ctx), &history, &p, 0).unwrap();
out.push(pick);
ctx.push(pick);
if i64::from(pick) == EOS {
break;
}
}
out
}
#[derive(Clone, Copy)]
struct Spec {
mtp_t: usize,
max_drafts: usize,
spec_min_p: f32,
noise: f32,
/// Draft vocabulary: every id, or only the ids with `id % 3 != 0` (a subset head).
subset: bool,
}
struct SpecRun {
tokens: Vec<i32>,
windows: usize,
offered: usize,
accepted: usize,
}
/// The mode-17 serve loop, generate.cpp's `while (!cancelled && produced_n < max_new)`.
fn speculative(sampling: &ServeSampling, prompt: &[i32], n: usize, spec: Spec) -> SpecRun {
let sub_to_id: Vec<i32> = (0..V as i32).filter(|id| id % 3 != 0).collect();
let mut id_to_sub = [-1i32; V];
for (s, &id) in sub_to_id.iter().enumerate() {
id_to_sub[id as usize] = s as i32;
}
let mut consumed: Vec<i32> = prompt[..prompt.len() - 1].to_vec();
let (mut x, mut p) = (prompt[prompt.len() - 1], prompt.len() as i64 - 1);
let (mut drafts, mut dprob): (Vec<i32>, Vec<f32>) = (Vec::new(), Vec::new());
let (mut first, mut out, mut run) = (
true,
Vec::new(),
SpecRun {
tokens: Vec::new(),
windows: 0,
offered: 0,
accepted: 0,
},
);
while out.len() < n {
let t = window_rows(spec.mtp_t, spec.spec_min_p, &dprob, first);
first = false;
let mut window = vec![x];
window.extend_from_slice(&drafts[..t - 1]);
// the verifier: row r draws counter p + r over the literal history of its row
let stage = sampling.window(p as u64, &consumed, &window).unwrap();
let picks: Vec<i32> = (0..t)
.map(|r| {
let mut ctx = consumed.clone();
ctx.extend_from_slice(&window[..=r]);
let hist = if stage.hist_n > 0 {
&stage.history[r * stage.hist_n..(r + 1) * stage.hist_n]
} else {
&[][..]
};
sample_row(&target_logits(&ctx), hist, &stage.params, r as u64).unwrap()
})
.collect();
let settled = settle_window(&window, &picks, &[EOS], out.len(), n);
let a = settled.accepted;
run.windows += 1;
run.offered += t - 1;
run.accepted += a;
consumed.extend_from_slice(&window[..=a]);
out.extend_from_slice(&picks[..settled.emitted]);
if settled.eos || out.len() >= n {
break;
}
// the drafter: chain from cell p + a; the verifying row of step j draws counter cell + 1
let next = picks[a];
let mut ring = vec![-1i32; COUPLED_HIST_CAP as usize + 8];
if sampling.draft_history_due(false, out.len(), n) {
let base = sampling.draft_history(&consumed, next).unwrap();
let h = sampling.hist_n();
let cap = COUPLED_HIST_CAP as usize;
ring[cap - h..cap].copy_from_slice(&base);
}
drafts.clear();
dprob.clear();
let mut ctx = consumed.clone();
ctx.push(next);
let limit = (spec.mtp_t - 1).min(spec.max_drafts);
let mut j = 0;
while j < limit.max(1) && (j == 0 || dprob[j - 1] >= spec.spec_min_p) {
let cell = coupled_draft_cell(p, a as i32, j as i32);
let logits = draft_logits(&ctx, cell, spec.noise);
let (id, prob) = if let Some(params) = sampling.draft_params() {
let (mut l, map): (Vec<f32>, Option<&[i32]>) = if spec.subset {
(
sub_to_id.iter().map(|&id| logits[id as usize]).collect(),
Some(&sub_to_id),
)
} else {
(logits, None)
};
let inv = spec.subset.then_some(&id_to_sub[..]);
let d = coupled_draft_sample(
&mut l,
map,
inv,
V,
params,
&mut ring,
COUPLED_HIST_CAP,
j as i32,
cell as i32,
);
(d.id, d.prob)
} else {
// uncoupled: the argmax proposal with its softmax confidence
let best = (0..V)
.max_by(|&i, &k| logits[i].total_cmp(&logits[k]).then(k.cmp(&i)))
.unwrap();
let z: f32 = logits.iter().map(|l| (l - logits[best]).exp()).sum();
(best as i32, 1.0 / z)
};
drafts.push(id);
dprob.push(prob);
ctx.push(id);
j += 1;
}
x = next;
p += a as i64 + 1;
}
run.tokens = out;
run
}
fn param_sets() -> Vec<SamplerParams> {
let mut sets = Vec::new();
for (temperature, top_k, top_p, min_p) in [
(0.8, 20, 0.95, 0.0),
(1.0, 0, 1.0, 0.0),
(0.6, 5, 0.9, 0.05),
(1.3, 70, 0.8, 0.0),
] {
for (last_n, repeat, freq, present) in [
(0, 1.0, 0.0, 0.0),
(8, 1.3, 0.0, 0.0),
(6, 1.0, 0.2, 0.3),
(5000, 1.15, 0.05, 0.1),
] {
sets.push(SamplerParams {
temperature,
top_k,
top_p,
min_p,
penalty_last_n: last_n,
penalty_repeat: repeat,
penalty_freq: freq,
penalty_present: present,
..SamplerParams::default()
});
}
}
sets
}
#[test]
fn sampled_speculation_equals_plain_sampling_for_every_window_draft_and_penalty() {
let prompts: [&[i32]; 4] = [
&[3],
&[3, 9],
&[1, 2, 3, 4, 5, 6],
&[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8],
];
let specs = [
Spec {
mtp_t: 2,
max_drafts: 1,
spec_min_p: 0.0,
noise: 0.0,
subset: false,
},
Spec {
mtp_t: 4,
max_drafts: 3,
spec_min_p: 0.0,
noise: 0.5,
subset: false,
},
Spec {
mtp_t: 8,
max_drafts: 7,
spec_min_p: 0.0,
noise: 3.0,
subset: false,
},
Spec {
mtp_t: 5,
max_drafts: 4,
spec_min_p: 0.3,
noise: 0.2,
subset: false,
},
Spec {
mtp_t: 6,
max_drafts: 5,
spec_min_p: 0.0,
noise: 0.0,
subset: true,
},
Spec {
mtp_t: 3,
max_drafts: 2,
spec_min_p: 0.5,
noise: 1.0,
subset: true,
},
];
let mut runs = 0;
for (index, params) in param_sets().iter().enumerate() {
for coupled in [true, false] {
for (seed_no, prompt) in prompts.iter().enumerate() {
for (spec_no, spec) in specs.iter().enumerate() {
// seed 0 exercises the clock fallback: the same tick drives both loops
let seed = if seed_no == 0 && spec_no == 0 {
0
} else {
1000 * index as u64 + 10 * seed_no as u64 + spec_no as u64 + 1
};
let sampling = ServeSampling::new(
&SamplerParams { seed, ..*params },
0xC10C_C10C,
coupled,
);
let want = plain(&sampling, prompt, 40);
let got = speculative(&sampling, prompt, 40, *spec);
assert_eq!(
got.tokens, want,
"params {index} coupled {coupled} prompt {seed_no} spec {spec_no}"
);
runs += 1;
}
}
}
}
assert_eq!(runs, 16 * 2 * 4 * 6);
}
#[test]
fn a_coupled_draft_close_to_the_target_is_accepted_far_more_often_than_an_argmax_draft() {
let params = SamplerParams {
temperature: 1.0,
top_k: 20,
top_p: 0.95,
penalty_last_n: 8,
penalty_repeat: 1.2,
..SamplerParams::default()
};
let spec = Spec {
mtp_t: 5,
max_drafts: 4,
spec_min_p: 0.0,
noise: 0.0,
subset: false,
};
let (mut coupled_rate, mut argmax_rate) = ((0, 0), (0, 0));
for seed in 1..=40u64 {
for (coupled, rate) in [(true, &mut coupled_rate), (false, &mut argmax_rate)] {
let sampling = ServeSampling::new(&SamplerParams { seed, ..params }, 1, coupled);
let run = speculative(&sampling, &[1, 2, 3, 4], 60, spec);
rate.0 += run.accepted;
rate.1 += run.offered;
}
}
// identical distributions, history and uniform: every coupled draft is the target's own pick
assert_eq!(
coupled_rate.0, coupled_rate.1,
"coupled drafts equal the verifying pick: {coupled_rate:?}"
);
assert!(
(argmax_rate.0 as f64) < 0.8 * argmax_rate.1 as f64,
"argmax drafts under sampling: {argmax_rate:?}"
);
}
#[test]
fn greedy_requests_never_arm_the_coupled_drafter() {
let sampling = ServeSampling::new(
&SamplerParams {
temperature: 0.0,
seed: 5,
..SamplerParams::default()
},
1,
true,
);
assert!(sampling.draft_params().is_none());
let want = plain(&sampling, &[1, 2, 3], 30);
let got = speculative(
&sampling,
&[1, 2, 3],
30,
Spec {
mtp_t: 5,
max_drafts: 4,
spec_min_p: 0.0,
noise: 0.5,
subset: false,
},
);
assert_eq!(got.tokens, want);
}