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-inference-abi / src / exact_head.rs
| 1 | //! Exact two-pass lm_head (HUM lever, ledger L314). |
| 2 | //! |
| 3 | //! The 35B head is bf16, `[248,320][2,048]`: 1.017 GB read per token. Pass 1 multiplies a |
| 4 | //! cheap copy `w~` (W4 or FP8, one bf16 scale per 128 columns) by the hidden vector `h`; pass 2 |
| 5 | //! recomputes the exact bf16 logits only for the rows that can still be the argmax. |
| 6 | //! |
| 7 | //! Why the token cannot change. Let `L_i` be today's logit (bf16 row times `h`, f32 sums in any |
| 8 | //! order) and `s_i` the screen logit. With `D = w - w~` per 128-column group `g`: |
| 9 | //! `|L_i - s_i| <= gamma |w_i||h| + sum_g |D_ig||h_g| + gamma |w~_i||h| <= B_i` |
| 10 | //! (Cauchy-Schwarz per group; `gamma = 2048 u / (1 - 2048 u)`, `u = 2^-24`, bounds any f32 dot |
| 11 | //! of length 2048 whatever its order, Higham 3.1). Let `i*` be the full argmax (first on ties) |
| 12 | //! and `tau = max_j (s_j - B_j)`. Every `L_j >= s_j - B_j`, so `L_i* >= tau`, so |
| 13 | //! `s_i* + B_i* >= L_i* >= tau`: `i*` is in `C = { i : s_i + B_i >= tau }`. The recheck uses the |
| 14 | //! same `L_i` bits and scans `C` in ascending order with the same strict `>`, so it returns `i*`. |
| 15 | //! |
| 16 | //! Every stored bound term (group norms, row norms) is rounded UP to bf16, so the stored bytes |
| 17 | //! are themselves an upper bound; the whole bound is then widened by `2^-20` for the rounding of |
| 18 | //! the few f64 operations that combine it. |
| 19 | |
| 20 | use rayon::prelude::*; |
| 21 | |
| 22 | use crate::qwen38::{dot, Matrix}; |
| 23 | use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16, f32_to_fp8_e4m3fn, fp8_table}; |
| 24 | |
| 25 | /// Columns per scale and per bound group. |
| 26 | pub const GROUP: usize = 128; |
| 27 | |
| 28 | /// The cheap copy pass 1 reads. |
| 29 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 30 | pub enum ScreenKind { |
| 31 | /// int4 in [-8, 7], scale = bf16(absmax / 7), round to nearest. |
| 32 | W4, |
| 33 | /// e4m3, scale = bf16(absmax / 448), round to nearest even. |
| 34 | Fp8, |
| 35 | /// e4m3 with one scale per 128 x 128 block, scale = bf16 rounded UP (absmax / 448): the layout |
| 36 | /// omega's FP8 GEMV reads (`weight_scale_inv` [n/128][k/128]), so the chip screen reuses it. |
| 37 | Fp8Block, |
| 38 | } |
| 39 | |
| 40 | /// Which upper bound on `|L_i - s_i|` builds the candidate set. |
| 41 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 42 | pub enum BoundKind { |
| 43 | /// `|D_i| |h|`: one stored value per row. |
| 44 | Row, |
| 45 | /// `sum_g |D_ig|_2 |h_g|_2`: 16 stored values per row. |
| 46 | Group, |
| 47 | /// `sum_g max|D_ig| |h_g|_1`: 16 stored values per row. |
| 48 | GroupLinf, |
| 49 | /// The smaller of `Group` and `GroupLinf` per row (both stored). |
| 50 | Min, |
| 51 | } |
| 52 | |
| 53 | /// Roundings per term the chip screen may add: k products and sums plus the 16 block partials. |
| 54 | pub const CHIP_GAMMA_LEN: usize = 2100; |
| 55 | |
| 56 | /// What [`chip_screen`] returns: e4m3 codes, bf16 block scales, Row coefficients. |
| 57 | pub type ChipScreen = (Vec<u8>, Vec<u16>, Vec<f32>); |
| 58 | |
| 59 | /// What the chip's exact head uploads for a bf16 `head`: the e4m3 codes `[n][k]`, the block |
| 60 | /// scales as bf16 words `[n / 128][k / 128]` and the Row coefficients `[n]` |
| 61 | /// ([`Screen::row_coef`] at [`CHIP_GAMMA_LEN`]). Refuses when the codes do not reproduce the |
| 62 | /// screen the bound was computed for, bit for bit. |
| 63 | pub fn chip_screen(head: &Matrix) -> Result<ChipScreen, String> { |
| 64 | chip_screen_with_roundings(head, CHIP_GAMMA_LEN) |
| 65 | } |
| 66 | |
| 67 | /// Export the existing checked screen with a caller-specified conservative rounding count. |
| 68 | pub fn chip_screen_with_roundings(head: &Matrix, roundings: usize) -> Result<ChipScreen, String> { |
| 69 | let scales = fp8_block_scales(head); |
| 70 | let codes = fp8_block_codes(head, &scales); |
| 71 | let screen = Screen::build(head, ScreenKind::Fp8Block)?; |
| 72 | let bad = screen.codes_mismatch(&codes, &scales); |
| 73 | if bad != 0 { |
| 74 | return Err(format!( |
| 75 | "exact head: {bad} rows of codes do not reproduce the screen" |
| 76 | )); |
| 77 | } |
| 78 | let coef = screen.row_coef(roundings); |
| 79 | Ok(( |
| 80 | codes, |
| 81 | scales.iter().map(|&s| f32_to_bf16(s)).collect(), |
| 82 | coef, |
| 83 | )) |
| 84 | } |
| 85 | |
| 86 | impl ScreenKind { |
| 87 | pub fn parse(s: &str) -> Option<Self> { |
| 88 | match s { |
| 89 | "w4" => Some(Self::W4), |
| 90 | "fp8" => Some(Self::Fp8), |
| 91 | "fp8b" => Some(Self::Fp8Block), |
| 92 | _ => None, |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Bytes of codes + bf16 scales for an `[n][k]` head. |
| 97 | pub fn bytes(self, n: usize, k: usize) -> u64 { |
| 98 | let codes = match self { |
| 99 | Self::W4 => n * k / 2, |
| 100 | Self::Fp8 => n * k, |
| 101 | Self::Fp8Block => return (n * k + (n / GROUP) * (k / GROUP) * 2) as u64, |
| 102 | }; |
| 103 | (codes + n * (k / GROUP) * 2) as u64 |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | impl BoundKind { |
| 108 | pub fn parse(s: &str) -> Option<Self> { |
| 109 | match s { |
| 110 | "row" => Some(Self::Row), |
| 111 | "group" => Some(Self::Group), |
| 112 | "linf" => Some(Self::GroupLinf), |
| 113 | "min" => Some(Self::Min), |
| 114 | _ => None, |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Bytes of stored bound terms (bf16) for `n` rows of `k`, the fp margin's row norm included. |
| 119 | pub fn bytes(self, n: usize, k: usize) -> u64 { |
| 120 | let g = k / GROUP; |
| 121 | let terms = match self { |
| 122 | Self::Row => n, |
| 123 | Self::Group | Self::GroupLinf => n * g, |
| 124 | Self::Min => 2 * n * g, |
| 125 | }; |
| 126 | ((terms + n) * 2) as u64 |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// `2048 u / (1 - 2048 u)` for length `k`: any f32 dot's error over `sum |a_i b_i|`. |
| 131 | pub fn gamma(k: usize) -> f64 { |
| 132 | let nu = k as f64 * 2f64.powi(-24); |
| 133 | nu / (1.0 - nu) |
| 134 | } |
| 135 | |
| 136 | /// The smallest bf16 value `>= x` (`x >= 0`), as f32. |
| 137 | pub fn bf16_up(x: f64) -> f32 { |
| 138 | let mut v = x as f32; |
| 139 | if (v as f64) < x { |
| 140 | v = f32::from_bits(v.to_bits() + 1); |
| 141 | } |
| 142 | let mut b = f32_to_bf16(v); |
| 143 | if bf16_to_f32(b) < v { |
| 144 | b += 1; |
| 145 | } |
| 146 | bf16_to_f32(b) |
| 147 | } |
| 148 | |
| 149 | /// Pass 1's copy of a bf16 head and the stored bound terms, built once at load. |
| 150 | pub struct Screen { |
| 151 | pub kind: ScreenKind, |
| 152 | pub n: usize, |
| 153 | pub k: usize, |
| 154 | /// `w~` as f32 `[n][k]` (host; the chip reads codes + scales). |
| 155 | deq: Vec<f32>, |
| 156 | /// `|D_ig|_2` rounded up, `[n][k / GROUP]`. |
| 157 | dnorm: Vec<f32>, |
| 158 | /// `max |D_ig|` rounded up, `[n][k / GROUP]`. |
| 159 | dmax: Vec<f32>, |
| 160 | /// `|D_i|_2` rounded up, `[n]`. |
| 161 | drow: Vec<f32>, |
| 162 | /// `|w_i|_2 + |w~_i|_2` rounded up, `[n]` (the f32 rounding margin). |
| 163 | rnorm: Vec<f32>, |
| 164 | } |
| 165 | |
| 166 | /// [`ScreenKind::Fp8Block`] scales, `[n / 128][k / 128]`: bf16 rounded UP (absmax / 448), so |
| 167 | /// `|w / scale| <= 448` always (no e4m3 saturation). Every value is a bf16, so it uploads as is. |
| 168 | pub fn fp8_block_scales(head: &Matrix) -> Vec<f32> { |
| 169 | let (n, g) = (head.n(), head.k() / GROUP); |
| 170 | (0..(n / GROUP) * g) |
| 171 | .into_par_iter() |
| 172 | .map(|b| { |
| 173 | let (br, gi) = (b / g, b % g); |
| 174 | let amax = (br * GROUP..(br + 1) * GROUP) |
| 175 | .flat_map(|r| head.bf16_row(r).unwrap()[gi * GROUP..(gi + 1) * GROUP].iter()) |
| 176 | .map(|&v| bf16_to_f32(v).abs()) |
| 177 | .fold(0f32, f32::max); |
| 178 | bf16_up(amax as f64 / 448.0) |
| 179 | }) |
| 180 | .collect() |
| 181 | } |
| 182 | |
| 183 | /// e4m3 codes of a bf16 `head` under `scales` ([`fp8_block_scales`]), `[n][k]`: the bytes the |
| 184 | /// chip screen reads. `lut[code] * scale` is exactly the screen's `w~`. |
| 185 | pub fn fp8_block_codes(head: &Matrix, scales: &[f32]) -> Vec<u8> { |
| 186 | let (n, k) = (head.n(), head.k()); |
| 187 | let g = k / GROUP; |
| 188 | let mut out = vec![0u8; n * k]; |
| 189 | out.par_chunks_mut(k).enumerate().for_each(|(r, o)| { |
| 190 | for (c, (d, &b)) in o.iter_mut().zip(head.bf16_row(r).unwrap()).enumerate() { |
| 191 | let s = scales[(r / GROUP) * g + c / GROUP]; |
| 192 | *d = if s == 0.0 { |
| 193 | 0 |
| 194 | } else { |
| 195 | f32_to_fp8_e4m3fn(bf16_to_f32(b) / s) |
| 196 | }; |
| 197 | } |
| 198 | }); |
| 199 | out |
| 200 | } |
| 201 | |
| 202 | impl Screen { |
| 203 | /// The chip's Row-bound coefficient per row: `c_i >= |D_i| + gamma(len) (|w_i| + |w~_i|)` |
| 204 | /// rounded up to f32 and widened `2^-20`; the chip bound is `c_i |h|` (its own margins on top). |
| 205 | /// `len` covers the chip screen's roundings per term (k products + the block partial sums). |
| 206 | pub fn row_coef(&self, len: usize) -> Vec<f32> { |
| 207 | let gm = gamma(len); |
| 208 | self.drow |
| 209 | .iter() |
| 210 | .zip(&self.rnorm) |
| 211 | .map(|(&d, &r)| { |
| 212 | let x = (d as f64 + gm * r as f64) * (1.0 + 2f64.powi(-20)); |
| 213 | let mut v = x as f32; |
| 214 | if (v as f64) < x { |
| 215 | v = f32::from_bits(v.to_bits() + 1); |
| 216 | } |
| 217 | v |
| 218 | }) |
| 219 | .collect() |
| 220 | } |
| 221 | |
| 222 | /// Rows whose exported e4m3 `codes` under block `scales` do not reproduce `w~` bit for bit. |
| 223 | pub fn codes_mismatch(&self, codes: &[u8], scales: &[f32]) -> usize { |
| 224 | let (k, g) = (self.k, self.k / GROUP); |
| 225 | let lut = fp8_table(); |
| 226 | (0..self.n) |
| 227 | .into_par_iter() |
| 228 | .filter(|&r| { |
| 229 | (0..k).any(|c| { |
| 230 | let s = scales[(r / GROUP) * g + c / GROUP]; |
| 231 | (lut[codes[r * k + c] as usize] * s).to_bits() != self.deq[r * k + c].to_bits() |
| 232 | }) |
| 233 | }) |
| 234 | .count() |
| 235 | } |
| 236 | /// Quantizes every row of the bf16 `head` (`k` a multiple of [`GROUP`]). |
| 237 | pub fn build(head: &Matrix, kind: ScreenKind) -> Result<Self, String> { |
| 238 | let (n, k) = (head.n(), head.k()); |
| 239 | if head.bf16_row(0).is_none() || k % GROUP != 0 { |
| 240 | return Err(format!("screen: needs a bf16 head with k % {GROUP} == 0")); |
| 241 | } |
| 242 | let g = k / GROUP; |
| 243 | let lut = fp8_table(); |
| 244 | let mut deq = vec![0f32; n * k]; |
| 245 | let mut dnorm = vec![0f32; n * g]; |
| 246 | let mut dmax = vec![0f32; n * g]; |
| 247 | let mut drow = vec![0f32; n]; |
| 248 | let mut rnorm = vec![0f32; n]; |
| 249 | if kind == ScreenKind::Fp8Block && n % GROUP != 0 { |
| 250 | return Err(format!("screen: fp8b needs n % {GROUP} == 0")); |
| 251 | } |
| 252 | let block = if kind == ScreenKind::Fp8Block { |
| 253 | fp8_block_scales(head) |
| 254 | } else { |
| 255 | Vec::new() |
| 256 | }; |
| 257 | deq.par_chunks_mut(k) |
| 258 | .zip(dnorm.par_chunks_mut(g)) |
| 259 | .zip(dmax.par_chunks_mut(g)) |
| 260 | .zip(drow.par_iter_mut().zip(rnorm.par_iter_mut())) |
| 261 | .enumerate() |
| 262 | .for_each(|(r, (((out, dn), dm), (dr, rn)))| { |
| 263 | let row = head.bf16_row(r).unwrap(); |
| 264 | let (mut d2, mut w2, mut q2) = (0f64, 0f64, 0f64); |
| 265 | for gi in 0..g { |
| 266 | let src = &row[gi * GROUP..(gi + 1) * GROUP]; |
| 267 | let dst = &mut out[gi * GROUP..(gi + 1) * GROUP]; |
| 268 | let amax = src |
| 269 | .iter() |
| 270 | .map(|&b| bf16_to_f32(b).abs()) |
| 271 | .fold(0f32, f32::max); |
| 272 | let scale = match kind { |
| 273 | ScreenKind::W4 => bf16_to_f32(f32_to_bf16(amax / 7.0)), |
| 274 | ScreenKind::Fp8 => bf16_to_f32(f32_to_bf16(amax / 448.0)), |
| 275 | ScreenKind::Fp8Block => block[(r / GROUP) * g + gi], |
| 276 | }; |
| 277 | let (mut gd2, mut gmax) = (0f64, 0f64); |
| 278 | for (o, &b) in dst.iter_mut().zip(src) { |
| 279 | let w = bf16_to_f32(b); |
| 280 | *o = if scale == 0.0 { |
| 281 | 0.0 |
| 282 | } else { |
| 283 | match kind { |
| 284 | ScreenKind::W4 => (w / scale).round().clamp(-8.0, 7.0) * scale, |
| 285 | ScreenKind::Fp8 | ScreenKind::Fp8Block => { |
| 286 | lut[f32_to_fp8_e4m3fn(w / scale) as usize] * scale |
| 287 | } |
| 288 | } |
| 289 | }; |
| 290 | let d = w as f64 - *o as f64; |
| 291 | gd2 += d * d; |
| 292 | gmax = gmax.max(d.abs()); |
| 293 | w2 += w as f64 * w as f64; |
| 294 | q2 += *o as f64 * *o as f64; |
| 295 | } |
| 296 | d2 += gd2; |
| 297 | dn[gi] = bf16_up(gd2.sqrt() * (1.0 + 1e-12)); |
| 298 | dm[gi] = bf16_up(gmax); |
| 299 | } |
| 300 | *dr = bf16_up(d2.sqrt() * (1.0 + 1e-12)); |
| 301 | *rn = bf16_up((w2.sqrt() + q2.sqrt()) * (1.0 + 1e-12)); |
| 302 | }); |
| 303 | Ok(Self { |
| 304 | kind, |
| 305 | n, |
| 306 | k, |
| 307 | deq, |
| 308 | dnorm, |
| 309 | dmax, |
| 310 | drow, |
| 311 | rnorm, |
| 312 | }) |
| 313 | } |
| 314 | |
| 315 | /// Pass 1: `s_i = w~_i . h` for every row. |
| 316 | pub fn logits(&self, h: &[f32]) -> Vec<f32> { |
| 317 | self.deq.par_chunks(self.k).map(|row| dot(row, h)).collect() |
| 318 | } |
| 319 | |
| 320 | /// `B_i` for every row, times `scale` (1 = the proven bound; below 1 = a mutant). |
| 321 | pub fn bounds(&self, h: &[f32], kind: BoundKind, scale: f64) -> Vec<f64> { |
| 322 | let g = self.k / GROUP; |
| 323 | let widen = 1.0 + 1e-12; |
| 324 | let h2: Vec<f64> = h |
| 325 | .chunks_exact(GROUP) |
| 326 | .map(|c| c.iter().map(|&v| v as f64 * v as f64).sum::<f64>().sqrt() * widen) |
| 327 | .collect(); |
| 328 | let h1: Vec<f64> = h |
| 329 | .chunks_exact(GROUP) |
| 330 | .map(|c| c.iter().map(|&v| (v as f64).abs()).sum::<f64>() * widen) |
| 331 | .collect(); |
| 332 | let hn = h2.iter().map(|v| v * v).sum::<f64>().sqrt() * widen; |
| 333 | let gm = gamma(self.k); |
| 334 | (0..self.n) |
| 335 | .into_par_iter() |
| 336 | .map(|r| { |
| 337 | let group = || { |
| 338 | (0..g) |
| 339 | .map(|i| self.dnorm[r * g + i] as f64 * h2[i]) |
| 340 | .sum::<f64>() |
| 341 | }; |
| 342 | let linf = || { |
| 343 | (0..g) |
| 344 | .map(|i| self.dmax[r * g + i] as f64 * h1[i]) |
| 345 | .sum::<f64>() |
| 346 | }; |
| 347 | let quant = match kind { |
| 348 | BoundKind::Row => self.drow[r] as f64 * hn, |
| 349 | BoundKind::Group => group(), |
| 350 | BoundKind::GroupLinf => linf(), |
| 351 | BoundKind::Min => group().min(linf()), |
| 352 | }; |
| 353 | (quant + gm * self.rnorm[r] as f64 * hn) * scale * (1.0 + 2f64.powi(-20)) |
| 354 | }) |
| 355 | .collect() |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /// Candidate rows, ascending: `{ i : s_i + B_i >= max_j (s_j - B_j) }`. |
| 360 | pub fn candidates(s: &[f32], b: &[f64]) -> Vec<u32> { |
| 361 | candidates_from(s, b, f64::NEG_INFINITY) |
| 362 | } |
| 363 | |
| 364 | /// [`candidates`] given a lower bound on the winner's exact logit (the exact logit of any row, |
| 365 | /// rechecked first): `tau = max(lower, max_j (s_j - B_j))`. Still exact: `L_i* >= tau`. |
| 366 | pub fn candidates_from(s: &[f32], b: &[f64], lower: f64) -> Vec<u32> { |
| 367 | let tau = s |
| 368 | .iter() |
| 369 | .zip(b) |
| 370 | .map(|(&v, &e)| v as f64 - e) |
| 371 | .fold(lower, f64::max); |
| 372 | s.iter() |
| 373 | .zip(b) |
| 374 | .enumerate() |
| 375 | .filter(|(_, (&v, &e))| v as f64 + e >= tau) |
| 376 | .map(|(i, _)| i as u32) |
| 377 | .collect() |
| 378 | } |
| 379 | |
| 380 | /// Candidate rows (ascending) that hold the exact top `kk` (the door's top-k mask before it |
| 381 | /// samples): `tau = kk`-th largest `s_j - B_j`, at least `lower`. `kk` rows have `L >= tau`, so |
| 382 | /// `L_(kk) >= tau`; a row outside has `L <= s + B < tau`, strictly below every kept logit, so the |
| 383 | /// top-k set and its order (logit desc, row asc) are those of the full head. |
| 384 | pub fn candidates_topk(s: &[f32], b: &[f64], kk: usize, lower: f64) -> Vec<u32> { |
| 385 | let mut low: Vec<f64> = s.iter().zip(b).map(|(&v, &e)| v as f64 - e).collect(); |
| 386 | let kk = kk.clamp(1, low.len()); |
| 387 | let (_, kth, _) = low.select_nth_unstable_by(kk - 1, |a, z| z.total_cmp(a)); |
| 388 | let tau = kth.max(lower); |
| 389 | s.iter() |
| 390 | .zip(b) |
| 391 | .enumerate() |
| 392 | .filter(|(_, (&v, &e))| v as f64 + e >= tau) |
| 393 | .map(|(i, _)| i as u32) |
| 394 | .collect() |
| 395 | } |
| 396 | |
| 397 | /// Pass 2: today's exact logit for each candidate (same widen + [`dot`] as [`Matrix::matmul`]), |
| 398 | /// argmax in ascending row order, first on ties. Returns `(row, logit)`. |
| 399 | pub fn recheck(head: &Matrix, h: &[f32], cands: &[u32]) -> (usize, f32) { |
| 400 | let exact: Vec<f32> = cands |
| 401 | .par_iter() |
| 402 | .map(|&r| { |
| 403 | let row: Vec<f32> = head |
| 404 | .bf16_row(r as usize) |
| 405 | .unwrap() |
| 406 | .iter() |
| 407 | .map(|&b| bf16_to_f32(b)) |
| 408 | .collect(); |
| 409 | dot(&row, h) |
| 410 | }) |
| 411 | .collect(); |
| 412 | let mut best = 0; |
| 413 | for (i, &v) in exact.iter().enumerate() { |
| 414 | if v > exact[best] { |
| 415 | best = i; |
| 416 | } |
| 417 | } |
| 418 | (cands[best] as usize, exact[best]) |
| 419 | } |
| 420 | |
| 421 | /// The two-pass head end to end: `(argmax, |C|)`. |
| 422 | pub fn argmax( |
| 423 | head: &Matrix, |
| 424 | screen: &Screen, |
| 425 | h: &[f32], |
| 426 | kind: BoundKind, |
| 427 | scale: f64, |
| 428 | ) -> (usize, usize) { |
| 429 | assert_eq!( |
| 430 | h.len(), |
| 431 | screen.k, |
| 432 | "exact_head::argmax: h must be one hidden vector of k values" |
| 433 | ); |
| 434 | let s = screen.logits(h); |
| 435 | let b = screen.bounds(h, kind, scale); |
| 436 | let c = candidates(&s, &b); |
| 437 | (recheck(head, h, &c).0, c.len()) |
| 438 | } |
| 439 | |
| 440 | #[cfg(test)] |
| 441 | mod tests { |
| 442 | use super::*; |
| 443 | use crate::qwen38::argmax as full_argmax; |
| 444 | |
| 445 | fn prand(seed: u64, i: usize) -> f32 { |
| 446 | let mut x = seed ^ (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 447 | x ^= x >> 33; |
| 448 | x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); |
| 449 | x ^= x >> 33; |
| 450 | (x >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 |
| 451 | } |
| 452 | |
| 453 | fn head(n: usize, k: usize, seed: u64) -> Matrix { |
| 454 | let w = (0..n * k) |
| 455 | .map(|i| f32_to_bf16(prand(seed, i) * 0.05)) |
| 456 | .collect(); |
| 457 | Matrix::Bf16 { n, k, w } |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn bf16_up_never_rounds_down() { |
| 462 | for &x in &[0.0, 1e-30, 0.1, 1.0 / 3.0, 7.0, 123.456, 1e30] { |
| 463 | assert!(bf16_up(x) as f64 >= x, "{x}"); |
| 464 | } |
| 465 | assert_eq!(bf16_up(1.0), 1.0); |
| 466 | } |
| 467 | |
| 468 | #[test] |
| 469 | fn two_pass_equals_full_argmax_on_random_heads() { |
| 470 | let (n, k) = (4096, 256); |
| 471 | for kind in [ScreenKind::W4, ScreenKind::Fp8, ScreenKind::Fp8Block] { |
| 472 | let m = head(n, k, 7); |
| 473 | let scr = Screen::build(&m, kind).unwrap(); |
| 474 | for t in 0..40 { |
| 475 | // A hidden vector with a planted winner so the top gap is sometimes tiny. |
| 476 | let mut h: Vec<f32> = (0..k).map(|i| prand(100 + t, i) * 3.0).collect(); |
| 477 | if t % 2 == 0 { |
| 478 | let row: Vec<f32> = m |
| 479 | .bf16_row(t as usize * 17) |
| 480 | .unwrap() |
| 481 | .iter() |
| 482 | .map(|&b| bf16_to_f32(b)) |
| 483 | .collect(); |
| 484 | h.iter_mut().zip(&row).for_each(|(a, b)| *a += b * 40.0); |
| 485 | } |
| 486 | let full = full_argmax(&m.matmul(&h, 1)); |
| 487 | for bk in [ |
| 488 | BoundKind::Row, |
| 489 | BoundKind::Group, |
| 490 | BoundKind::GroupLinf, |
| 491 | BoundKind::Min, |
| 492 | ] { |
| 493 | let (got, c) = argmax(&m, &scr, &h, bk, 1.0); |
| 494 | assert_eq!(got, full, "{kind:?} {bk:?} t {t}"); |
| 495 | assert!(c >= 1 && c <= n); |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | #[test] |
| 502 | fn topk_candidates_hold_the_exact_top_k() { |
| 503 | let (n, k, kk) = (4096, 256, 20); |
| 504 | let m = head(n, k, 9); |
| 505 | let scr = Screen::build(&m, ScreenKind::W4).unwrap(); |
| 506 | for t in 0..20 { |
| 507 | let h: Vec<f32> = (0..k).map(|i| prand(900 + t, i) * 2.0).collect(); |
| 508 | let l = m.matmul(&h, 1); |
| 509 | let mut order: Vec<usize> = (0..n).collect(); |
| 510 | order.sort_by(|&a, &b| l[b].total_cmp(&l[a]).then(a.cmp(&b))); |
| 511 | let c = candidates_topk( |
| 512 | &scr.logits(&h), |
| 513 | &scr.bounds(&h, BoundKind::Min, 1.0), |
| 514 | kk, |
| 515 | f64::NEG_INFINITY, |
| 516 | ); |
| 517 | let mut sub: Vec<usize> = c.iter().map(|&r| r as usize).collect(); |
| 518 | sub.sort_by(|&a, &b| l[b].total_cmp(&l[a]).then(a.cmp(&b))); |
| 519 | assert_eq!(&sub[..kk], &order[..kk], "t {t}"); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | #[test] |
| 524 | fn ties_go_to_the_first_row_like_the_full_argmax() { |
| 525 | let (n, k) = (300, 128); |
| 526 | let mut w: Vec<u16> = (0..n * k) |
| 527 | .map(|i| f32_to_bf16(prand(3, i) * 0.01)) |
| 528 | .collect(); |
| 529 | // Rows 40 and 200 identical and largest along h = ones. |
| 530 | for c in 0..k { |
| 531 | w[40 * k + c] = f32_to_bf16(0.5); |
| 532 | w[200 * k + c] = f32_to_bf16(0.5); |
| 533 | } |
| 534 | let m = Matrix::Bf16 { n, k, w }; |
| 535 | let h = vec![1f32; k]; |
| 536 | let scr = Screen::build(&m, ScreenKind::W4).unwrap(); |
| 537 | assert_eq!(full_argmax(&m.matmul(&h, 1)), 40); |
| 538 | assert_eq!(argmax(&m, &scr, &h, BoundKind::Group, 1.0).0, 40); |
| 539 | } |
| 540 | |
| 541 | #[test] |
| 542 | fn a_zero_bound_mutant_can_lose_the_argmax() { |
| 543 | // The screen alone (bound x 0) must miss the exact winner on some input, or this test |
| 544 | // could not tell a working bound from none. |
| 545 | let (n, k) = (4096, 256); |
| 546 | let m = head(n, k, 11); |
| 547 | let scr = Screen::build(&m, ScreenKind::W4).unwrap(); |
| 548 | let missed = (0..200).any(|t| { |
| 549 | let h: Vec<f32> = (0..k).map(|i| prand(500 + t, i)).collect(); |
| 550 | argmax(&m, &scr, &h, BoundKind::Group, 0.0).0 != full_argmax(&m.matmul(&h, 1)) |
| 551 | }); |
| 552 | assert!(missed); |
| 553 | } |
| 554 | } |