aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-serve-http / src / sampling.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Shared next-token sampling for engines that produce logits on the host. |
| 17 | //! |
| 18 | //! The rule (OWN-8B stage S, unchanged from before it, written down here): |
| 19 | //! - `temperature <= 0.001` is argmax, whatever the seed. |
| 20 | //! - Otherwise: top-k mask (here, because the workspace `SamplingParams` has no |
| 21 | //! top-k field), then the workspace `sample_with_params` math (softmax at |
| 22 | //! 1/temperature in f64, nucleus cut at `top_p`, one uniform draw) seeded per |
| 23 | //! step by `decode_sampling_seed(seed, step)`. |
| 24 | //! |
| 25 | //! So the same seed and prompt give the same token stream on the same build and |
| 26 | //! weights. Every draw is observed ([`SamplingObserver`]): the request's |
| 27 | //! [`SamplingRecord`] carries the kept-set size of each sampled step, so a model |
| 28 | //! that is confident (kept set of 1) can be told apart from a sampler that |
| 29 | //! ignores its seed (kept set above 1, replies still identical). |
| 30 | //! |
| 31 | //! Negative controls (`AIEN_SAMPLING_MUTANT`, builds with debug assertions only, |
| 32 | //! read once at start): `ignore-seed` draws every request with seed 0, |
| 33 | //! `force-greedy` takes the argmax at any temperature. A build without debug |
| 34 | //! assertions refuses to start when the variable is set. |
| 35 | |
| 36 | use std::sync::OnceLock; |
| 37 | |
| 38 | use aien_inference_abi::transformer_backend::{decode_sampling_seed, sample_with_params_traced}; |
| 39 | use aien_inference_abi::{DecodeObservation, SamplingParams}; |
| 40 | use serde::Serialize; |
| 41 | |
| 42 | use crate::engine::GenerateParams; |
| 43 | |
| 44 | /// The environment variable that selects a sampling mutant. |
| 45 | pub const MUTANT_ENV: &str = "AIEN_SAMPLING_MUTANT"; |
| 46 | |
| 47 | /// A deliberately broken sampler, for the gate's negative controls. |
| 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 49 | pub enum SamplingMutant { |
| 50 | /// Every request is drawn with seed 0. |
| 51 | IgnoreSeed, |
| 52 | /// Argmax at any temperature. |
| 53 | ForceGreedy, |
| 54 | } |
| 55 | |
| 56 | impl SamplingMutant { |
| 57 | pub fn name(self) -> &'static str { |
| 58 | match self { |
| 59 | Self::IgnoreSeed => "ignore-seed", |
| 60 | Self::ForceGreedy => "force-greedy", |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Parses the value of [`MUTANT_ENV`]. `debug_build` says the binary was built |
| 66 | /// with debug assertions; without them any non-empty value is refused. |
| 67 | pub fn parse_mutant( |
| 68 | value: Option<&str>, |
| 69 | debug_build: bool, |
| 70 | ) -> Result<Option<SamplingMutant>, String> { |
| 71 | let v = match value.map(str::trim) { |
| 72 | None | Some("") => return Ok(None), |
| 73 | Some(v) => v, |
| 74 | }; |
| 75 | if !debug_build { |
| 76 | return Err(format!( |
| 77 | "{MUTANT_ENV}={v} is refused: sampling mutants exist only in builds with debug assertions" |
| 78 | )); |
| 79 | } |
| 80 | match v { |
| 81 | "ignore-seed" => Ok(Some(SamplingMutant::IgnoreSeed)), |
| 82 | "force-greedy" => Ok(Some(SamplingMutant::ForceGreedy)), |
| 83 | _ => Err(format!( |
| 84 | "{MUTANT_ENV}={v} is not a mutant (ignore-seed | force-greedy)" |
| 85 | )), |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | static MUTANT: OnceLock<Option<SamplingMutant>> = OnceLock::new(); |
| 90 | |
| 91 | /// Reads [`MUTANT_ENV`] once for the whole process (the server calls this at start). |
| 92 | /// An error means the server must not start. |
| 93 | pub fn install_mutant_from_env() -> Result<Option<SamplingMutant>, String> { |
| 94 | let parsed = parse_mutant( |
| 95 | std::env::var(MUTANT_ENV).ok().as_deref(), |
| 96 | cfg!(debug_assertions), |
| 97 | )?; |
| 98 | Ok(*MUTANT.get_or_init(|| parsed)) |
| 99 | } |
| 100 | |
| 101 | /// The process's mutant; `None` until [`install_mutant_from_env`] ran, and always |
| 102 | /// `None` in a build without debug assertions. |
| 103 | pub fn active_mutant() -> Option<SamplingMutant> { |
| 104 | if cfg!(debug_assertions) { |
| 105 | MUTANT.get().copied().flatten() |
| 106 | } else { |
| 107 | None |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// How one request was sampled, as observed at each draw. Goes into the server |
| 112 | /// log line and the reply (`usage.aien_sampling`, an extra field OpenAI clients ignore). |
| 113 | #[derive(Debug, Clone, PartialEq, Serialize)] |
| 114 | pub struct SamplingRecord { |
| 115 | /// `greedy` (argmax at every step) or `sampled`. |
| 116 | pub mode: &'static str, |
| 117 | /// The seed the draws used (the request's, or the server's choice when the |
| 118 | /// request sent none). Send it back to replay the request. |
| 119 | pub seed: u64, |
| 120 | pub temperature: f32, |
| 121 | pub top_p: f32, |
| 122 | pub top_k: usize, |
| 123 | /// Whether the top-k mask ran (`0 < top_k < vocab` and not greedy). |
| 124 | pub top_k_applied: bool, |
| 125 | /// Draws decided by argmax. Every draw counts, including the one that picked a |
| 126 | /// stop token, so `greedy_tokens + sampled_tokens` can be one more than the reply's |
| 127 | /// `completion_tokens`. |
| 128 | pub greedy_tokens: usize, |
| 129 | /// Draws made at random (same counting as `greedy_tokens`). |
| 130 | pub sampled_tokens: usize, |
| 131 | /// Kept-set size of every sampled draw, in step order (empty when greedy). |
| 132 | pub kept: Vec<usize>, |
| 133 | /// Smallest, median (lower middle), largest kept-set size and the mean; |
| 134 | /// all 0 when nothing was sampled. |
| 135 | pub kept_min: usize, |
| 136 | pub kept_median: usize, |
| 137 | pub kept_max: usize, |
| 138 | pub kept_mean: f64, |
| 139 | /// Sampled draws whose kept set was a single token (the seed had no choice). |
| 140 | pub kept_single: usize, |
| 141 | /// Smallest and mean probability of the most likely token at a sampled draw (after |
| 142 | /// temperature, before the nucleus cut); 1.0 when nothing was sampled. Shows confidence |
| 143 | /// where the kept set cannot (at top_p 1.0 every token is kept). |
| 144 | pub top_prob_min: f64, |
| 145 | pub top_prob_mean: f64, |
| 146 | /// Natural-log probability of this exact sequence of sampled draws under the kept |
| 147 | /// distributions (the sum of each chosen token's log-probability); 0 when nothing was sampled. |
| 148 | pub reply_logprob: f64, |
| 149 | /// `exp(reply_logprob)`: the chance that an honest sampler with another seed repeats these |
| 150 | /// draws exactly. Identical replies across seeds are expected when this is large and are a |
| 151 | /// sign of an ignored seed when it is small. |
| 152 | pub p_repeat: f64, |
| 153 | /// The sampling mutant in force, if any (debug builds only). |
| 154 | #[serde(skip_serializing_if = "Option::is_none")] |
| 155 | pub mutant: Option<&'static str>, |
| 156 | } |
| 157 | |
| 158 | impl SamplingRecord { |
| 159 | /// One-line form for the server log. |
| 160 | pub fn log_fields(&self) -> String { |
| 161 | let mut s = format!( |
| 162 | "sampling mode={} seed={} temp={} top_p={} top_k={} greedy={} sampled={} kept(min/med/mean/max)={}/{}/{:.2}/{} kept1={}/{} top_prob(min/mean)={:.4}/{:.4} p_repeat={:.3e}", |
| 163 | self.mode, |
| 164 | self.seed, |
| 165 | self.temperature, |
| 166 | self.top_p, |
| 167 | self.top_k, |
| 168 | self.greedy_tokens, |
| 169 | self.sampled_tokens, |
| 170 | self.kept_min, |
| 171 | self.kept_median, |
| 172 | self.kept_mean, |
| 173 | self.kept_max, |
| 174 | self.kept_single, |
| 175 | self.sampled_tokens, |
| 176 | self.top_prob_min, |
| 177 | self.top_prob_mean, |
| 178 | self.p_repeat |
| 179 | ); |
| 180 | if let Some(m) = self.mutant { |
| 181 | s.push_str(&format!(" MUTANT={m}")); |
| 182 | } |
| 183 | s |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// The sampler of one request: picks tokens and records how. |
| 188 | #[derive(Debug, Clone)] |
| 189 | pub struct SamplingObserver { |
| 190 | params: GenerateParams, |
| 191 | mutant: Option<SamplingMutant>, |
| 192 | top_k_applied: bool, |
| 193 | greedy: usize, |
| 194 | kept: Vec<usize>, |
| 195 | top_prob_min: f64, |
| 196 | top_prob_sum: f64, |
| 197 | logprob_sum: f64, |
| 198 | obs: DecodeObservation, |
| 199 | } |
| 200 | |
| 201 | impl SamplingObserver { |
| 202 | /// An observer under the process's mutant (none in a normal server). |
| 203 | pub fn new(params: &GenerateParams) -> Self { |
| 204 | Self::with_mutant(params, active_mutant()) |
| 205 | } |
| 206 | |
| 207 | /// An observer under an explicit mutant (tests). |
| 208 | pub fn with_mutant(params: &GenerateParams, mutant: Option<SamplingMutant>) -> Self { |
| 209 | Self { |
| 210 | params: params.clone(), |
| 211 | mutant, |
| 212 | top_k_applied: false, |
| 213 | greedy: 0, |
| 214 | kept: Vec::new(), |
| 215 | top_prob_min: 1.0, |
| 216 | top_prob_sum: 0.0, |
| 217 | logprob_sum: 0.0, |
| 218 | obs: DecodeObservation::default(), |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | fn seed(&self) -> u64 { |
| 223 | match self.mutant { |
| 224 | Some(SamplingMutant::IgnoreSeed) => 0, |
| 225 | _ => self.params.seed, |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn temperature(&self) -> f32 { |
| 230 | match self.mutant { |
| 231 | Some(SamplingMutant::ForceGreedy) => 0.0, |
| 232 | _ => self.params.temperature, |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// True when every draw is the argmax (temperature 0, or the force-greedy mutant): the |
| 237 | /// decode graph's own greedy token (ARGMAX on the chip, strict >, first index, as |
| 238 | /// `sample_argmax`) is then the draw, and the logits need not be read (L356). |
| 239 | pub fn is_greedy(&self) -> bool { |
| 240 | self.temperature() <= 0.001 |
| 241 | } |
| 242 | |
| 243 | /// Counts one greedy draw taken from the chip, as [`Self::sample`] would at temperature 0. |
| 244 | pub fn note_greedy(&mut self) { |
| 245 | self.obs.greedy_tokens += 1; |
| 246 | self.greedy += 1; |
| 247 | } |
| 248 | |
| 249 | /// Picks the token for decode step `step` (0-based count of tokens already |
| 250 | /// generated in this request). |
| 251 | pub fn sample(&mut self, logits: &[f32], step: usize) -> u32 { |
| 252 | let temperature = self.temperature(); |
| 253 | let k = self.params.top_k; |
| 254 | let masked; |
| 255 | let logits = if k > 0 && k < logits.len() && temperature > 0.001 { |
| 256 | self.top_k_applied = true; |
| 257 | masked = top_k_mask(logits, k); |
| 258 | masked.as_slice() |
| 259 | } else { |
| 260 | logits |
| 261 | }; |
| 262 | let sp = SamplingParams { |
| 263 | temperature, |
| 264 | top_p: self.params.top_p, |
| 265 | max_tokens: 1, |
| 266 | stop_token_ids: Vec::new(), |
| 267 | }; |
| 268 | let seed = decode_sampling_seed(self.seed(), step); |
| 269 | let (token, logprob, trace) = sample_with_params_traced(logits, &sp, seed, &mut self.obs); |
| 270 | if temperature > 0.001 { |
| 271 | self.kept.push(trace.kept); |
| 272 | self.top_prob_min = self.top_prob_min.min(trace.top_prob); |
| 273 | self.top_prob_sum += trace.top_prob; |
| 274 | self.logprob_sum += f64::from(logprob); |
| 275 | } else { |
| 276 | self.greedy += 1; |
| 277 | } |
| 278 | token |
| 279 | } |
| 280 | |
| 281 | /// The record of every draw so far. |
| 282 | pub fn record(&self) -> SamplingRecord { |
| 283 | let mut sorted = self.kept.clone(); |
| 284 | sorted.sort_unstable(); |
| 285 | let n = sorted.len(); |
| 286 | let (min, median, max, mean) = if n == 0 { |
| 287 | (0, 0, 0, 0.0) |
| 288 | } else { |
| 289 | ( |
| 290 | sorted[0], |
| 291 | sorted[(n - 1) / 2], |
| 292 | sorted[n - 1], |
| 293 | sorted.iter().sum::<usize>() as f64 / n as f64, |
| 294 | ) |
| 295 | }; |
| 296 | SamplingRecord { |
| 297 | mode: if self.temperature() > 0.001 { |
| 298 | "sampled" |
| 299 | } else { |
| 300 | "greedy" |
| 301 | }, |
| 302 | seed: self.seed(), |
| 303 | temperature: self.params.temperature, |
| 304 | top_p: self.params.top_p, |
| 305 | top_k: self.params.top_k, |
| 306 | top_k_applied: self.top_k_applied, |
| 307 | greedy_tokens: self.greedy, |
| 308 | sampled_tokens: n, |
| 309 | kept_min: min, |
| 310 | kept_median: median, |
| 311 | kept_max: max, |
| 312 | kept_mean: mean, |
| 313 | kept_single: sorted.iter().take_while(|&&k| k == 1).count(), |
| 314 | top_prob_min: self.top_prob_min, |
| 315 | top_prob_mean: if n == 0 { |
| 316 | 1.0 |
| 317 | } else { |
| 318 | self.top_prob_sum / n as f64 |
| 319 | }, |
| 320 | reply_logprob: self.logprob_sum, |
| 321 | p_repeat: self.logprob_sum.exp(), |
| 322 | kept: self.kept.clone(), |
| 323 | mutant: self.mutant.map(SamplingMutant::name), |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// Picks the next token from `logits` for decode step `step`, unobserved (the |
| 329 | /// same choice as [`SamplingObserver::sample`]). |
| 330 | pub fn sample_next(logits: &[f32], params: &GenerateParams, step: usize) -> u32 { |
| 331 | SamplingObserver::new(params).sample(logits, step) |
| 332 | } |
| 333 | |
| 334 | /// Rank order: higher value first, lower token id first on exact ties. |
| 335 | fn rank_cmp(logits: &[f32], a: usize, b: usize) -> std::cmp::Ordering { |
| 336 | logits[b] |
| 337 | .partial_cmp(&logits[a]) |
| 338 | .unwrap_or(std::cmp::Ordering::Equal) |
| 339 | .then(a.cmp(&b)) |
| 340 | } |
| 341 | |
| 342 | /// Copies `logits` with everything outside the `k` largest values set to -inf. |
| 343 | /// Ties at the boundary keep the lower token id, matching the nucleus tie rule. |
| 344 | /// |
| 345 | /// Uses an O(V) partial selection. The comparator is a strict total order only |
| 346 | /// when no logit is NaN (NaN compares Equal to everything, which is not |
| 347 | /// transitive), so any NaN input takes the original full-sort path to keep its |
| 348 | /// exact historical output. |
| 349 | fn top_k_mask(logits: &[f32], k: usize) -> Vec<f32> { |
| 350 | if logits.iter().any(|v| v.is_nan()) { |
| 351 | return top_k_mask_full_sort(logits, k); |
| 352 | } |
| 353 | let mut out = vec![f32::NEG_INFINITY; logits.len()]; |
| 354 | if k == 0 { |
| 355 | return out; |
| 356 | } |
| 357 | let mut order: Vec<usize> = (0..logits.len()).collect(); |
| 358 | let winners = if k < order.len() { |
| 359 | order.select_nth_unstable_by(k - 1, |&a, &b| rank_cmp(logits, a, b)); |
| 360 | &order[..k] |
| 361 | } else { |
| 362 | &order[..] |
| 363 | }; |
| 364 | for &i in winners { |
| 365 | out[i] = logits[i]; |
| 366 | } |
| 367 | out |
| 368 | } |
| 369 | |
| 370 | /// The original O(V log V) implementation: reference for tests and the path for |
| 371 | /// vectors containing NaN. |
| 372 | fn top_k_mask_full_sort(logits: &[f32], k: usize) -> Vec<f32> { |
| 373 | let mut order: Vec<usize> = (0..logits.len()).collect(); |
| 374 | order.sort_by(|&a, &b| rank_cmp(logits, a, b)); |
| 375 | let mut out = vec![f32::NEG_INFINITY; logits.len()]; |
| 376 | for &i in &order[..k] { |
| 377 | out[i] = logits[i]; |
| 378 | } |
| 379 | out |
| 380 | } |
| 381 | |
| 382 | #[cfg(test)] |
| 383 | mod tests { |
| 384 | use super::*; |
| 385 | |
| 386 | fn p(temperature: f32, top_k: usize) -> GenerateParams { |
| 387 | GenerateParams { |
| 388 | max_new_tokens: 1, |
| 389 | temperature, |
| 390 | top_p: 1.0, |
| 391 | top_k, |
| 392 | seed: 42, |
| 393 | stop_token_ids: vec![], |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn chip_greedy_draw_records_as_a_host_greedy_draw() { |
| 399 | // L356: a greedy reply that takes the chip's token must leave the same record as one |
| 400 | // that took the host argmax; a sampled reply is never greedy. |
| 401 | let (mut host, mut chip) = ( |
| 402 | SamplingObserver::new(&p(0.0, 20)), |
| 403 | SamplingObserver::new(&p(0.0, 20)), |
| 404 | ); |
| 405 | assert!(chip.is_greedy()); |
| 406 | assert!(!SamplingObserver::new(&p(0.7, 20)).is_greedy()); |
| 407 | for step in 0..3 { |
| 408 | host.sample(&[0.1, 5.0, 2.0], step); |
| 409 | chip.note_greedy(); |
| 410 | } |
| 411 | assert_eq!( |
| 412 | format!("{:?}", host.record()), |
| 413 | format!("{:?}", chip.record()) |
| 414 | ); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn greedy_is_argmax() { |
| 419 | assert_eq!(sample_next(&[0.1, 5.0, 2.0], &p(0.0, 0), 0), 1); |
| 420 | } |
| 421 | |
| 422 | #[test] |
| 423 | fn top_k_never_picks_outside_the_k_best() { |
| 424 | let logits = [1.0, 9.0, 8.0, 0.5, 7.9]; |
| 425 | for step in 0..200 { |
| 426 | let t = sample_next(&logits, &p(2.0, 2), step); |
| 427 | assert!(t == 1 || t == 2, "step {step} picked {t}"); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | #[test] |
| 432 | fn same_seed_same_token() { |
| 433 | let logits = [1.0, 1.1, 0.9, 1.05]; |
| 434 | for step in 0..20 { |
| 435 | assert_eq!( |
| 436 | sample_next(&logits, &p(1.0, 0), step), |
| 437 | sample_next(&logits, &p(1.0, 0), step) |
| 438 | ); |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | /// Tokens of 16 steps over a flat 8-way distribution for `seed` under `mutant`. |
| 443 | fn stream(seed: u64, temperature: f32, mutant: Option<SamplingMutant>) -> Vec<u32> { |
| 444 | let params = GenerateParams { |
| 445 | seed, |
| 446 | temperature, |
| 447 | ..p(temperature, 0) |
| 448 | }; |
| 449 | let mut o = SamplingObserver::with_mutant(¶ms, mutant); |
| 450 | (0..16).map(|s| o.sample(&[0.0; 8], s)).collect() |
| 451 | } |
| 452 | |
| 453 | #[test] |
| 454 | fn seeds_spread_and_mutants_break_the_spread() { |
| 455 | let honest: Vec<_> = (1..=3).map(|s| stream(s, 1.0, None)).collect(); |
| 456 | assert!(honest[0] != honest[1] && honest[1] != honest[2] && honest[0] != honest[2]); |
| 457 | let ign: Vec<_> = (1..=3) |
| 458 | .map(|s| stream(s, 1.0, Some(SamplingMutant::IgnoreSeed))) |
| 459 | .collect(); |
| 460 | assert!( |
| 461 | ign[0] == ign[1] && ign[1] == ign[2], |
| 462 | "ignore-seed must not spread" |
| 463 | ); |
| 464 | let fg = stream(1, 1.0, Some(SamplingMutant::ForceGreedy)); |
| 465 | assert_eq!( |
| 466 | fg, |
| 467 | stream(2, 0.0, None), |
| 468 | "force-greedy is the argmax stream" |
| 469 | ); |
| 470 | } |
| 471 | |
| 472 | #[test] |
| 473 | fn record_counts_kept_sets_and_modes() { |
| 474 | let params = GenerateParams { |
| 475 | top_p: 0.8, |
| 476 | ..p(0.7, 0) |
| 477 | }; |
| 478 | let mut o = SamplingObserver::with_mutant(¶ms, None); |
| 479 | o.sample(&[10.0, 0.0, 0.0, 0.0], 0); // confident: kept 1 |
| 480 | o.sample(&[0.0; 4], 1); // flat: nucleus 0.8 of 4 equal keeps 4 |
| 481 | o.sample(&[0.0; 4], 2); |
| 482 | let r = o.record(); |
| 483 | assert_eq!(r.mode, "sampled"); |
| 484 | assert_eq!(r.seed, 42); |
| 485 | assert_eq!(r.kept, vec![1, 4, 4]); |
| 486 | assert_eq!( |
| 487 | (r.kept_min, r.kept_median, r.kept_max, r.kept_single), |
| 488 | (1, 4, 4, 1) |
| 489 | ); |
| 490 | assert!((r.kept_mean - 3.0).abs() < 1e-12); |
| 491 | assert_eq!((r.greedy_tokens, r.sampled_tokens), (0, 3)); |
| 492 | // Two flat draws of 4: the chance of repeating them is (1/4)^2. |
| 493 | assert!((r.p_repeat - 1.0 / 16.0).abs() < 1e-6, "{r:?}"); |
| 494 | assert!((r.reply_logprob - 2.0 * 0.25f64.ln()).abs() < 1e-5); |
| 495 | assert!((r.top_prob_min - 0.25).abs() < 1e-12); |
| 496 | assert!((r.top_prob_mean - 0.5).abs() < 1e-3, "{r:?}"); |
| 497 | assert!( |
| 498 | r.log_fields().contains( |
| 499 | "kept(min/med/mean/max)=1/4/3.00/4 kept1=1/3 top_prob(min/mean)=0.2500/0.5000 p_repeat=6.250e-2" |
| 500 | ), |
| 501 | "{}", |
| 502 | r.log_fields() |
| 503 | ); |
| 504 | |
| 505 | let mut g = SamplingObserver::with_mutant(&p(0.0, 5), None); |
| 506 | g.sample(&[0.0, 1.0], 0); |
| 507 | let r = g.record(); |
| 508 | assert_eq!( |
| 509 | (r.mode, r.greedy_tokens, r.sampled_tokens), |
| 510 | ("greedy", 1, 0) |
| 511 | ); |
| 512 | assert!(!r.top_k_applied && r.kept.is_empty()); |
| 513 | assert_eq!( |
| 514 | (r.p_repeat, r.top_prob_min, r.top_prob_mean), |
| 515 | (1.0, 1.0, 1.0) |
| 516 | ); |
| 517 | |
| 518 | let mut m = SamplingObserver::with_mutant(¶ms, Some(SamplingMutant::IgnoreSeed)); |
| 519 | m.sample(&[0.0; 4], 0); |
| 520 | let r = m.record(); |
| 521 | assert_eq!((r.seed, r.mutant), (0, Some("ignore-seed"))); |
| 522 | assert!(r.log_fields().ends_with("MUTANT=ignore-seed")); |
| 523 | } |
| 524 | |
| 525 | /// Deterministic xorshift for reproducible vectors. |
| 526 | fn rng(state: &mut u64) -> u64 { |
| 527 | *state ^= *state << 13; |
| 528 | *state ^= *state >> 7; |
| 529 | *state ^= *state << 17; |
| 530 | *state |
| 531 | } |
| 532 | |
| 533 | fn same_bits(a: &[f32], b: &[f32]) -> bool { |
| 534 | a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()) |
| 535 | } |
| 536 | |
| 537 | fn check_all_k(logits: &[f32], ks: &[usize]) { |
| 538 | for &k in ks.iter().filter(|&&k| k <= logits.len()) { |
| 539 | assert!( |
| 540 | same_bits(&top_k_mask(logits, k), &top_k_mask_full_sort(logits, k)), |
| 541 | "k={k} len={}", |
| 542 | logits.len() |
| 543 | ); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | #[test] |
| 548 | fn top_k_selection_matches_full_sort_random_and_tied() { |
| 549 | let mut st = 0x9E37_79B9_7F4A_7C15u64; |
| 550 | for len in [1usize, 2, 5, 64, 1000, 4097] { |
| 551 | let ks = [0, 1, 20, 100, len.saturating_sub(1), len]; |
| 552 | // Random finite, with negatives. |
| 553 | let v: Vec<f32> = (0..len) |
| 554 | .map(|_| (rng(&mut st) % 20001) as f32 / 1000.0 - 10.0) |
| 555 | .collect(); |
| 556 | check_all_k(&v, &ks); |
| 557 | // Tie-heavy: only 4 distinct values, includes -0.0 and 0.0. |
| 558 | let t: Vec<f32> = (0..len) |
| 559 | .map(|_| [-1.0f32, 0.0, -0.0, 2.5][(rng(&mut st) % 4) as usize]) |
| 560 | .collect(); |
| 561 | check_all_k(&t, &ks); |
| 562 | // All equal. |
| 563 | check_all_k(&vec![1.5; len], &ks); |
| 564 | // Infinities mixed in. |
| 565 | let i: Vec<f32> = (0..len) |
| 566 | .map(|_| match rng(&mut st) % 6 { |
| 567 | 0 => f32::INFINITY, |
| 568 | 1 => f32::NEG_INFINITY, |
| 569 | _ => (rng(&mut st) % 7) as f32, |
| 570 | }) |
| 571 | .collect(); |
| 572 | check_all_k(&i, &ks); |
| 573 | // NaN mixed in: falls back to the original path, bit-identical. |
| 574 | let n: Vec<f32> = (0..len) |
| 575 | .map(|_| match rng(&mut st) % 5 { |
| 576 | 0 => f32::NAN, |
| 577 | 1 => f32::INFINITY, |
| 578 | _ => (rng(&mut st) % 5) as f32, |
| 579 | }) |
| 580 | .collect(); |
| 581 | // The original comparator is not a total order with NaN, so the |
| 582 | // full sort may itself panic; the new path must match either way. |
| 583 | for k in [0, 1, 20.min(len), len] { |
| 584 | let a = std::panic::catch_unwind(|| top_k_mask(&n, k)); |
| 585 | let b = std::panic::catch_unwind(|| top_k_mask_full_sort(&n, k)); |
| 586 | match (a, b) { |
| 587 | (Ok(a), Ok(b)) => assert!(same_bits(&a, &b)), |
| 588 | (Err(_), Err(_)) => {} |
| 589 | _ => panic!("NaN behavior diverged at k={k}"), |
| 590 | } |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | #[test] |
| 596 | fn top_k_ties_at_cutoff_keep_lower_token_id() { |
| 597 | let m = top_k_mask(&[1.0, 3.0, 1.0, 1.0, 3.0], 3); |
| 598 | assert_eq!(m, vec![1.0, 3.0, f32::NEG_INFINITY, f32::NEG_INFINITY, 3.0]); |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn sampled_tokens_and_record_match_with_reference_mask() { |
| 603 | let mut st = 7u64; |
| 604 | let logits: Vec<f32> = (0..5000) |
| 605 | .map(|_| (rng(&mut st) % 400) as f32 / 40.0 - 5.0) |
| 606 | .collect(); |
| 607 | for k in [1usize, 20, 100] { |
| 608 | let masked = top_k_mask(&logits, k); |
| 609 | let reference = top_k_mask_full_sort(&logits, k); |
| 610 | assert!(same_bits(&masked, &reference)); |
| 611 | let params = GenerateParams { |
| 612 | top_p: 0.9, |
| 613 | ..p(0.8, k) |
| 614 | }; |
| 615 | let mut o = SamplingObserver::with_mutant(¶ms, None); |
| 616 | let mut r = SamplingObserver::with_mutant( |
| 617 | &GenerateParams { |
| 618 | top_k: 0, |
| 619 | ..params.clone() |
| 620 | }, |
| 621 | None, |
| 622 | ); |
| 623 | for step in 0..50 { |
| 624 | assert_eq!(o.sample(&logits, step), r.sample(&reference, step)); |
| 625 | } |
| 626 | assert_eq!(o.record().kept, r.record().kept); |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | /// Microbenchmark: `cargo test --release -p aien-serve-http --lib |
| 631 | /// sampling::tests::bench_top_k -- --ignored --nocapture`. |
| 632 | #[test] |
| 633 | #[ignore] |
| 634 | fn bench_top_k() { |
| 635 | let mut st = 1u64; |
| 636 | let logits: Vec<f32> = (0..152_064) |
| 637 | .map(|_| (rng(&mut st) % 100_000) as f32 / 5000.0 - 10.0) |
| 638 | .collect(); |
| 639 | for k in [1usize, 20, 100] { |
| 640 | for (name, f) in [ |
| 641 | ( |
| 642 | "full_sort", |
| 643 | top_k_mask_full_sort as fn(&[f32], usize) -> Vec<f32>, |
| 644 | ), |
| 645 | ("select", top_k_mask), |
| 646 | ] { |
| 647 | let mut t: Vec<f64> = (0..21) |
| 648 | .map(|_| { |
| 649 | let s = std::time::Instant::now(); |
| 650 | std::hint::black_box(f(std::hint::black_box(&logits), k)); |
| 651 | s.elapsed().as_secs_f64() * 1e3 |
| 652 | }) |
| 653 | .collect(); |
| 654 | t.sort_by(|a, b| a.partial_cmp(b).unwrap()); |
| 655 | println!( |
| 656 | "k={k:<3} {name:<9} median {:.3} ms min {:.3} max {:.3}", |
| 657 | t[10], t[0], t[20] |
| 658 | ); |
| 659 | } |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn mutant_variable_is_refused_without_debug_assertions() { |
| 665 | assert_eq!(parse_mutant(None, false), Ok(None)); |
| 666 | assert_eq!(parse_mutant(Some(""), false), Ok(None)); |
| 667 | assert!(parse_mutant(Some("ignore-seed"), false).is_err()); |
| 668 | assert_eq!( |
| 669 | parse_mutant(Some("ignore-seed"), true), |
| 670 | Ok(Some(SamplingMutant::IgnoreSeed)) |
| 671 | ); |
| 672 | assert_eq!( |
| 673 | parse_mutant(Some("force-greedy"), true), |
| 674 | Ok(Some(SamplingMutant::ForceGreedy)) |
| 675 | ); |
| 676 | assert!(parse_mutant(Some("bogus"), true).is_err()); |
| 677 | } |
| 678 | } |