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>
745 lines
25 KiB
Rust
745 lines
25 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> {
|
|
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, "a finite number in 0..=1")?;
|
|
finite_in("min_p", self.min_p, 0.0, 1.0, "a finite number in 0..=1")?;
|
|
finite_in(
|
|
"frequency_penalty",
|
|
self.frequency_penalty,
|
|
-2.0,
|
|
2.0,
|
|
"a finite number in -2..=2",
|
|
)?;
|
|
finite_in(
|
|
"presence_penalty",
|
|
self.presence_penalty,
|
|
-2.0,
|
|
2.0,
|
|
"a finite number in -2..=2",
|
|
)?;
|
|
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 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();
|
|
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)));
|
|
}
|
|
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);
|
|
if let Some(v) = rp {
|
|
keys.push_str(&format!(" penalty_repeat={}", py_float_repr(v)));
|
|
}
|
|
if let Some(v) = pf {
|
|
keys.push_str(&format!(" penalty_freq={}", py_float_repr(v)));
|
|
}
|
|
if let Some(v) = pp {
|
|
keys.push_str(&format!(" penalty_present={}", 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"),
|
|
}
|
|
}
|
|
if let Some(s) = self.seed.filter(|s| *s > 0) {
|
|
keys.push_str(&format!(" seed={s}"));
|
|
}
|
|
Ok(keys)
|
|
}
|
|
}
|
|
|
|
/// 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 rp = request.repetition_penalty.filter(|v| *v != 1.0);
|
|
let pf = request.frequency_penalty.filter(|v| *v != 0.0);
|
|
let pp = request.presence_penalty.filter(|v| *v != 0.0);
|
|
let penalty_last_n = if request.penalties_on() {
|
|
match request.penalty_last_n.filter(|n| *n > 0) {
|
|
Some(n) => n as i32,
|
|
None => DEFAULT_PENALTY_LAST_N,
|
|
}
|
|
} else {
|
|
0
|
|
};
|
|
Ok(Self {
|
|
temperature,
|
|
top_p,
|
|
top_k,
|
|
min_p,
|
|
penalty_repeat: rp.map_or(1.0, wire_f32),
|
|
penalty_freq: pf.map_or(0.0, wire_f32),
|
|
penalty_present: pp.map_or(0.0, wire_f32),
|
|
penalty_last_n,
|
|
seed: request.seed.and_then(NonZeroU64::new),
|
|
})
|
|
}
|
|
|
|
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) {
|
|
if exp >= 0 {
|
|
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..])
|
|
}
|
|
} else {
|
|
format!("0.{}{digits}", "0".repeat((-exp - 1) as usize))
|
|
}
|
|
} else {
|
|
let m = if digits.len() == 1 {
|
|
digits
|
|
} else {
|
|
format!("{}.{}", &digits[..1], &digits[1..])
|
|
};
|
|
format!("{m}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs())
|
|
};
|
|
format!("{sign}{body}")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn python_repr_matches_known_values() {
|
|
for (x, want) in [
|
|
(0.0, "0.0"),
|
|
(1.0, "1.0"),
|
|
(0.7, "0.7"),
|
|
(0.95, "0.95"),
|
|
(100.0, "100.0"),
|
|
(1e15, "1000000000000000.0"),
|
|
(1e16, "1e+16"),
|
|
(1.5e16, "1.5e+16"),
|
|
(0.0001, "0.0001"),
|
|
(0.00001, "1e-05"),
|
|
(1.5e-7, "1.5e-07"),
|
|
(123.456, "123.456"),
|
|
(-2.5, "-2.5"),
|
|
(0.1 + 0.2, "0.30000000000000004"),
|
|
] {
|
|
assert_eq!(py_float_repr(x), want, "{x:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn absent_fields_are_the_originals_gen_defaults() {
|
|
let p = SamplingParams::resolve(&RequestSampling::default()).unwrap();
|
|
assert!(p.is_greedy());
|
|
assert_eq!((p.top_p, p.top_k, p.min_p), (1.0, 20, 0.0));
|
|
assert_eq!(
|
|
(p.penalty_repeat, p.penalty_freq, p.penalty_present),
|
|
(1.0, 0.0, 0.0)
|
|
);
|
|
assert_eq!(p.penalty_last_n, 0);
|
|
assert_eq!(p.seed, None);
|
|
assert_eq!(RequestSampling::default().gen_keys().unwrap(), "");
|
|
}
|
|
|
|
#[test]
|
|
fn top_k_normalises_to_the_engine_range() {
|
|
for (given, want) in [(0, 64), (1, 1), (20, 20), (64, 64), (65, 64), (100_000, 64)] {
|
|
let r = RequestSampling {
|
|
top_k: Some(given),
|
|
..Default::default()
|
|
};
|
|
assert_eq!(SamplingParams::resolve(&r).unwrap().top_k, want);
|
|
assert_eq!(r.gen_keys().unwrap(), format!(" top_k={want}"));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_penalty_without_a_window_gets_64() {
|
|
let r = RequestSampling {
|
|
presence_penalty: Some(0.5),
|
|
..Default::default()
|
|
};
|
|
let p = SamplingParams::resolve(&r).unwrap();
|
|
assert_eq!(p.penalty_last_n, 64);
|
|
assert_eq!(
|
|
r.gen_keys().unwrap(),
|
|
" penalty_present=0.5 penalty_last_n=64"
|
|
);
|
|
// a window with no active penalty is not emitted and not applied
|
|
let r = RequestSampling {
|
|
penalty_last_n: Some(10),
|
|
..Default::default()
|
|
};
|
|
assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 0);
|
|
assert_eq!(r.gen_keys().unwrap(), "");
|
|
// an explicit window wins; a zero window falls back to 64 like Python
|
|
let r = RequestSampling {
|
|
repetition_penalty: Some(1.1),
|
|
penalty_last_n: Some(0),
|
|
..Default::default()
|
|
};
|
|
assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 64);
|
|
let r = RequestSampling {
|
|
repetition_penalty: Some(1.1),
|
|
penalty_last_n: Some(4097),
|
|
..Default::default()
|
|
};
|
|
let p = SamplingParams::resolve(&r).unwrap();
|
|
assert_eq!(p.penalty_last_n, 4097);
|
|
assert_eq!(p.history_slots(), 4096);
|
|
}
|
|
|
|
#[test]
|
|
fn engine_params_follow_generate_cpp() {
|
|
let r = RequestSampling {
|
|
temperature: Some(0.7),
|
|
top_p: Some(0.9),
|
|
seed: Some(42),
|
|
..Default::default()
|
|
};
|
|
let sp = SamplingParams::resolve(&r).unwrap().to_sampler_params(999);
|
|
assert!(!sp.greedy);
|
|
assert_eq!(sp.seed, 42);
|
|
assert_eq!(sp.counter, 0);
|
|
assert_eq!(sp.min_keep, 1);
|
|
assert_eq!(sp.temperature, 0.7f32);
|
|
// no seed: the caller's entropy
|
|
let r = RequestSampling {
|
|
temperature: Some(1.0),
|
|
..Default::default()
|
|
};
|
|
assert_eq!(
|
|
SamplingParams::resolve(&r)
|
|
.unwrap()
|
|
.to_sampler_params(999)
|
|
.seed,
|
|
999
|
|
);
|
|
// temperature 0 stays greedy whatever else is set
|
|
let r = RequestSampling {
|
|
temperature: Some(0.0),
|
|
top_p: Some(0.5),
|
|
..Default::default()
|
|
};
|
|
assert!(
|
|
SamplingParams::resolve(&r)
|
|
.unwrap()
|
|
.to_sampler_params(1)
|
|
.greedy
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_fields_are_rejected() {
|
|
let bad = |r: RequestSampling| SamplingParams::resolve(&r).unwrap_err().field;
|
|
let d = RequestSampling::default;
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
temperature: Some(-0.1),
|
|
..d()
|
|
}),
|
|
"temperature"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
temperature: Some(2.5),
|
|
..d()
|
|
}),
|
|
"temperature"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
temperature: Some(f64::NAN),
|
|
..d()
|
|
}),
|
|
"temperature"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
top_p: Some(1.5),
|
|
..d()
|
|
}),
|
|
"top_p"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
top_p: Some(f64::INFINITY),
|
|
..d()
|
|
}),
|
|
"top_p"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
top_k: Some(-1),
|
|
..d()
|
|
}),
|
|
"top_k"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
min_p: Some(1.01),
|
|
..d()
|
|
}),
|
|
"min_p"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
repetition_penalty: Some(0.0),
|
|
..d()
|
|
}),
|
|
"repetition_penalty"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
frequency_penalty: Some(3.0),
|
|
..d()
|
|
}),
|
|
"frequency_penalty"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
presence_penalty: Some(f64::NAN),
|
|
..d()
|
|
}),
|
|
"presence_penalty"
|
|
);
|
|
assert_eq!(
|
|
bad(RequestSampling {
|
|
penalty_last_n: Some(-1),
|
|
..d()
|
|
}),
|
|
"penalty_last_n"
|
|
);
|
|
// a bad request never reaches the wire either
|
|
assert!(
|
|
RequestSampling {
|
|
top_k: Some(-5),
|
|
..d()
|
|
}
|
|
.gen_keys()
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn config_defaults_use_the_servers_stricter_ranges() {
|
|
let d = RequestSampling::default;
|
|
assert!(
|
|
RequestSampling {
|
|
top_p: Some(0.0),
|
|
..d()
|
|
}
|
|
.validate()
|
|
.is_ok()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
top_p: Some(0.0),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
top_k: Some(0),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
top_k: Some(65),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
presence_penalty: Some(-0.5),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
seed: Some(0),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RequestSampling {
|
|
temperature: Some(0.6),
|
|
top_k: Some(20),
|
|
seed: Some(7),
|
|
..d()
|
|
}
|
|
.validate_config_defaults()
|
|
.is_ok()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn overlay_lets_the_request_win_including_explicit_zero() {
|
|
let defaults = RequestSampling {
|
|
temperature: Some(0.6),
|
|
top_p: Some(0.95),
|
|
top_k: Some(20),
|
|
..Default::default()
|
|
};
|
|
let request = RequestSampling {
|
|
temperature: Some(0.0),
|
|
seed: Some(9),
|
|
..Default::default()
|
|
};
|
|
let merged = RequestSampling::overlay(&defaults, &request);
|
|
assert_eq!(merged.temperature, Some(0.0));
|
|
assert_eq!(merged.top_p, Some(0.95));
|
|
assert_eq!(merged.seed, Some(9));
|
|
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);
|
|
assert_eq!(wire_f32(1e-7), 1e-7f32);
|
|
assert_eq!(wire_f32(1.0), 1.0f32);
|
|
}
|
|
}
|