395 lines
15 KiB
Rust
395 lines
15 KiB
Rust
//! Request-level sampling parameters: validation, normalisation and the
|
|
//! Original's defaults, in one struct.
|
|
//!
|
|
//! Sources of truth in the Original:
|
|
//!
|
|
//! * `engine/strata/src/program/generate.cpp` (`GEN` key grammar and the
|
|
//! defaults an absent key keeps): greedy, `top_p = 1.0`, `top_k = 20`,
|
|
//! `min_p = 0`, no penalties, `seed = 0` meaning "clock seed"; `min_p` is
|
|
//! clamped to `[0, 1]` and `penalty_last_n` to `>= 0`.
|
|
//! * `engine/strata/serve/server.py` `StrataEngine.sampling_keys` (which keys are
|
|
//! emitted and how floats are printed) and `sampling_defaults_from_config` /
|
|
//! `clean_shared_defaults` (the ranges the server enforces on configured
|
|
//! defaults).
|
|
//!
|
|
//! Where the Original silently ignores an invalid request field (it simply does
|
|
//! not emit the key) this module returns an error instead: the HTTP boundary
|
|
//! must fail closed rather than quietly change sampling. Valid inputs normalise
|
|
//! exactly as the Original does.
|
|
|
|
use crate::chain::{PENALTY_WINDOW_CAP, SamplerParams};
|
|
use std::num::NonZeroU64;
|
|
|
|
/// Sampling fields as they arrive from a Responses/Chat/Messages request (or
|
|
/// from configured defaults); `None` means the field was absent or null.
|
|
#[derive(Clone, Debug, Default, PartialEq)]
|
|
pub struct RequestSampling {
|
|
pub temperature: Option<f64>,
|
|
pub top_p: Option<f64>,
|
|
pub top_k: Option<i64>,
|
|
pub min_p: Option<f64>,
|
|
pub repetition_penalty: Option<f64>,
|
|
pub frequency_penalty: Option<f64>,
|
|
pub presence_penalty: Option<f64>,
|
|
pub penalty_last_n: Option<i64>,
|
|
/// Unsigned: a negative JSON seed is a deserialisation error at the boundary.
|
|
pub seed: Option<u64>,
|
|
}
|
|
|
|
/// A rejected field and the contract it broke.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct SamplingError {
|
|
pub field: &'static str,
|
|
pub expected: &'static str,
|
|
}
|
|
|
|
impl std::fmt::Display for SamplingError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "{}: expected {}", self.field, self.expected)
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for SamplingError {}
|
|
|
|
fn err(field: &'static str, expected: &'static str) -> SamplingError {
|
|
SamplingError { field, expected }
|
|
}
|
|
|
|
fn finite_in(
|
|
field: &'static str,
|
|
value: Option<f64>,
|
|
lo: f64,
|
|
hi: f64,
|
|
expected: &'static str,
|
|
) -> Result<(), SamplingError> {
|
|
match value {
|
|
Some(v) if !v.is_finite() || v < lo || v > hi => Err(err(field, expected)),
|
|
_ => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// Window the Original's Python layer adds when a penalty is on and none given.
|
|
pub const DEFAULT_PENALTY_LAST_N: i32 = 64;
|
|
/// The engine's own `top_k` default for an absent key.
|
|
pub const DEFAULT_TOP_K: i32 = 20;
|
|
|
|
impl RequestSampling {
|
|
/// Request-boundary validation. Ranges: `temperature` in `[0, 2]` (0 is
|
|
/// greedy), `top_p` in `[0, 1]` (1 disables), `top_k >= 0`, `min_p` in
|
|
/// `[0, 1]`, `repetition_penalty > 0` (1 is off), frequency/presence
|
|
/// penalties finite and within the OpenAI `[-2, 2]`, `penalty_last_n` in
|
|
/// `[0, i32::MAX]`, `seed` any `u64` (0 means a fresh clock seed).
|
|
pub fn validate(&self) -> Result<(), SamplingError> {
|
|
self.validate_finite()?;
|
|
if let Some(v) = self.repetition_penalty
|
|
&& (!v.is_finite() || v <= 0.0)
|
|
{
|
|
return Err(err("repetition_penalty", "a finite number > 0 (1 = off)"));
|
|
}
|
|
if self.top_k.is_some_and(|k| k < 0) {
|
|
return Err(err("top_k", "an integer >= 0 (0 = widest list, 64)"));
|
|
}
|
|
if self.penalty_last_n.is_some_and(|n| n < 0 || n > i64::from(i32::MAX)) {
|
|
return Err(err("penalty_last_n", "an integer in 0..=2147483647"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The float fields that must be finite and inside a fixed range.
|
|
fn validate_finite(&self) -> Result<(), SamplingError> {
|
|
const UNIT: &str = "a finite number in 0..=1";
|
|
const PENALTY: &str = "a finite number in -2..=2";
|
|
finite_in("temperature", self.temperature, 0.0, 2.0, "a finite number in 0..=2")?;
|
|
finite_in("top_p", self.top_p, 0.0, 1.0, UNIT)?;
|
|
finite_in("min_p", self.min_p, 0.0, 1.0, UNIT)?;
|
|
finite_in("frequency_penalty", self.frequency_penalty, -2.0, 2.0, PENALTY)?;
|
|
finite_in("presence_penalty", self.presence_penalty, -2.0, 2.0, PENALTY)
|
|
}
|
|
|
|
/// The stricter ranges the Original enforces on *configured defaults*
|
|
/// (`sampling_defaults_from_config`): `temperature >= 0`, `0 < top_p <= 1`,
|
|
/// `0 <= min_p <= 1`, `top_k` in `1..=64`, penalties `>= 0` with
|
|
/// `repetition_penalty > 0`, `penalty_last_n >= 0`, `seed > 0`.
|
|
pub fn validate_config_defaults(&self) -> Result<(), SamplingError> {
|
|
self.validate()?;
|
|
if self.top_p.is_some_and(|v| v <= 0.0) {
|
|
return Err(err("top_p", "0 < top_p <= 1"));
|
|
}
|
|
if self.top_k.is_some_and(|k| !(1..=64).contains(&k)) {
|
|
return Err(err("top_k", "an integer 1..=64"));
|
|
}
|
|
if self.presence_penalty.is_some_and(|v| v < 0.0) {
|
|
return Err(err("presence_penalty", "a number >= 0"));
|
|
}
|
|
if self.frequency_penalty.is_some_and(|v| v < 0.0) {
|
|
return Err(err("frequency_penalty", "a number >= 0"));
|
|
}
|
|
if self.seed == Some(0) {
|
|
return Err(err("seed", "a positive integer"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Defaults first, then the request's own non-null fields on top (an
|
|
/// explicit `temperature = 0` stays greedy). `Service.run` in server.py.
|
|
pub fn overlay(defaults: &Self, request: &Self) -> Self {
|
|
Self {
|
|
temperature: request.temperature.or(defaults.temperature),
|
|
top_p: request.top_p.or(defaults.top_p),
|
|
top_k: request.top_k.or(defaults.top_k),
|
|
min_p: request.min_p.or(defaults.min_p),
|
|
repetition_penalty: request.repetition_penalty.or(defaults.repetition_penalty),
|
|
frequency_penalty: request.frequency_penalty.or(defaults.frequency_penalty),
|
|
presence_penalty: request.presence_penalty.or(defaults.presence_penalty),
|
|
penalty_last_n: request.penalty_last_n.or(defaults.penalty_last_n),
|
|
seed: request.seed.or(defaults.seed),
|
|
}
|
|
}
|
|
|
|
fn penalties_on(&self) -> bool {
|
|
self.repetition_penalty.is_some_and(|v| v != 1.0)
|
|
|| self.frequency_penalty.is_some_and(|v| v != 0.0)
|
|
|| self.presence_penalty.is_some_and(|v| v != 0.0)
|
|
}
|
|
|
|
/// The `GEN` sampling keys exactly as `StrataEngine.sampling_keys` prints
|
|
/// them (leading space per key, `repr(float)` formatting, same order),
|
|
/// after [`validate`](Self::validate). Does not emit `strata_tune` or `cvec`.
|
|
pub fn gen_keys(&self) -> Result<String, SamplingError> {
|
|
self.validate()?;
|
|
let mut keys = String::new();
|
|
self.push_sampling_keys(&mut keys);
|
|
self.push_penalty_keys(&mut keys);
|
|
if let Some(s) = self.seed.filter(|s| *s > 0) {
|
|
keys.push_str(&format!(" seed={s}"));
|
|
}
|
|
Ok(keys)
|
|
}
|
|
|
|
fn push_sampling_keys(&self, keys: &mut String) {
|
|
if let Some(t) = self.temperature.filter(|t| *t > 0.0) {
|
|
keys.push_str(&format!(" temperature={}", py_float_repr(t)));
|
|
}
|
|
if let Some(p) = self.top_p.filter(|p| *p < 1.0) {
|
|
keys.push_str(&format!(" top_p={}", py_float_repr(p)));
|
|
}
|
|
if let Some(k) = self.top_k {
|
|
let k = if (1..=64).contains(&k) { k } else { 64 };
|
|
keys.push_str(&format!(" top_k={k}"));
|
|
}
|
|
if let Some(m) = self.min_p.filter(|m| *m > 0.0 && *m <= 1.0) {
|
|
keys.push_str(&format!(" min_p={}", py_float_repr(m)));
|
|
}
|
|
}
|
|
|
|
fn push_penalty_keys(&self, keys: &mut String) {
|
|
let rp = self.repetition_penalty.filter(|v| *v != 1.0);
|
|
let pf = self.frequency_penalty.filter(|v| *v != 0.0);
|
|
let pp = self.presence_penalty.filter(|v| *v != 0.0);
|
|
for (name, v) in [("penalty_repeat", rp), ("penalty_freq", pf), ("penalty_present", pp)] {
|
|
if let Some(v) = v {
|
|
keys.push_str(&format!(" {name}={}", py_float_repr(v)));
|
|
}
|
|
}
|
|
if rp.is_some() || pf.is_some() || pp.is_some() {
|
|
match self.penalty_last_n.filter(|n| *n > 0) {
|
|
Some(n) => keys.push_str(&format!(" penalty_last_n={n}")),
|
|
None => keys.push_str(" penalty_last_n=64"),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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`).
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct SamplingParams {
|
|
/// `<= 0` is greedy.
|
|
pub temperature: f32,
|
|
/// `1.0` disables.
|
|
pub top_p: f32,
|
|
/// Normalised to `1..=64`.
|
|
pub top_k: i32,
|
|
pub min_p: f32,
|
|
pub penalty_repeat: f32,
|
|
pub penalty_freq: f32,
|
|
pub penalty_present: f32,
|
|
/// 0 when no penalty is active; otherwise the requested window (or 64).
|
|
/// Kernels cap it at [`PENALTY_WINDOW_CAP`] history slots.
|
|
pub penalty_last_n: i32,
|
|
/// `None`: draw a fresh clock seed per request (the Original's `seed = 0`).
|
|
pub seed: Option<NonZeroU64>,
|
|
}
|
|
|
|
/// The `f32` the Original's `strtof` makes of the text Python prints for `x`.
|
|
pub fn wire_f32(x: f64) -> f32 {
|
|
// `{:?}` is the shortest round-trip decimal, like Python's repr; parsing
|
|
// it as f32 is correctly rounded, like strtof.
|
|
format!("{x:?}").parse::<f32>().unwrap_or(f32::NAN)
|
|
}
|
|
|
|
impl SamplingParams {
|
|
/// Validate and normalise. Absent fields take the Original's `GEN`
|
|
/// defaults: greedy, `top_p = 1`, `top_k = 20`, `min_p = 0`, no penalties.
|
|
pub fn resolve(request: &RequestSampling) -> Result<Self, SamplingError> {
|
|
request.validate()?;
|
|
let temperature = wire_f32(request.temperature.unwrap_or(0.0));
|
|
let top_p = wire_f32(request.top_p.unwrap_or(1.0));
|
|
let top_k = match request.top_k {
|
|
None => DEFAULT_TOP_K,
|
|
Some(k) if (1..=64).contains(&k) => k as i32,
|
|
Some(_) => 64,
|
|
};
|
|
let min_p = wire_f32(request.min_p.unwrap_or(0.0));
|
|
let min_p = if request.min_p.is_some_and(|m| m > 0.0 && m <= 1.0) {
|
|
min_p.clamp(0.0, 1.0)
|
|
} else {
|
|
0.0
|
|
};
|
|
let penalty_last_n = Self::resolve_last_n(request);
|
|
Ok(Self {
|
|
temperature,
|
|
top_p,
|
|
top_k,
|
|
min_p,
|
|
penalty_repeat: request.repetition_penalty.filter(|v| *v != 1.0).map_or(1.0, wire_f32),
|
|
penalty_freq: request.frequency_penalty.filter(|v| *v != 0.0).map_or(0.0, wire_f32),
|
|
penalty_present: request.presence_penalty.filter(|v| *v != 0.0).map_or(0.0, wire_f32),
|
|
penalty_last_n,
|
|
seed: request.seed.and_then(NonZeroU64::new),
|
|
})
|
|
}
|
|
|
|
fn resolve_last_n(request: &RequestSampling) -> i32 {
|
|
if !request.penalties_on() {
|
|
return 0;
|
|
}
|
|
match request.penalty_last_n.filter(|n| *n > 0) {
|
|
Some(n) => n as i32,
|
|
None => DEFAULT_PENALTY_LAST_N,
|
|
}
|
|
}
|
|
|
|
pub fn is_greedy(&self) -> bool {
|
|
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.
|
|
pub fn to_sampler_params(&self, entropy: u64) -> SamplerParams {
|
|
SamplerParams {
|
|
top_k: self.top_k,
|
|
top_p: self.top_p,
|
|
min_p: self.min_p,
|
|
temperature: self.temperature,
|
|
min_keep: 1,
|
|
penalty_last_n: self.penalty_last_n,
|
|
penalty_repeat: self.penalty_repeat,
|
|
penalty_freq: self.penalty_freq,
|
|
penalty_present: self.penalty_present,
|
|
seed: self.seed.map_or(entropy, NonZeroU64::get),
|
|
counter: 0,
|
|
greedy: self.temperature <= 0.0,
|
|
}
|
|
}
|
|
|
|
/// History slots a request needs per row: `min(penalty_last_n, 4096)`.
|
|
pub fn history_slots(&self) -> usize {
|
|
(self.penalty_last_n.max(0) as usize).min(PENALTY_WINDOW_CAP)
|
|
}
|
|
}
|
|
|
|
/// Python's `repr(float)` for a finite `f64` (shortest round-trip digits;
|
|
/// fixed notation for decimal exponents -4..=15, otherwise `d.ddde+XX`).
|
|
pub fn py_float_repr(x: f64) -> String {
|
|
if x == 0.0 {
|
|
return if x.is_sign_negative() {
|
|
"-0.0".into()
|
|
} else {
|
|
"0.0".into()
|
|
};
|
|
}
|
|
let sign = if x < 0.0 { "-" } else { "" };
|
|
let sci = format!("{:e}", x.abs());
|
|
let (mantissa, exponent) = sci
|
|
.split_once('e')
|
|
.expect("LowerExp always has an exponent");
|
|
let exp: i32 = exponent.parse().expect("integer exponent");
|
|
let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
|
|
let body = if (-4..16).contains(&exp) {
|
|
fixed_notation(&digits, exp)
|
|
} else {
|
|
scientific_notation(digits, exp)
|
|
};
|
|
format!("{sign}{body}")
|
|
}
|
|
|
|
/// Fixed notation of `digits` times ten to `exp` (decimal exponent -4..=15).
|
|
fn fixed_notation(digits: &str, exp: i32) -> String {
|
|
if exp < 0 {
|
|
return format!("0.{}{digits}", "0".repeat((-exp - 1) as usize));
|
|
}
|
|
let int_len = exp as usize + 1;
|
|
if digits.len() <= int_len {
|
|
format!("{digits}{}.0", "0".repeat(int_len - digits.len()))
|
|
} else {
|
|
format!("{}.{}", &digits[..int_len], &digits[int_len..])
|
|
}
|
|
}
|
|
|
|
/// Scientific notation `d.ddde+XX` of `digits` times ten to `exp`.
|
|
fn scientific_notation(digits: String, exp: i32) -> String {
|
|
let m = if digits.len() == 1 {
|
|
digits
|
|
} else {
|
|
format!("{}.{}", &digits[..1], &digits[1..])
|
|
};
|
|
format!("{m}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|