Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-infer/src/dotprod.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-infer / src / dotprod.rs` 792 lines ยท 28340 bytes Raw Blame History 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 //! Quantized dot products on int8 activations with Armv8.2 dot product 17 //! (SDOT), for Cortex-A76 class cores (Raspberry Pi 5) and anything newer. 18 //! 19 //! Method (the one llama.cpp uses for K-quants, `ggml_vec_dot_q4_K_q8_K` and 20 //! `ggml_vec_dot_q6_K_q8_K`, ggml-cpu/arch/arm/quants.c at `4a89937`: Q4_K body 21 //! lines 2789-2840, Q6_K body lines 3492-3560; `vdotq_s32` is 22 //! `ggml_vdotq_s32`, ggml-cpu-impl.h:319): the activation vector is quantized 23 //! once per 256-wide block to int8 ("Q8_K": scale `d = max/-127`, rounding to 24 //! nearest even, plus 16 group sums), the 4-bit/6-bit weights are unpacked to 25 //! bytes with and/shift/or, `sdot` multiplies 16 byte pairs into 4 i32 lanes, 26 //! and the per-sub-block scales are applied in integer arithmetic. Only the 27 //! block scale and min scale are floats. 28 //! 29 //! Selection is a typed capability: a [`DotProd`] token exists only when the 30 //! caller said the CPU has dotprod (the kernel passes the decode of 31 //! `ID_AA64ISAR0_EL1.DP`, never assumed here). Every SDOT function checks 32 //! nothing itself; it is only reachable with a token. Without the token the 33 //! scalar f32 path in `quant.rs` runs, unchanged. On non-aarch64 targets no 34 //! token can be made and the portable integer reference below is the only 35 //! implementation (it is also what the tests compare the SDOT code with). 36 //! 37 //! No libm, no allocation in the dot path; `Q8Act` is sized once. 38 39 use alloc::vec; 40 use alloc::vec::Vec; 41 use core::sync::atomic::{AtomicBool, Ordering}; 42 43 use crate::gguf::GgmlType; 44 use crate::half::f16_to_f32; 45 use crate::quant::{scale_min_k4, QuantError, Q4K_BYTES, Q6K_BYTES, QK_K}; 46 47 /// Proof that the CPU running this code has the Armv8.2 dot product 48 /// instructions. Made only by [`DotProd::new`] from a feature flag. 49 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 50 pub struct DotProd(()); 51 52 impl DotProd { 53 /// `Some` when `cpu_has_dotprod` is true and this build targets aarch64. 54 pub fn new(cpu_has_dotprod: bool) -> Option { 55 if cfg!(target_arch = "aarch64") && cpu_has_dotprod { 56 Some(Self(())) 57 } else { 58 None 59 } 60 } 61 } 62 63 static CPU_DOTPROD: AtomicBool = AtomicBool::new(false); 64 65 /// Record the CPU's dotprod feature (the kernel calls this once at boot from 66 /// its feature decode). New `DecodeState`s pick it up. Default: off. 67 pub fn set_cpu_dotprod(on: bool) { 68 CPU_DOTPROD.store(on, Ordering::Relaxed); 69 } 70 71 /// The recorded capability, if any. 72 pub fn cpu_dotprod() -> Option { 73 DotProd::new(CPU_DOTPROD.load(Ordering::Relaxed)) 74 } 75 76 /// Activations quantized to ggml's Q8_K blocks, preallocated. 77 pub struct Q8Act { 78 qs: Vec, 79 d: Vec, 80 bsums: Vec, 81 nblk: usize, 82 } 83 84 impl Q8Act { 85 /// Room for vectors of up to `cols` values (rounded up to whole blocks). 86 pub fn with_capacity(cols: usize) -> Self { 87 let nb = cols.div_ceil(QK_K); 88 Self { 89 qs: vec![0; nb * QK_K], 90 d: vec![0.0; nb], 91 bsums: vec![0; nb * 16], 92 nblk: 0, 93 } 94 } 95 96 /// Quantize `x` (length a multiple of 256, at most the capacity). Same 97 /// arithmetic as ggml `quantize_row_q8_K_ref`: the element of largest 98 /// magnitude (first on ties) maps to -127, `d = 1/iscale`, round to 99 /// nearest even, clamp at 127. 100 pub fn quantize(&mut self, x: &[f32]) -> Result<(), QuantError> { 101 if x.len() % QK_K != 0 || x.len() / QK_K > self.d.len() { 102 return Err(QuantError::BadLength); 103 } 104 self.nblk = x.len() / QK_K; 105 for (i, blk) in x.chunks_exact(QK_K).enumerate() { 106 let qs = &mut self.qs[i * QK_K..(i + 1) * QK_K]; 107 let bs = &mut self.bsums[i * 16..(i + 1) * 16]; 108 let mut amax = 0f32; 109 let mut max = 0f32; 110 for &v in blk { 111 if v.abs() > amax { 112 amax = v.abs(); 113 max = v; 114 } 115 } 116 if amax == 0.0 { 117 self.d[i] = 0.0; 118 qs.fill(0); 119 bs.fill(0); 120 continue; 121 } 122 let iscale = -127.0 / max; 123 for (q, &v) in qs.iter_mut().zip(blk) { 124 let t = v * iscale; 125 // nearest_int: magic-number rounding (ties to even), as ggml. 126 *q = (((t + 12_582_912.0) - 12_582_912.0).min(127.0)) as i8; 127 } 128 for (g, s) in bs.iter_mut().enumerate() { 129 *s = qs[16 * g..16 * g + 16].iter().map(|&q| q as i16).sum(); 130 } 131 self.d[i] = 1.0 / iscale; 132 } 133 Ok(()) 134 } 135 136 /// Number of 256-blocks in the last quantized vector. 137 pub fn blocks(&self) -> usize { 138 self.nblk 139 } 140 141 /// Dequantized value `q * d` (what the dot actually sees); for tests. 142 pub fn value(&self, i: usize) -> f32 { 143 self.qs[i] as f32 * self.d[i / QK_K] 144 } 145 146 fn block(&self, i: usize) -> Q8Blk<'_> { 147 Q8Blk { 148 d: self.d[i], 149 qs: self.qs[i * QK_K..(i + 1) * QK_K].try_into().expect("QK_K"), 150 bsums: self.bsums[i * 16..(i + 1) * 16].try_into().expect("16"), 151 } 152 } 153 } 154 155 #[derive(Clone, Copy)] 156 struct Q8Blk<'a> { 157 d: f32, 158 qs: &'a [i8; QK_K], 159 bsums: &'a [i16; 16], 160 } 161 162 fn rd_f16(b: &[u8], at: usize) -> f32 { 163 f16_to_f32(u16::from_le_bytes([b[at], b[at + 1]])) 164 } 165 166 /// Unpack the eight 6-bit scales and mins of a Q4_K block. 167 fn q4k_scales(blk: &[u8; Q4K_BYTES]) -> ([u8; 8], [u8; 8]) { 168 let (mut sc, mut mn) = ([0u8; 8], [0u8; 8]); 169 for j in 0..8 { 170 let (s, m) = scale_min_k4(j, &blk[4..16]); 171 sc[j] = s; 172 mn[j] = m; 173 } 174 (sc, mn) 175 } 176 177 /// Portable integer reference for one Q4_K block: `(sumi, sumi_mins)` where 178 /// `sumi = sum_sb scale[sb] * sum_{l in sb} nibble * q8` and 179 /// `sumi_mins = sum_sb min[sb] * sum_{l in sb} q8`. 180 fn q4k_accum_ref(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { 181 let (sc, mn) = q4k_scales(blk); 182 let qs = &blk[16..144]; 183 let (mut sumi, mut mins) = (0i32, 0i32); 184 for j in 0..4 { 185 let (mut lo, mut hi) = (0i32, 0i32); 186 for l in 0..32 { 187 let b = qs[32 * j + l]; 188 lo += (b & 0x0f) as i32 * y.qs[64 * j + l] as i32; 189 hi += (b >> 4) as i32 * y.qs[64 * j + 32 + l] as i32; 190 } 191 sumi += lo * sc[2 * j] as i32 + hi * sc[2 * j + 1] as i32; 192 } 193 for sb in 0..8 { 194 mins += mn[sb] as i32 * (y.bsums[2 * sb] as i32 + y.bsums[2 * sb + 1] as i32); 195 } 196 (sumi, mins) 197 } 198 199 /// Portable integer reference for one Q6_K block: `(isum, isum_mins)`; the 200 /// weight is `d * scale * (q - 32)`, so the block dot is 201 /// `isum - 32 * isum_mins` with `isum_mins = sum_g scale[g] * bsum[g]`. 202 fn q6k_accum_ref(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { 203 let sc = &blk[192..208]; 204 let mut isum = 0i32; 205 for half in 0..2 { 206 let ql = &blk[64 * half..64 * half + 64]; 207 let qh = &blk[128 + 32 * half..128 + 32 * half + 32]; 208 let yy = &y.qs[128 * half..128 * half + 128]; 209 for l in 0..32 { 210 let is = l / 16; 211 let h = qh[l]; 212 let q1 = ((ql[l] & 0x0f) | ((h & 3) << 4)) as i32; 213 let q2 = ((ql[l + 32] & 0x0f) | (((h >> 2) & 3) << 4)) as i32; 214 let q3 = ((ql[l] >> 4) | (((h >> 4) & 3) << 4)) as i32; 215 let q4 = ((ql[l + 32] >> 4) | (((h >> 6) & 3) << 4)) as i32; 216 let s = |k: usize| sc[8 * half + is + k] as i8 as i32; 217 isum += q1 * yy[l] as i32 * s(0) 218 + q2 * yy[l + 32] as i32 * s(2) 219 + q3 * yy[l + 64] as i32 * s(4) 220 + q4 * yy[l + 96] as i32 * s(6); 221 } 222 } 223 let mut mins = 0i32; 224 for g in 0..16 { 225 mins += sc[g] as i8 as i32 * y.bsums[g] as i32; 226 } 227 (isum, mins) 228 } 229 230 fn q4k_finish(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>, acc: (i32, i32)) -> f32 { 231 let d = y.d * rd_f16(blk, 0); 232 let dmin = y.d * rd_f16(blk, 2); 233 d * acc.0 as f32 - dmin * acc.1 as f32 234 } 235 236 fn q6k_finish(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>, acc: (i32, i32)) -> f32 { 237 rd_f16(blk, 208) * y.d * (acc.0 - 32 * acc.1) as f32 238 } 239 240 /// Block dot with the portable integer arithmetic (reference for the tests; 241 /// also the only path on non-aarch64). 242 pub fn dot_q4k_q8_ref(blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> f32 { 243 let y = q8.block(bi); 244 q4k_finish(blk, &y, q4k_accum_ref(blk, &y)) 245 } 246 247 /// Same for Q6_K. 248 pub fn dot_q6k_q8_ref(blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> f32 { 249 let y = q8.block(bi); 250 q6k_finish(blk, &y, q6k_accum_ref(blk, &y)) 251 } 252 253 #[cfg(target_arch = "aarch64")] 254 mod neon { 255 use super::*; 256 use core::arch::aarch64::*; 257 258 /// # Safety 259 /// CPU must implement FEAT_DotProd (guaranteed by holding a [`DotProd`]). 260 #[inline] 261 #[target_feature(enable = "dotprod")] 262 pub unsafe fn q4k_accum(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { 263 let (sc, mn) = q4k_scales(blk); 264 let m4 = vdupq_n_u8(0x0f); 265 let qp = blk.as_ptr().add(16); 266 let yp = y.qs.as_ptr(); 267 let mut sumv = vdupq_n_s32(0); 268 let zero = vdupq_n_s32(0); 269 for j in 0..4 { 270 let a0 = vld1q_u8(qp.add(32 * j)); 271 let a1 = vld1q_u8(qp.add(32 * j + 16)); 272 let y0 = vld1q_s8(yp.add(64 * j)); 273 let y1 = vld1q_s8(yp.add(64 * j + 16)); 274 let y2 = vld1q_s8(yp.add(64 * j + 32)); 275 let y3 = vld1q_s8(yp.add(64 * j + 48)); 276 let lo = vdotq_s32( 277 vdotq_s32(zero, vreinterpretq_s8_u8(vandq_u8(a0, m4)), y0), 278 vreinterpretq_s8_u8(vandq_u8(a1, m4)), 279 y1, 280 ); 281 let hi = vdotq_s32( 282 vdotq_s32(zero, vreinterpretq_s8_u8(vshrq_n_u8::<4>(a0)), y2), 283 vreinterpretq_s8_u8(vshrq_n_u8::<4>(a1)), 284 y3, 285 ); 286 sumv = vmlaq_n_s32(sumv, lo, sc[2 * j] as i32); 287 sumv = vmlaq_n_s32(sumv, hi, sc[2 * j + 1] as i32); 288 } 289 let mut mins = 0i32; 290 for sb in 0..8 { 291 mins += mn[sb] as i32 * (y.bsums[2 * sb] as i32 + y.bsums[2 * sb + 1] as i32); 292 } 293 (vaddvq_s32(sumv), mins) 294 } 295 296 /// # Safety 297 /// As [`q4k_accum`]. 298 #[inline] 299 #[target_feature(enable = "dotprod")] 300 pub unsafe fn q6k_accum(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { 301 let m4 = vdupq_n_u8(0x0f); 302 let m3 = vdupq_n_u8(0x03); 303 let zero = vdupq_n_s32(0); 304 let sc = &blk[192..208]; 305 let mut isum = 0i32; 306 for half in 0..2 { 307 let ql = blk.as_ptr().add(64 * half); 308 let qh = blk.as_ptr().add(128 + 32 * half); 309 let yp = y.qs.as_ptr().add(128 * half); 310 let s = &sc[8 * half..8 * half + 8]; 311 let (qh0, qh1) = (vld1q_u8(qh), vld1q_u8(qh.add(16))); 312 let (l0, l1, l2, l3) = ( 313 vld1q_u8(ql), 314 vld1q_u8(ql.add(16)), 315 vld1q_u8(ql.add(32)), 316 vld1q_u8(ql.add(48)), 317 ); 318 // low nibbles, qh bit pairs 0 and 1 319 let h0 = vshlq_n_u8::<4>(vandq_u8(qh0, m3)); 320 let h1 = vshlq_n_u8::<4>(vandq_u8(qh1, m3)); 321 let h2 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<2>(qh0), m3)); 322 let h3 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<2>(qh1), m3)); 323 let b = [ 324 vorrq_u8(vandq_u8(l0, m4), h0), 325 vorrq_u8(vandq_u8(l1, m4), h1), 326 vorrq_u8(vandq_u8(l2, m4), h2), 327 vorrq_u8(vandq_u8(l3, m4), h3), 328 ]; 329 for k in 0..4 { 330 let p = vdotq_s32(zero, vreinterpretq_s8_u8(b[k]), vld1q_s8(yp.add(16 * k))); 331 isum += vaddvq_s32(p) * s[k] as i8 as i32; 332 } 333 // high nibbles, qh bit pairs 2 and 3 334 let h0 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<4>(qh0), m3)); 335 let h1 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<4>(qh1), m3)); 336 let h2 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<6>(qh0), m3)); 337 let h3 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<6>(qh1), m3)); 338 let b = [ 339 vorrq_u8(vshrq_n_u8::<4>(l0), h0), 340 vorrq_u8(vshrq_n_u8::<4>(l1), h1), 341 vorrq_u8(vshrq_n_u8::<4>(l2), h2), 342 vorrq_u8(vshrq_n_u8::<4>(l3), h3), 343 ]; 344 for k in 0..4 { 345 let p = vdotq_s32( 346 zero, 347 vreinterpretq_s8_u8(b[k]), 348 vld1q_s8(yp.add(64 + 16 * k)), 349 ); 350 isum += vaddvq_s32(p) * s[4 + k] as i8 as i32; 351 } 352 } 353 let mut mins = 0i32; 354 for g in 0..16 { 355 mins += sc[g] as i8 as i32 * y.bsums[g] as i32; 356 } 357 (isum, mins) 358 } 359 360 /// # Safety 361 /// As [`q4k_accum`]; `src` is whole Q4_K blocks and `q8` has the same count. 362 #[target_feature(enable = "dotprod")] 363 pub unsafe fn row_q4k(src: &[u8], q8: &Q8Act) -> f32 { 364 let mut acc = 0f32; 365 for (i, b) in src.chunks_exact(Q4K_BYTES).enumerate() { 366 let blk: &[u8; Q4K_BYTES] = b.try_into().expect("Q4K_BYTES"); 367 let y = q8.block(i); 368 acc += q4k_finish(blk, &y, q4k_accum(blk, &y)); 369 } 370 acc 371 } 372 373 /// # Safety 374 /// As [`row_q4k`] for Q6_K. 375 #[target_feature(enable = "dotprod")] 376 pub unsafe fn row_q6k(src: &[u8], q8: &Q8Act) -> f32 { 377 let mut acc = 0f32; 378 for (i, b) in src.chunks_exact(Q6K_BYTES).enumerate() { 379 let blk: &[u8; Q6K_BYTES] = b.try_into().expect("Q6K_BYTES"); 380 let y = q8.block(i); 381 acc += q6k_finish(blk, &y, q6k_accum(blk, &y)); 382 } 383 acc 384 } 385 } 386 387 /// SDOT block dot (Q4_K); test and bench hook, needs the capability token. 388 #[cfg(target_arch = "aarch64")] 389 pub fn dot_q4k_q8_sdot(_t: DotProd, blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> f32 { 390 let y = q8.block(bi); 391 // SAFETY: the token proves FEAT_DotProd. 392 unsafe { q4k_finish(blk, &y, neon::q4k_accum(blk, &y)) } 393 } 394 395 /// SDOT block dot (Q6_K). 396 #[cfg(target_arch = "aarch64")] 397 pub fn dot_q6k_q8_sdot(_t: DotProd, blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> f32 { 398 let y = q8.block(bi); 399 // SAFETY: the token proves FEAT_DotProd. 400 unsafe { q6k_finish(blk, &y, neon::q6k_accum(blk, &y)) } 401 } 402 403 /// Integer accumulations `(sum, mins)` of the SDOT block code; tests compare 404 /// them bit for bit with the portable reference. 405 #[cfg(target_arch = "aarch64")] 406 pub fn q4k_accum_sdot(_t: DotProd, blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { 407 let y = q8.block(bi); 408 // SAFETY: the token proves FEAT_DotProd. 409 unsafe { neon::q4k_accum(blk, &y) } 410 } 411 412 /// As [`q4k_accum_sdot`] for Q6_K. 413 #[cfg(target_arch = "aarch64")] 414 pub fn q6k_accum_sdot(_t: DotProd, blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { 415 let y = q8.block(bi); 416 // SAFETY: the token proves FEAT_DotProd. 417 unsafe { neon::q6k_accum(blk, &y) } 418 } 419 420 /// Portable accumulations (reference) for the tests. 421 pub fn q4k_accum_portable(blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { 422 q4k_accum_ref(blk, &q8.block(bi)) 423 } 424 425 /// As [`q4k_accum_portable`] for Q6_K. 426 pub fn q6k_accum_portable(blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { 427 q6k_accum_ref(blk, &q8.block(bi)) 428 } 429 430 /// Dot of a whole quantized row with the quantized activations, using SDOT. 431 pub fn dot_row_q8(_t: DotProd, ty: GgmlType, src: &[u8], q8: &Q8Act) -> Result { 432 let (bw, bb) = ty.block(); 433 if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) { 434 return Err(QuantError::Unsupported(ty)); 435 } 436 if src.len() % bb != 0 || src.len() / bb != q8.blocks() || bw != QK_K { 437 return Err(QuantError::BadLength); 438 } 439 #[cfg(target_arch = "aarch64")] 440 { 441 // SAFETY: the token proves FEAT_DotProd; lengths checked above. 442 Ok(unsafe { 443 if ty == GgmlType::Q4K { 444 neon::row_q4k(src, q8) 445 } else { 446 neon::row_q6k(src, q8) 447 } 448 }) 449 } 450 #[cfg(not(target_arch = "aarch64"))] 451 { 452 let mut acc = 0f32; 453 for (i, b) in src.chunks_exact(bb).enumerate() { 454 acc += if ty == GgmlType::Q4K { 455 dot_q4k_q8_ref(b.try_into().expect("Q4K_BYTES"), q8, i) 456 } else { 457 dot_q6k_q8_ref(b.try_into().expect("Q6K_BYTES"), q8, i) 458 }; 459 } 460 Ok(acc) 461 } 462 } 463 464 #[cfg(test)] 465 mod tests { 466 use super::*; 467 use crate::decode::q8k_round; 468 use crate::quant::{dequant_q4k_block, dequant_q6k_block, dot_row}; 469 #[cfg(target_arch = "aarch64")] 470 use std::eprintln; 471 use std::vec::Vec; 472 473 /// xorshift64*, fixed seeds. 474 struct Rng(u64); 475 impl Rng { 476 fn next(&mut self) -> u64 { 477 self.0 ^= self.0 >> 12; 478 self.0 ^= self.0 << 25; 479 self.0 ^= self.0 >> 27; 480 self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) 481 } 482 fn byte(&mut self) -> u8 { 483 (self.next() >> 32) as u8 484 } 485 fn unit(&mut self) -> f32 { 486 ((self.next() >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 487 } 488 } 489 490 fn token() -> Option { 491 #[cfg(target_arch = "aarch64")] 492 { 493 DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")) 494 } 495 #[cfg(not(target_arch = "aarch64"))] 496 { 497 None 498 } 499 } 500 501 fn f16(v: f32) -> [u8; 2] { 502 // exact for the values used here (small integers and halves) 503 let bits = v.to_bits(); 504 if v == 0.0 { 505 return [0, 0]; 506 } 507 let sign = ((bits >> 16) & 0x8000) as u16; 508 let e = ((bits >> 23) & 0xff) as i32 - 127 + 15; 509 let m = ((bits >> 13) & 0x3ff) as u16; 510 (sign | ((e as u16) << 10) | m).to_le_bytes() 511 } 512 513 #[derive(Clone, Copy)] 514 enum Fill { 515 Random, 516 MaxScales, 517 ZeroScales, 518 AllOnes, 519 AllZero, 520 } 521 522 fn q4k_block(r: &mut Rng, fill: Fill) -> [u8; Q4K_BYTES] { 523 let mut b = [0u8; Q4K_BYTES]; 524 for x in b.iter_mut() { 525 *x = r.byte(); 526 } 527 match fill { 528 Fill::Random => {} 529 Fill::MaxScales => b[4..16].fill(0xff), // all scales and mins = 63 530 Fill::ZeroScales => b[4..16].fill(0), 531 Fill::AllOnes => { 532 b[4..].fill(0xff); 533 } 534 Fill::AllZero => b[4..].fill(0), 535 } 536 b[0..2].copy_from_slice(&f16(0.0625 * (1 + r.byte() % 8) as f32)); 537 b[2..4].copy_from_slice(&f16(0.03125 * (1 + r.byte() % 8) as f32)); 538 b 539 } 540 541 fn q6k_block(r: &mut Rng, fill: Fill) -> [u8; Q6K_BYTES] { 542 let mut b = [0u8; Q6K_BYTES]; 543 for x in b.iter_mut() { 544 *x = r.byte(); 545 } 546 match fill { 547 Fill::Random => {} 548 Fill::MaxScales => { 549 for (i, s) in b[192..208].iter_mut().enumerate() { 550 *s = if i % 2 == 0 { 127 } else { 0x80 }; // +127 and -128 551 } 552 } 553 Fill::ZeroScales => b[192..208].fill(0), 554 Fill::AllOnes => b[..192].fill(0xff), 555 Fill::AllZero => b[..192].fill(0), 556 } 557 b[208..210].copy_from_slice(&f16(0.0625 * (1 + r.byte() % 8) as f32)); 558 b 559 } 560 561 fn acts(r: &mut Rng, nblk: usize, kind: u8) -> (Vec, Q8Act) { 562 let mut x = std::vec![0f32; nblk * QK_K]; 563 for (i, v) in x.iter_mut().enumerate() { 564 *v = match kind { 565 0 => r.unit() * 3.0, 566 1 => 1.0, // all equal: every q = -127 567 2 => { 568 if i % 2 == 0 { 569 100.0 570 } else { 571 -100.0 572 } 573 } // extremes of both signs 574 _ => 0.0, 575 }; 576 } 577 let mut q = Q8Act::with_capacity(x.len()); 578 q.quantize(&x).unwrap(); 579 (x, q) 580 } 581 582 #[test] 583 fn quantize_matches_q8k_round_and_sums() { 584 let mut r = Rng(0x1234_5678_9abc_def1); 585 let (x, q) = acts(&mut r, 6, 0); 586 let mut want = x.clone(); 587 q8k_round(&mut want); 588 for i in 0..x.len() { 589 assert_eq!(q.value(i).to_bits(), want[i].to_bits(), "elem {i}"); 590 } 591 for b in 0..6 { 592 for g in 0..16 { 593 let s: i32 = (0..16).map(|l| q.qs[b * QK_K + 16 * g + l] as i32).sum(); 594 assert_eq!(q.bsums[b * 16 + g] as i32, s); 595 } 596 let m = q.qs[b * QK_K..(b + 1) * QK_K] 597 .iter() 598 .map(|&v| (v as i32).abs()) 599 .max(); 600 assert_eq!(m, Some(127)); 601 } 602 // all-zero block: scale 0, all zero 603 let (_, z) = acts(&mut r, 2, 3); 604 assert!(z.d[..2].iter().all(|&d| d == 0.0) && z.qs.iter().all(|&v| v == 0)); 605 // length rules 606 let mut q = Q8Act::with_capacity(256); 607 assert_eq!(q.quantize(&[0.0; 100]), Err(QuantError::BadLength)); 608 assert_eq!(q.quantize(&[0.0; 512]), Err(QuantError::BadLength)); 609 } 610 611 /// Dot of the dequantized weights with the dequantized (rounded) 612 /// activations in f32: what the integer path must reproduce up to float 613 /// summation order and the f16-scaled products. 614 fn f32_reference(w: &[f32; QK_K], q: &Q8Act, bi: usize) -> (f32, f32) { 615 let mut dot = 0f64; 616 let mut mag = 0f64; 617 for l in 0..QK_K { 618 let t = w[l] as f64 * q.value(bi * QK_K + l) as f64; 619 dot += t; 620 mag += t.abs(); 621 } 622 (dot as f32, mag as f32) 623 } 624 625 const FILLS: [Fill; 5] = [ 626 Fill::Random, 627 Fill::MaxScales, 628 Fill::ZeroScales, 629 Fill::AllOnes, 630 Fill::AllZero, 631 ]; 632 633 #[test] 634 fn q4k_integer_dot_equals_f32_dot_of_rounded_activations() { 635 let mut r = Rng(0xdead_beef_0001); 636 for n in 0..400 { 637 let blk = q4k_block(&mut r, FILLS[n % 5]); 638 let (_, q) = acts(&mut r, 1, (n % 4) as u8); 639 let mut w = [0f32; QK_K]; 640 dequant_q4k_block(&blk, &mut w); 641 let (want, mag) = f32_reference(&w, &q, 0); 642 let got = dot_q4k_q8_ref(&blk, &q, 0); 643 assert!( 644 (got - want).abs() <= 2e-5 * mag.max(1e-3), 645 "n {n}: {got} vs {want}" 646 ); 647 } 648 } 649 650 #[test] 651 fn q6k_integer_dot_equals_f32_dot_of_rounded_activations() { 652 let mut r = Rng(0xdead_beef_0002); 653 for n in 0..400 { 654 let blk = q6k_block(&mut r, FILLS[n % 5]); 655 let (_, q) = acts(&mut r, 1, (n % 4) as u8); 656 let mut w = [0f32; QK_K]; 657 dequant_q6k_block(&blk, &mut w); 658 let (want, mag) = f32_reference(&w, &q, 0); 659 let got = dot_q6k_q8_ref(&blk, &q, 0); 660 assert!( 661 (got - want).abs() <= 2e-5 * mag.max(1e-3), 662 "n {n}: {got} vs {want}" 663 ); 664 } 665 } 666 667 #[test] 668 #[cfg(target_arch = "aarch64")] 669 fn sdot_accumulations_are_bit_exact_vs_portable_q4k() { 670 let Some(t) = token() else { 671 eprintln!("SKIP: no dotprod on this CPU or not aarch64"); 672 return; 673 }; 674 let mut r = Rng(0x5eed_0004); 675 for n in 0..2000 { 676 let blk = q4k_block(&mut r, FILLS[n % 5]); 677 let (_, q) = acts(&mut r, 1, (n % 4) as u8); 678 #[cfg(target_arch = "aarch64")] 679 { 680 assert_eq!( 681 q4k_accum_sdot(t, &blk, &q, 0), 682 q4k_accum_portable(&blk, &q, 0), 683 "n {n}" 684 ); 685 assert_eq!( 686 dot_q4k_q8_sdot(t, &blk, &q, 0).to_bits(), 687 dot_q4k_q8_ref(&blk, &q, 0).to_bits() 688 ); 689 } 690 let _ = t; 691 } 692 } 693 694 #[test] 695 #[cfg(target_arch = "aarch64")] 696 fn sdot_accumulations_are_bit_exact_vs_portable_q6k() { 697 let Some(t) = token() else { 698 eprintln!("SKIP: no dotprod on this CPU or not aarch64"); 699 return; 700 }; 701 let mut r = Rng(0x5eed_0006); 702 for n in 0..2000 { 703 let blk = q6k_block(&mut r, FILLS[n % 5]); 704 let (_, q) = acts(&mut r, 1, (n % 4) as u8); 705 #[cfg(target_arch = "aarch64")] 706 { 707 assert_eq!( 708 q6k_accum_sdot(t, &blk, &q, 0), 709 q6k_accum_portable(&blk, &q, 0), 710 "n {n}" 711 ); 712 assert_eq!( 713 dot_q6k_q8_sdot(t, &blk, &q, 0).to_bits(), 714 dot_q6k_q8_ref(&blk, &q, 0).to_bits() 715 ); 716 } 717 let _ = t; 718 } 719 } 720 721 /// Hand-computed block (no random data): Q4_K, d=1, dmin=1, scale of 722 /// sub-block j is j+1, min j, all nibbles 3, activations all equal so 723 /// every q8 is -127 and d_y = 1/(-127/1) = -1/127. 724 #[test] 725 fn q4k_hand_computed_scale_application() { 726 let mut b = [0u8; Q4K_BYTES]; 727 b[0..2].copy_from_slice(&f16(1.0)); 728 b[2..4].copy_from_slice(&f16(1.0)); 729 for j in 0..4 { 730 b[4 + j] = (j + 1) as u8; 731 b[8 + j] = j as u8; 732 } 733 for j in 4..8 { 734 b[8 + j] = ((j + 1) as u8) | ((j as u8) << 4); 735 } 736 b[16..].fill(0x33); 737 let x = [1.0f32; QK_K]; 738 let mut q = Q8Act::with_capacity(QK_K); 739 q.quantize(&x).unwrap(); 740 // sumi = sum_sb scale*3*32*(-127); sumi_mins = sum_sb min*32*(-127) 741 let sumi: i32 = (1..=8).map(|s| s * 3 * 32 * -127).sum(); 742 let mins: i32 = (0..8).map(|m| m * 32 * -127).sum(); 743 assert_eq!(q4k_accum_portable(&b, &q, 0), (sumi, mins)); 744 let dy = 1.0f32 / (-127.0f32 / 1.0); 745 let want = dy * sumi as f32 - dy * mins as f32; 746 assert_eq!(dot_q4k_q8_ref(&b, &q, 0), want); 747 // the true f32 dot is sum(scale*3 - min) over 32 values each 748 let truth: f32 = (0..8).map(|s| ((s + 1) * 3 - s) as f32 * 32.0).sum(); 749 assert!((want - truth).abs() < 1e-3, "{want} vs {truth}"); 750 #[cfg(target_arch = "aarch64")] 751 if let Some(t) = token() { 752 assert_eq!(dot_q4k_q8_sdot(t, &b, &q, 0), want); 753 } 754 } 755 756 #[test] 757 fn row_dot_matches_scalar_path_and_checks_lengths() { 758 let mut r = Rng(0x7007); 759 let nb = 9; 760 let mut src4 = Vec::new(); 761 let mut src6 = Vec::new(); 762 for n in 0..nb { 763 src4.extend_from_slice(&q4k_block(&mut r, FILLS[n % 5])); 764 src6.extend_from_slice(&q6k_block(&mut r, FILLS[n % 5])); 765 } 766 let (x, q) = acts(&mut r, nb, 0); 767 let mut xr = x.clone(); 768 q8k_round(&mut xr); 769 let Some(t) = token() else { 770 // portable reference still agrees with the scalar f32 row dot 771 return; 772 }; 773 for (ty, src) in [(GgmlType::Q4K, &src4), (GgmlType::Q6K, &src6)] { 774 let got = dot_row_q8(t, ty, src, &q).unwrap(); 775 let want = dot_row(ty, src, &xr).unwrap(); 776 let mag: f32 = xr.iter().map(|v| v.abs()).sum::() * 60.0; 777 assert!((got - want).abs() <= 1e-4 * mag, "{ty:?}: {got} vs {want}"); 778 assert_eq!(dot_row_q8(t, ty, &src[1..], &q), Err(QuantError::BadLength)); 779 } 780 assert_eq!( 781 dot_row_q8(t, GgmlType::F32, &src4, &q), 782 Err(QuantError::Unsupported(GgmlType::F32)) 783 ); 784 } 785 786 #[test] 787 fn token_only_when_flag_set() { 788 assert_eq!(DotProd::new(false), None); 789 set_cpu_dotprod(false); 790 assert_eq!(cpu_dotprod(), None); 791 } 792 }