aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#361 (code only)
Apply it
git checkout -b patch-927ee75488460cd6 72278a4c614c46cb9c432b52b16446668f5d0313 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/927ee75488460cd6.patch | git am
Provenance
github-import 1
aien-dev/aienux
361
d46ab0704b2dbf50f1d7729ca7dd2d1559db6392
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":361,"url":"https://github.com/aien-dev/aienux/pull/361","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:16Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 39da37e2..13b8e325 100644 --- a/.crumb +++ b/.crumb @@ -21,8 +21,8 @@ "generated": { "children": [ { - "digest": "84164b4dfc3d06c6c73911cef9ed013d20631fdc4781ad312f1f9229ef429190", - "last_commit": "49ff776", + "digest": "e04ed38306b5ade84b4d72cfef14db7d58ab3952031806b43c8132a985a3d403", + "last_commit": "7df4066", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, @@ -33,8 +33,8 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "36d90b1bdc1a7e33efc7d385e66c3301de434c889046cc6855725eabfceb31ff", - "last_commit": "4b74ebf", + "digest": "9ae0942a460fa8108c8087cb4c7e30944198fa6e405816490aad5b37754b99f4", + "last_commit": "e7de707", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, @@ -45,15 +45,15 @@ "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:dcdd12bc141cebd89b36ad1c4caab70017daa3bb6936774e4bf57c688770abf3", - "compiled_at": "2026-10-13T15:00:51Z", + "children_root": "sha256:e383c1ef8d2eba26822b417e687d88011aebcd83cf429ffafb46caf19a0ab1d7", + "compiled_at": "2026-10-13T15:46:48Z", "compiler": "crumb-compile/1", - "digest": "sha256:7b1327342af743273c65bd8e9c7c501f5e583d87c030c29cacf7a6a4fe572fc8", + "digest": "sha256:ad2e48b9868cc8482da606133b85bbdce6256d01ea36d94b631a4277cdcb9f65", "evidence_files": 156, "evidence_root": "sha256:cd53ab119be9de6ce28c4f5949b106c9622f1fe105611de3de21c3bce7932694", - "files": 3152, - "generated_at_commit": "4b74ebf18be00aa0ae3cf512ff1368f1590ddc8a", - "source_tree": "sha256:4a8e325c0973c835b344bee654dab3a291ac4c948dc95b23a29060c713827e7a" + "files": 3154, + "generated_at_commit": "7df4066ad6dbe14a05fbfc4408bcf48399b2b010", + "source_tree": "sha256:5ab3a23d83a0133b3334141fd79ef5094c4d6807bd982f1fb11960b36b7ec435" }, "owner_lane": "", "provenance": { diff --git a/crates/.crumb b/crates/.crumb index 12c68f77..8a13f1c6 100644 --- a/crates/.crumb +++ b/crates/.crumb @@ -96,7 +96,7 @@ }, { "digest": "223e3399133c766986b1044a16c8367b51b78158d3070c0ec63c7ed3e639d644", - "last_commit": "3761935", + "last_commit": "49ff776", "name": "aienos-boot", "purpose": "Directory crates/aienos-boot. Purpose not yet described by a human." }, @@ -138,7 +138,7 @@ }, { "digest": "1f8ba1326707e021f21de9eea6a03533e02e48089471d5561373cca1ed6cea64", - "last_commit": "fbbfc9c", + "last_commit": "49ff776", "name": "aienos-kernel", "purpose": "Directory crates/aienos-kernel. Purpose not yet described by a human." }, @@ -150,14 +150,14 @@ } ], "children_root": "sha256:94f052910f8e65e9eca98d9c0b5d433ef2288dcd8ca1c474518e716295999644", - "compiled_at": "2026-10-13T02:27:54Z", + "compiled_at": "2026-10-13T15:46:48Z", "compiler": "crumb-compile/1", - "digest": "sha256:84164b4dfc3d06c6c73911cef9ed013d20631fdc4781ad312f1f9229ef429190", + "digest": "sha256:e04ed38306b5ade84b4d72cfef14db7d58ab3952031806b43c8132a985a3d403", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 232, - "generated_at_commit": "74f638c298bc04543b03d6851a83dac815d36645", - "source_tree": "sha256:51694aa77b212261cbe94615f12b5a21d34ac05c46cda80d29d48a3e960efe40" + "files": 234, + "generated_at_commit": "7df4066ad6dbe14a05fbfc4408bcf48399b2b010", + "source_tree": "sha256:82a2287958cb9ab68a6a6afaa45609e62ae9af7c510713aa7390bc6f3dd773d0" }, "owner_lane": "", "provenance": { diff --git a/crates/aienos-infer-kernel/src/lib.rs b/crates/aienos-infer-kernel/src/lib.rs index 7cd0cfed..46f5dbf5 100644 --- a/crates/aienos-infer-kernel/src/lib.rs +++ b/crates/aienos-infer-kernel/src/lib.rs @@ -313,3 +313,19 @@ pub unsafe extern "C" fn aienos_infer_run( r.words[8] = (*HEAP.peak.get() / 1024) as u32; rc } + +/// Record the CPU's dot product feature (`ck_cpu_features.dotprod`, decoded by +/// the kernel from `ID_AA64ISAR0_EL1.DP`; native/kernel/core/cpufeat.c). Call +/// before opening a model: new decode states take the SDOT int8-activation +/// matvec path only when this is nonzero, otherwise the scalar f32 path runs +/// unchanged. Nothing in this crate detects features itself. +#[no_mangle] +pub extern "C" fn aienos_infer_set_cpu_features(dotprod: u32) { + aienos_infer::set_cpu_dotprod(dotprod != 0); +} + +/// 1 when a decode state created now would use the SDOT path, else 0. +#[no_mangle] +pub extern "C" fn aienos_infer_dot_path() -> u32 { + aienos_infer::cpu_dotprod().is_some() as u32 +} diff --git a/crates/aienos-infer/examples/dot_bench.rs b/crates/aienos-infer/examples/dot_bench.rs new file mode 100644 index 00000000..f8f99223 --- /dev/null +++ b/crates/aienos-infer/examples/dot_bench.rs @@ -0,0 +1,70 @@ +//! Row-dot microbenchmark, one thread: ns per Q4_K / Q6_K row dot of 8192 +//! weights, scalar f32 path vs SDOT path (aienos#34 PI5-6). Random blocks +//! with a fixed seed; `AIENOS_DOT_ITERS` (default 20000) rows per timing. +//! Prints `key: value` lines. The SDOT numbers appear only when the CPU has +//! dotprod (runtime detection on the host). + +use aienos_infer::dotprod::{dot_row_q8, Q8Act}; +use aienos_infer::quant::{dot_row, Q4K_BYTES, Q6K_BYTES, QK_K}; +use aienos_infer::{DotProd, GgmlType}; +use std::hint::black_box; +use std::time::Instant; + +fn main() { + let iters: usize = std::env::var("AIENOS_DOT_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20000); + let nb = 32; // 8192 weights, the Llama-3.2-1B FFN width + let mut s = 0x9e37_79b9_7f4a_7c15u64; + let mut rnd = || { + s ^= s >> 12; + s ^= s << 25; + s ^= s >> 27; + (s.wrapping_mul(0x2545_f491_4f6c_dd1d) >> 32) as u32 + }; + let x: Vec<f32> = (0..nb * QK_K) + .map(|_| (rnd() as f32 / u32::MAX as f32) * 2.0 - 1.0) + .collect(); + let mut q8 = Q8Act::with_capacity(x.len()); + q8.quantize(&x).unwrap(); + #[cfg(target_arch = "aarch64")] + let tok = DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")); + #[cfg(not(target_arch = "aarch64"))] + let tok: Option<DotProd> = None; + println!("dotprod: {}", tok.is_some()); + println!("weights_per_row: {}", nb * QK_K); + for (ty, bb, name) in [ + (GgmlType::Q4K, Q4K_BYTES, "q4k"), + (GgmlType::Q6K, Q6K_BYTES, "q6k"), + ] { + let mut row: Vec<u8> = (0..nb * bb).map(|_| rnd() as u8).collect(); + for b in row.chunks_exact_mut(bb) { + // sane f16 scales (0.0625) so values stay finite + let at = if ty == GgmlType::Q4K { 0 } else { 208 }; + b[at..at + 2].copy_from_slice(&[0x00, 0x2c]); + if ty == GgmlType::Q4K { + b[2..4].copy_from_slice(&[0x00, 0x2c]); + } + } + let t0 = Instant::now(); + let mut acc = 0f32; + for _ in 0..iters { + acc += dot_row(ty, black_box(&row), black_box(&x)).unwrap(); + } + let scalar = t0.elapsed().as_nanos() as f64 / iters as f64; + black_box(acc); + println!("{name}_scalar_f32_ns_per_row: {scalar:.1}"); + if let Some(t) = tok { + let t0 = Instant::now(); + let mut acc = 0f32; + for _ in 0..iters { + acc += dot_row_q8(t, ty, black_box(&row), black_box(&q8)).unwrap(); + } + let sdot = t0.elapsed().as_nanos() as f64 / iters as f64; + black_box(acc); + println!("{name}_sdot_ns_per_row: {sdot:.1}"); + println!("{name}_speedup: {:.2}", scalar / sdot); + } + } +} diff --git a/crates/aienos-infer/examples/l6_host.rs b/crates/aienos-infer/examples/l6_host.rs index a2a3ddff..24385c39 100644 --- a/crates/aienos-infer/examples/l6_host.rs +++ b/crates/aienos-infer/examples/l6_host.rs @@ -6,11 +6,12 @@ //! golden reply; Part B keeps decoding (ignoring end-of-turn) to N tokens and //! times each `forward` call in microseconds. //! -//! Env: AIENOS_MODEL (default $HOME/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf), +//! Env: AIENOS_DOT (`sdot` = dotprod int8 path if present, default f32 scalar), +//! AIENOS_MODEL (default $HOME/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf), //! AIENOS_N (default 64), AIENOS_COMMIT (printed as `commit`). //! Output: one `key: value` line per fact. Exit 0 ok, 1 parity FAIL, 2 wrong model. -use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer}; +use aienos_infer::{argmax, DecodeState, DotProd, Gguf, Model, Tokenizer}; use std::time::Instant; const PROMPT: &str = "What is the capital of France?"; @@ -133,6 +134,20 @@ fn main() { println!("threads: 1"); let mut st = DecodeState::new(&m, ids.len() + n + 8); + // AIENOS_DOT=sdot uses the dotprod int8 path when the CPU reports it (runtime + // detection here; the kernel passes its own decode); f32 (default) is the scalar path. + let want_sdot = std::env::var("AIENOS_DOT") + .map(|v| v == "sdot") + .unwrap_or(false); + st.dotprod = None; + if want_sdot { + #[cfg(target_arch = "aarch64")] + { + st.dotprod = DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")); + } + } + let _: Option<DotProd> = st.dotprod; + println!("dot: {}", if st.dotprod.is_some() { "sdot" } else { "f32" }); let t0 = Instant::now(); st.prefill(&m, &ids).expect("prefill"); let prefill_us = t0.elapsed().as_micros() as u64; diff --git a/crates/aienos-infer/src/decode.rs b/crates/aienos-infer/src/decode.rs index 782622d0..3fa06c15 100644 --- a/crates/aienos-infer/src/decode.rs +++ b/crates/aienos-infer/src/decode.rs @@ -9,8 +9,9 @@ use alloc::vec; use alloc::vec::Vec; +use crate::dotprod::{cpu_dotprod, DotProd, Q8Act}; use crate::math; -use crate::model::{InferError, Model}; +use crate::model::{InferError, Model, Weight}; /// KV cache plus scratch buffers for one sequence. pub struct DecodeState { @@ -37,6 +38,13 @@ pub struct DecodeState { pub logits: Vec<f32>, /// Round matvec inputs to the Q8_K grid like ggml does (default off). pub emulate_q8k: bool, + /// SDOT int8-activation path for the K-quant matvecs (Q8_K activations, + /// integer dots; see `dotprod`). `Some` only with a capability token; a + /// new state takes it from `set_cpu_dotprod` (kernel boot decode), never + /// assumed. `None` runs the scalar f32 path unchanged. Takes over the + /// Q8_K rounding of `emulate_q8k` (the quantizer does it). + pub dotprod: Option<DotProd>, + q8: Q8Act, } impl DecodeState { @@ -67,6 +75,8 @@ impl DecodeState { rope_sin: vec![0.0; model.head_dim / 2], logits: vec![0.0; p.vocab_size as usize], emulate_q8k: false, + dotprod: cpu_dotprod(), + q8: Q8Act::with_capacity(e.max(ff)), } } @@ -158,6 +168,7 @@ impl DecodeState { let group = n_head / p.head_count_kv as usize; let eps = p.rms_norm_eps; let scale = 1.0 / math::sqrt(hd as f32); + let (dp, emu) = (self.dotprod, self.emulate_q8k); m.tok_embd.row_into(token as usize, &mut self.x)?; rope_cache( @@ -170,12 +181,24 @@ impl DecodeState { for (l, layer) in m.layers.iter().enumerate() { rms_norm(&self.x, &layer.attn_norm, eps, &mut self.h); - if self.emulate_q8k { - q8k_round(&mut self.h); - } - layer.wq.matvec(&self.h, &mut self.q, &mut self.scr)?; - layer.wk.matvec(&self.h, &mut self.kk, &mut self.scr)?; - layer.wv.matvec(&self.h, &mut self.vv, &mut self.scr)?; + prep(dp, emu, &mut self.q8, &mut self.h)?; + mv(dp, &layer.wq, &self.h, &self.q8, &mut self.q, &mut self.scr)?; + mv( + dp, + &layer.wk, + &self.h, + &self.q8, + &mut self.kk, + &mut self.scr, + )?; + mv( + dp, + &layer.wv, + &self.h, + &self.q8, + &mut self.vv, + &mut self.scr, + )?; rope_apply(&mut self.q, hd, &self.rope_cos, &self.rope_sin); rope_apply(&mut self.kk, hd, &self.rope_cos, &self.rope_sin); @@ -203,33 +226,49 @@ impl DecodeState { } } let e = self.x.len(); - if self.emulate_q8k { - q8k_round(&mut self.att); - } - layer - .wo - .matvec(&self.att, &mut self.tmp[..e], &mut self.scr)?; + prep(dp, emu, &mut self.q8, &mut self.att)?; + mv( + dp, + &layer.wo, + &self.att, + &self.q8, + &mut self.tmp[..e], + &mut self.scr, + )?; for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) { *x += d; } rms_norm(&self.x, &layer.ffn_norm, eps, &mut self.h); - if self.emulate_q8k { - q8k_round(&mut self.h); - } - layer - .w_gate - .matvec(&self.h, &mut self.gate, &mut self.scr)?; - layer.w_up.matvec(&self.h, &mut self.up, &mut self.scr)?; + prep(dp, emu, &mut self.q8, &mut self.h)?; + mv( + dp, + &layer.w_gate, + &self.h, + &self.q8, + &mut self.gate, + &mut self.scr, + )?; + mv( + dp, + &layer.w_up, + &self.h, + &self.q8, + &mut self.up, + &mut self.scr, + )?; for (g, u) in self.gate.iter_mut().zip(&self.up) { *g = *g / (1.0 + math::exp(-*g)) * u; } - if self.emulate_q8k { - q8k_round(&mut self.gate); - } - layer - .w_down - .matvec(&self.gate, &mut self.tmp[..e], &mut self.scr)?; + prep(dp, emu, &mut self.q8, &mut self.gate)?; + mv( + dp, + &layer.w_down, + &self.gate, + &self.q8, + &mut self.tmp[..e], + &mut self.scr, + )?; for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) { *x += d; } @@ -237,10 +276,15 @@ impl DecodeState { self.pos += 1; if want_logits { rms_norm(&self.x, &m.output_norm, eps, &mut self.h); - if self.emulate_q8k { - q8k_round(&mut self.h); - } - m.output.matvec(&self.h, &mut self.logits, &mut self.scr)?; + prep(dp, emu, &mut self.q8, &mut self.h)?; + mv( + dp, + &m.output, + &self.h, + &self.q8, + &mut self.logits, + &mut self.scr, + )?; } Ok(()) } @@ -254,6 +298,34 @@ impl DecodeState { } } +/// Prepare an activation vector for the quantized matvecs that follow: the +/// SDOT path quantizes it into `q8`; otherwise the optional Q8_K rounding +/// emulation rounds it in place. +fn prep(dp: Option<DotProd>, emu: bool, q8: &mut Q8Act, x: &mut [f32]) -> Result<(), InferError> { + if dp.is_some() { + q8.quantize(x)?; + } else if emu { + q8k_round(x); + } + Ok(()) +} + +/// One matvec: SDOT on `q8` for K-quant weights when `dp` is set, else the +/// scalar f32 path on `x`. +fn mv( + dp: Option<DotProd>, + w: &Weight<'_>, + x: &[f32], + q8: &Q8Act, + out: &mut [f32], + scr: &mut [f32], +) -> Result<(), InferError> { + match dp { + Some(t) if w.is_kquant() => w.matvec_q8(t, q8, out), + _ => w.matvec(x, out, scr), + } +} + /// Index of the largest logit (first on ties, like llama.cpp's greedy). pub fn argmax(logits: &[f32]) -> u32 { let mut best = 0usize; diff --git a/crates/aienos-infer/src/dotprod.rs b/crates/aienos-infer/src/dotprod.rs new file mode 100644 index 00000000..ee25977e --- /dev/null +++ b/crates/aienos-infer/src/dotprod.rs @@ -0,0 +1,777 @@ +//! Quantized dot products on int8 activations with Armv8.2 dot product +//! (SDOT), for Cortex-A76 class cores (Raspberry Pi 5) and anything newer. +//! +//! Method (the one llama.cpp uses for K-quants, `ggml_vec_dot_q4_K_q8_K` and +//! `ggml_vec_dot_q6_K_q8_K`, ggml-cpu/arch/arm/quants.c at 4a89937: Q4_K body +//! lines 2789-2840, Q6_K body lines 3492-3560; `vdotq_s32` is +//! `ggml_vdotq_s32`, ggml-cpu-impl.h:319): the activation vector is quantized +//! once per 256-wide block to int8 ("Q8_K": scale `d = max/-127`, rounding to +//! nearest even, plus 16 group sums), the 4-bit/6-bit weights are unpacked to +//! bytes with and/shift/or, `sdot` multiplies 16 byte pairs into 4 i32 lanes, +//! and the per-sub-block scales are applied in integer arithmetic. Only the +//! block scale and min scale are floats. +//! +//! Selection is a typed capability: a [`DotProd`] token exists only when the +//! caller said the CPU has dotprod (the kernel passes the decode of +//! `ID_AA64ISAR0_EL1.DP`, never assumed here). Every SDOT function checks +//! nothing itself; it is only reachable with a token. Without the token the +//! scalar f32 path in `quant.rs` runs, unchanged. On non-aarch64 targets no +//! token can be made and the portable integer reference below is the only +//! implementation (it is also what the tests compare the SDOT code with). +//! +//! No libm, no allocation in the dot path; `Q8Act` is sized once. + +use alloc::vec; +use alloc::vec::Vec; +use core::sync::atomic::{AtomicBool, Ordering}; + +use crate::gguf::GgmlType; +use crate::half::f16_to_f32; +use crate::quant::{scale_min_k4, QuantError, Q4K_BYTES, Q6K_BYTES, QK_K}; + +/// Proof that the CPU running this code has the Armv8.2 dot product +/// instructions. Made only by [`DotProd::new`] from a feature flag. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DotProd(()); + +impl DotProd { + /// `Some` when `cpu_has_dotprod` is true and this build targets aarch64. + pub fn new(cpu_has_dotprod: bool) -> Option<Self> { + if cfg!(target_arch = "aarch64") && cpu_has_dotprod { + Some(Self(())) + } else { + None + } + } +} + +static CPU_DOTPROD: AtomicBool = AtomicBool::new(false); + +/// Record the CPU's dotprod feature (the kernel calls this once at boot from +/// its feature decode). New `DecodeState`s pick it up. Default: off. +pub fn set_cpu_dotprod(on: bool) { + CPU_DOTPROD.store(on, Ordering::Relaxed); +} + +/// The recorded capability, if any. +pub fn cpu_dotprod() -> Option<DotProd> { + DotProd::new(CPU_DOTPROD.load(Ordering::Relaxed)) +} + +/// Activations quantized to ggml's Q8_K blocks, preallocated. +pub struct Q8Act { + qs: Vec<i8>, + d: Vec<f32>, + bsums: Vec<i16>, + nblk: usize, +} + +impl Q8Act { + /// Room for vectors of up to `cols` values (rounded up to whole blocks). + pub fn with_capacity(cols: usize) -> Self { + let nb = cols.div_ceil(QK_K); + Self { + qs: vec![0; nb * QK_K], + d: vec![0.0; nb], + bsums: vec![0; nb * 16], + nblk: 0, + } + } + + /// Quantize `x` (length a multiple of 256, at most the capacity). Same + /// arithmetic as ggml `quantize_row_q8_K_ref`: the element of largest + /// magnitude (first on ties) maps to -127, `d = 1/iscale`, round to + /// nearest even, clamp at 127. + pub fn quantize(&mut self, x: &[f32]) -> Result<(), QuantError> { + if x.len() % QK_K != 0 || x.len() / QK_K > self.d.len() { + return Err(QuantError::BadLength); + } + self.nblk = x.len() / QK_K; + for (i, blk) in x.chunks_exact(QK_K).enumerate() { + let qs = &mut self.qs[i * QK_K..(i + 1) * QK_K]; + let bs = &mut self.bsums[i * 16..(i + 1) * 16]; + let mut amax = 0f32; + let mut max = 0f32; + for &v in blk { + if v.abs() > amax { + amax = v.abs(); + max = v; + } + } + if amax == 0.0 { + self.d[i] = 0.0; + qs.fill(0); + bs.fill(0); + continue; + } + let iscale = -127.0 / max; + for (q, &v) in qs.iter_mut().zip(blk) { + let t = v * iscale; + // nearest_int: magic-number rounding (ties to even), as ggml. + *q = (((t + 12_582_912.0) - 12_582_912.0).min(127.0)) as i8; + } + for (g, s) in bs.iter_mut().enumerate() { + *s = qs[16 * g..16 * g + 16].iter().map(|&q| q as i16).sum(); + } + self.d[i] = 1.0 / iscale; + } + Ok(()) + } + + /// Number of 256-blocks in the last quantized vector. + pub fn blocks(&self) -> usize { + self.nblk + } + + /// Dequantized value `q * d` (what the dot actually sees); for tests. + pub fn value(&self, i: usize) -> f32 { + self.qs[i] as f32 * self.d[i / QK_K] + } + + fn block(&self, i: usize) -> Q8Blk<'_> { + Q8Blk { + d: self.d[i], + qs: self.qs[i * QK_K..(i + 1) * QK_K].try_into().expect("QK_K"), + bsums: self.bsums[i * 16..(i + 1) * 16].try_into().expect("16"), + } + } +} + +#[derive(Clone, Copy)] +struct Q8Blk<'a> { + d: f32, + qs: &'a [i8; QK_K], + bsums: &'a [i16; 16], +} + +fn rd_f16(b: &[u8], at: usize) -> f32 { + f16_to_f32(u16::from_le_bytes([b[at], b[at + 1]])) +} + +/// Unpack the eight 6-bit scales and mins of a Q4_K block. +fn q4k_scales(blk: &[u8; Q4K_BYTES]) -> ([u8; 8], [u8; 8]) { + let (mut sc, mut mn) = ([0u8; 8], [0u8; 8]); + for j in 0..8 { + let (s, m) = scale_min_k4(j, &blk[4..16]); + sc[j] = s; + mn[j] = m; + } + (sc, mn) +} + +/// Portable integer reference for one Q4_K block: `(sumi, sumi_mins)` where +/// `sumi = sum_sb scale[sb] * sum_{l in sb} nibble * q8` and +/// `sumi_mins = sum_sb min[sb] * sum_{l in sb} q8`. +fn q4k_accum_ref(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { + let (sc, mn) = q4k_scales(blk); + let qs = &blk[16..144]; + let (mut sumi, mut mins) = (0i32, 0i32); + for j in 0..4 { + let (mut lo, mut hi) = (0i32, 0i32); + for l in 0..32 { + let b = qs[32 * j + l]; + lo += (b & 0x0f) as i32 * y.qs[64 * j + l] as i32; + hi += (b >> 4) as i32 * y.qs[64 * j + 32 + l] as i32; + } + sumi += lo * sc[2 * j] as i32 + hi * sc[2 * j + 1] as i32; + } + for sb in 0..8 { + mins += mn[sb] as i32 * (y.bsums[2 * sb] as i32 + y.bsums[2 * sb + 1] as i32); + } + (sumi, mins) +} + +/// Portable integer reference for one Q6_K block: `(isum, isum_mins)`; the +/// weight is `d * scale * (q - 32)`, so the block dot is +/// `isum - 32 * isum_mins` with `isum_mins = sum_g scale[g] * bsum[g]`. +fn q6k_accum_ref(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { + let sc = &blk[192..208]; + let mut isum = 0i32; + for half in 0..2 { + let ql = &blk[64 * half..64 * half + 64]; + let qh = &blk[128 + 32 * half..128 + 32 * half + 32]; + let yy = &y.qs[128 * half..128 * half + 128]; + for l in 0..32 { + let is = l / 16; + let h = qh[l]; + let q1 = ((ql[l] & 0x0f) | ((h & 3) << 4)) as i32; + let q2 = ((ql[l + 32] & 0x0f) | (((h >> 2) & 3) << 4)) as i32; + let q3 = ((ql[l] >> 4) | (((h >> 4) & 3) << 4)) as i32; + let q4 = ((ql[l + 32] >> 4) | (((h >> 6) & 3) << 4)) as i32; + let s = |k: usize| sc[8 * half + is + k] as i8 as i32; + isum += q1 * yy[l] as i32 * s(0) + + q2 * yy[l + 32] as i32 * s(2) + + q3 * yy[l + 64] as i32 * s(4) + + q4 * yy[l + 96] as i32 * s(6); + } + } + let mut mins = 0i32; + for g in 0..16 { + mins += sc[g] as i8 as i32 * y.bsums[g] as i32; + } + (isum, mins) +} + +fn q4k_finish(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>, acc: (i32, i32)) -> f32 { + let d = y.d * rd_f16(blk, 0); + let dmin = y.d * rd_f16(blk, 2); + d * acc.0 as f32 - dmin * acc.1 as f32 +} + +fn q6k_finish(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>, acc: (i32, i32)) -> f32 { + rd_f16(blk, 208) * y.d * (acc.0 - 32 * acc.1) as f32 +} + +/// Block dot with the portable integer arithmetic (reference for the tests; +/// also the only path on non-aarch64). +pub fn dot_q4k_q8_ref(blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> f32 { + let y = q8.block(bi); + q4k_finish(blk, &y, q4k_accum_ref(blk, &y)) +} + +/// Same for Q6_K. +pub fn dot_q6k_q8_ref(blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> f32 { + let y = q8.block(bi); + q6k_finish(blk, &y, q6k_accum_ref(blk, &y)) +} + +#[cfg(target_arch = "aarch64")] +mod neon { + use super::*; + use core::arch::aarch64::*; + + /// # Safety + /// CPU must implement FEAT_DotProd (guaranteed by holding a [`DotProd`]). + #[inline] + #[target_feature(enable = "dotprod")] + pub unsafe fn q4k_accum(blk: &[u8; Q4K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { + let (sc, mn) = q4k_scales(blk); + let m4 = vdupq_n_u8(0x0f); + let qp = blk.as_ptr().add(16); + let yp = y.qs.as_ptr(); + let mut sumv = vdupq_n_s32(0); + let zero = vdupq_n_s32(0); + for j in 0..4 { + let a0 = vld1q_u8(qp.add(32 * j)); + let a1 = vld1q_u8(qp.add(32 * j + 16)); + let y0 = vld1q_s8(yp.add(64 * j)); + let y1 = vld1q_s8(yp.add(64 * j + 16)); + let y2 = vld1q_s8(yp.add(64 * j + 32)); + let y3 = vld1q_s8(yp.add(64 * j + 48)); + let lo = vdotq_s32( + vdotq_s32(zero, vreinterpretq_s8_u8(vandq_u8(a0, m4)), y0), + vreinterpretq_s8_u8(vandq_u8(a1, m4)), + y1, + ); + let hi = vdotq_s32( + vdotq_s32(zero, vreinterpretq_s8_u8(vshrq_n_u8::<4>(a0)), y2), + vreinterpretq_s8_u8(vshrq_n_u8::<4>(a1)), + y3, + ); + sumv = vmlaq_n_s32(sumv, lo, sc[2 * j] as i32); + sumv = vmlaq_n_s32(sumv, hi, sc[2 * j + 1] as i32); + } + let mut mins = 0i32; + for sb in 0..8 { + mins += mn[sb] as i32 * (y.bsums[2 * sb] as i32 + y.bsums[2 * sb + 1] as i32); + } + (vaddvq_s32(sumv), mins) + } + + /// # Safety + /// As [`q4k_accum`]. + #[inline] + #[target_feature(enable = "dotprod")] + pub unsafe fn q6k_accum(blk: &[u8; Q6K_BYTES], y: &Q8Blk<'_>) -> (i32, i32) { + let m4 = vdupq_n_u8(0x0f); + let m3 = vdupq_n_u8(0x03); + let zero = vdupq_n_s32(0); + let sc = &blk[192..208]; + let mut isum = 0i32; + for half in 0..2 { + let ql = blk.as_ptr().add(64 * half); + let qh = blk.as_ptr().add(128 + 32 * half); + let yp = y.qs.as_ptr().add(128 * half); + let s = &sc[8 * half..8 * half + 8]; + let (qh0, qh1) = (vld1q_u8(qh), vld1q_u8(qh.add(16))); + let (l0, l1, l2, l3) = ( + vld1q_u8(ql), + vld1q_u8(ql.add(16)), + vld1q_u8(ql.add(32)), + vld1q_u8(ql.add(48)), + ); + // low nibbles, qh bit pairs 0 and 1 + let h0 = vshlq_n_u8::<4>(vandq_u8(qh0, m3)); + let h1 = vshlq_n_u8::<4>(vandq_u8(qh1, m3)); + let h2 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<2>(qh0), m3)); + let h3 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<2>(qh1), m3)); + let b = [ + vorrq_u8(vandq_u8(l0, m4), h0), + vorrq_u8(vandq_u8(l1, m4), h1), + vorrq_u8(vandq_u8(l2, m4), h2), + vorrq_u8(vandq_u8(l3, m4), h3), + ]; + for k in 0..4 { + let p = vdotq_s32(zero, vreinterpretq_s8_u8(b[k]), vld1q_s8(yp.add(16 * k))); + isum += vaddvq_s32(p) * s[k] as i8 as i32; + } + // high nibbles, qh bit pairs 2 and 3 + let h0 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<4>(qh0), m3)); + let h1 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<4>(qh1), m3)); + let h2 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<6>(qh0), m3)); + let h3 = vshlq_n_u8::<4>(vandq_u8(vshrq_n_u8::<6>(qh1), m3)); + let b = [ + vorrq_u8(vshrq_n_u8::<4>(l0), h0), + vorrq_u8(vshrq_n_u8::<4>(l1), h1), + vorrq_u8(vshrq_n_u8::<4>(l2), h2), + vorrq_u8(vshrq_n_u8::<4>(l3), h3), + ]; + for k in 0..4 { + let p = vdotq_s32( + zero, + vreinterpretq_s8_u8(b[k]), + vld1q_s8(yp.add(64 + 16 * k)), + ); + isum += vaddvq_s32(p) * s[4 + k] as i8 as i32; + } + } + let mut mins = 0i32; + for g in 0..16 { + mins += sc[g] as i8 as i32 * y.bsums[g] as i32; + } + (isum, mins) + } + + /// # Safety + /// As [`q4k_accum`]; `src` is whole Q4_K blocks and `q8` has the same count. + #[target_feature(enable = "dotprod")] + pub unsafe fn row_q4k(src: &[u8], q8: &Q8Act) -> f32 { + let mut acc = 0f32; + for (i, b) in src.chunks_exact(Q4K_BYTES).enumerate() { + let blk: &[u8; Q4K_BYTES] = b.try_into().expect("Q4K_BYTES"); + let y = q8.block(i); + acc += q4k_finish(blk, &y, q4k_accum(blk, &y)); + } + acc + } + + /// # Safety + /// As [`row_q4k`] for Q6_K. + #[target_feature(enable = "dotprod")] + pub unsafe fn row_q6k(src: &[u8], q8: &Q8Act) -> f32 { + let mut acc = 0f32; + for (i, b) in src.chunks_exact(Q6K_BYTES).enumerate() { + let blk: &[u8; Q6K_BYTES] = b.try_into().expect("Q6K_BYTES"); + let y = q8.block(i); + acc += q6k_finish(blk, &y, q6k_accum(blk, &y)); + } + acc + } +} + +/// SDOT block dot (Q4_K); test and bench hook, needs the capability token. +#[cfg(target_arch = "aarch64")] +pub fn dot_q4k_q8_sdot(_t: DotProd, blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> f32 { + let y = q8.block(bi); + // SAFETY: the token proves FEAT_DotProd. + unsafe { q4k_finish(blk, &y, neon::q4k_accum(blk, &y)) } +} + +/// SDOT block dot (Q6_K). +#[cfg(target_arch = "aarch64")] +pub fn dot_q6k_q8_sdot(_t: DotProd, blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> f32 { + let y = q8.block(bi); + // SAFETY: the token proves FEAT_DotProd. + unsafe { q6k_finish(blk, &y, neon::q6k_accum(blk, &y)) } +} + +/// Integer accumulations `(sum, mins)` of the SDOT block code; tests compare +/// them bit for bit with the portable reference. +#[cfg(target_arch = "aarch64")] +pub fn q4k_accum_sdot(_t: DotProd, blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { + let y = q8.block(bi); + // SAFETY: the token proves FEAT_DotProd. + unsafe { neon::q4k_accum(blk, &y) } +} + +/// As [`q4k_accum_sdot`] for Q6_K. +#[cfg(target_arch = "aarch64")] +pub fn q6k_accum_sdot(_t: DotProd, blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { + let y = q8.block(bi); + // SAFETY: the token proves FEAT_DotProd. + unsafe { neon::q6k_accum(blk, &y) } +} + +/// Portable accumulations (reference) for the tests. +pub fn q4k_accum_portable(blk: &[u8; Q4K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { + q4k_accum_ref(blk, &q8.block(bi)) +} + +/// As [`q4k_accum_portable`] for Q6_K. +pub fn q6k_accum_portable(blk: &[u8; Q6K_BYTES], q8: &Q8Act, bi: usize) -> (i32, i32) { + q6k_accum_ref(blk, &q8.block(bi)) +} + +/// Dot of a whole quantized row with the quantized activations, using SDOT. +pub fn dot_row_q8(_t: DotProd, ty: GgmlType, src: &[u8], q8: &Q8Act) -> Result<f32, QuantError> { + let (bw, bb) = ty.block(); + if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) { + return Err(QuantError::Unsupported(ty)); + } + if src.len() % bb != 0 || src.len() / bb != q8.blocks() || bw != QK_K { + return Err(QuantError::BadLength); + } + #[cfg(target_arch = "aarch64")] + { + // SAFETY: the token proves FEAT_DotProd; lengths checked above. + Ok(unsafe { + if ty == GgmlType::Q4K { + neon::row_q4k(src, q8) + } else { + neon::row_q6k(src, q8) + } + }) + } + #[cfg(not(target_arch = "aarch64"))] + { + let mut acc = 0f32; + for (i, b) in src.chunks_exact(bb).enumerate() { + acc += if ty == GgmlType::Q4K { + dot_q4k_q8_ref(b.try_into().expect("Q4K_BYTES"), q8, i) + } else { + dot_q6k_q8_ref(b.try_into().expect("Q6K_BYTES"), q8, i) + }; + } + Ok(acc) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decode::q8k_round; + use crate::quant::{dequant_q4k_block, dequant_q6k_block, dot_row}; + #[cfg(target_arch = "aarch64")] + use std::eprintln; + use std::vec::Vec; + + /// xorshift64*, fixed seeds. + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn byte(&mut self) -> u8 { + (self.next() >> 32) as u8 + } + fn unit(&mut self) -> f32 { + ((self.next() >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 + } + } + + fn token() -> Option<DotProd> { + #[cfg(target_arch = "aarch64")] + { + DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")) + } + #[cfg(not(target_arch = "aarch64"))] + { + None + } + } + + fn f16(v: f32) -> [u8; 2] { + // exact for the values used here (small integers and halves) + let bits = v.to_bits(); + if v == 0.0 { + return [0, 0]; + } + let sign = ((bits >> 16) & 0x8000) as u16; + let e = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let m = ((bits >> 13) & 0x3ff) as u16; + (sign | ((e as u16) << 10) | m).to_le_bytes() + } + + #[derive(Clone, Copy)] + enum Fill { + Random, + MaxScales, + ZeroScales, + AllOnes, + AllZero, + } + + fn q4k_block(r: &mut Rng, fill: Fill) -> [u8; Q4K_BYTES] { + let mut b = [0u8; Q4K_BYTES]; + for x in b.iter_mut() { + *x = r.byte(); + } + match fill { + Fill::Random => {} + Fill::MaxScales => b[4..16].fill(0xff), // all scales and mins = 63 + Fill::ZeroScales => b[4..16].fill(0), + Fill::AllOnes => { + b[4..].fill(0xff); + } + Fill::AllZero => b[4..].fill(0), + } + b[0..2].copy_from_slice(&f16(0.0625 * (1 + r.byte() % 8) as f32)); + b[2..4].copy_from_slice(&f16(0.03125 * (1 + r.byte() % 8) as f32)); + b + } + + fn q6k_block(r: &mut Rng, fill: Fill) -> [u8; Q6K_BYTES] { + let mut b = [0u8; Q6K_BYTES]; + for x in b.iter_mut() { + *x = r.byte(); + } + match fill { + Fill::Random => {} + Fill::MaxScales => { + for (i, s) in b[192..208].iter_mut().enumerate() { + *s = if i % 2 == 0 { 127 } else { 0x80 }; // +127 and -128 + } + } + Fill::ZeroScales => b[192..208].fill(0), + Fill::AllOnes => b[..192].fill(0xff), + Fill::AllZero => b[..192].fill(0), + } + b[208..210].copy_from_slice(&f16(0.0625 * (1 + r.byte() % 8) as f32)); + b + } + + fn acts(r: &mut Rng, nblk: usize, kind: u8) -> (Vec<f32>, Q8Act) { + let mut x = std::vec![0f32; nblk * QK_K]; + for (i, v) in x.iter_mut().enumerate() { + *v = match kind { + 0 => r.unit() * 3.0, + 1 => 1.0, // all equal: every q = -127 + 2 => { + if i % 2 == 0 { + 100.0 + } else { + -100.0 + } + } // extremes of both signs + _ => 0.0, + }; + } + let mut q = Q8Act::with_capacity(x.len()); + q.quantize(&x).unwrap(); + (x, q) + } + + #[test] + fn quantize_matches_q8k_round_and_sums() { + let mut r = Rng(0x1234_5678_9abc_def1); + let (x, q) = acts(&mut r, 6, 0); + let mut want = x.clone(); + q8k_round(&mut want); + for i in 0..x.len() { + assert_eq!(q.value(i).to_bits(), want[i].to_bits(), "elem {i}"); + } + for b in 0..6 { + for g in 0..16 { + let s: i32 = (0..16).map(|l| q.qs[b * QK_K + 16 * g + l] as i32).sum(); + assert_eq!(q.bsums[b * 16 + g] as i32, s); + } + let m = q.qs[b * QK_K..(b + 1) * QK_K] + .iter() + .map(|&v| (v as i32).abs()) + .max(); + assert_eq!(m, Some(127)); + } + // all-zero block: scale 0, all zero + let (_, z) = acts(&mut r, 2, 3); + assert!(z.d[..2].iter().all(|&d| d == 0.0) && z.qs.iter().all(|&v| v == 0)); + // length rules + let mut q = Q8Act::with_capacity(256); + assert_eq!(q.quantize(&[0.0; 100]), Err(QuantError::BadLength)); + assert_eq!(q.quantize(&[0.0; 512]), Err(QuantError::BadLength)); + } + + /// Dot of the dequantized weights with the dequantized (rounded) + /// activations in f32: what the integer path must reproduce up to float + /// summation order and the f16-scaled products. + fn f32_reference(w: &[f32; QK_K], q: &Q8Act, bi: usize) -> (f32, f32) { + let mut dot = 0f64; + let mut mag = 0f64; + for l in 0..QK_K { + let t = w[l] as f64 * q.value(bi * QK_K + l) as f64; + dot += t; + mag += t.abs(); + } + (dot as f32, mag as f32) + } + + const FILLS: [Fill; 5] = [ + Fill::Random, + Fill::MaxScales, + Fill::ZeroScales, + Fill::AllOnes, + Fill::AllZero, + ]; + + #[test] + fn q4k_integer_dot_equals_f32_dot_of_rounded_activations() { + let mut r = Rng(0xdead_beef_0001); + for n in 0..400 { + let blk = q4k_block(&mut r, FILLS[n % 5]); + let (_, q) = acts(&mut r, 1, (n % 4) as u8); + let mut w = [0f32; QK_K]; + dequant_q4k_block(&blk, &mut w); + let (want, mag) = f32_reference(&w, &q, 0); + let got = dot_q4k_q8_ref(&blk, &q, 0); + assert!( + (got - want).abs() <= 2e-5 * mag.max(1e-3), + "n {n}: {got} vs {want}" + ); + } + } + + #[test] + fn q6k_integer_dot_equals_f32_dot_of_rounded_activations() { + let mut r = Rng(0xdead_beef_0002); + for n in 0..400 { + let blk = q6k_block(&mut r, FILLS[n % 5]); + let (_, q) = acts(&mut r, 1, (n % 4) as u8); + let mut w = [0f32; QK_K]; + dequant_q6k_block(&blk, &mut w); + let (want, mag) = f32_reference(&w, &q, 0); + let got = dot_q6k_q8_ref(&blk, &q, 0); + assert!( + (got - want).abs() <= 2e-5 * mag.max(1e-3), + "n {n}: {got} vs {want}" + ); + } + } + + #[test] + #[cfg(target_arch = "aarch64")] + fn sdot_accumulations_are_bit_exact_vs_portable_q4k() { + let Some(t) = token() else { + eprintln!("SKIP: no dotprod on this CPU or not aarch64"); + return; + }; + let mut r = Rng(0x5eed_0004); + for n in 0..2000 { + let blk = q4k_block(&mut r, FILLS[n % 5]); + let (_, q) = acts(&mut r, 1, (n % 4) as u8); + #[cfg(target_arch = "aarch64")] + { + assert_eq!( + q4k_accum_sdot(t, &blk, &q, 0), + q4k_accum_portable(&blk, &q, 0), + "n {n}" + ); + assert_eq!( + dot_q4k_q8_sdot(t, &blk, &q, 0).to_bits(), + dot_q4k_q8_ref(&blk, &q, 0).to_bits() + ); + } + let _ = t; + } + } + + #[test] + #[cfg(target_arch = "aarch64")] + fn sdot_accumulations_are_bit_exact_vs_portable_q6k() { + let Some(t) = token() else { + eprintln!("SKIP: no dotprod on this CPU or not aarch64"); + return; + }; + let mut r = Rng(0x5eed_0006); + for n in 0..2000 { + let blk = q6k_block(&mut r, FILLS[n % 5]); + let (_, q) = acts(&mut r, 1, (n % 4) as u8); + #[cfg(target_arch = "aarch64")] + { + assert_eq!( + q6k_accum_sdot(t, &blk, &q, 0), + q6k_accum_portable(&blk, &q, 0), + "n {n}" + ); + assert_eq!( + dot_q6k_q8_sdot(t, &blk, &q, 0).to_bits(), + dot_q6k_q8_ref(&blk, &q, 0).to_bits() + ); + } + let _ = t; + } + } + + /// Hand-computed block (no random data): Q4_K, d=1, dmin=1, scale of + /// sub-block j is j+1, min j, all nibbles 3, activations all equal so + /// every q8 is -127 and d_y = 1/(-127/1) = -1/127. + #[test] + fn q4k_hand_computed_scale_application() { + let mut b = [0u8; Q4K_BYTES]; + b[0..2].copy_from_slice(&f16(1.0)); + b[2..4].copy_from_slice(&f16(1.0)); + for j in 0..4 { + b[4 + j] = (j + 1) as u8; + b[8 + j] = j as u8; + } + for j in 4..8 { + b[8 + j] = ((j + 1) as u8) | ((j as u8) << 4); + } + b[16..].fill(0x33); + let x = [1.0f32; QK_K]; + let mut q = Q8Act::with_capacity(QK_K); + q.quantize(&x).unwrap(); + // sumi = sum_sb scale*3*32*(-127); sumi_mins = sum_sb min*32*(-127) + let sumi: i32 = (1..=8).map(|s| s * 3 * 32 * -127).sum(); + let mins: i32 = (0..8).map(|m| m * 32 * -127).sum(); + assert_eq!(q4k_accum_portable(&b, &q, 0), (sumi, mins)); + let dy = 1.0f32 / (-127.0f32 / 1.0); + let want = dy * sumi as f32 - dy * mins as f32; + assert_eq!(dot_q4k_q8_ref(&b, &q, 0), want); + // the true f32 dot is sum(scale*3 - min) over 32 values each + let truth: f32 = (0..8).map(|s| ((s + 1) * 3 - s) as f32 * 32.0).sum(); + assert!((want - truth).abs() < 1e-3, "{want} vs {truth}"); + #[cfg(target_arch = "aarch64")] + if let Some(t) = token() { + assert_eq!(dot_q4k_q8_sdot(t, &b, &q, 0), want); + } + } + + #[test] + fn row_dot_matches_scalar_path_and_checks_lengths() { + let mut r = Rng(0x7007); + let nb = 9; + let mut src4 = Vec::new(); + let mut src6 = Vec::new(); + for n in 0..nb { + src4.extend_from_slice(&q4k_block(&mut r, FILLS[n % 5])); + src6.extend_from_slice(&q6k_block(&mut r, FILLS[n % 5])); + } + let (x, q) = acts(&mut r, nb, 0); + let mut xr = x.clone(); + q8k_round(&mut xr); + let Some(t) = token() else { + // portable reference still agrees with the scalar f32 row dot + return; + }; + for (ty, src) in [(GgmlType::Q4K, &src4), (GgmlType::Q6K, &src6)] { + let got = dot_row_q8(t, ty, src, &q).unwrap(); + let want = dot_row(ty, src, &xr).unwrap(); + let mag: f32 = xr.iter().map(|v| v.abs()).sum::<f32>() * 60.0; + assert!((got - want).abs() <= 1e-4 * mag, "{ty:?}: {got} vs {want}"); + assert_eq!(dot_row_q8(t, ty, &src[1..], &q), Err(QuantError::BadLength)); + } + assert_eq!( + dot_row_q8(t, GgmlType::F32, &src4, &q), + Err(QuantError::Unsupported(GgmlType::F32)) + ); + } + + #[test] + fn token_only_when_flag_set() { + assert_eq!(DotProd::new(false), None); + set_cpu_dotprod(false); + assert_eq!(cpu_dotprod(), None); + } +} diff --git a/crates/aienos-infer/src/lib.rs b/crates/aienos-infer/src/lib.rs index 1217992c..8d7253bb 100644 --- a/crates/aienos-infer/src/lib.rs +++ b/crates/aienos-infer/src/lib.rs @@ -1,5 +1,5 @@ #![no_std] -#![forbid(unsafe_code)] +#![deny(unsafe_code)] // Block loops mirror ggml index arithmetic; as_chunks/is_multiple_of are too // new for this workspace to rely on. #![allow( @@ -21,6 +21,8 @@ extern crate alloc; extern crate std; pub mod decode; +#[allow(unsafe_code)] // the only unsafe in this crate: SDOT intrinsics behind a capability token +pub mod dotprod; pub mod gguf; pub mod half; pub mod math; @@ -29,6 +31,7 @@ pub mod quant; pub mod tokenizer; pub use decode::{argmax, generate_greedy, DecodeState}; +pub use dotprod::{cpu_dotprod, set_cpu_dotprod, DotProd, Q8Act}; pub use gguf::{ArrayView, GgmlType, Gguf, GgufError, TensorInfo, Value, ValueType}; pub use model::{InferError, Model}; pub use tokenizer::Tokenizer; diff --git a/crates/aienos-infer/src/model.rs b/crates/aienos-infer/src/model.rs index 8c7dc8fe..6d2fe024 100644 --- a/crates/aienos-infer/src/model.rs +++ b/crates/aienos-infer/src/model.rs @@ -9,6 +9,7 @@ use alloc::string::String; use alloc::vec; use alloc::vec::Vec; +use crate::dotprod::{self, DotProd, Q8Act}; use crate::gguf::{plain_to_f32, GgmlType, Gguf, GgufError, LlamaParams}; use crate::quant::{self, QuantError}; @@ -119,6 +120,24 @@ impl<'a> Weight<'a> { } Ok(()) } + + /// True for the K-quant types the SDOT path handles. + pub fn is_kquant(&self) -> bool { + matches!(self.ty, GgmlType::Q4K | GgmlType::Q6K) + } + + /// `out[r] = row_r . x` on int8 activations with SDOT (K-quant weights + /// only; `q8` holds the quantized `x`). The capability token proves the + /// CPU has dotprod. + pub fn matvec_q8(&self, t: DotProd, q8: &Q8Act, out: &mut [f32]) -> Result<(), InferError> { + if !self.is_kquant() || out.len() != self.rows || q8.blocks() * 256 != self.cols { + return Err(InferError::BadParams("matvec_q8 shape")); + } + for (r, o) in out.iter_mut().enumerate() { + *o = dotprod::dot_row_q8(t, self.ty, self.row(r), q8)?; + } + Ok(()) + } } /// One transformer block's tensors. diff --git a/crates/aienos-infer/src/quant.rs b/crates/aienos-infer/src/quant.rs index 1f453d2c..3251cff6 100644 --- a/crates/aienos-infer/src/quant.rs +++ b/crates/aienos-infer/src/quant.rs @@ -27,7 +27,7 @@ fn rd_f16(b: &[u8], at: usize) -> f32 { } /// 6-bit scale and min for sub-block `j` (0..8) from the 12 packed bytes. -fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) { +pub(crate) fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) { if j < 4 { (q[j] & 63, q[j + 4] & 63) } else { diff --git a/crates/aienos-infer/tests/forward.rs b/crates/aienos-infer/tests/forward.rs index 156ad863..14cddaad 100644 --- a/crates/aienos-infer/tests/forward.rs +++ b/crates/aienos-infer/tests/forward.rs @@ -8,7 +8,7 @@ //! model file (`AIENOS_MODEL`, default `~/models/aien-mail/ //! Llama-3.2-1B-Instruct-Q4_K_M.gguf`) and print SKIPPED when it is absent. -use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer}; +use aienos_infer::{argmax, DecodeState, DotProd, Gguf, Model, Tokenizer}; use std::time::Instant; fn model_bytes() -> Option<Vec<u8>> { @@ -91,7 +91,12 @@ fn decode_round_trips_text() { } } -fn check(q8k: bool, max_logit_diff: f32) { +fn check(q8k: bool, dot: bool, max_logit_diff: f32) { + let dp = if dot { host_dotprod() } else { None }; + if dot && dp.is_none() { + eprintln!("SKIPPED: this CPU has no dotprod"); + return; + } let Some(bytes) = model_bytes() else { return }; let g = Gguf::parse(&bytes).unwrap(); let m = Model::new(&g).unwrap(); @@ -104,6 +109,7 @@ fn check(q8k: bool, max_logit_diff: f32) { // (c) free-running greedy let mut st = DecodeState::new(&m, 256); st.emulate_q8k = q8k; + st.dotprod = dp; let t0 = Instant::now(); st.prefill(&m, &ids).unwrap(); if name == "cow" { @@ -177,6 +183,7 @@ fn check(q8k: bool, max_logit_diff: f32) { // teacher-forced top-1 match rate let mut st = DecodeState::new(&m, 256); st.emulate_q8k = q8k; + st.dotprod = dp; st.prefill(&m, &ids).unwrap(); let mut hit = 0; for (i, &(t, gap)) in r.steps.iter().enumerate() { @@ -202,12 +209,31 @@ fn check(q8k: bool, max_logit_diff: f32) { /// small, bounded logit difference is expected). #[test] fn forward_matches_llama_cpp_f32_activations() { - check(false, 1.0); + check(false, false, 1.0); +} + +/// Runtime dotprod detection on the host (the kernel uses its own decode). +fn host_dotprod() -> Option<DotProd> { + #[cfg(target_arch = "aarch64")] + { + DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")) + } + #[cfg(not(target_arch = "aarch64"))] + { + None + } +} + +/// SDOT path: int8 Q8_K activations, integer dots (aienos#34 PI5-6). Same +/// bounds as the f32 and Q8_K-emulation tests. +#[test] +fn forward_matches_llama_cpp_dotprod() { + check(false, true, 1.0); } /// Activations rounded to ggml's Q8_K grid before every quantized dot. #[test] #[ignore = "slow; run with --ignored"] fn forward_matches_llama_cpp_q8k_emulation() { - check(true, 1.0); + check(true, false, 1.0); } diff --git a/native/.crumb b/native/.crumb index dcc5e6f2..2c806ff0 100644 --- a/native/.crumb +++ b/native/.crumb @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "8fabc55ffb5f66c05299aa5a7eb1f53a7944198f49358f9c032d5a89b9e6227b", - "last_commit": "4b74ebf", + "digest": "b82ed23dcdd3dffd17f7eb14e3c0ffef3a555ef87b7ae853ce2608bfd49f2cb7", + "last_commit": "e7de707", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:29c901c939f8e26a5f29c603af36860484117befeb833b656f25b69f299c9f08", - "compiled_at": "2026-10-13T15:00:51Z", + "children_root": "sha256:bc04e169e5fbea8687d587e936760a5daf31dbb43d11d9d9c99bb121e538ae8f", + "compiled_at": "2026-10-13T15:35:38Z", "compiler": "crumb-compile/1", - "digest": "sha256:36d90b1bdc1a7e33efc7d385e66c3301de434c889046cc6855725eabfceb31ff", + "digest": "sha256:9ae0942a460fa8108c8087cb4c7e30944198fa6e405816490aad5b37754b99f4", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", "files": 518, - "generated_at_commit": "4b74ebf18be00aa0ae3cf512ff1368f1590ddc8a", - "source_tree": "sha256:58f95fcaf10ffc25eb6cfdd4c6409d057a97c0bd4dc06980d4f6fe9a45db14e0" + "generated_at_commit": "e7de707d8b32e94e16bb88267b3844426fba6cc2", + "source_tree": "sha256:1a9615ff741b86dc16f7aa09c2d90f11f0dc4a691a6ab4e51f9a4c055ccf33be" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 1f606839..49d400b4 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -57,14 +57,14 @@ "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "59ed62d9cc65c8b4a4fd0a8abef018cc6fc05eba56ead699ad50ae25cbfd4e3a", - "last_commit": "e059bfe", + "digest": "daf8d6a0ed9f9c461cb237680425ccb6a151a669b96917b1d94d01ddd6abbd27", + "last_commit": "e7de707", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { "digest": "f860bfc274faf7b2ae08dbd4c51bf71f57825ed15725c35ae549c20cb01b9489", - "last_commit": "4b74ebf", + "last_commit": "72278a4", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, @@ -87,8 +87,8 @@ "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "06a5ce6933f29268a72b8617e288985f4335c21c90707a65179a45da070a69c6", - "last_commit": "4b74ebf", + "digest": "a292c04c07dffdabb96cd51efc5b51956246ce72d4c855db53e4183e999f879d", + "last_commit": "e7de707", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, @@ -99,15 +99,15 @@ "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:cfe8c1e7a598ec42431650dceabc0285b737d3f78a71b44192db2284d12ec30a", - "compiled_at": "2026-10-13T15:00:51Z", + "children_root": "sha256:25256d9d4ed73cca40a18ec219274e3b630e0c02091bb53bac4b8bd7b2184d8f", + "compiled_at": "2026-10-13T15:35:38Z", "compiler": "crumb-compile/1", - "digest": "sha256:8fabc55ffb5f66c05299aa5a7eb1f53a7944198f49358f9c032d5a89b9e6227b", + "digest": "sha256:b82ed23dcdd3dffd17f7eb14e3c0ffef3a555ef87b7ae853ce2608bfd49f2cb7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 341, - "generated_at_commit": "4b74ebf18be00aa0ae3cf512ff1368f1590ddc8a", - "source_tree": "sha256:a52fa5dc24c1eea59bbde95be175a7e7d1f4a63e5c970534ef542afbbaed2cef" + "generated_at_commit": "e7de707d8b32e94e16bb88267b3844426fba6cc2", + "source_tree": "sha256:02fb92bb55f28f964c8a6f2aa9687427c98e9b7ad84dbd053d679351b648ddab" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index d249cecb..07b47883 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-13T14:40:44Z", + "compiled_at": "2026-10-13T15:35:38Z", "compiler": "crumb-compile/1", - "digest": "sha256:59ed62d9cc65c8b4a4fd0a8abef018cc6fc05eba56ead699ad50ae25cbfd4e3a", + "digest": "sha256:daf8d6a0ed9f9c461cb237680425ccb6a151a669b96917b1d94d01ddd6abbd27", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 55, - "generated_at_commit": "1fd895aef29f2163f075e7b35bb13fa2c9389192", - "source_tree": "sha256:0671fcd1367c59c78e6d2b3b93bd05dff2a268aa4d2e5a8bcc24cc462b01c8d1" + "generated_at_commit": "e7de707d8b32e94e16bb88267b3844426fba6cc2", + "source_tree": "sha256:2ec59e1cb98a38dadbcc6da840dff70d61ca4267b1eb066c7c194e963262254d" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/cpufeat.c b/native/kernel/core/cpufeat.c index a720786f..566d25e8 100644 --- a/native/kernel/core/cpufeat.c +++ b/native/kernel/core/cpufeat.c @@ -30,3 +30,18 @@ int ck_cpufeat_format(const struct ck_cpu_features *f, char *buf, size_t n) return ck_snprintf(buf, n, "cpu_features: dotprod=%u i8mm=%u bf16=%u fhm=%u fp16=%u sve=%u rndr=%u", f->dotprod, f->i8mm, f->bf16, f->fhm, f->fp16, f->sve, f->rndr); } + +/* The boot core's decode, kept for consumers that select code by feature + * (core/infer.c passes dotprod to the Rust inference unit). All zero until + * kmain records it, so nothing is ever assumed present. */ +static struct ck_cpu_features g_boot_features; + +void ck_cpufeat_set_boot(const struct ck_cpu_features *f) +{ + g_boot_features = *f; +} + +const struct ck_cpu_features *ck_cpufeat_boot(void) +{ + return &g_boot_features; +} diff --git a/native/kernel/core/cpufeat.h b/native/kernel/core/cpufeat.h index 8ea5624c..c6831e71 100644 --- a/native/kernel/core/cpufeat.h +++ b/native/kernel/core/cpufeat.h @@ -23,5 +23,8 @@ struct ck_cpu_features { void ck_cpufeat_decode(uint64_t isar0, uint64_t isar1, uint64_t pfr0, struct ck_cpu_features *out); /* "cpu_features: dotprod=1 i8mm=0 bf16=0 fhm=1 fp16=1 sve=0 rndr=0" (no newline). */ int ck_cpufeat_format(const struct ck_cpu_features *f, char *buf, size_t n); +/* Record / read the boot core's decode (all zero until recorded). */ +void ck_cpufeat_set_boot(const struct ck_cpu_features *f); +const struct ck_cpu_features *ck_cpufeat_boot(void); #endif diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c index dec7ce4e..e8e69a6d 100644 --- a/native/kernel/core/infer.c +++ b/native/kernel/core/infer.c @@ -34,6 +34,7 @@ #include "arch.h" #include "ck_internal.h" +#include "cpufeat.h" #ifdef CK_INFER_PROBE #include "sha256.h" @@ -42,6 +43,20 @@ #endif extern void aienos_infer_heap_init(uintptr_t base, uintptr_t len); +/* crates/aienos-infer-kernel: record the CPU's dotprod feature (from the boot decode, + * core/cpufeat.c) and report whether the SDOT matvec path is then selected. */ +extern void aienos_infer_set_cpu_features(uint32_t dotprod); +extern uint32_t aienos_infer_dot_path(void); + +/* Open the heap and tell the Rust unit what the CPU has. The feature comes from + * the kernel's own ID-register decode; the unit assumes nothing. */ +static void infer_heap_open(uintptr_t base, uintptr_t len) +{ + aienos_infer_set_cpu_features(ck_cpufeat_boot()->dotprod); + aienos_infer_heap_init(base, len); + ck_printf("infer: dot_path=%s cpu_dotprod=%u\n", aienos_infer_dot_path() ? "sdot" : "scalar_f32", + ck_cpufeat_boot()->dotprod); +} /* Mirror of crates/aienos-infer-kernel/src/lib.rs `InferResult` (#[repr(C)]). */ #define INFER_MAX_NEW 16 #define INFER_TEXT_BYTES 256 @@ -318,7 +333,7 @@ static void session_run(uint64_t mpa, uint64_t msize) ck_printf("infer: session FAIL (no frames for the heap)\nAIENOS_CK_INFER_SESSION: FAIL\n"); return; } - aienos_infer_heap_init((uintptr_t)hpa, HEAP_BYTES); + infer_heap_open((uintptr_t)hpa, HEAP_BYTES); uint64_t daif = ck_rd(daif); __asm__ volatile("msr daifset, #0xf" ::: "memory"); @@ -379,7 +394,7 @@ static void resident_open(uint64_t mpa, uint64_t msize, uint64_t mpages, uint64_ v |= 3ull << CPACR_FPEN_SHIFT; ck_wr(cpacr_el1, v); ck_isb(); - aienos_infer_heap_init((uintptr_t)hpa, HEAP_BYTES); + infer_heap_open((uintptr_t)hpa, HEAP_BYTES); struct infer_limits lim = { SESS_KV, SESS_MAX_NEW, SESS_PROMPT_BYTES, SESS_RESERVE }; struct infer_info info = { 0, 0, 0, 0 }; uint64_t t0 = ck_time_us(), daif = ck_rd(daif); @@ -614,7 +629,7 @@ void ck_infer_run(void) v |= 3ull << CPACR_FPEN_SHIFT; ck_wr(cpacr_el1, v); ck_isb(); - aienos_infer_heap_init((uintptr_t)hpa, HEAP_BYTES); + infer_heap_open((uintptr_t)hpa, HEAP_BYTES); uint64_t daif = ck_rd(daif); __asm__ volatile("msr daifset, #0xf" ::: "memory"); uint64_t t2 = ck_time_us(); diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c index 3fc69110..9b0a69cb 100644 --- a/native/kernel/core/kmain.c +++ b/native/kernel/core/kmain.c @@ -211,6 +211,7 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) struct ck_cpu_features cf; char cfl[96]; ck_cpufeat_decode(ck_rd(id_aa64isar0_el1), ck_rd(id_aa64isar1_el1), ck_rd(id_aa64pfr0_el1), &cf); + ck_cpufeat_set_boot(&cf); ck_cpufeat_format(&cf, cfl, sizeof cfl); ck_printf("%s\n", cfl); /* boot core only; see core/cpufeat.h */ } diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index a0b86413..8b941583 100644 --- a/native/kernel/tests/.crumb +++ b/native/kernel/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-13T15:00:51Z", + "compiled_at": "2026-10-13T15:35:38Z", "compiler": "crumb-compile/1", - "digest": "sha256:06a5ce6933f29268a72b8617e288985f4335c21c90707a65179a45da070a69c6", + "digest": "sha256:a292c04c07dffdabb96cd51efc5b51956246ce72d4c855db53e4183e999f879d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 158, - "generated_at_commit": "4b74ebf18be00aa0ae3cf512ff1368f1590ddc8a", - "source_tree": "sha256:5e6e65d312be0fcae4c78d1216e269018b1a8b88ad5ec044f254ae208d34b8b1" + "generated_at_commit": "e7de707d8b32e94e16bb88267b3844426fba6cc2", + "source_tree": "sha256:c5fd8fd244860df29ffd1af7fdc7afe94a309a6594c6c8ff9aad8c42bb797ac2" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/test_cpufeat.c b/native/kernel/tests/test_cpufeat.c index c887b8d7..2a5c149f 100644 --- a/native/kernel/tests/test_cpufeat.c +++ b/native/kernel/tests/test_cpufeat.c @@ -14,6 +14,8 @@ static struct ck_cpu_features dec(uint64_t a, uint64_t b, uint64_t p) int main(void) { + /* Boot record: all zero until kmain records the decode; nothing assumed. */ + CHECK(!ck_cpufeat_boot()->dotprod && !ck_cpufeat_boot()->i8mm); struct ck_cpu_features f = dec(0, 0, 0); CHECK(!f.dotprod && !f.i8mm && !f.bf16 && !f.fhm && !f.sve && !f.rndr); CHECK(!f.fp16); /* FP=0 AdvSIMD=0: implemented, no half precision */ @@ -45,5 +47,12 @@ int main(void) char small[8]; ck_cpufeat_format(&f, small, sizeof small); CHECK(strlen(small) == 7); + /* The recorded boot decode is what core/infer.c hands the Rust unit. */ + f = dec(1ull << 44, 0, 0); + ck_cpufeat_set_boot(&f); + CHECK(ck_cpufeat_boot()->dotprod == 1 && ck_cpufeat_boot()->i8mm == 0); + f = dec(0, 0, 0); + ck_cpufeat_set_boot(&f); + CHECK(ck_cpufeat_boot()->dotprod == 0); return ck_t_verdict("test_cpufeat"); }