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 / bitnet_forward.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 | //! Our CPU reference forward for BitNet b1.58 2B-4T (stage T2): the oracle the chip engine is |
| 17 | //! checked against. f32 arithmetic throughout, exact int32 ternary products. |
| 18 | //! |
| 19 | //! One layer, as spec 1.2 states it from `REF/model.py:237-242` (prefill path, `use_kernel=False`, |
| 20 | //! `REF/generate.py:56,63,70`), cross-checked with `HF/models/bitnet/modeling_bitnet.py`: |
| 21 | //! |
| 22 | //! ```text |
| 23 | //! a = rms_norm(x, input_norm) model.py:237-241 |
| 24 | //! q,k,v = BitLinear_qkv(a) (one fused linear, rows [q | k | v], one weight scale per segment) |
| 25 | //! q,k = rope_half_split(q, k, position) spec 1.3, HF :83-85, :299, :314 |
| 26 | //! o = causal GQA softmax(q k^T / sqrt(128)) v HF :161; q head h reads kv head h / 4 |
| 27 | //! h = x + BitLinear_o(rms_norm(o, attn_sub_norm)) model.py:159-160 |
| 28 | //! g,u = BitLinear_gate_up(rms_norm(h, post_norm)) |
| 29 | //! out = h + BitLinear_down(rms_norm(relu(g)^2 * u, ffn_sub_norm)) model.py:192-197 |
| 30 | //! logits = rms_norm(x_last_layer, final_norm) . embed^T model.py:280-281 (tied) |
| 31 | //! ``` |
| 32 | //! |
| 33 | //! BitLinear (spec 2.2, `REF/model.py:78-81`): per token `s_a = 127 / max(max|x|, 1e-5)`, |
| 34 | //! `q = clamp(round_half_even(x * s_a), -128, 127)`, then `y[r] = acc[r] / s_a * w_scale(r)` with |
| 35 | //! `acc` the exact int32 ternary product and `w_scale` the bf16 scale of the segment row `r` |
| 36 | //! belongs to (one scale each for q, k, v, gate, up; never the decode kernel's thirds, |
| 37 | //! `bitnet_kernels.h:80`). |
| 38 | //! |
| 39 | //! RMSNorm is `w * x / sqrt(mean(x^2) + eps)` with the square sum in f64 (HF :53-58 upcasts to |
| 40 | //! f32; f64 is the more exact oracle). RoPE angles are `pos * 500000^(-2j/128)` in f64, position |
| 41 | //! 0 for the first token (BOS when present). |
| 42 | |
| 43 | use rayon::prelude::*; |
| 44 | |
| 45 | use crate::bitnet_omega::{ |
| 46 | check_ternary_upload, code_trit, BitNetConfig, BitNetOmegaWeights, TernMatrix, TernPart, |
| 47 | TernSegment, TernTensor, TernUploader, TRITS_PER_WORD, |
| 48 | }; |
| 49 | use crate::qwen3_dense_omega::{DenseGemv, HostFp8Gemv}; |
| 50 | use crate::qwen3_moe::bf16_to_f32; |
| 51 | use std::sync::Arc; |
| 52 | |
| 53 | // --------------------------------------------------------------------------- |
| 54 | // Host matrices: the packed words unpacked once to one i8 trit per weight. |
| 55 | // --------------------------------------------------------------------------- |
| 56 | |
| 57 | /// A ternary matrix held as `[n][k]` i8 trits (unpacked from [`crate::bitnet_omega::TERN_LAYOUT_ID`] |
| 58 | /// words after [`check_ternary_upload`]), with a token-batched exact int32 product. |
| 59 | #[derive(Debug)] |
| 60 | pub struct I8TernMatrix { |
| 61 | n: usize, |
| 62 | k: usize, |
| 63 | trits: Vec<i8>, |
| 64 | segments: Vec<TernSegment>, |
| 65 | } |
| 66 | |
| 67 | impl I8TernMatrix { |
| 68 | pub fn from_words( |
| 69 | n: usize, |
| 70 | k: usize, |
| 71 | words: &[u32], |
| 72 | segments: &[TernSegment], |
| 73 | ) -> Result<Self, String> { |
| 74 | check_ternary_upload(n, k, words, segments)?; |
| 75 | let mut trits = vec![0i8; n * k]; |
| 76 | trits |
| 77 | .par_chunks_mut(TRITS_PER_WORD) |
| 78 | .zip(words.par_iter()) |
| 79 | .for_each(|(t, &w)| { |
| 80 | for (i, v) in t.iter_mut().enumerate() { |
| 81 | // Validated above: no 0b11 code. |
| 82 | *v = code_trit(w >> (2 * i)).unwrap_or(0); |
| 83 | } |
| 84 | }); |
| 85 | Ok(Self { |
| 86 | n, |
| 87 | k, |
| 88 | trits, |
| 89 | segments: segments.to_vec(), |
| 90 | }) |
| 91 | } |
| 92 | |
| 93 | /// `acc[t][r] = sum_c W[r][c] * x[t][c]` for `t` tokens, exact. |
| 94 | pub fn gemm(&self, x: &[i8], t: usize, acc: &mut [i32]) -> Result<(), String> { |
| 95 | let (n, k) = (self.n, self.k); |
| 96 | if x.len() != t * k || acc.len() != t * n { |
| 97 | return Err(format!( |
| 98 | "ternary gemm [{n}][{k}] for {t} tokens given x {} acc {}", |
| 99 | x.len(), |
| 100 | acc.len() |
| 101 | )); |
| 102 | } |
| 103 | const ROWS: usize = 32; |
| 104 | const TOKENS: usize = 16; |
| 105 | let blocks: Vec<Vec<i32>> = self |
| 106 | .trits |
| 107 | .par_chunks(ROWS * k) |
| 108 | .map(|rows| { |
| 109 | let nr = rows.len() / k; |
| 110 | let mut out = vec![0i32; nr * t]; |
| 111 | for t0 in (0..t).step_by(TOKENS) { |
| 112 | let t1 = (t0 + TOKENS).min(t); |
| 113 | for (r, row) in rows.chunks_exact(k).enumerate() { |
| 114 | for tt in t0..t1 { |
| 115 | out[r * t + tt] = dot_i8(row, &x[tt * k..(tt + 1) * k]); |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | out |
| 120 | }) |
| 121 | .collect(); |
| 122 | for (b, out) in blocks.iter().enumerate() { |
| 123 | let nr = out.len() / t.max(1); |
| 124 | for r in 0..nr { |
| 125 | for tt in 0..t { |
| 126 | acc[tt * n + b * ROWS + r] = out[r * t + tt]; |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | Ok(()) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | impl TernMatrix for I8TernMatrix { |
| 135 | fn n(&self) -> usize { |
| 136 | self.n |
| 137 | } |
| 138 | fn k(&self) -> usize { |
| 139 | self.k |
| 140 | } |
| 141 | fn segments(&self) -> &[TernSegment] { |
| 142 | &self.segments |
| 143 | } |
| 144 | fn gemv_i8(&self, x: &[i8], acc: &mut [i32]) -> Result<(), String> { |
| 145 | self.gemm(x, 1, acc) |
| 146 | } |
| 147 | fn gemm_i8(&self, x: &[i8], t: usize, acc: &mut [i32]) -> Result<(), String> { |
| 148 | self.gemm(x, t, acc) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | #[inline] |
| 153 | fn dot_i8(a: &[i8], b: &[i8]) -> i32 { |
| 154 | // Lanes of 16 so the compiler keeps independent vector sums. |
| 155 | let mut lanes = [0i32; 16]; |
| 156 | let (ca, cb) = (a.chunks_exact(16), b.chunks_exact(16)); |
| 157 | let (ra, rb) = (ca.remainder(), cb.remainder()); |
| 158 | for (x, y) in ca.zip(cb) { |
| 159 | for i in 0..16 { |
| 160 | lanes[i] += x[i] as i32 * y[i] as i32; |
| 161 | } |
| 162 | } |
| 163 | let tail: i32 = ra.iter().zip(rb).map(|(&x, &y)| x as i32 * y as i32).sum(); |
| 164 | lanes.iter().sum::<i32>() + tail |
| 165 | } |
| 166 | |
| 167 | #[inline] |
| 168 | fn dot_f32(a: &[f32], b: &[f32]) -> f32 { |
| 169 | let mut lanes = [0f32; 8]; |
| 170 | let (ca, cb) = (a.chunks_exact(8), b.chunks_exact(8)); |
| 171 | let (ra, rb) = (ca.remainder(), cb.remainder()); |
| 172 | for (x, y) in ca.zip(cb) { |
| 173 | for i in 0..8 { |
| 174 | lanes[i] += x[i] * y[i]; |
| 175 | } |
| 176 | } |
| 177 | let tail: f32 = ra.iter().zip(rb).map(|(&x, &y)| x * y).sum(); |
| 178 | lanes.iter().sum::<f32>() + tail |
| 179 | } |
| 180 | |
| 181 | /// The host uploader for the reference: i8 trit matrices and the host e4m3 table. |
| 182 | #[derive(Debug, Default)] |
| 183 | pub struct HostRefUploader; |
| 184 | |
| 185 | impl TernUploader for HostRefUploader { |
| 186 | fn upload_ternary( |
| 187 | &self, |
| 188 | _layer: usize, |
| 189 | _what: TernTensor, |
| 190 | n: usize, |
| 191 | k: usize, |
| 192 | words: &[u32], |
| 193 | segments: &[TernSegment], |
| 194 | ) -> Result<Arc<dyn TernMatrix>, String> { |
| 195 | Ok(Arc::new(I8TernMatrix::from_words(n, k, words, segments)?)) |
| 196 | } |
| 197 | |
| 198 | fn upload_table_fp8( |
| 199 | &self, |
| 200 | n: usize, |
| 201 | k: usize, |
| 202 | w: &[u8], |
| 203 | scales: &[u16], |
| 204 | ) -> Result<Arc<dyn DenseGemv>, String> { |
| 205 | Ok(Arc::new(HostFp8Gemv::new( |
| 206 | n, |
| 207 | k, |
| 208 | w.to_vec(), |
| 209 | scales.to_vec(), |
| 210 | )?)) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | // --------------------------------------------------------------------------- |
| 215 | // The pieces of one layer. |
| 216 | // --------------------------------------------------------------------------- |
| 217 | |
| 218 | /// Per-token int8 absmax quantisation (spec 2.2): returns `s_a`. |
| 219 | pub fn quant_act(x: &[f32], q: &mut [i8]) -> f32 { |
| 220 | let amax = x.iter().fold(0f32, |m, v| m.max(v.abs())); |
| 221 | let s = 127.0 / amax.max(1e-5); |
| 222 | for (o, &v) in q.iter_mut().zip(x) { |
| 223 | *o = (v * s).round_ties_even().clamp(-128.0, 127.0) as i8; |
| 224 | } |
| 225 | s |
| 226 | } |
| 227 | |
| 228 | /// `w * x / sqrt(mean(x^2) + eps)`, square sum in f64. |
| 229 | pub fn rms_norm(x: &[f32], w: &[f32], eps: f32, out: &mut [f32]) { |
| 230 | let ss: f64 = x.iter().map(|&v| v as f64 * v as f64).sum(); |
| 231 | let inv = 1.0 / (ss / x.len() as f64 + eps as f64).sqrt(); |
| 232 | for ((o, &v), &g) in out.iter_mut().zip(x).zip(w) { |
| 233 | *o = (v as f64 * inv) as f32 * g; |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn rms_norm_rows(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> { |
| 238 | let d = w.len(); |
| 239 | let mut out = vec![0f32; x.len()]; |
| 240 | out.par_chunks_mut(d) |
| 241 | .zip(x.par_chunks(d)) |
| 242 | .for_each(|(o, xr)| rms_norm(xr, w, eps, o)); |
| 243 | out |
| 244 | } |
| 245 | |
| 246 | /// cos and sin of `pos * theta^(-2j/d)`, j < d/2, in f64 then rounded to f32. |
| 247 | pub fn rope_table(pos: usize, d: usize, theta: f64) -> Vec<(f32, f32)> { |
| 248 | (0..d / 2) |
| 249 | .map(|j| { |
| 250 | let a = pos as f64 * theta.powf(-((2 * j) as f64) / d as f64); |
| 251 | let (s, c) = a.sin_cos(); |
| 252 | (c as f32, s as f32) |
| 253 | }) |
| 254 | .collect() |
| 255 | } |
| 256 | |
| 257 | /// Half-split rotation of one head: dim j pairs with j + d/2 (HF `rotate_half`). |
| 258 | pub fn rope_half_split(v: &mut [f32], table: &[(f32, f32)]) { |
| 259 | let half = v.len() / 2; |
| 260 | for (j, &(c, s)) in table.iter().enumerate() { |
| 261 | let (x0, x1) = (v[j], v[j + half]); |
| 262 | v[j] = x0 * c - x1 * s; |
| 263 | v[j + half] = x1 * c + x0 * s; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | /// Deliberately wrong forwards, the negative controls of the T2 perplexity gate. |
| 268 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 269 | pub enum Variant { |
| 270 | /// Spec 1.2. |
| 271 | Reference, |
| 272 | /// Wrong norm order: `attn_sub_norm` after `o_proj` instead of before it. |
| 273 | SubNormAfterO, |
| 274 | /// Both sub-norms skipped. |
| 275 | SkipSubNorms, |
| 276 | /// The q and v segment scales swapped. Swapping q and k alone would be a no-op (scores |
| 277 | /// scale by `s_q * s_k` either way) and a v scale is undone by `attn_sub_norm`, so this |
| 278 | /// scales every attention score by `s_v / s_q`. |
| 279 | SwapQvScales, |
| 280 | /// The q and k segment scales swapped: kept to show that control is vacuous. |
| 281 | SwapQkScales, |
| 282 | } |
| 283 | |
| 284 | impl Variant { |
| 285 | pub fn name(self) -> &'static str { |
| 286 | match self { |
| 287 | Self::Reference => "reference", |
| 288 | Self::SubNormAfterO => "sub-norm-after-o", |
| 289 | Self::SkipSubNorms => "skip-sub-norms", |
| 290 | Self::SwapQvScales => "swap-q-v-scales", |
| 291 | Self::SwapQkScales => "swap-q-k-scales", |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Keys and values of every layer, `[len][kv_dim]` f32, roped keys. |
| 297 | #[derive(Debug, Clone)] |
| 298 | pub struct KvCache { |
| 299 | pub len: usize, |
| 300 | k: Vec<Vec<f32>>, |
| 301 | v: Vec<Vec<f32>>, |
| 302 | } |
| 303 | |
| 304 | impl KvCache { |
| 305 | pub fn new(c: &BitNetConfig) -> Self { |
| 306 | Self { |
| 307 | len: 0, |
| 308 | k: vec![Vec::new(); c.layers], |
| 309 | v: vec![Vec::new(); c.layers], |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// Drops every position from `len` on. |
| 314 | pub fn truncate(&mut self, len: usize, kv_dim: usize) { |
| 315 | for x in self.k.iter_mut().chain(self.v.iter_mut()) { |
| 316 | x.truncate(len * kv_dim); |
| 317 | } |
| 318 | self.len = self.len.min(len); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Causal GQA attention for `t` query rows at positions `pos0 ..` over the cached keys (roped) |
| 323 | /// and values `[pos0 + t][kv_dim]`: query head `h` reads kv head `h / (q_heads / kv_heads)`, |
| 324 | /// scores scaled by `head_dim^-0.5`, softmax over positions `0..=pos0 + i`. Returns `[t][q_dim]`. |
| 325 | pub fn attend(c: &BitNetConfig, q: &[f32], kc: &[f32], vc: &[f32], pos0: usize) -> Vec<f32> { |
| 326 | let (qd, kvd, hd) = (c.q_dim(), c.kv_dim(), c.head_dim); |
| 327 | let group = c.q_heads / c.kv_heads; |
| 328 | let scale = (hd as f32).powf(-0.5); |
| 329 | let t = q.len() / qd; |
| 330 | let mut att = vec![0f32; t * qd]; |
| 331 | att.par_chunks_mut(hd).enumerate().for_each(|(idx, o)| { |
| 332 | let (i, head) = (idx / c.q_heads, idx % c.q_heads); |
| 333 | let kvh = head / group; |
| 334 | let p = pos0 + i; |
| 335 | let qv = &q[i * qd + head * hd..i * qd + (head + 1) * hd]; |
| 336 | let scores: Vec<f32> = (0..=p) |
| 337 | .map(|j| dot_f32(qv, &kc[j * kvd + kvh * hd..j * kvd + (kvh + 1) * hd]) * scale) |
| 338 | .collect(); |
| 339 | let m = scores.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)); |
| 340 | let e: Vec<f32> = scores.iter().map(|&s| (s - m).exp()).collect(); |
| 341 | let sum: f64 = e.iter().map(|&v| v as f64).sum(); |
| 342 | let inv = (1.0 / sum) as f32; |
| 343 | for (j, &ej) in e.iter().enumerate() { |
| 344 | let wgt = ej * inv; |
| 345 | let vv = &vc[j * kvd + kvh * hd..j * kvd + (kvh + 1) * hd]; |
| 346 | for (od, &vd) in o.iter_mut().zip(vv) { |
| 347 | *od += wgt * vd; |
| 348 | } |
| 349 | } |
| 350 | }); |
| 351 | att |
| 352 | } |
| 353 | |
| 354 | /// The reference model over loaded weights. |
| 355 | pub struct HostBitNetForward<'a> { |
| 356 | pub w: &'a BitNetOmegaWeights, |
| 357 | pub variant: Variant, |
| 358 | /// The tied table widened to f32 once, `[vocab][hidden]`. |
| 359 | embed: Vec<f32>, |
| 360 | } |
| 361 | |
| 362 | impl<'a> HostBitNetForward<'a> { |
| 363 | pub fn new(w: &'a BitNetOmegaWeights) -> Self { |
| 364 | let embed = w.embed_bf16.par_iter().map(|&b| bf16_to_f32(b)).collect(); |
| 365 | Self { |
| 366 | w, |
| 367 | variant: Variant::Reference, |
| 368 | embed, |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | fn config(&self) -> &BitNetConfig { |
| 373 | &self.w.config |
| 374 | } |
| 375 | |
| 376 | /// One BitLinear over `t` token rows of `x`: `[t][n]` outputs. |
| 377 | fn bit_linear(&self, m: &dyn TernMatrix, x: &[f32], t: usize) -> Result<Vec<f32>, String> { |
| 378 | let (n, k) = (m.n(), m.k()); |
| 379 | let mut q = vec![0i8; t * k]; |
| 380 | let s_a: Vec<f32> = q |
| 381 | .par_chunks_mut(k) |
| 382 | .zip(x.par_chunks(k)) |
| 383 | .map(|(qr, xr)| quant_act(xr, qr)) |
| 384 | .collect(); |
| 385 | let mut acc = vec![0i32; t * n]; |
| 386 | m.gemm_i8(&q, t, &mut acc)?; |
| 387 | let mut seg: Vec<(TernPart, f32, usize)> = m |
| 388 | .segments() |
| 389 | .iter() |
| 390 | .map(|s| (s.part, bf16_to_f32(s.scale_bf16), s.rows)) |
| 391 | .collect(); |
| 392 | let swap = match self.variant { |
| 393 | Variant::SwapQvScales => Some((TernPart::Q, TernPart::V)), |
| 394 | Variant::SwapQkScales => Some((TernPart::Q, TernPart::K)), |
| 395 | _ => None, |
| 396 | }; |
| 397 | if let Some((a, b)) = swap { |
| 398 | let ia = seg.iter().position(|s| s.0 == a); |
| 399 | let ib = seg.iter().position(|s| s.0 == b); |
| 400 | if let (Some(ia), Some(ib)) = (ia, ib) { |
| 401 | let sa = seg[ia].1; |
| 402 | seg[ia].1 = seg[ib].1; |
| 403 | seg[ib].1 = sa; |
| 404 | } |
| 405 | } |
| 406 | let mut row_scale = Vec::with_capacity(n); |
| 407 | for &(_, s, rows) in &seg { |
| 408 | row_scale.extend(std::iter::repeat_n(s, rows)); |
| 409 | } |
| 410 | let mut y = vec![0f32; t * n]; |
| 411 | y.par_chunks_mut(n) |
| 412 | .zip(acc.par_chunks(n)) |
| 413 | .zip(s_a.par_iter()) |
| 414 | .for_each(|((yr, ar), &s)| { |
| 415 | for ((o, &a), &ws) in yr.iter_mut().zip(ar).zip(&row_scale) { |
| 416 | *o = a as f32 / s * ws; |
| 417 | } |
| 418 | }); |
| 419 | Ok(y) |
| 420 | } |
| 421 | |
| 422 | /// Runs `tokens` (positions `cache.len ..`) through every layer, appending to `cache`. |
| 423 | /// Returns the final-norm hidden rows `[t][hidden]`; `taps` receives the residual stream |
| 424 | /// after each listed layer, `[t][hidden]`. On an error the cache is rolled back to where it |
| 425 | /// was, so it stays usable. |
| 426 | pub fn forward( |
| 427 | &self, |
| 428 | tokens: &[u32], |
| 429 | cache: &mut KvCache, |
| 430 | tap_layers: &[usize], |
| 431 | taps: &mut Vec<(usize, Vec<f32>)>, |
| 432 | ) -> Result<Vec<f32>, String> { |
| 433 | let len = cache.len; |
| 434 | let r = self.forward_inner(tokens, cache, tap_layers, taps); |
| 435 | if r.is_err() { |
| 436 | cache.truncate(len, self.config().kv_dim()); |
| 437 | } |
| 438 | r |
| 439 | } |
| 440 | |
| 441 | fn forward_inner( |
| 442 | &self, |
| 443 | tokens: &[u32], |
| 444 | cache: &mut KvCache, |
| 445 | tap_layers: &[usize], |
| 446 | taps: &mut Vec<(usize, Vec<f32>)>, |
| 447 | ) -> Result<Vec<f32>, String> { |
| 448 | let c = self.config(); |
| 449 | let (h, qd, kvd, hd, eps) = (c.hidden, c.q_dim(), c.kv_dim(), c.head_dim, c.rms_eps); |
| 450 | let t = tokens.len(); |
| 451 | if t == 0 { |
| 452 | return Err("forward of no tokens".into()); |
| 453 | } |
| 454 | let pos0 = cache.len; |
| 455 | if pos0 + t > c.max_position { |
| 456 | return Err(format!( |
| 457 | "positions {pos0}..{} beyond max_position {}", |
| 458 | pos0 + t, |
| 459 | c.max_position |
| 460 | )); |
| 461 | } |
| 462 | let mut x = Vec::with_capacity(t * h); |
| 463 | for &tok in tokens { |
| 464 | x.extend(self.w.embed_row(tok)?); |
| 465 | } |
| 466 | let tables: Vec<Vec<(f32, f32)>> = (0..t) |
| 467 | .map(|i| rope_table(pos0 + i, hd, f64::from(c.rope_theta))) |
| 468 | .collect(); |
| 469 | |
| 470 | for (li, layer) in self.w.layers.iter().enumerate() { |
| 471 | // Attention. |
| 472 | let a = rms_norm_rows(&x, &layer.input_norm, eps); |
| 473 | let qkv = self.bit_linear(layer.qkv.as_ref(), &a, t)?; |
| 474 | let n_qkv = qd + 2 * kvd; |
| 475 | let mut q = vec![0f32; t * qd]; |
| 476 | for i in 0..t { |
| 477 | let row = &qkv[i * n_qkv..(i + 1) * n_qkv]; |
| 478 | q[i * qd..(i + 1) * qd].copy_from_slice(&row[..qd]); |
| 479 | for head in q[i * qd..(i + 1) * qd].chunks_exact_mut(hd) { |
| 480 | rope_half_split(head, &tables[i]); |
| 481 | } |
| 482 | let mut k = row[qd..qd + kvd].to_vec(); |
| 483 | for head in k.chunks_exact_mut(hd) { |
| 484 | rope_half_split(head, &tables[i]); |
| 485 | } |
| 486 | cache.k[li].extend_from_slice(&k); |
| 487 | cache.v[li].extend_from_slice(&row[qd + kvd..]); |
| 488 | } |
| 489 | let att = attend(c, &q, &cache.k[li], &cache.v[li], pos0); |
| 490 | let o = match self.variant { |
| 491 | Variant::SubNormAfterO => { |
| 492 | let y = self.bit_linear(layer.o.as_ref(), &att, t)?; |
| 493 | rms_norm_rows(&y, &layer.attn_sub_norm, eps) |
| 494 | } |
| 495 | Variant::SkipSubNorms => self.bit_linear(layer.o.as_ref(), &att, t)?, |
| 496 | _ => { |
| 497 | let n = rms_norm_rows(&att, &layer.attn_sub_norm, eps); |
| 498 | self.bit_linear(layer.o.as_ref(), &n, t)? |
| 499 | } |
| 500 | }; |
| 501 | for (xv, ov) in x.iter_mut().zip(&o) { |
| 502 | *xv += ov; |
| 503 | } |
| 504 | |
| 505 | // Feed-forward. |
| 506 | let f = rms_norm_rows(&x, &layer.post_norm, eps); |
| 507 | let gu = self.bit_linear(layer.gate_up.as_ref(), &f, t)?; |
| 508 | let im = c.intermediate; |
| 509 | let mut inner = vec![0f32; t * im]; |
| 510 | for i in 0..t { |
| 511 | let row = &gu[i * 2 * im..(i + 1) * 2 * im]; |
| 512 | let (g, u) = row.split_at(im); |
| 513 | for ((o, &gv), &uv) in inner[i * im..(i + 1) * im].iter_mut().zip(g).zip(u) { |
| 514 | let r = gv.max(0.0); |
| 515 | *o = r * r * uv; |
| 516 | } |
| 517 | } |
| 518 | let inner = match self.variant { |
| 519 | Variant::SkipSubNorms => inner, |
| 520 | _ => rms_norm_rows(&inner, &layer.ffn_sub_norm, eps), |
| 521 | }; |
| 522 | let d = self.bit_linear(layer.down.as_ref(), &inner, t)?; |
| 523 | for (xv, dv) in x.iter_mut().zip(&d) { |
| 524 | *xv += dv; |
| 525 | } |
| 526 | if tap_layers.contains(&li) { |
| 527 | taps.push((li, x.clone())); |
| 528 | } |
| 529 | } |
| 530 | cache.len += t; |
| 531 | Ok(rms_norm_rows(&x, &self.w.final_norm, eps)) |
| 532 | } |
| 533 | |
| 534 | /// Logits `[t][vocab]` of final-norm rows, with the tied 16-bit table (exact in f32). |
| 535 | pub fn logits(&self, normed: &[f32]) -> Vec<f32> { |
| 536 | let c = self.config(); |
| 537 | let (h, vocab) = (c.hidden, c.vocab); |
| 538 | let t = normed.len() / h; |
| 539 | if t == 0 { |
| 540 | return Vec::new(); |
| 541 | } |
| 542 | const ROWS: usize = 64; |
| 543 | let blocks: Vec<Vec<f32>> = self |
| 544 | .embed |
| 545 | .par_chunks(ROWS * h) |
| 546 | .map(|rows| { |
| 547 | let nr = rows.len() / h; |
| 548 | let mut out = vec![0f32; nr * t]; |
| 549 | for (r, row) in rows.chunks_exact(h).enumerate() { |
| 550 | for i in 0..t { |
| 551 | out[r * t + i] = dot_f32(row, &normed[i * h..(i + 1) * h]); |
| 552 | } |
| 553 | } |
| 554 | out |
| 555 | }) |
| 556 | .collect(); |
| 557 | let mut logits = vec![0f32; t * vocab]; |
| 558 | for (b, out) in blocks.iter().enumerate() { |
| 559 | for r in 0..out.len() / t { |
| 560 | for i in 0..t { |
| 561 | logits[i * vocab + b * ROWS + r] = out[r * t + i]; |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | logits |
| 566 | } |
| 567 | |
| 568 | /// Teacher-forced negative log-likelihoods (natural log, f64): row `i` of `normed` |
| 569 | /// predicts `targets[i]`. Done in chunks so the logits never exceed 64 rows. |
| 570 | pub fn nll(&self, normed: &[f32], targets: &[u32]) -> Result<Vec<f64>, String> { |
| 571 | let (h, vocab) = (self.config().hidden, self.config().vocab); |
| 572 | if normed.len() != targets.len() * h { |
| 573 | return Err(format!( |
| 574 | "{} hidden rows for {} targets", |
| 575 | normed.len() / h, |
| 576 | targets.len() |
| 577 | )); |
| 578 | } |
| 579 | let mut out = Vec::with_capacity(targets.len()); |
| 580 | for (rows, tg) in normed.chunks(64 * h).zip(targets.chunks(64)) { |
| 581 | let lg = self.logits(rows); |
| 582 | for (l, &tgt) in lg.chunks_exact(vocab).zip(tg) { |
| 583 | if tgt as usize >= vocab { |
| 584 | return Err(format!("target {tgt} outside the vocabulary")); |
| 585 | } |
| 586 | out.push(log_sum_exp(l) - l[tgt as usize] as f64); |
| 587 | } |
| 588 | } |
| 589 | Ok(out) |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | /// `ln(sum exp(l))` in f64. |
| 594 | pub fn log_sum_exp(l: &[f32]) -> f64 { |
| 595 | let m = l.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64; |
| 596 | m + l.iter().map(|&v| (v as f64 - m).exp()).sum::<f64>().ln() |
| 597 | } |
| 598 | |
| 599 | /// The highest logit, lowest id on a tie. |
| 600 | pub fn argmax(l: &[f32]) -> u32 { |
| 601 | let mut best = 0; |
| 602 | for (i, &v) in l.iter().enumerate() { |
| 603 | if v > l[best] { |
| 604 | best = i; |
| 605 | } |
| 606 | } |
| 607 | best as u32 |
| 608 | } |
| 609 | |
| 610 | #[cfg(test)] |
| 611 | mod tests; |