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 / tensor.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 | //! Pure native Rust tensor operations for transformer forward execution. |
| 17 | //! Provides cache-friendly vector and matrix math, RMSNorm, RoPE, and SwiGLU activations. |
| 18 | |
| 19 | use aien_abi_core::RopeParams; |
| 20 | use rayon::prelude::*; |
| 21 | |
| 22 | /// Vector-matrix multiplication for PyTorch row-major weights: out = x * W^T |
| 23 | /// where x is [in_dim], W is row-major [out_dim, in_dim], and out is [out_dim]. |
| 24 | /// Each out[j] is the inner dot product of vector x with the j-th row of W. |
| 25 | #[inline] |
| 26 | pub fn matmul_vec(x: &[f32], w: &[f32], out: &mut [f32], in_dim: usize, out_dim: usize) { |
| 27 | debug_assert_eq!(x.len(), in_dim); |
| 28 | debug_assert_eq!(w.len(), in_dim * out_dim); |
| 29 | debug_assert_eq!(out.len(), out_dim); |
| 30 | |
| 31 | for j in 0..out_dim { |
| 32 | let w_row = &w[j * in_dim..(j + 1) * in_dim]; |
| 33 | let mut sum0 = 0.0f64; |
| 34 | let mut sum1 = 0.0f64; |
| 35 | let mut sum2 = 0.0f64; |
| 36 | let mut sum3 = 0.0f64; |
| 37 | let mut sum4 = 0.0f64; |
| 38 | let mut sum5 = 0.0f64; |
| 39 | let mut sum6 = 0.0f64; |
| 40 | let mut sum7 = 0.0f64; |
| 41 | |
| 42 | let mut i = 0; |
| 43 | while i + 8 <= in_dim { |
| 44 | sum0 += (x[i] as f64) * (w_row[i] as f64); |
| 45 | sum1 += (x[i + 1] as f64) * (w_row[i + 1] as f64); |
| 46 | sum2 += (x[i + 2] as f64) * (w_row[i + 2] as f64); |
| 47 | sum3 += (x[i + 3] as f64) * (w_row[i + 3] as f64); |
| 48 | sum4 += (x[i + 4] as f64) * (w_row[i + 4] as f64); |
| 49 | sum5 += (x[i + 5] as f64) * (w_row[i + 5] as f64); |
| 50 | sum6 += (x[i + 6] as f64) * (w_row[i + 6] as f64); |
| 51 | sum7 += (x[i + 7] as f64) * (w_row[i + 7] as f64); |
| 52 | i += 8; |
| 53 | } |
| 54 | let mut sum = (sum0 + sum1) + (sum2 + sum3) + (sum4 + sum5) + (sum6 + sum7); |
| 55 | while i < in_dim { |
| 56 | sum += (x[i] as f64) * (w_row[i] as f64); |
| 57 | i += 1; |
| 58 | } |
| 59 | out[j] = sum as f32; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Batched matrix multiplication for row-major weights: out = X * W^T |
| 64 | /// where X is [batch_size, in_dim], W is row-major [out_dim, in_dim], and out is [batch_size, out_dim]. |
| 65 | /// Parallelizes batch rows across available CPU threads with Rayon. |
| 66 | pub fn matmul_batch( |
| 67 | x: &[f32], |
| 68 | w: &[f32], |
| 69 | out: &mut [f32], |
| 70 | batch_size: usize, |
| 71 | in_dim: usize, |
| 72 | out_dim: usize, |
| 73 | ) { |
| 74 | debug_assert_eq!(x.len(), batch_size * in_dim); |
| 75 | debug_assert_eq!(w.len(), in_dim * out_dim); |
| 76 | debug_assert_eq!(out.len(), batch_size * out_dim); |
| 77 | |
| 78 | if batch_size == 1 { |
| 79 | matmul_vec(x, w, out, in_dim, out_dim); |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | out.par_chunks_exact_mut(out_dim) |
| 84 | .enumerate() |
| 85 | .for_each(|(b, out_b)| { |
| 86 | let x_b = &x[b * in_dim..(b + 1) * in_dim]; |
| 87 | matmul_vec(x_b, w, out_b, in_dim, out_dim); |
| 88 | }); |
| 89 | } |
| 90 | |
| 91 | /// In-place Root Mean Square Normalization: |
| 92 | /// out[i] = x[i] * weight[i] / sqrt(mean(x^2) + eps) |
| 93 | #[inline] |
| 94 | pub fn rmsnorm(x: &[f32], weight: &[f32], eps: f32, out: &mut [f32]) { |
| 95 | debug_assert_eq!(x.len(), weight.len()); |
| 96 | debug_assert_eq!(x.len(), out.len()); |
| 97 | |
| 98 | let dim = x.len(); |
| 99 | let mut sum_sq = 0.0f64; |
| 100 | for &v in x.iter() { |
| 101 | let vf = v as f64; |
| 102 | sum_sq += vf * vf; |
| 103 | } |
| 104 | let mean_sq = sum_sq / (dim as f64); |
| 105 | let scale = (1.0 / (mean_sq + (eps as f64)).sqrt()) as f32; |
| 106 | |
| 107 | for i in 0..dim { |
| 108 | out[i] = x[i] * scale * weight[i]; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Qwen3 per-head RMSNorm in place: `x` is `[heads][head_dim]`, every head is normalised over |
| 113 | /// its own `head_dim` values with the shared `weight` (`[head_dim]`), same maths as [`rmsnorm`]. |
| 114 | pub fn rmsnorm_heads_in_place(x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { |
| 115 | assert!(head_dim > 0 && x.len().is_multiple_of(head_dim) && weight.len() == head_dim); |
| 116 | let mut scratch = vec![0.0f32; head_dim]; |
| 117 | for head in x.chunks_exact_mut(head_dim) { |
| 118 | rmsnorm(head, weight, eps, &mut scratch); |
| 119 | head.copy_from_slice(&scratch); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | /// Applies Rotary Positional Embeddings (RoPE) to query and key head slices. |
| 124 | /// Follows canonical Hugging Face LLaMA rotate_half pairing coordinate i with coordinate i + half_dim: |
| 125 | /// out[i] = q[i] * cos - q[i + half_dim] * sin |
| 126 | /// out[i + half_dim] = q[i] * sin + q[i + half_dim] * cos |
| 127 | #[inline] |
| 128 | pub fn apply_rope( |
| 129 | q: &mut [f32], |
| 130 | k: &mut [f32], |
| 131 | pos: usize, |
| 132 | num_heads: usize, |
| 133 | num_kv_heads: usize, |
| 134 | head_dim: usize, |
| 135 | theta: f32, |
| 136 | ) { |
| 137 | apply_rope_params( |
| 138 | q, |
| 139 | k, |
| 140 | pos, |
| 141 | num_heads, |
| 142 | num_kv_heads, |
| 143 | head_dim, |
| 144 | &RopeParams::plain(theta), |
| 145 | ); |
| 146 | } |
| 147 | |
| 148 | /// The cos and sin of every rotary pair at `pos`: f64 frequency and angle, cast to f32. |
| 149 | /// Both the reference rope and the Omega GPU rope table use this. |
| 150 | pub fn rope_cos_sin(rope: &RopeParams, head_dim: usize, pos: usize) -> (Vec<f32>, Vec<f32>) { |
| 151 | let half_dim = head_dim / 2; |
| 152 | let mut cos = Vec::with_capacity(half_dim); |
| 153 | let mut sin = Vec::with_capacity(half_dim); |
| 154 | for i in 0..half_dim { |
| 155 | let rot = (pos as f64) * rope.inv_freq(i, head_dim); |
| 156 | sin.push(rot.sin() as f32); |
| 157 | cos.push(rot.cos() as f32); |
| 158 | } |
| 159 | (cos, sin) |
| 160 | } |
| 161 | |
| 162 | /// [`apply_rope`] with explicit rope parameters (base theta and optional llama3 scaling). |
| 163 | #[inline] |
| 164 | pub fn apply_rope_params( |
| 165 | q: &mut [f32], |
| 166 | k: &mut [f32], |
| 167 | pos: usize, |
| 168 | num_heads: usize, |
| 169 | num_kv_heads: usize, |
| 170 | head_dim: usize, |
| 171 | rope: &RopeParams, |
| 172 | ) { |
| 173 | let half_dim = head_dim / 2; |
| 174 | let (cos, sin) = rope_cos_sin(rope, head_dim, pos); |
| 175 | for (v, heads) in [(q, num_heads), (k, num_kv_heads)] { |
| 176 | for h in 0..heads { |
| 177 | let head_offset = h * head_dim; |
| 178 | for i in 0..half_dim { |
| 179 | let idx0 = head_offset + i; |
| 180 | let idx1 = head_offset + i + half_dim; |
| 181 | let v0 = v[idx0]; |
| 182 | let v1 = v[idx1]; |
| 183 | v[idx0] = v0 * cos[i] - v1 * sin[i]; |
| 184 | v[idx1] = v0 * sin[i] + v1 * cos[i]; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Scaled Dot-Product Grouped-Query Attention (GQA) for a single query token position: |
| 191 | /// Scores = Softmax((Q * K^T) / sqrt(d_k)) |
| 192 | /// Out = Scores * V |
| 193 | /// |
| 194 | /// f64 scores, one softmax over the whole context. [`HostKv`] and the independent f32 |
| 195 | /// reference use this. Oracle A's host pool uses [`kernel_online_attention`] instead. |
| 196 | pub fn scaled_dot_product_attention_single( |
| 197 | q: &[f32], |
| 198 | cached_k: &[Vec<f32>], |
| 199 | cached_v: &[Vec<f32>], |
| 200 | num_heads: usize, |
| 201 | num_kv_heads: usize, |
| 202 | head_dim: usize, |
| 203 | out: &mut [f32], |
| 204 | ) { |
| 205 | debug_assert_eq!(q.len(), num_heads * head_dim); |
| 206 | debug_assert_eq!(out.len(), num_heads * head_dim); |
| 207 | debug_assert_eq!(cached_k.len(), cached_v.len()); |
| 208 | |
| 209 | let seq_len = cached_k.len(); |
| 210 | if seq_len == 0 { |
| 211 | out.fill(0.0); |
| 212 | return; |
| 213 | } |
| 214 | |
| 215 | let gqa_ratio = num_heads / num_kv_heads; |
| 216 | let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); |
| 217 | |
| 218 | let mut scores = vec![0.0f64; seq_len]; |
| 219 | |
| 220 | for h in 0..num_heads { |
| 221 | let kv_head = h / gqa_ratio; |
| 222 | let q_head = &q[h * head_dim..(h + 1) * head_dim]; |
| 223 | |
| 224 | // 1. Compute attention score for each cached token in f64 |
| 225 | for t in 0..seq_len { |
| 226 | let k_t = &cached_k[t][kv_head * head_dim..(kv_head + 1) * head_dim]; |
| 227 | let mut dot = 0.0f64; |
| 228 | for d in 0..head_dim { |
| 229 | dot += (q_head[d] as f64) * (k_t[d] as f64); |
| 230 | } |
| 231 | scores[t] = dot * inv_sqrt_d; |
| 232 | } |
| 233 | |
| 234 | // 2. Softmax over sequence length |
| 235 | let max_score = scores.iter().cloned().fold(f64::NEG_INFINITY, f64::max); |
| 236 | let mut sum_exp = 0.0f64; |
| 237 | for s in scores.iter_mut() { |
| 238 | *s = (*s - max_score).exp(); |
| 239 | sum_exp += *s; |
| 240 | } |
| 241 | let inv_sum = 1.0 / sum_exp.max(1e-12); |
| 242 | for s in scores.iter_mut() { |
| 243 | *s *= inv_sum; |
| 244 | } |
| 245 | |
| 246 | // 3. Weighted sum of values in f64 |
| 247 | let out_head = &mut out[h * head_dim..(h + 1) * head_dim]; |
| 248 | for d in 0..head_dim { |
| 249 | let mut sum = 0.0f64; |
| 250 | for t in 0..seq_len { |
| 251 | sum += scores[t] * (cached_v[t][kv_head * head_dim + d] as f64); |
| 252 | } |
| 253 | out_head[d] = sum as f32; |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// SHFL.DOWN by 16, 8, 4, 2, 1. Same tree as the omega GEMV and the paged-attention chunk reduce. |
| 259 | fn warp_reduce(mut lane: [f32; 32], max: bool) -> f32 { |
| 260 | for d in [16usize, 8, 4, 2, 1] { |
| 261 | for i in 0..32 - d { |
| 262 | lane[i] = if max { |
| 263 | lane[i].max(lane[i + d]) |
| 264 | } else { |
| 265 | lane[i] + lane[i + d] |
| 266 | }; |
| 267 | } |
| 268 | } |
| 269 | lane[0] |
| 270 | } |
| 271 | |
| 272 | /// Oracle A's host attention, matched to `omega_gpu_paged_attention_bf16` (omega pin `a647b6a9`, |
| 273 | /// `omega_gpu_attention_api.c`): f32 FFMA scores in head order, `s = dot * log2(e) / sqrt(d)`, |
| 274 | /// online softmax over chunks of `head_dim` tokens. Each chunk takes a warp SHFL max and sum |
| 275 | /// (then the warps fold left to right), `alpha = exp2(m - m_new)`, `p = exp2(s - m_new)`, |
| 276 | /// `l = fma(l, alpha, chunk_sum)`, and `acc = fma(p, v, acc * alpha)` in token order. |
| 277 | /// `exp2` and the final `1/l` are IEEE f32. The chip's MUFU.EX2 and MUFU.RCP are the same |
| 278 | /// operations at f32 width with a hardware approximation this CPU reference does not reproduce. |
| 279 | /// `head_dim` is 64 or 128, the two widths that kernel accepts. |
| 280 | pub fn kernel_online_attention( |
| 281 | q: &[f32], |
| 282 | cached_k: &[Vec<f32>], |
| 283 | cached_v: &[Vec<f32>], |
| 284 | num_heads: usize, |
| 285 | num_kv_heads: usize, |
| 286 | head_dim: usize, |
| 287 | out: &mut [f32], |
| 288 | ) { |
| 289 | let seq_len = cached_k.len(); |
| 290 | if seq_len == 0 || head_dim == 0 { |
| 291 | out.fill(0.0); |
| 292 | return; |
| 293 | } |
| 294 | debug_assert!(head_dim == 64 || head_dim == 128); |
| 295 | debug_assert_eq!(q.len(), num_heads * head_dim); |
| 296 | debug_assert_eq!(out.len(), num_heads * head_dim); |
| 297 | let scale = std::f32::consts::LOG2_E / (head_dim as f32).sqrt(); |
| 298 | let gqa_ratio = num_heads / num_kv_heads; |
| 299 | let nwarps = head_dim / 32; |
| 300 | for h in 0..num_heads { |
| 301 | let kv_head = h / gqa_ratio; |
| 302 | let q_head = &q[h * head_dim..(h + 1) * head_dim]; |
| 303 | let mut acc = vec![0.0f32; head_dim]; |
| 304 | let mut m = f32::NEG_INFINITY; |
| 305 | let mut l = 0.0f32; |
| 306 | let mut base = 0; |
| 307 | while base < seq_len { |
| 308 | let n = (seq_len - base).min(head_dim); |
| 309 | let mut scores = vec![f32::NEG_INFINITY; head_dim]; |
| 310 | for t in 0..n { |
| 311 | let k_t = &cached_k[base + t][kv_head * head_dim..(kv_head + 1) * head_dim]; |
| 312 | let mut dot = 0.0f32; |
| 313 | for d in 0..head_dim { |
| 314 | dot = k_t[d].mul_add(q_head[d], dot); |
| 315 | } |
| 316 | scores[t] = dot * scale; |
| 317 | } |
| 318 | let mut warp_max = [f32::NEG_INFINITY; 4]; |
| 319 | for w in 0..nwarps { |
| 320 | let mut lanes = [f32::NEG_INFINITY; 32]; |
| 321 | for lane in 0..32 { |
| 322 | lanes[lane] = scores[w * 32 + lane]; |
| 323 | } |
| 324 | warp_max[w] = warp_reduce(lanes, true); |
| 325 | } |
| 326 | let mut chunk_max = warp_max[0]; |
| 327 | for w in 1..nwarps { |
| 328 | chunk_max = chunk_max.max(warp_max[w]); |
| 329 | } |
| 330 | let m_new = m.max(chunk_max); |
| 331 | let alpha = (m - m_new).exp2(); |
| 332 | let mut p = vec![0.0f32; head_dim]; |
| 333 | for t in 0..head_dim { |
| 334 | p[t] = (scores[t] - m_new).exp2(); |
| 335 | } |
| 336 | let mut warp_sum = [0.0f32; 4]; |
| 337 | for w in 0..nwarps { |
| 338 | let mut lanes = [0.0f32; 32]; |
| 339 | for lane in 0..32 { |
| 340 | lanes[lane] = p[w * 32 + lane]; |
| 341 | } |
| 342 | warp_sum[w] = warp_reduce(lanes, false); |
| 343 | } |
| 344 | let mut chunk_sum = warp_sum[0]; |
| 345 | for w in 1..nwarps { |
| 346 | chunk_sum += warp_sum[w]; |
| 347 | } |
| 348 | l = l.mul_add(alpha, chunk_sum); |
| 349 | for d in 0..head_dim { |
| 350 | acc[d] *= alpha; |
| 351 | } |
| 352 | for t in 0..n { |
| 353 | let v_t = &cached_v[base + t][kv_head * head_dim..(kv_head + 1) * head_dim]; |
| 354 | let pt = p[t]; |
| 355 | for d in 0..head_dim { |
| 356 | acc[d] = pt.mul_add(v_t[d], acc[d]); |
| 357 | } |
| 358 | } |
| 359 | m = m_new; |
| 360 | base += head_dim; |
| 361 | } |
| 362 | let inv = 1.0 / l; |
| 363 | let out_head = &mut out[h * head_dim..(h + 1) * head_dim]; |
| 364 | for d in 0..head_dim { |
| 365 | out_head[d] = acc[d] * inv; |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// SwiGLU Feed-Forward Network: |
| 371 | /// out = (silu(x * W_gate) * (x * W_up)) * W_down |
| 372 | pub fn swiglu( |
| 373 | x: &[f32], |
| 374 | gate_w: &[f32], |
| 375 | up_w: &[f32], |
| 376 | down_w: &[f32], |
| 377 | hidden_dim: usize, |
| 378 | intermediate_dim: usize, |
| 379 | out: &mut [f32], |
| 380 | ) { |
| 381 | let mut gate = vec![0.0f32; intermediate_dim]; |
| 382 | let mut up = vec![0.0f32; intermediate_dim]; |
| 383 | let mut activated = vec![0.0f32; intermediate_dim]; |
| 384 | |
| 385 | matmul_vec(x, gate_w, &mut gate, hidden_dim, intermediate_dim); |
| 386 | matmul_vec(x, up_w, &mut up, hidden_dim, intermediate_dim); |
| 387 | |
| 388 | // silu(x) = x / (1 + exp(-x)) with f64 precision |
| 389 | for i in 0..intermediate_dim { |
| 390 | let g = gate[i] as f64; |
| 391 | let silu = g / (1.0 + (-g).exp()); |
| 392 | activated[i] = (silu * (up[i] as f64)) as f32; |
| 393 | } |
| 394 | |
| 395 | matmul_vec(&activated, down_w, out, intermediate_dim, hidden_dim); |
| 396 | } |
| 397 | |
| 398 | /// Softmax activation over logits vector in-place. |
| 399 | pub fn softmax_inplace(logits: &mut [f32]) { |
| 400 | let max_val = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max); |
| 401 | let mut sum_exp = 0.0f32; |
| 402 | for v in logits.iter_mut() { |
| 403 | *v = (*v - max_val).exp(); |
| 404 | sum_exp += *v; |
| 405 | } |
| 406 | let inv_sum = 1.0 / sum_exp.max(1e-12); |
| 407 | for v in logits.iter_mut() { |
| 408 | *v *= inv_sum; |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// Greedy argmax token selection from logits vector. |
| 413 | /// Returns (token_id, logprob). |
| 414 | pub fn sample_argmax(logits: &[f32]) -> (u32, f32) { |
| 415 | assert!(!logits.is_empty(), "Logits cannot be empty"); |
| 416 | |
| 417 | let mut best_idx = 0; |
| 418 | let mut best_val = logits[0]; |
| 419 | |
| 420 | for (idx, &val) in logits.iter().enumerate().skip(1) { |
| 421 | if val > best_val { |
| 422 | best_val = val; |
| 423 | best_idx = idx; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | // Compute logprob = log(softmax(best_val)) |
| 428 | let max_val = best_val; |
| 429 | let sum_exp: f32 = logits.iter().map(|&v| (v - max_val).exp()).sum(); |
| 430 | let logprob = best_val - max_val - sum_exp.ln(); |
| 431 | |
| 432 | (best_idx as u32, logprob) |
| 433 | } |
| 434 | |
| 435 | /// Temperature-scaled sampling with pseudo-random choice. |
| 436 | pub fn sample_temperature(logits: &[f32], temperature: f32, seed: u64) -> (u32, f32) { |
| 437 | if temperature <= 0.001 { |
| 438 | return sample_argmax(logits); |
| 439 | } |
| 440 | |
| 441 | let mut scaled: Vec<f32> = logits.iter().map(|&v| v / temperature).collect(); |
| 442 | softmax_inplace(&mut scaled); |
| 443 | |
| 444 | // Deterministic pseudo-random number generator for reproducible sampling |
| 445 | let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1); |
| 446 | state = state.wrapping_mul(6364136223846793005).wrapping_add(1); |
| 447 | let r = ((state >> 33) as f32) / ((1u64 << 31) as f32); |
| 448 | |
| 449 | let mut cumulative = 0.0f32; |
| 450 | for (idx, &prob) in scaled.iter().enumerate() { |
| 451 | cumulative += prob; |
| 452 | if r <= cumulative { |
| 453 | return (idx as u32, prob.max(1e-12).ln()); |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | let last_idx = logits.len().saturating_sub(1); |
| 458 | (last_idx as u32, scaled[last_idx].max(1e-12).ln()) |
| 459 | } |
| 460 | |
| 461 | #[cfg(test)] |
| 462 | mod tests { |
| 463 | use super::*; |
| 464 | |
| 465 | #[test] |
| 466 | fn test_rmsnorm_invariance() { |
| 467 | let x = vec![1.0, 2.0, 3.0, 4.0]; |
| 468 | let weight = vec![1.0, 1.0, 1.0, 1.0]; |
| 469 | let mut out = vec![0.0; 4]; |
| 470 | |
| 471 | rmsnorm(&x, &weight, 1e-5, &mut out); |
| 472 | |
| 473 | // RMS of output with all unit weights must equal sqrt(dim) * sqrt(1/dim) = 1.0 |
| 474 | let sum_sq: f32 = out.iter().map(|v| v * v).sum(); |
| 475 | let rms = (sum_sq / 4.0).sqrt(); |
| 476 | assert!((rms - 1.0).abs() < 1e-4); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn test_rope_norm_preservation() { |
| 481 | let mut q = vec![1.0, 0.0, 0.0, 1.0]; |
| 482 | let mut k = vec![0.5, 0.5, 0.5, 0.5]; |
| 483 | |
| 484 | let orig_q_norm: f32 = q.iter().map(|v| v * v).sum(); |
| 485 | apply_rope(&mut q, &mut k, 5, 1, 1, 4, 10000.0); |
| 486 | let new_q_norm: f32 = q.iter().map(|v| v * v).sum(); |
| 487 | |
| 488 | assert!((orig_q_norm - new_q_norm).abs() < 1e-5); |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn test_matmul_exact() { |
| 493 | let x = vec![2.0, 3.0]; |
| 494 | // 3x2 row-major matrix [out_dim = 3, in_dim = 2]: |
| 495 | // Row 0: [1.0, 4.0] -> 2*1 + 3*4 = 14 |
| 496 | // Row 1: [2.0, 5.0] -> 2*2 + 3*5 = 19 |
| 497 | // Row 2: [3.0, 6.0] -> 2*3 + 3*6 = 24 |
| 498 | let w = vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]; |
| 499 | let mut out = vec![0.0; 3]; |
| 500 | |
| 501 | matmul_vec(&x, &w, &mut out, 2, 3); |
| 502 | assert_eq!(out, vec![14.0, 19.0, 24.0]); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn test_rope_rotate_half() { |
| 507 | // Coordinate i pairs with i + half_dim |
| 508 | let mut q = vec![1.0, 2.0, 3.0, 4.0]; |
| 509 | let mut k = vec![1.0, 2.0, 3.0, 4.0]; |
| 510 | |
| 511 | // pos = 0 means angle = 0, so cos = 1, sin = 0 -> identity |
| 512 | apply_rope(&mut q, &mut k, 0, 1, 1, 4, 10000.0); |
| 513 | assert_eq!(q, vec![1.0, 2.0, 3.0, 4.0]); |
| 514 | assert_eq!(k, vec![1.0, 2.0, 3.0, 4.0]); |
| 515 | |
| 516 | // Verify norm preservation across non-zero position |
| 517 | let mut q2 = vec![1.0, 2.0, 3.0, 4.0]; |
| 518 | let mut k2 = vec![1.0, 2.0, 3.0, 4.0]; |
| 519 | let norm_before: f32 = q2.iter().map(|v| v * v).sum(); |
| 520 | apply_rope(&mut q2, &mut k2, 7, 1, 1, 4, 10000.0); |
| 521 | let norm_after: f32 = q2.iter().map(|v| v * v).sum(); |
| 522 | assert!((norm_before - norm_after).abs() < 1e-5); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn test_swiglu_activation() { |
| 527 | let x = vec![1.0, 1.0]; |
| 528 | let gate_w = vec![1.0, 1.0]; // 2x1 |
| 529 | let up_w = vec![2.0, 2.0]; // 2x1 |
| 530 | let down_w = vec![1.0, 1.0]; // 1x2 |
| 531 | |
| 532 | let mut out = vec![0.0; 2]; |
| 533 | swiglu(&x, &gate_w, &up_w, &down_w, 2, 1, &mut out); |
| 534 | |
| 535 | // gate = 2.0, silu(2.0) = 2.0 / (1 + exp(-2.0)) = 2.0 / 1.135335 = 1.761594 |
| 536 | // up = 4.0 |
| 537 | // activated = 1.761594 * 4.0 = 7.046376 |
| 538 | // out = [7.046376, 7.046376] |
| 539 | assert!((out[0] - 7.046376).abs() < 1e-4); |
| 540 | assert!((out[1] - 7.046376).abs() < 1e-4); |
| 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn test_sample_argmax() { |
| 545 | let logits = vec![-2.0, 0.5, 4.2, 1.1]; |
| 546 | let (tok, logprob) = sample_argmax(&logits); |
| 547 | assert_eq!(tok, 2); |
| 548 | assert!(logprob < 0.0); |
| 549 | } |
| 550 | } |