feat(serving): serve non-greedy requests through the Original sampler chain

backend-api carries SamplingOptions; backend.rs plans each request with the
validated SamplingParams instead of refusing temperature != 0; the output stage
bypasses the compact argmax for an armed request and draws with the bit-exact
host reference (counter = fed-token position, penalty history = prompt+generated).
MTP with sampling is refused explicitly. Desktop RPC only bounds temperature.
Docs: docs/sampler-reference.md (verified vs open).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:55:55 +02:00
co-authored by Claude Sonnet 5.5
parent 4d1594f71c
commit 3ca559cebc
14 changed files with 525 additions and 13 deletions
+25
View File
@@ -131,7 +131,32 @@ pub struct GenerationRequest {
pub request_id: String,
pub prompt: String,
pub max_output_tokens: u32,
/// Thousandths; 0 is greedy.
pub temperature_milli: u32,
/// Remaining sampling controls. All-`None` keeps the Original defaults.
pub sampling: SamplingOptions,
}
/// Sampling controls beyond temperature, as the Original serving layer takes them.
/// Fractions are fixed-point millionths so a request stays `Eq`; the runtime
/// validates ranges (see `leleka-sampler-ref`). `None` keeps the Original's default.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SamplingOptions {
/// `0..=1_000_000`; 1_000_000 disables nucleus filtering.
pub top_p_micro: Option<u32>,
/// Integer; 0 or above 64 selects the widest list (64).
pub top_k: Option<u32>,
/// `0..=1_000_000`.
pub min_p_micro: Option<u32>,
/// `> 0`; 1_000_000 is off.
pub repetition_penalty_micro: Option<u32>,
/// `-2_000_000..=2_000_000`.
pub frequency_penalty_micro: Option<i32>,
/// `-2_000_000..=2_000_000`.
pub presence_penalty_micro: Option<i32>,
pub penalty_last_n: Option<u32>,
/// `None` or 0 draws a fresh seed per request.
pub seed: Option<u64>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
+1
View File
@@ -12,6 +12,7 @@ leleka-backend-api = { path = "../backend-api" }
leleka-tokenizer = { path = "../tokenizer" }
leleka-model-format = { path = "../model-format" }
leleka-quant-core = { path = "../quant-core" }
leleka-sampler-ref = { path = "../sampler-ref" }
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver"] }
[target.'cfg(target_os = "linux")'.dependencies]
+93 -4
View File
@@ -1456,10 +1456,16 @@ fn serve_load(
eos,
mtp: matches!(loaded.effective_mode, InferenceMode::ExperimentalMtp { .. }),
};
let sampler = request_sampler(&request, clock_seed());
let result = if !shared.ready.load(Ordering::Acquire) {
Err(GenerationFailure::Backend(unavailable(
"resident prefix unavailable",
)))
} else if matches!(sampler, Err(_) | Ok(Some(_))) && run.mtp {
// Sampled drafting/verification (coupled draft sampling) is not wired.
Err(GenerationFailure::Backend(unsupported(
"sampling is unavailable with MTP",
)))
} else if run.mtp {
generate_mtp_resume(
run,
@@ -1469,7 +1475,26 @@ fn serve_load(
&mut pending_prefix,
)
} else {
generate(run, &prompt, request.max_output_tokens)
match sampler {
Ok(None) => generate(run, &prompt, request.max_output_tokens),
Ok(Some(params)) => match crate::qwen_forward::step_sampler::StepSampler::new(
params, &prompt,
)
.and_then(|plan| output.arm_sampler(plan))
{
Ok(()) => {
let result = generate(run, &prompt, request.max_output_tokens);
output.disarm_sampler();
result
}
Err(_) => Err(GenerationFailure::Backend(unavailable(
"sampling setup failed",
))),
},
Err(_) => Err(GenerationFailure::Backend(invalid(
"unsupported generation request",
))),
}
};
{
use std::io::Write;
@@ -1959,12 +1984,43 @@ fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> {
|| request.prompt.len() > PROMPT_LIMIT
|| request.max_output_tokens == 0
|| request.max_output_tokens > OUTPUT_LIMIT
|| request.temperature_milli != 0
|| request_sampler(request, 1).is_err()
{
return Err(invalid("unsupported generation request"));
}
Ok(())
}
/// Validated sampling plan of a request: `None` keeps the ordinary greedy path
/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for
/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`).
fn request_sampler(
request: &GenerationRequest,
entropy: u64,
) -> Result<Option<leleka_sampler_ref::SamplerParams>, leleka_sampler_ref::SamplingError> {
let s = &request.sampling;
let raw = leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint {
temperature_milli: request.temperature_milli,
top_p_micro: s.top_p_micro,
top_k: s.top_k,
min_p_micro: s.min_p_micro,
repetition_penalty_micro: s.repetition_penalty_micro,
frequency_penalty_micro: s.frequency_penalty_micro,
presence_penalty_micro: s.presence_penalty_micro,
penalty_last_n: s.penalty_last_n,
seed: s.seed,
});
let params = leleka_sampler_ref::SamplingParams::resolve(&raw)?;
Ok(params.needs_sampler().then(|| params.to_sampler_params(entropy)))
}
/// The steady-clock tick the Original takes as the seed of a request without one.
fn clock_seed() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(1, |d| d.as_nanos() as u64)
.max(1)
}
fn prepare_prompt(
tokenizer: &Tokenizer,
request: &GenerationRequest,
@@ -2748,7 +2804,7 @@ mod tests {
request_id: "synthetic-1".into(),
prompt: "x".into(),
max_output_tokens: 1,
temperature_milli: 0,
temperature_milli: 0, sampling: Default::default(),
}
}
#[test]
@@ -2850,13 +2906,46 @@ mod tests {
r.max_output_tokens = 4097;
assert!(validate_request(&r).is_err());
r.max_output_tokens = 1;
r.temperature_milli = 1;
r.temperature_milli = 2001;
assert!(validate_request(&r).is_err());
r.temperature_milli = 700;
assert!(validate_request(&r).is_ok());
r.temperature_milli = 0;
r.prompt = "x".repeat(PROMPT_LIMIT + 1);
assert!(validate_request(&r).is_err());
}
#[test]
fn sampling_requests_are_planned_instead_of_refused() {
let mut r = request();
// plain greedy: no sampler, the ordinary compact path
assert!(matches!(request_sampler(&r, 5), Ok(None)));
// temperature: a sampler with the request's seed or the supplied entropy
r.temperature_milli = 700;
r.sampling.top_p_micro = Some(950_000);
r.sampling.top_k = Some(40);
let p = request_sampler(&r, 5).unwrap().expect("sampler");
assert!(!p.greedy && p.seed == 5 && p.top_k == 40 && p.counter == 0);
r.sampling.seed = Some(77);
assert_eq!(request_sampler(&r, 5).unwrap().unwrap().seed, 77);
// greedy plus a penalty still needs the penalised argmax
r.temperature_milli = 0;
r.sampling = Default::default();
r.sampling.presence_penalty_micro = Some(500_000);
let p = request_sampler(&r, 5).unwrap().expect("penalised greedy");
assert!(p.greedy && p.penalty_last_n == 64);
// out-of-contract fields are refused before acceptance
for bad in [
|r: &mut GenerationRequest| r.sampling.top_p_micro = Some(1_000_001),
|r: &mut GenerationRequest| r.sampling.repetition_penalty_micro = Some(0),
|r: &mut GenerationRequest| r.sampling.min_p_micro = Some(2_000_000),
|r: &mut GenerationRequest| r.sampling.frequency_penalty_micro = Some(3_000_000),
] {
let mut r = request();
bad(&mut r);
assert!(validate_request(&r).is_err());
}
}
#[test]
fn utf8_split_tokens_publish_only_complete_prefix() {
let mut pending = Utf8Pending::default();
assert_eq!(pending.push(&[b'a', 0xf0]).unwrap(), Some("a".into()));
+1 -1
View File
@@ -67,7 +67,7 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
], public_renderer::Effort::None,
).expect("actual public renderer refused frame variant");
let req = GenerationRequest { request_id: CASE_IDS[index + 1].into(), prompt,
max_output_tokens: CAP, temperature_milli: 0 };
max_output_tokens: CAP, temperature_milli: 0, sampling: Default::default() };
let ids = prepare_prompt(inputs.tokenizer, &req, 262144)
.expect("actual admitted tokenizer refused public frame variant");
requests.push((req, ids));
@@ -119,7 +119,7 @@ fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec<Case> {
assert!(wire.len() <= 32768);
assert_eq!(wire.len() as u64, number(entry, "wire_bytes"));
assert_eq!(sha(wire.as_bytes()), text(entry, "wire_sha256"));
let request = GenerationRequest { request_id: PHASES[i].into(), prompt: prompt.to_owned(), max_output_tokens: CAP, temperature_milli: 0 };
let request = GenerationRequest { request_id: PHASES[i].into(), prompt: prompt.to_owned(), max_output_tokens: CAP, temperature_milli: 0, sampling: Default::default() };
// Actual admitted tokenizer, never trust supplied count/IDs as a producer.
assert_eq!(prepare_prompt(tokenizer, &request, 262144).expect("genuine public frame tokenization refused"), ids);
assert!(cases.iter().all(|old| old.ids != ids && old.request.prompt != request.prompt));
@@ -108,7 +108,7 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec<u32>, Value) {
request_id: "public-paired-owner-generation".into(),
prompt,
max_output_tokens: CAP,
temperature_milli: 0,
temperature_milli: 0, sampling: Default::default(),
};
let ids = prepare_prompt(tokenizer, &req, 262144)
.expect("actual pinned tokenizer refused public frame");
@@ -109,7 +109,7 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec<u32>, Value) {
request_id: "public-paired-owner-generation".into(),
prompt,
max_output_tokens: CAP,
temperature_milli: 0,
temperature_milli: 0, sampling: Default::default(),
};
let ids = prepare_prompt(tokenizer, &req, 262144)
.expect("actual pinned tokenizer refused public frame");
@@ -18,6 +18,7 @@ pub(crate) mod moe_weight_cache;
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
pub(crate) mod oracle_capture;
pub(crate) mod output;
pub(crate) mod step_sampler;
pub(crate) mod qsa_attention;
pub(crate) mod qsa_index;
#[cfg(all(target_os="linux",target_arch="x86_64"))]
@@ -30,6 +30,8 @@ pub(crate) struct OutputStage<'context, 'driver> {
binding: BindingIdentity,
weights: DeviceBuffer<'context>,
compact: std::cell::RefCell<Option<HeadGreedyWorkspace<'context>>>,
// Armed by the backend for one non-greedy request only; see step_sampler.rs.
sampler: std::cell::RefCell<Option<super::step_sampler::StepSampler>>,
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
compact_completions: std::cell::Cell<u64>,
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
@@ -94,6 +96,8 @@ impl OriginalPromptSample {
enum LogitValues {
Full(Box<[FiniteF32]>),
Compact(HeadGreedySelection),
// The token already drawn from the complete vector by the armed request sampler.
Selected(TokenId),
}
impl FiniteLogits {
@@ -115,7 +119,7 @@ impl FiniteLogits {
LogitValues::Compact(selection) => {
selected_token(selection)?;
}
LogitValues::Full(_) => {}
LogitValues::Full(_) | LogitValues::Selected(_) => {}
}
Ok(())
}
@@ -133,7 +137,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch)}
let mixed=GrStage::final_mix_original_prompt(binding,completed,txn,cache)?;
if mixed.len()!=EMBEDDING||mixed.iter().any(|value|!value.is_finite()){return Err(Error::NonFinite)}
let logits=self.project_mixed(binding.identity(),completed.token(),completed.position(),&mixed,context)?;
if self.sampler_wants(completed.position())? {return Err(Error::Unsupported(Stage::Output));}
let logits=self.project_mixed(binding.identity(),completed.token(),completed.position(),&mixed,context,false)?;
txn.validate_final(completed)?;logits.validate_for(&binding.identity(),completed.token(),completed.position())?;
if matches!(&logits.values,LogitValues::Compact(_)){self.record_compact_completion()?;}
Ok(logits)
@@ -168,6 +173,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
binding: binding.identity(),
weights: device_weights,
compact: std::cell::RefCell::new(None),
sampler: std::cell::RefCell::new(None),
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
compact_completions: std::cell::Cell::new(0),
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
@@ -274,7 +280,19 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
if super::oracle_capture::enabled() {
super::oracle_capture::stage_f32(-1, "final_head_mixed", &mixed)?;
}
let logits = self.project_mixed(identity, token, position, &mixed, txn.cuda_context()?)?;
// A request sampler needs the complete vector, never the compact device argmax.
let sampled = self.sampler_wants(position)?;
let mut logits = self.project_mixed(
identity,
token,
position,
&mixed,
txn.cuda_context()?,
sampled,
)?;
if sampled {
logits = self.sample_complete(logits)?;
}
if matches!(&logits.values, LogitValues::Compact(_)) {
let current = binding.identity();
txn.validate_binding(&current)?;
@@ -305,12 +323,17 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) {
return Err(Error::IdentityMismatch);
}
// Sampling under MTP needs the coupled-draft machinery; it is not wired.
if self.sampler_wants(mixed.frame().position())? {
return Err(Error::Unsupported(Stage::Output));
}
let logits = self.project_mixed(
identity,
mixed.frame().token(),
mixed.frame().position(),
mixed.values(),
context,
false,
)?;
if matches!(&logits.values, LogitValues::Compact(_)) {
mixed.frame().validate(binding, session)?;
@@ -331,6 +354,55 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
greedy(logits)
}
/// Arm the per-request sampler for the plain decode path. One request at a time.
pub(crate) fn arm_sampler(&self, sampler: super::step_sampler::StepSampler) -> Result<()> {
let mut slot = self
.sampler
.try_borrow_mut()
.map_err(|_| Error::IdentityMismatch)?;
if slot.is_some() {
return Err(Error::IdentityMismatch);
}
*slot = Some(sampler);
Ok(())
}
/// Disarm at request end, whatever its outcome. Never fails.
pub(crate) fn disarm_sampler(&self) {
if let Ok(mut slot) = self.sampler.try_borrow_mut() {
*slot = None;
}
}
fn sampler_wants(&self, position: Position) -> Result<bool> {
Ok(self
.sampler
.try_borrow()
.map_err(|_| Error::IdentityMismatch)?
.as_ref()
.is_some_and(|s| s.wants(position.get())))
}
/// Replace a complete finite vector by the token the armed sampler draws from it.
fn sample_complete(&self, logits: FiniteLogits) -> Result<FiniteLogits> {
let LogitValues::Full(values) = &logits.values else {
return Err(Error::IdentityMismatch);
};
let floats: Vec<f32> = values.iter().map(|v| v.get()).collect();
let token = self
.sampler
.try_borrow_mut()
.map_err(|_| Error::IdentityMismatch)?
.as_mut()
.ok_or(Error::IdentityMismatch)?
.pick(&floats, logits.position.get())?;
let token = TokenId::new(u64::from(token), Dimension::new(VOCABULARY as u64)?)?;
Ok(FiniteLogits {
values: LogitValues::Selected(token),
..logits
})
}
fn project_mixed(
&self,
identity: BindingIdentity,
@@ -338,6 +410,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
position: Position,
mixed: &[f32],
context: &Context<'_>,
force_full: bool,
) -> Result<FiniteLogits> {
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(
@@ -348,6 +421,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> {
.try_borrow()
.map_err(|_| Error::IdentityMismatch)?
.is_some()
&& !force_full
&& !self.full_head_observer_active()
{
return self.project_mixed_compact(identity, token, position, mixed, context);
@@ -581,6 +655,7 @@ impl OutputStage<'_, '_> {
pub(super) fn test_reset_replay_capture(&self, logits: &FiniteLogits) -> Result<()> {
let values = match &logits.values {
LogitValues::Full(values) => values,
LogitValues::Selected(_) => return Err(Error::IdentityMismatch),
LogitValues::Compact(_) => {
return if self.full_head_observer_active() {
Err(Error::IdentityMismatch)
@@ -636,6 +711,7 @@ pub(super) fn greedy(logits: FiniteLogits) -> Result<TokenId> {
let values = match logits.values {
LogitValues::Full(values) => values,
LogitValues::Compact(selection) => return selected_token(&selection),
LogitValues::Selected(token) => return Ok(token),
};
if values.len() != VOCABULARY || values.is_empty() {
return Err(Error::InvalidDimension);
@@ -0,0 +1,177 @@
//! Per-request sampling for the plain (non-MTP) decode path.
//!
//! The Q6 output stage already materialises the complete finite logit vector
//! on the host, so the Original sampler chain is applied there with the
//! bit-exact CPU reference (`leleka-sampler-ref`, verified against the
//! Original's host oracle). The GPU `OriginalSampler` (cuda-driver) replaces
//! this only once its compiled asset is pinned; the token contract is the same.
//!
//! Draw positions follow the Original verify window of one row: the row that
//! follows the fed token at sequence index `p` draws Philox counter `p`
//! (`sp.counter = pos0`, row `t = 0`), and the penalty history is the last
//! `min(penalty_last_n, 4096)` tokens of `prompt ++ generated`, the fed token
//! last (`penalty_rows` with a one-token window).
use super::contract::{Error, Result};
use leleka_sampler_ref::chain::{PENALTY_WINDOW_CAP, SamplerParams, sample_row};
pub(crate) const VOCABULARY: usize = 248_320;
/// One request's sampling plan and the tokens it has produced so far.
pub(crate) struct StepSampler {
params: SamplerParams,
prompt: Box<[i32]>,
generated: Vec<i32>,
}
impl StepSampler {
/// `params` must carry the resolved seed; its `counter` is ignored and set per draw.
pub(crate) fn new(params: SamplerParams, prompt: &[u32]) -> Result<Self> {
if prompt.is_empty() || prompt.iter().any(|&t| t as usize >= VOCABULARY) {
return Err(Error::InvalidToken);
}
Ok(Self {
params,
prompt: prompt.iter().map(|&t| t as i32).collect(),
generated: Vec::new(),
})
}
/// The fed token at `position` is the first whose logits are sampled (the last prompt
/// token); earlier prompt steps stay on the ordinary path and are never sampled.
pub(crate) fn wants(&self, position: u64) -> bool {
position >= self.prompt.len() as u64 - 1
}
/// Sequence index of the token that must be fed next.
fn fed_index(&self) -> u64 {
self.prompt.len() as u64 - 1 + self.generated.len() as u64
}
/// Sample the token following the fed token at `position` from its complete logits.
pub(crate) fn pick(&mut self, logits: &[f32], position: u64) -> Result<u32> {
if logits.len() != VOCABULARY {
return Err(Error::InvalidDimension);
}
if position != self.fed_index() {
return Err(Error::IdentityMismatch);
}
let h = usize::try_from(self.params.penalty_last_n.max(0))
.map_err(|_| Error::Overflow)?
.min(PENALTY_WINDOW_CAP);
let total = self.prompt.len() + self.generated.len();
let take = h.min(total);
let mut history = Vec::new();
history
.try_reserve_exact(take)
.map_err(|_| Error::InputAllocation)?;
for i in total - take..total {
history.push(if i < self.prompt.len() {
self.prompt[i]
} else {
self.generated[i - self.prompt.len()]
});
}
let mut params = self.params;
params.counter = position;
let token = sample_row(logits, &history, &params, 0).map_err(|_| Error::InvalidDimension)?;
if token < 0 || token as usize >= VOCABULARY {
return Err(Error::InvalidToken);
}
self.generated
.try_reserve(1)
.map_err(|_| Error::InputAllocation)?;
self.generated.push(token);
Ok(token as u32)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sampled(seed: u64) -> SamplerParams {
SamplerParams {
top_k: 8,
top_p: 0.9,
temperature: 0.8,
seed,
..SamplerParams::default()
}
}
fn logits(salt: usize) -> Vec<f32> {
(0..VOCABULARY)
.map(|i| ((i.wrapping_mul(2_654_435_761).wrapping_add(salt * 97)) % 1009) as f32 / 101.0 - 5.0)
.collect()
}
#[test]
fn only_the_last_prompt_step_and_later_are_sampled() {
let s = StepSampler::new(sampled(1), &[5, 6, 7]).unwrap();
assert!(!s.wants(0) && !s.wants(1));
assert!(s.wants(2) && s.wants(3));
}
#[test]
fn draws_follow_the_originals_counter_and_history_rule() {
let prompt = [11u32, 22, 33];
let mut params = sampled(99);
params.penalty_last_n = 4;
params.penalty_repeat = 1.3;
params.penalty_present = 0.5;
let mut s = StepSampler::new(params, &prompt).unwrap();
let mut seen: Vec<i32> = prompt.iter().map(|&t| t as i32).collect();
for step in 0..6u64 {
let l = logits(step as usize);
let position = 2 + step;
let got = s.pick(&l, position).unwrap();
// independent expectation: window = last 4 of everything fed so far, counter = position
let start = seen.len().saturating_sub(4);
let want_params = SamplerParams { counter: position, ..params };
let want = sample_row(&l, &seen[start..], &want_params, 0).unwrap();
assert_eq!(got as i32, want, "step {step}");
seen.push(got as i32);
}
}
#[test]
fn same_seed_replays_and_a_different_seed_diverges() {
let run = |seed| {
let mut s = StepSampler::new(sampled(seed), &[1, 2]).unwrap();
(0..16u64)
.map(|i| {
let l = vec![0.0f32; VOCABULARY];
s.pick(&l, 1 + i).unwrap()
})
.collect::<Vec<_>>()
};
assert_eq!(run(7), run(7));
assert_ne!(run(7), run(8));
}
#[test]
fn greedy_with_penalties_is_the_penalised_argmax() {
let mut params = SamplerParams { greedy: true, temperature: 0.0, ..sampled(1) };
params.penalty_last_n = 8;
params.penalty_repeat = 100.0;
let mut l = vec![-1.0f32; VOCABULARY];
l[10] = 5.0;
l[11] = 4.0;
let mut s = StepSampler::new(params, &[10]).unwrap();
// token 10 sits in the window and is divided by 100, so 11 wins
assert_eq!(s.pick(&l, 0).unwrap(), 11);
}
#[test]
fn position_and_shape_mismatches_are_refused() {
let mut s = StepSampler::new(sampled(1), &[1, 2, 3]).unwrap();
let l = logits(0);
assert_eq!(s.pick(&l, 5), Err(Error::IdentityMismatch));
assert_eq!(s.pick(&l[..10], 2), Err(Error::InvalidDimension));
assert!(StepSampler::new(sampled(1), &[]).is_err());
assert!(StepSampler::new(sampled(1), &[VOCABULARY as u32]).is_err());
// a refused step consumed nothing
assert!(s.pick(&l, 2).is_ok());
assert_eq!(s.pick(&l, 2), Err(Error::IdentityMismatch));
}
}
+1 -1
View File
@@ -26,4 +26,4 @@ pub mod params;
pub mod philox;
pub use chain::{SamplerError, SamplerParams, sample_tokens};
pub use params::{RequestSampling, SamplingError, SamplingParams};
pub use params::{FixedPoint, RequestSampling, SamplingError, SamplingParams};
+82
View File
@@ -210,6 +210,41 @@ impl RequestSampling {
}
}
/// A request's sampling controls in fixed point (thousandths / millionths), the
/// form the in-process backend API carries them in so requests stay `Eq`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct FixedPoint {
pub temperature_milli: u32,
pub top_p_micro: Option<u32>,
pub top_k: Option<u32>,
pub min_p_micro: Option<u32>,
pub repetition_penalty_micro: Option<u32>,
pub frequency_penalty_micro: Option<i32>,
pub presence_penalty_micro: Option<i32>,
pub penalty_last_n: Option<u32>,
pub seed: Option<u64>,
}
impl RequestSampling {
/// Exact conversion: `micro / 1e6` is the correctly rounded quotient, i.e. the
/// double nearest the decimal the client wrote (`950000 -> 0.95`).
pub fn from_fixed_point(f: &FixedPoint) -> Self {
let frac = |v: u32| f64::from(v) / 1_000_000.0;
let signed = |v: i32| f64::from(v) / 1_000_000.0;
Self {
temperature: Some(f64::from(f.temperature_milli) / 1000.0),
top_p: f.top_p_micro.map(frac),
top_k: f.top_k.map(i64::from),
min_p: f.min_p_micro.map(frac),
repetition_penalty: f.repetition_penalty_micro.map(frac),
frequency_penalty: f.frequency_penalty_micro.map(signed),
presence_penalty: f.presence_penalty_micro.map(signed),
penalty_last_n: f.penalty_last_n.map(i64::from),
seed: f.seed,
}
}
}
/// Fully normalised sampling parameters, as the engine sees them after the
/// wire: every float has been through the same decimal text the Original's
/// `strtof` parses (`repr(double)` -> nearest `f32`).
@@ -285,6 +320,12 @@ impl SamplingParams {
self.temperature <= 0.0
}
/// Whether the plain argmax of the output head is NOT enough: a non-greedy draw, or a
/// greedy pick over penalised logits (the Original's greedy kernel applies the penalties).
pub fn needs_sampler(&self) -> bool {
!self.is_greedy() || self.penalty_last_n > 0
}
/// The engine's `SamplerParams` for a request (generate.cpp `req_sp`):
/// `greedy = temperature <= 0`, `min_keep = 1`, `counter = 0`. `entropy` is
/// used only when the request carries no seed.
@@ -653,6 +694,47 @@ mod tests {
assert!(SamplingParams::resolve(&merged).unwrap().is_greedy());
}
#[test]
fn fixed_point_requests_match_the_decimal_the_client_wrote() {
let f = FixedPoint {
temperature_milli: 700,
top_p_micro: Some(950_000),
top_k: Some(40),
min_p_micro: Some(50_000),
repetition_penalty_micro: Some(1_100_000),
frequency_penalty_micro: Some(-250_000),
presence_penalty_micro: Some(500_000),
penalty_last_n: Some(128),
seed: Some(9),
};
let r = RequestSampling::from_fixed_point(&f);
assert_eq!(r.temperature, Some(0.7));
assert_eq!(r.top_p, Some(0.95));
assert_eq!(r.min_p, Some(0.05));
assert_eq!(r.repetition_penalty, Some(1.1));
assert_eq!(r.frequency_penalty, Some(-0.25));
let p = SamplingParams::resolve(&r).unwrap();
assert!(p.needs_sampler() && !p.is_greedy());
assert_eq!((p.top_k, p.penalty_last_n), (40, 128));
// the all-default request stays on the plain greedy path
let d = SamplingParams::resolve(&RequestSampling::from_fixed_point(&FixedPoint::default()))
.unwrap();
assert!(d.is_greedy() && !d.needs_sampler());
// greedy with a penalty still needs the penalised argmax
let g = FixedPoint {
presence_penalty_micro: Some(500_000),
..FixedPoint::default()
};
let g = SamplingParams::resolve(&RequestSampling::from_fixed_point(&g)).unwrap();
assert!(g.is_greedy() && g.needs_sampler());
// out-of-range temperatures are refused
let hot = FixedPoint {
temperature_milli: 2001,
..FixedPoint::default()
};
assert!(SamplingParams::resolve(&RequestSampling::from_fixed_point(&hot)).is_err());
}
#[test]
fn wire_floats_go_through_the_decimal_text() {
assert_eq!(wire_f32(0.7), 0.7f32);
+4 -1
View File
@@ -545,7 +545,9 @@ impl proto::runtime_server::Runtime for RuntimeServer {
if command.prompt.len() > 1024 * 1024
|| command.max_output_tokens == 0
|| command.max_output_tokens > 4096
|| command.temperature_milli != 0
// Sampling is validated and served by the backend (Original sampler chain);
// only the documented range is enforced at this boundary.
|| command.temperature_milli > 2000
{
return Err(refusal(
tonic::Code::InvalidArgument,
@@ -592,6 +594,7 @@ impl proto::runtime_server::Runtime for RuntimeServer {
prompt: command.prompt,
max_output_tokens: command.max_output_tokens,
temperature_milli: command.temperature_milli,
sampling: Default::default(),
};
let mut acceptance_guard = AcceptanceGuard {
inner: self.inner.clone(),
+58
View File
@@ -0,0 +1,58 @@
# Sampler reference, request plumbing and serving path
Status: source-level work, no GPU run, no speed or quality claim.
## What exists
| Piece | Where |
| --- | --- |
| Bit-exact CPU reference: 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 | `crates/sampler-ref` |
| Request validation/normalisation into one `SamplingParams` (Original `GEN` defaults, ranges, `GEN` wire keys) | `crates/sampler-ref/src/params.rs` |
| Golden fixtures from the Original's host logic | `crates/sampler-ref/tests/fixtures/*.json`, generators in `crates/sampler-ref/oracle/` |
| Per-request host sampler on the plain decode path | `leleka-runtime` `qwen_forward/step_sampler.rs`, hooked in `output.rs`, armed by `backend.rs` |
| Backend request carries the sampling controls | `backend-api` `SamplingOptions` |
## What is verified (macOS, no CUDA)
* The fixture generator compiles the Original `sampler_parity.cpp` host reference **unmodified** (stub `<cuda_runtime.h>`),
the Original `sampler.hpp`/`coupled_draft.hpp` headers, with `-ffp-contract=off`. 322 cases: Philox words, full chain
(random, ties, NaN/inf/denormal rows, penalties, top_p exact-boundary cases, full 248,320-vocabulary rows with up to
4,096 history slots), the 64-byte `SamplerParams` ABI, counter/ring arithmetic, `penalty_rows`.
Rust matches bitwise (token, selection list, uniform bits). Mutating `>=`->`>` in top_p, the repeat rule, tie order and
the min_p comparison each fail the suite.
* The coupled-draft kernels have no host twin in the Original; `coupled_ref` in the generator transcribes them and is
cross-checked against the Original `mirror_pick`.
* `StrataEngine.sampling_keys` (lifted verbatim from `server.py` by AST) gives the golden `GEN` strings.
* Existing source-port host logic checked against the same fixtures: `cuda-driver` `SamplerParams` (size, alignment,
offsets, 64 bytes), `leleka-runtime` `original_sampler.rs` helpers.
`crates/sampler-ref/oracle/run_port_host_tests.sh` runs these on macOS; on Linux they are ordinary crate tests.
* Linux gated code type-checks: `cargo check --target x86_64-unknown-linux-gnu -p leleka-cuda-driver --features cuda-driver -p leleka-runtime --all-targets`.
## Defects found in the existing source-port and fixed
* `SamplerParams::validate` rejected `top_p == 0`, which the Original accepts (Python emits it; the kernel keeps `min_keep`).
* Draft cell `-1` (`draft_first` for a window at position 0, Philox counter 0) was refused by `coupled_draft_counter`
and `OriginalSampler::sample_coupled`.
* `OriginalSampler::set_subset` rejected duplicate or out-of-range subset ids; `setup_coupled` keeps the first index and
ignores out-of-range entries.
## Serving path
`temperature_milli != 0` is no longer refused in `backend.rs` / desktop `runtime_rpc.rs`. A request is planned by
`request_sampler`: all-default greedy keeps the compact device head; any temperature or penalty arms `StepSampler` on the
output stage, which forces the complete logit vector (no compact argmax) and draws with the CPU reference at counter =
sequence index of the fed token, penalty history = last `min(penalty_last_n, 4096)` tokens of prompt + generated.
Requests without a seed take a clock seed (the Original's `seed = 0`).
## Open
* nvcc/PTX: `ASSET`/`SAMPLER_ASSET` stay `None`; no PTX exists, so the GPU `OriginalSampler` and the NativeHead sampler
have never run. The serving path therefore samples on the host from the Q6 head's full logits. Switching it to the
GPU sampler is a later step once the asset is pinned; the token contract is the same.
* Sampling with MTP is refused (`sampling is unavailable with MTP`): coupled draft sampling is not wired into the actor.
* The desktop gRPC protocol still carries only `temperature_milli`; top_p/top_k/min_p/penalties/seed need a proto bump.
The control plane's C++ worker wire (`wire.rs`) still forwards only temperature and top_p; `RequestSampling::gen_keys`
is the tested replacement.
* Float caveat: `exp`/`ln` use the platform libm. Device `exp` (f64) and `logf` can differ by 1 ulp from the host and
nvcc `--fmad=true` may contract `count*freq + flag*present`; these can change a pick only on cumulative-boundary
or threshold ties. Compare GPU output with the fixtures and report disagreements; do not treat them as noise.