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#300 (code only)
Apply it
git checkout -b patch-73603a791f552aa3 e90226ba1016368289d953c449dde74646fb26bf curl -fsSL https://interplane.io/drakestapleton/aienux/patches/73603a791f552aa3.patch | git am
Provenance
github-import 1
aien-dev/aienux
300
43d4a09d00749588c74719d919444e31b0adcac4
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":300,"url":"https://github.com/aien-dev/aienux/pull/300","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:10Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index b18b22e9..a147bba5 100644 --- a/.crumb +++ b/.crumb @@ -21,39 +21,39 @@ "generated": { "children": [ { - "digest": "ebc8d5c8bacd11bfcc717785e74cb4de592e0aab8f41a6f81f75f4cda158dc21", - "last_commit": "3761935", + "digest": "e41ee8160d017e8a4d624396c8dde2d191be7c099e646743198a13ba1df72353", + "last_commit": "a362beb", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "30f908b47375e088c78fe9123dac1ef2df0551c10de30c8c19ba7b053c065f91", - "last_commit": "ed308de", + "digest": "98e2f17d73935a249d0048ff81b0e2a2d7e1ad23b0b5e91f63ffb51b153365af", + "last_commit": "02edc84", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { "digest": "1dd726352055e65ac3c21d6f8c4e0c841a8c4912ba8384dfa8968fb7ce4d82fb", - "last_commit": "ed308de", + "last_commit": "e90226b", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "d9cd564824903777dd323019bb8d5673331383e961bc3da703d5589be1eb6b4c", - "last_commit": "c731baf", + "digest": "87580f35633fabdbc1d2d07a061b0022500dfcdf3499c815cce956d553eb9e59", + "last_commit": "a362beb", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:03cc72c852977cfbb531f9c497786a19a44ad112cdcee9756cb05db438fae2b4", - "compiled_at": "2026-10-10T04:29:33Z", + "children_root": "sha256:913c7ad458d5b94b73064bc816e342884e2a094fd09cc2f732d879272ade792d", + "compiled_at": "2026-10-11T01:16:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:87605929e4a875c96f065abb54460aec06c7c835b38ab2b97c4f2bff361a000e", - "evidence_files": 155, - "evidence_root": "sha256:d59c0cef4e7dd5172923754a95b411ca54b01f35baca4587f792f1b259f1eaf7", - "files": 3036, - "generated_at_commit": "ed308de52ede1d4c8a211d88e0e4a3ac5c92ec23", - "source_tree": "sha256:84adae421ac7242801cac74a09f3a3b660fa3d1d44b540034700bed7f0b4d852" + "digest": "sha256:8c5641c432de9b04dc9f1241b9f96c66337bd2441b4ce65e8d820797ae439b79", + "evidence_files": 158, + "evidence_root": "sha256:e5087babc606da0029ccc472d7738d89f0cadac0bb70fa2facc7d83d1672f5a5", + "files": 3045, + "generated_at_commit": "02edc84247d9ff8a06750ec885b3c7a006fc5dbe", + "source_tree": "sha256:0c33606f65716b36f20aab0376fc6042f6e8970161dda9dfed973a0c228e3123" }, "owner_lane": "", "provenance": { diff --git a/crates/.crumb b/crates/.crumb index b65d0d54..e2028577 100644 --- a/crates/.crumb +++ b/crates/.crumb @@ -96,7 +96,7 @@ }, { "digest": "41559b6187a30de12fdf5ee7e749662f3576d60e4bf0e0753284c05aa64baec0", - "last_commit": "7acfbcf", + "last_commit": "3761935", "name": "aienos-boot", "purpose": "Directory crates/aienos-boot. Purpose not yet described by a human." }, @@ -150,14 +150,14 @@ } ], "children_root": "sha256:1334b8befdc1f899fa2171246a25c0dcb502d6ea6bb724f007e22b884f6040c3", - "compiled_at": "2026-10-07T01:17:46Z", + "compiled_at": "2026-10-11T01:16:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:ebc8d5c8bacd11bfcc717785e74cb4de592e0aab8f41a6f81f75f4cda158dc21", + "digest": "sha256:e41ee8160d017e8a4d624396c8dde2d191be7c099e646743198a13ba1df72353", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 231, - "generated_at_commit": "7acfbcf2acfbc8c505a60d0e20cebf4d5f963c00", - "source_tree": "sha256:dd6b4a3aade84dd3a50986ad97114e1338b5e3b820119356f4ffbb599e099e0b" + "files": 234, + "generated_at_commit": "02edc84247d9ff8a06750ec885b3c7a006fc5dbe", + "source_tree": "sha256:6b88878ce85098c93382e3711b4e2c874efaa6dd5f90f04d6cc558e73442cd29" }, "owner_lane": "", "provenance": { diff --git a/crates/aienos-infer/examples/l6_host.rs b/crates/aienos-infer/examples/l6_host.rs index a2a3ddff..1ee59292 100644 --- a/crates/aienos-infer/examples/l6_host.rs +++ b/crates/aienos-infer/examples/l6_host.rs @@ -7,10 +7,15 @@ //! times each `forward` call in microseconds. //! //! Env: 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`). +//! AIENOS_N (default 64), AIENOS_COMMIT (printed as `commit`), AIENOS_DOT: +//! `f32` forces the f32 path whatever the CPU features are (the rollback), +//! `int8` forces activations on the Q8_K grid with i32 dots, unset or `auto` +//! runs `DotPath::select` with the features read from the Linux auxiliary +//! vector (f32 while `INT8_PROMOTION_DEFAULT` is false). Build with +//! `RUSTFLAGS="-C target-feature=+dotprod,+i8mm"` for `usdot`. //! 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, DotPath, DotSetting, Features, Gguf, Model, Tokenizer}; use std::time::Instant; const PROMPT: &str = "What is the capital of France?"; @@ -90,6 +95,32 @@ fn sha256_hex(data: &[u8]) -> String { h.iter().map(|x| format!("{x:08x}")).collect() } +/// CPU features from the Linux auxiliary vector (`AT_HWCAP`, `AT_HWCAP2`), +/// read from `/proc/self/auxv` (the vector `getauxval` returns) so that no +/// `unsafe` is needed. aarch64 only: the bit meanings are arm64's. Any read +/// problem means no features, which keeps the f32 path. +fn host_features() -> Features { + if !cfg!(target_arch = "aarch64") { + return Features::NONE; + } + const AT_HWCAP: u64 = 16; + const AT_HWCAP2: u64 = 26; + let Ok(raw) = std::fs::read("/proc/self/auxv") else { + return Features::NONE; + }; + let (mut hwcap, mut hwcap2) = (0u64, 0u64); + for pair in raw.as_chunks::<16>().0 { + let key = u64::from_ne_bytes(pair[..8].try_into().expect("8 bytes")); + let val = u64::from_ne_bytes(pair[8..].try_into().expect("8 bytes")); + match key { + AT_HWCAP => hwcap = val, + AT_HWCAP2 => hwcap2 = val, + _ => {} + } + } + Features::from_hwcap(hwcap, hwcap2) +} + fn join(v: &[impl ToString]) -> String { v.iter() .map(|x| x.to_string()) @@ -132,7 +163,24 @@ fn main() { println!("prompt_ids: {}", join(&ids)); println!("threads: 1"); + let raw = std::env::var("AIENOS_DOT").ok(); + let setting = DotSetting::parse(raw.as_deref()).unwrap_or_else(|| { + eprintln!("AIENOS_DOT must be f32, int8 or auto, got {raw:?}"); + std::process::exit(2); + }); + let features = host_features(); + let path = DotPath::resolve(features, setting); let mut st = DecodeState::new(&m, ids.len() + n + 8); + st.int8_dot = path == DotPath::Int8; + println!( + "features: dotprod={} i8mm={}", + features.dotprod, features.i8mm + ); + println!("dot_setting: {}", raw.as_deref().unwrap_or("auto")); + println!( + "dot: {}", + if path == DotPath::Int8 { "int8" } 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..95057d4c 100644 --- a/crates/aienos-infer/src/decode.rs +++ b/crates/aienos-infer/src/decode.rs @@ -10,7 +10,21 @@ use alloc::vec; use alloc::vec::Vec; use crate::math; -use crate::model::{InferError, Model}; +use crate::model::{InferError, Model, Weight}; +use crate::quant::Q8Act; + +/// Matvec class: Q, K and V projections (input: attention RMSNorm output). +pub const Q8_QKV: u8 = 1; +/// Matvec class: attention output projection. +pub const Q8_WO: u8 = 2; +/// Matvec class: FFN gate and up projections (input: FFN RMSNorm output). +pub const Q8_GATE_UP: u8 = 4; +/// Matvec class: FFN down projection (input: SwiGLU output). +pub const Q8_DOWN: u8 = 8; +/// Matvec class: output head (logits). +pub const Q8_OUTPUT: u8 = 16; +/// All matvec classes. +pub const Q8_ALL: u8 = 31; /// KV cache plus scratch buffers for one sequence. pub struct DecodeState { @@ -37,6 +51,19 @@ pub struct DecodeState { pub logits: Vec<f32>, /// Round matvec inputs to the Q8_K grid like ggml does (default off). pub emulate_q8k: bool, + /// Run the quantized matvecs on int8 activations (ggml's Q8_K grid, + /// i32 dots; aienos#34 L6). Implies the Q8_K rounding. Default off. + pub int8_dot: bool, + /// Diagnostic selector for the int8 parity diagnosis (aienos#34): bit `l` + /// lets layer `l` take the int8 / Q8_K-rounding path. Default: all layers. + /// Only consulted when `int8_dot` or `emulate_q8k` is on, so the plain f32 + /// path is unaffected. + pub q8_layers: u64, + /// Diagnostic selector: which matvec classes take that path (bits + /// [`Q8_QKV`], [`Q8_WO`], [`Q8_GATE_UP`], [`Q8_DOWN`], [`Q8_OUTPUT`]). + /// Default: [`Q8_ALL`]. + pub q8_classes: u8, + q8: Q8Act, } impl DecodeState { @@ -67,6 +94,10 @@ impl DecodeState { rope_sin: vec![0.0; model.head_dim / 2], logits: vec![0.0; p.vocab_size as usize], emulate_q8k: false, + int8_dot: false, + q8_layers: u64::MAX, + q8_classes: Q8_ALL, + q8: Q8Act::with_capacity(e.max(ff)), } } @@ -168,14 +199,42 @@ impl DecodeState { &mut self.rope_sin, ); + let (int8_on, round_on) = (self.int8_dot, self.emulate_q8k); + let (lmask, cmask) = (self.q8_layers, self.q8_classes); + // Per (layer, class) path choice; all-ones masks give the old behaviour. + let pick = move |layer_on: bool, c: u8| { + let on = layer_on && cmask & c != 0; + (int8_on && on, round_on && on) + }; for (l, layer) in m.layers.iter().enumerate() { + let layer_on = l >= 64 || (lmask >> l) & 1 == 1; + let (int8, round) = pick(layer_on, Q8_QKV); 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(&mut self.h, &mut self.q8, int8, round)?; + mv( + &layer.wq, + &self.h, + &self.q8, + int8, + &mut self.q, + &mut self.scr, + )?; + mv( + &layer.wk, + &self.h, + &self.q8, + int8, + &mut self.kk, + &mut self.scr, + )?; + mv( + &layer.wv, + &self.h, + &self.q8, + int8, + &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 +262,52 @@ 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)?; + let (int8, round) = pick(layer_on, Q8_WO); + prep(&mut self.att, &mut self.q8, int8, round)?; + mv( + &layer.wo, + &self.att, + &self.q8, + int8, + &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)?; + let (int8, round) = pick(layer_on, Q8_GATE_UP); + prep(&mut self.h, &mut self.q8, int8, round)?; + mv( + &layer.w_gate, + &self.h, + &self.q8, + int8, + &mut self.gate, + &mut self.scr, + )?; + mv( + &layer.w_up, + &self.h, + &self.q8, + int8, + &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)?; + let (int8, round) = pick(layer_on, Q8_DOWN); + prep(&mut self.gate, &mut self.q8, int8, round)?; + mv( + &layer.w_down, + &self.gate, + &self.q8, + int8, + &mut self.tmp[..e], + &mut self.scr, + )?; for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) { *x += d; } @@ -237,10 +315,16 @@ 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)?; + let (int8, round) = pick(true, Q8_OUTPUT); + prep(&mut self.h, &mut self.q8, int8, round)?; + mv( + &m.output, + &self.h, + &self.q8, + int8, + &mut self.logits, + &mut self.scr, + )?; } Ok(()) } @@ -287,6 +371,33 @@ pub fn generate_greedy( Ok(out) } +/// Prepare an activation vector for the quantized matvecs that follow: the +/// int8 path quantizes it into `q8`; the emulation path rounds it in place. +fn prep(x: &mut [f32], q8: &mut Q8Act, int8: bool, round: bool) -> Result<(), InferError> { + if int8 { + q8.quantize(x)?; + } else if round { + q8k_round(x); + } + Ok(()) +} + +/// One matvec on whichever path applies (int8 only for K-quant weights). +fn mv( + w: &Weight<'_>, + x: &[f32], + q8: &Q8Act, + int8: bool, + out: &mut [f32], + scr: &mut [f32], +) -> Result<(), InferError> { + if int8 && w.is_kquant() { + w.matvec_q8(q8, out) + } else { + w.matvec(x, out, scr) + } +} + /// Round activations to ggml's Q8_K grid in place (per 256-block: scale /// `d = max/-127` where `max` is the signed value of largest magnitude, /// `q = round-half-even(x / d)` clamped to 127, value `q * d`). ggml quantizes diff --git a/crates/aienos-infer/src/dotpath.rs b/crates/aienos-infer/src/dotpath.rs new file mode 100644 index 00000000..b75eb174 --- /dev/null +++ b/crates/aienos-infer/src/dotpath.rs @@ -0,0 +1,232 @@ +//! Choice between the f32 and the int8 activation dot path (aienos#34 L6-B, +//! qualification in `docs/l6b-int8-qualification.md`). +//! +//! The crate is `no_std` and `forbid(unsafe_code)`, so it cannot read CPU +//! registers. The caller detects CPU features and passes a [`Features`] value. +//! The host harness (`examples/l6_host.rs`) fills it from the Linux auxiliary +//! vector. +//! +//! Kernel hook point (not implemented here; kernel register reads go through +//! the manual-guard process): the native kernel must fill [`Features`] from +//! the AArch64 ID registers, `dotprod` from `ID_AA64ISAR0_EL1.DP` (field value +//! 1 or more) and `i8mm` from `ID_AA64ISAR1_EL1.I8MM` (field value 1 or more), +//! read at EL1 on the boot core and checked on every core that will decode. +//! +//! Rollback: [`INT8_PROMOTION_DEFAULT`] is `false`. With it `false` nothing +//! selects int8 unless the caller explicitly asks for it. On a host, +//! `AIENOS_DOT=f32` forces f32 regardless of features. + +/// Build-time switch for the kernel. `false`: int8 is never chosen by feature +/// detection alone, the f32 path stays the default. Changing it to `true` is +/// the promotion, changing it back is the rollback. +pub const INT8_PROMOTION_DEFAULT: bool = false; + +/// CPU features that make the int8 path fast (`sdot`/`udot` and `usdot`). +/// Supplied by the caller; this crate never probes the CPU. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Features { + /// Armv8.2 dot product (`HWCAP_ASIMDDP`, `ID_AA64ISAR0_EL1.DP`). + pub dotprod: bool, + /// Armv8.6 int8 matrix multiply (`HWCAP2_I8MM`, `ID_AA64ISAR1_EL1.I8MM`). + pub i8mm: bool, +} + +/// `HWCAP_ASIMDDP` in the Linux `AT_HWCAP` word (arm64). +pub const HWCAP_ASIMDDP: u64 = 1 << 20; +/// `HWCAP2_I8MM` in the Linux `AT_HWCAP2` word (arm64). +pub const HWCAP2_I8MM: u64 = 1 << 13; + +impl Features { + /// No feature present. + pub const NONE: Features = Features { + dotprod: false, + i8mm: false, + }; + + /// Decode the arm64 Linux auxiliary-vector words `AT_HWCAP` and `AT_HWCAP2`. + pub fn from_hwcap(hwcap: u64, hwcap2: u64) -> Self { + Self { + dotprod: hwcap & HWCAP_ASIMDDP != 0, + i8mm: hwcap2 & HWCAP2_I8MM != 0, + } + } + + /// Both features present. + pub fn both(&self) -> bool { + self.dotprod && self.i8mm + } +} + +/// Which activation path the decoder runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DotPath { + /// f32 activations (the default and the fallback). + F32, + /// Q8_K int8 activations with i32 dots. + Int8, +} + +impl DotPath { + /// Selector with the build-time default ([`INT8_PROMOTION_DEFAULT`]). + pub fn select(features: Features, requested: bool) -> Self { + Self::select_with(features, requested, INT8_PROMOTION_DEFAULT) + } + + /// Int8 only when the caller requests it, or when promotion is enabled and + /// both features are present. Otherwise f32. An explicit request is + /// honoured without the features: the int8 code is portable, only slower. + pub fn select_with(features: Features, requested: bool, promotion: bool) -> Self { + if requested || (promotion && features.both()) { + DotPath::Int8 + } else { + DotPath::F32 + } + } + + /// Apply an operator setting (`AIENOS_DOT`) with the build-time default. + pub fn resolve(features: Features, setting: DotSetting) -> Self { + Self::resolve_with(features, setting, INT8_PROMOTION_DEFAULT) + } + + /// `F32` forces f32 whatever the features and promotion say (the + /// rollback). `Int8` forces int8. `Auto` runs the selector. + pub fn resolve_with(features: Features, setting: DotSetting, promotion: bool) -> Self { + match setting { + DotSetting::F32 => DotPath::F32, + DotSetting::Int8 => DotPath::Int8, + DotSetting::Auto => Self::select_with(features, false, promotion), + } + } +} + +/// The operator's choice (host: the `AIENOS_DOT` environment variable). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DotSetting { + /// Let the selector decide (variable unset or `auto`). + Auto, + /// Force f32, the rollback. + F32, + /// Force int8. + Int8, +} + +impl DotSetting { + /// Parse the variable's value (`None` when unset). Unknown text is `None` + /// so the caller can refuse it rather than guess. + pub fn parse(value: Option<&str>) -> Option<Self> { + match value { + None | Some("auto") => Some(DotSetting::Auto), + Some("f32") => Some(DotSetting::F32), + Some("int8") => Some(DotSetting::Int8), + Some(_) => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NONE: Features = Features { + dotprod: false, + i8mm: false, + }; + const DOT_ONLY: Features = Features { + dotprod: true, + i8mm: false, + }; + const MM_ONLY: Features = Features { + dotprod: false, + i8mm: true, + }; + const BOTH: Features = Features { + dotprod: true, + i8mm: true, + }; + + #[test] + fn select_matrix_all_combinations() { + use DotPath::{Int8, F32}; + // (features, requested, promotion, expected) + let rows: [(Features, bool, bool, DotPath); 16] = [ + (NONE, false, false, F32), + (NONE, false, true, F32), + (NONE, true, false, Int8), + (NONE, true, true, Int8), + (DOT_ONLY, false, false, F32), + (DOT_ONLY, false, true, F32), + (DOT_ONLY, true, false, Int8), + (DOT_ONLY, true, true, Int8), + (MM_ONLY, false, false, F32), + (MM_ONLY, false, true, F32), + (MM_ONLY, true, false, Int8), + (MM_ONLY, true, true, Int8), + (BOTH, false, false, F32), + (BOTH, false, true, Int8), + (BOTH, true, false, Int8), + (BOTH, true, true, Int8), + ]; + for (f, requested, promotion, want) in rows { + assert_eq!( + DotPath::select_with(f, requested, promotion), + want, + "features {f:?} requested {requested} promotion {promotion}" + ); + } + } + + #[test] + fn features_from_hwcap_bits() { + let dp = 1u64 << 20; + let mm = 1u64 << 13; + assert_eq!(Features::from_hwcap(0, 0), NONE); + assert_eq!(Features::from_hwcap(dp, 0), DOT_ONLY); + assert_eq!(Features::from_hwcap(0, mm), MM_ONLY); + assert_eq!(Features::from_hwcap(dp, mm), BOTH); + // The i8mm bit in AT_HWCAP (not AT_HWCAP2) and the dotprod bit in + // AT_HWCAP2 mean something else and must not be read. + assert_eq!(Features::from_hwcap(mm, dp), NONE); + // Unrelated bits do not set anything. + assert_eq!(Features::from_hwcap(!dp, !mm), NONE); + } + + #[test] + fn default_constant_off_and_auto_is_f32_with_features() { + assert!(!core::hint::black_box(INT8_PROMOTION_DEFAULT)); + assert_eq!(DotPath::select(BOTH, false), DotPath::F32); + assert_eq!(DotPath::resolve(BOTH, DotSetting::Auto), DotPath::F32); + assert_eq!(DotPath::select(BOTH, true), DotPath::Int8); + } + + #[test] + fn rollback_setting_f32_forces_f32_with_all_features() { + // AIENOS_DOT=f32: f32 with every feature present, promotion on or off. + for promotion in [false, true] { + assert_eq!( + DotPath::resolve_with(BOTH, DotSetting::parse(Some("f32")).unwrap(), promotion), + DotPath::F32 + ); + } + // Auto with promotion on and features present is the only way to int8 + // without asking; the F32 setting overrides it. + assert_eq!( + DotPath::resolve_with(BOTH, DotSetting::Auto, true), + DotPath::Int8 + ); + assert_eq!( + DotPath::resolve_with(NONE, DotSetting::Int8, false), + DotPath::Int8 + ); + } + + #[test] + fn setting_parse() { + assert_eq!(DotSetting::parse(None), Some(DotSetting::Auto)); + assert_eq!(DotSetting::parse(Some("auto")), Some(DotSetting::Auto)); + assert_eq!(DotSetting::parse(Some("f32")), Some(DotSetting::F32)); + assert_eq!(DotSetting::parse(Some("int8")), Some(DotSetting::Int8)); + assert_eq!(DotSetting::parse(Some("INT8")), None); + assert_eq!(DotSetting::parse(Some("")), None); + assert_eq!(DotSetting::parse(Some("i8")), None); + } +} diff --git a/crates/aienos-infer/src/lib.rs b/crates/aienos-infer/src/lib.rs index 1217992c..c66986bb 100644 --- a/crates/aienos-infer/src/lib.rs +++ b/crates/aienos-infer/src/lib.rs @@ -21,6 +21,7 @@ extern crate alloc; extern crate std; pub mod decode; +pub mod dotpath; pub mod gguf; pub mod half; pub mod math; @@ -28,7 +29,10 @@ pub mod model; pub mod quant; pub mod tokenizer; -pub use decode::{argmax, generate_greedy, DecodeState}; +pub use decode::{ + argmax, generate_greedy, DecodeState, Q8_ALL, Q8_DOWN, Q8_GATE_UP, Q8_OUTPUT, Q8_QKV, Q8_WO, +}; +pub use dotpath::{DotPath, DotSetting, Features, INT8_PROMOTION_DEFAULT}; 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..7b716678 100644 --- a/crates/aienos-infer/src/model.rs +++ b/crates/aienos-infer/src/model.rs @@ -107,9 +107,16 @@ impl<'a> Weight<'a> { if x.len() != self.cols || out.len() != self.rows || scratch.len() < self.cols { return Err(InferError::BadParams("matvec shape")); } + // Sub-block sums of x are shared by every Q4_K row (aienos#34 L6). + let nsums = self.cols / quant::Q4K_SUB; + if matches!(self.ty, GgmlType::Q4K | GgmlType::Q6K) { + quant::sub_block_sums(x, &mut scratch[..nsums]); + } for (r, o) in out.iter_mut().enumerate() { *o = match self.ty { - GgmlType::Q4K | GgmlType::Q6K => quant::dot_row(self.ty, self.row(r), x)?, + GgmlType::Q4K | GgmlType::Q6K => { + quant::dot_row_sums(self.ty, self.row(r), x, &scratch[..nsums])? + } _ => { let s = &mut scratch[..self.cols]; plain_to_f32(self.ty, self.row(r), s); @@ -119,6 +126,26 @@ impl<'a> Weight<'a> { } Ok(()) } + + /// True for the K-quant types the int8 activation path handles. + pub fn is_kquant(&self) -> bool { + matches!(self.ty, GgmlType::Q4K | GgmlType::Q6K) + } + + /// `out[r] = row_r . act` with activations on the Q8_K grid (aienos#34 + /// L6 int8 path); K-quant weights only, see [`Weight::is_kquant`]. + pub fn matvec_q8(&self, act: &quant::Q8Act, out: &mut [f32]) -> Result<(), InferError> { + if act.len() != self.cols || out.len() != self.rows { + return Err(InferError::BadParams("matvec shape")); + } + if !self.is_kquant() { + return Err(InferError::BadParams("matvec_q8 needs a K-quant weight")); + } + for (r, o) in out.iter_mut().enumerate() { + *o = quant::dot_row_q8k(self.ty, self.row(r), act)?; + } + Ok(()) + } } /// One transformer block's tensors. diff --git a/crates/aienos-infer/src/quant.rs b/crates/aienos-infer/src/quant.rs index 1f453d2c..4244fcc9 100644 --- a/crates/aienos-infer/src/quant.rs +++ b/crates/aienos-infer/src/quant.rs @@ -3,6 +3,8 @@ //! Formulas follow ggml's `dequantize_row_q4_K` / `dequantize_row_q6_K` //! (ggml-quants.c). Both formats pack 256 weights per super-block. +use alloc::vec::Vec; + use crate::gguf::GgmlType; use crate::half::f16_to_f32; @@ -86,35 +88,146 @@ fn as_block<const N: usize>(b: &[u8]) -> &[u8; N] { b.try_into().expect("chunk length is N") } -/// Dot product of one Q4_K block with 256 f32 activations (dequantize, then -/// accumulate in f32; scalar reference, not bit-identical to ggml's q8 path). +/// Independent partial sums per 32-weight sub-block. Eight f32 lanes give the +/// compiler two NEON vectors of fused multiply-adds in flight instead of one +/// serial chain of dependent additions, with no `unsafe` (aienos#34 L6). +const LANES: usize = 8; + +/// Weights per Q4_K sub-block (one 6-bit scale and min each). +pub const Q4K_SUB: usize = 32; + +/// `sums[k] = sum(x[32k..32k+32])`, one per Q4_K sub-block of `x`. Independent +/// of the weights, so a matvec computes it once and reuses it for every row. +pub fn sub_block_sums(x: &[f32], sums: &mut [f32]) { + for (c, s) in x.chunks_exact(Q4K_SUB).zip(sums.iter_mut()) { + let mut lanes = [0f32; LANES]; + for b in c.chunks_exact(LANES) { + for i in 0..LANES { + lanes[i] += b[i]; + } + } + *s = lanes.iter().sum(); + } +} + +/// Sum of `v` by lanes, then a short tail: fixed order, vectorizable. +#[inline(always)] +fn lane_sum<const N: usize>(v: &[f32; N]) -> f32 { + let mut lanes = [0f32; LANES]; + for c in v.chunks_exact(LANES) { + for i in 0..LANES { + lanes[i] += c[i]; + } + } + let mut s = 0f32; + for l in lanes { + s += l; + } + s +} + +/// Dot product of one Q4_K block with 256 f32 activations, given the eight +/// sub-block sums of `x` (see [`sub_block_sums`]). +/// +/// Same quantity as `dequant_q4k_block` followed by a dot (f32 throughout, no +/// int8 rounding of `x`), evaluated per sub-block as +/// `d*sc * sum(q*x) - dmin*m * sum(x)`: products into a 32-wide array, then +/// a lane sum (two plain loops, each vectorizes). Only the floating-point +/// summation order differs from the serial reference. +pub fn dot_q4k_f32_sums(block: &[u8; Q4K_BYTES], x: &[f32; QK_K], xs: &[f32; 8]) -> f32 { + let d = rd_f16(block, 0); + let dmin = rd_f16(block, 2); + let scales = &block[4..16]; + let qs: &[u8; 128] = block[16..144].try_into().expect("128 nibble bytes"); + let mut acc = 0f32; + for j in 0..4 { + let (sc1, m1) = scale_min_k4(2 * j, scales); + let (sc2, m2) = scale_min_k4(2 * j + 1, scales); + let q: &[u8; Q4K_SUB] = qs[32 * j..32 * j + 32].try_into().expect("32 bytes"); + let x1: &[f32; Q4K_SUB] = x[64 * j..64 * j + 32].try_into().expect("32 x"); + let x2: &[f32; Q4K_SUB] = x[64 * j + 32..64 * j + 64].try_into().expect("32 x"); + let mut p1 = [0f32; Q4K_SUB]; + let mut p2 = [0f32; Q4K_SUB]; + for l in 0..Q4K_SUB { + p1[l] = (q[l] & 0x0f) as f32 * x1[l]; + p2[l] = (q[l] >> 4) as f32 * x2[l]; + } + acc += d * sc1 as f32 * lane_sum(&p1) - dmin * m1 as f32 * xs[2 * j]; + acc += d * sc2 as f32 * lane_sum(&p2) - dmin * m2 as f32 * xs[2 * j + 1]; + } + acc +} + +/// Dot product of one Q4_K block with 256 f32 activations (computes the +/// sub-block sums of `x` itself; use [`dot_q4k_f32_sums`] in a row loop). pub fn dot_q4k_f32(block: &[u8; Q4K_BYTES], x: &[f32; QK_K]) -> f32 { - let mut w = [0f32; QK_K]; - dequant_q4k_block(block, &mut w); - w.iter().zip(x).map(|(a, b)| a * b).sum() + let mut xs = [0f32; 8]; + sub_block_sums(x, &mut xs); + dot_q4k_f32_sums(block, x, &xs) } -/// Dot product of one Q6_K block with 256 f32 activations. +/// Dot product of one Q6_K block with 256 f32 activations (same scheme as +/// [`dot_q4k_f32_sums`]: per 16-weight scale group, `d*sc * sum((q-32)*x)`). pub fn dot_q6k_f32(block: &[u8; Q6K_BYTES], x: &[f32; QK_K]) -> f32 { - let mut w = [0f32; QK_K]; - dequant_q6k_block(block, &mut w); - w.iter().zip(x).map(|(a, b)| a * b).sum() + let d = rd_f16(block, 208); + let mut acc = 0f32; + for half in 0..2 { + let ql: &[u8; 64] = block[64 * half..64 * half + 64].try_into().expect("64 ql"); + let qh: &[u8; 32] = block[128 + 32 * half..128 + 32 * half + 32] + .try_into() + .expect("32 qh"); + let sc = &block[192 + 8 * half..192 + 8 * half + 8]; + let xs: &[f32; 128] = x[128 * half..128 * half + 128].try_into().expect("128 x"); + // Four 32-weight quarters; each quarter has two 16-weight scale groups + // (same bit layout as dequant_q6k_block). + let mut p = [[0f32; 32]; 4]; + for l in 0..32 { + let h = qh[l]; + let q1 = ((ql[l] & 0x0f) | ((h & 3) << 4)) as i32 - 32; + let q2 = ((ql[l + 32] & 0x0f) | (((h >> 2) & 3) << 4)) as i32 - 32; + let q3 = ((ql[l] >> 4) | (((h >> 4) & 3) << 4)) as i32 - 32; + let q4 = ((ql[l + 32] >> 4) | (((h >> 6) & 3) << 4)) as i32 - 32; + p[0][l] = q1 as f32 * xs[l]; + p[1][l] = q2 as f32 * xs[l + 32]; + p[2][l] = q3 as f32 * xs[l + 64]; + p[3][l] = q4 as f32 * xs[l + 96]; + } + for (k, pk) in p.iter().enumerate() { + let lo: &[f32; 16] = pk[..16].try_into().expect("16"); + let hi: &[f32; 16] = pk[16..].try_into().expect("16"); + acc += d * (sc[2 * k] as i8) as f32 * lane_sum(lo); + acc += d * (sc[2 * k + 1] as i8) as f32 * lane_sum(hi); + } + } + acc } /// Dot of a whole quantized row (`src`, `x.len()` weights) with `x`. pub fn dot_row(ty: GgmlType, src: &[u8], x: &[f32]) -> Result<f32, QuantError> { + let mut sums = alloc::vec![0f32; x.len() / Q4K_SUB]; + sub_block_sums(x, &mut sums); + dot_row_sums(ty, src, x, &sums) +} + +/// [`dot_row`] with the sub-block sums of `x` supplied (`x.len() / 32` values +/// from [`sub_block_sums`]); only Q4_K reads them. +pub fn dot_row_sums(ty: GgmlType, src: &[u8], x: &[f32], sums: &[f32]) -> Result<f32, QuantError> { let (bw, bb) = ty.block(); if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) { return Err(QuantError::Unsupported(ty)); } - if x.len() % bw != 0 || src.len() != x.len() / bw * bb { + if x.len() % bw != 0 || src.len() != x.len() / bw * bb || sums.len() < x.len() / Q4K_SUB { return Err(QuantError::BadLength); } let mut acc = 0f32; - for (blk, xs) in src.chunks_exact(bb).zip(x.chunks_exact(QK_K)) { + for ((blk, xs), ss) in src + .chunks_exact(bb) + .zip(x.chunks_exact(QK_K)) + .zip(sums.chunks_exact(QK_K / Q4K_SUB)) + { let xs: &[f32; QK_K] = xs.try_into().expect("chunk is QK_K"); acc += if ty == GgmlType::Q4K { - dot_q4k_f32(as_block(blk), xs) + dot_q4k_f32_sums(as_block(blk), xs, ss.try_into().expect("8 sums")) } else { dot_q6k_f32(as_block(blk), xs) }; @@ -148,6 +261,279 @@ pub fn dequantize(ty: GgmlType, src: &[u8], out: &mut [f32]) -> Result<(), Quant Ok(()) } +// --------------------------------------------------------------------------- +// Int8 activation path (aienos#34 L6): activations on ggml's Q8_K grid, dots +// accumulated in i32. The inner loops are written in the shape the compiler +// turns into `sdot`/`usdot` when the target has dotprod/i8mm (build with +// `-C target-feature=+dotprod,+i8mm`; GB10 has both). Without those features +// they still vectorize to widening multiplies. +// --------------------------------------------------------------------------- + +/// Activations per Q8_K group sum (ggml's `bsums`). +pub const Q8K_GROUP: usize = 16; + +/// Activations quantized to ggml's Q8_K grid (see [`quantize_q8k`]), with +/// room for `capacity` values so a forward pass allocates nothing. +pub struct Q8Act { + d: Vec<f32>, + q: Vec<i8>, + bsums: Vec<i32>, + len: usize, +} + +impl Q8Act { + /// Room for `capacity` activations (rounded down to whole 256-blocks). + pub fn with_capacity(capacity: usize) -> Self { + let blocks = capacity / QK_K; + Self { + d: alloc::vec![0.0; blocks], + q: alloc::vec![0; blocks * QK_K], + bsums: alloc::vec![0; blocks * (QK_K / Q8K_GROUP)], + len: 0, + } + } + + /// Quantize `x` (a multiple of 256 values, at most the capacity). + pub fn quantize(&mut self, x: &[f32]) -> Result<(), QuantError> { + if x.len() % QK_K != 0 || x.len() > self.q.len() { + return Err(QuantError::BadLength); + } + self.len = x.len(); + quantize_q8k( + x, + &mut self.q[..x.len()], + &mut self.d[..x.len() / QK_K], + &mut self.bsums[..x.len() / Q8K_GROUP], + ); + Ok(()) + } + + /// Number of quantized activations held. + pub fn len(&self) -> usize { + self.len + } + + /// True before the first `quantize`. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Per-block scales (`len / 256`). + pub fn scales(&self) -> &[f32] { + &self.d[..self.len / QK_K] + } + + /// The int8 values. + pub fn values(&self) -> &[i8] { + &self.q[..self.len] + } + + /// Sums of the int8 values over 16 consecutive positions (`len / 16`). + pub fn group_sums(&self) -> &[i32] { + &self.bsums[..self.len / Q8K_GROUP] + } +} + +/// ggml's `quantize_row_q8_K`: per 256-block, `d = max / -127` (`max` the +/// value of largest magnitude), `q = min(127, nearest_int(x / d))` with ties +/// to even, `bsums` the sums of `q` over 16 consecutive values. The values +/// `q * d` are exactly what `decode::q8k_round` leaves in place. +pub fn quantize_q8k(x: &[f32], q: &mut [i8], d: &mut [f32], bsums: &mut [i32]) { + let rows = x + .chunks_exact(QK_K) + .zip(q.chunks_exact_mut(QK_K)) + .zip(d.iter_mut()) + .zip(bsums.chunks_exact_mut(QK_K / Q8K_GROUP)); + for (((xb, qb), db), sb) in rows { + let mut amax = 0f32; + let mut max = 0f32; + for &v in xb { + if v.abs() > amax { + amax = v.abs(); + max = v; + } + } + if amax == 0.0 { + *db = 0.0; + qb.fill(0); + sb.fill(0); + continue; + } + let iscale = -127.0 / max; + *db = 1.0 / iscale; + for (xi, qi) in xb.iter().zip(qb.iter_mut()) { + // nearest_int: magic-number rounding (ties to even), as ggml. + let t = (*xi * iscale + 12_582_912.0) - 12_582_912.0; + *qi = t.min(127.0) as i8; + } + for (g, s) in qb.chunks_exact(Q8K_GROUP).zip(sb.iter_mut()) { + *s = g.iter().map(|&v| v as i32).sum(); + } + } +} + +/// `(sum(lo_nibble(q[l]) * y[l]), sum(hi_nibble(q[l]) * y[32 + l]))` over +/// 32 bytes: the shape that becomes four `usdot`. +#[inline(always)] +fn nibble_dot_i8(q: &[u8; Q4K_SUB], y: &[i8; 2 * Q4K_SUB]) -> (i32, i32) { + let mut lo = 0i32; + let mut hi = 0i32; + for l in 0..Q4K_SUB { + lo += (q[l] & 0x0f) as i32 * y[l] as i32; + } + for l in 0..Q4K_SUB { + hi += (q[l] >> 4) as i32 * y[Q4K_SUB + l] as i32; + } + (lo, hi) +} + +/// The two i32 accumulations of one Q4_K block against 256 Q8_K activations: +/// `(sum(sc*q.y), sum(m*sum(y)))`. +pub(crate) fn q4k_q8k_accum( + block: &[u8; Q4K_BYTES], + y: &[i8; QK_K], + ys: &[i32; QK_K / Q8K_GROUP], +) -> (i32, i32) { + let scales = &block[4..16]; + let qs: &[u8; 128] = block[16..144].try_into().expect("128 nibble bytes"); + let mut sumi = 0i32; + let mut mins = 0i32; + for j in 0..4 { + let (sc1, m1) = scale_min_k4(2 * j, scales); + let (sc2, m2) = scale_min_k4(2 * j + 1, scales); + let q: &[u8; Q4K_SUB] = qs[32 * j..32 * j + 32].try_into().expect("32 bytes"); + let yj: &[i8; 2 * Q4K_SUB] = y[64 * j..64 * j + 64].try_into().expect("64 y"); + let (lo, hi) = nibble_dot_i8(q, yj); + sumi += sc1 as i32 * lo + sc2 as i32 * hi; + mins += + m1 as i32 * (ys[4 * j] + ys[4 * j + 1]) + m2 as i32 * (ys[4 * j + 2] + ys[4 * j + 3]); + } + (sumi, mins) +} + +/// Dot of one Q4_K block with 256 Q8_K activations (`y`, block scale `yd`, +/// 16 group sums `ys`): ggml's `ggml_vec_dot_q4_K_q8_K`, i32 accumulation, +/// `d*sum(sc*q.y) - dmin*sum(m*sum(y))`. +pub fn dot_q4k_q8k( + block: &[u8; Q4K_BYTES], + y: &[i8; QK_K], + yd: f32, + ys: &[i32; QK_K / Q8K_GROUP], +) -> f32 { + let d = rd_f16(block, 0); + let dmin = rd_f16(block, 2); + let (sumi, mins) = q4k_q8k_accum(block, y, ys); + yd * (d * sumi as f32 - dmin * mins as f32) +} + +/// One 32-weight quarter of a Q6_K half: two 16-weight scale groups, +/// `sum(sc * (q - 32) * y)` with `q` the unsigned 6-bit value (0..=63) from +/// nibble shift `SL` of `ql` and bit pair `SH` of `qh`, and the `-32` +/// applied through the group sums of `y`. Two plain loops (assemble, then +/// multiply) so each becomes vector code (`usdot` with i8mm). +#[inline(always)] +fn q6_quarter_i8<const SL: u32, const SH: u32>( + ql: &[u8; 32], + qh: &[u8; 32], + sc: &[u8; 2], + y: &[i8; 32], + ys: &[i32; 2], +) -> i32 { + let mut q = [0u8; 32]; + for l in 0..32 { + q[l] = ((ql[l] >> SL) & 0x0f) | (((qh[l] >> SH) & 3) << 4); + } + let mut acc = 0i32; + for g in 0..2 { + let mut s = 0i32; + for l in 0..Q8K_GROUP { + s += q[Q8K_GROUP * g + l] as i32 * y[Q8K_GROUP * g + l] as i32; + } + acc += (sc[g] as i8) as i32 * (s - 32 * ys[g]); + } + acc +} + +/// The i32 accumulation of one Q6_K block against 256 Q8_K activations. +pub(crate) fn q6k_q8k_isum( + block: &[u8; Q6K_BYTES], + y: &[i8; QK_K], + ys: &[i32; QK_K / Q8K_GROUP], +) -> i32 { + let mut isum = 0i32; + for half in 0..2 { + let ql = &block[64 * half..64 * half + 64]; + let ql0: &[u8; 32] = ql[..32].try_into().expect("32 ql"); + let ql1: &[u8; 32] = ql[32..].try_into().expect("32 ql"); + let qh: &[u8; 32] = block[128 + 32 * half..128 + 32 * half + 32] + .try_into() + .expect("32 qh"); + let sc = &block[192 + 8 * half..192 + 8 * half + 8]; + let yh = &y[128 * half..128 * half + 128]; + let sh = &ys[8 * half..8 * half + 8]; + // Quarter k uses ql bytes (k&1)*32.., nibble shift 4*(k>>1), qh bit + // pair 2k and scales sc[2k..2k+2], exactly as dequant_q6k_block. + let a = |r: core::ops::Range<usize>| -> (&[u8; 2], &[i8; 32], &[i32; 2]) { + ( + sc[r.start / 16..r.start / 16 + 2].try_into().expect("2 sc"), + yh[r.clone()].try_into().expect("32 y"), + sh[r.start / 16..r.start / 16 + 2] + .try_into() + .expect("2 sums"), + ) + }; + let (s0, y0, b0) = a(0..32); + let (s1, y1, b1) = a(32..64); + let (s2, y2, b2) = a(64..96); + let (s3, y3, b3) = a(96..128); + isum += q6_quarter_i8::<0, 0>(ql0, qh, s0, y0, b0); + isum += q6_quarter_i8::<0, 2>(ql1, qh, s1, y1, b1); + isum += q6_quarter_i8::<4, 4>(ql0, qh, s2, y2, b2); + isum += q6_quarter_i8::<4, 6>(ql1, qh, s3, y3, b3); + } + isum +} + +/// Dot of one Q6_K block with 256 Q8_K activations: ggml's +/// `ggml_vec_dot_q6_K_q8_K` (i32 accumulation). +pub fn dot_q6k_q8k( + block: &[u8; Q6K_BYTES], + y: &[i8; QK_K], + yd: f32, + ys: &[i32; QK_K / Q8K_GROUP], +) -> f32 { + let d = rd_f16(block, 208); + yd * d * q6k_q8k_isum(block, y, ys) as f32 +} + +/// Dot of a whole quantized row (`act.len()` weights) with Q8_K activations. +pub fn dot_row_q8k(ty: GgmlType, src: &[u8], act: &Q8Act) -> Result<f32, QuantError> { + let (bw, bb) = ty.block(); + if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) { + return Err(QuantError::Unsupported(ty)); + } + let n = act.len(); + if n % bw != 0 || src.len() != n / bw * bb { + return Err(QuantError::BadLength); + } + let mut acc = 0f32; + let blocks = src + .chunks_exact(bb) + .zip(act.values().chunks_exact(QK_K)) + .zip(act.scales()) + .zip(act.group_sums().chunks_exact(QK_K / Q8K_GROUP)); + for (((blk, y), &yd), ys) in blocks { + let y: &[i8; QK_K] = y.try_into().expect("chunk is QK_K"); + let ys: &[i32; QK_K / Q8K_GROUP] = ys.try_into().expect("16 sums"); + acc += if ty == GgmlType::Q4K { + dot_q4k_q8k(as_block(blk), y, yd, ys) + } else { + dot_q6k_q8k(as_block(blk), y, yd, ys) + }; + } + Ok(acc) +} + #[cfg(test)] mod tests { use super::*; @@ -247,6 +633,212 @@ mod tests { } } + fn lcg(seed: &mut u64) -> u32 { + *seed = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (*seed >> 33) as u32 + } + + fn serial_dot(w: &[f32; QK_K], x: &[f32; QK_K]) -> f32 { + w.iter().zip(x).map(|(a, b)| a * b).sum() + } + + #[test] + fn q4k_fused_dot_matches_dequant_then_dot() { + let mut seed = 7u64; + for _ in 0..200 { + let mut b = [0u8; Q4K_BYTES]; + for v in b.iter_mut() { + *v = lcg(&mut seed) as u8; + } + // Keep d and dmin finite and modest: exponent bits in a sane range. + b[1] = 0x30 | (b[1] & 0x03); + b[3] = 0x2c | (b[3] & 0x03); + let mut x = [0f32; QK_K]; + for v in x.iter_mut() { + *v = (lcg(&mut seed) % 2001) as f32 / 1000.0 - 1.0; + } + let mut w = [0f32; QK_K]; + dequant_q4k_block(&b, &mut w); + let want = serial_dot(&w, &x); + let got = dot_q4k_f32(&b, &x); + let scale = w.iter().zip(x).map(|(a, b)| (a * b).abs()).sum::<f32>(); + assert!( + (got - want).abs() <= 1e-5 * scale.max(1e-3), + "got {got} want {want} (scale {scale})" + ); + } + } + + #[test] + fn q6k_fused_dot_matches_dequant_then_dot() { + let mut seed = 11u64; + for _ in 0..200 { + let mut b = [0u8; Q6K_BYTES]; + for v in b.iter_mut() { + *v = lcg(&mut seed) as u8; + } + b[209] = 0x30 | (b[209] & 0x03); + let mut x = [0f32; QK_K]; + for v in x.iter_mut() { + *v = (lcg(&mut seed) % 2001) as f32 / 1000.0 - 1.0; + } + let mut w = [0f32; QK_K]; + dequant_q6k_block(&b, &mut w); + let want = serial_dot(&w, &x); + let got = dot_q6k_f32(&b, &x); + let scale = w.iter().zip(x).map(|(a, b)| (a * b).abs()).sum::<f32>(); + assert!( + (got - want).abs() <= 1e-5 * scale.max(1e-3), + "got {got} want {want} (scale {scale})" + ); + } + } + + fn random_block<const N: usize>(seed: &mut u64) -> [u8; N] { + let mut b = [0u8; N]; + for v in b.iter_mut() { + *v = lcg(seed) as u8; + } + b + } + + fn random_x(seed: &mut u64, x: &mut [f32]) { + for v in x.iter_mut() { + *v = (lcg(seed) % 2001) as f32 / 1000.0 - 1.0; + } + } + + #[test] + fn q8k_quantize_matches_q8k_round() { + let mut seed = 11u64; + let mut x = [0f32; 2 * QK_K]; + random_x(&mut seed, &mut x); + x[300] = 0.0; + let mut act = Q8Act::with_capacity(2 * QK_K); + act.quantize(&x).unwrap(); + let mut rounded = x; + crate::decode::q8k_round(&mut rounded); + assert_eq!(act.len(), 2 * QK_K); + for (blk, (&d, q)) in act + .scales() + .iter() + .zip(act.values().chunks_exact(QK_K)) + .enumerate() + { + for (l, &qi) in q.iter().enumerate() { + assert_eq!( + qi as f32 * d, + rounded[blk * QK_K + l], + "block {blk} value {l}" + ); + } + } + for (g, &s) in act.group_sums().iter().enumerate() { + let want: i32 = act.values()[16 * g..16 * g + 16] + .iter() + .map(|&v| v as i32) + .sum(); + assert_eq!(s, want); + } + // Zero block: zero scale, zero values. + let z = [0f32; QK_K]; + act.quantize(&z).unwrap(); + assert_eq!(act.scales(), &[0.0]); + assert!(act.values().iter().all(|&v| v == 0)); + // Length rules. + assert_eq!(act.quantize(&x[..100]), Err(QuantError::BadLength)); + let big = [0f32; 3 * QK_K]; + assert_eq!(act.quantize(&big), Err(QuantError::BadLength)); + } + + #[test] + fn q4k_int8_dot_matches_f32_dot_of_rounded_activations() { + let mut seed = 13u64; + let mut act = Q8Act::with_capacity(QK_K); + for _ in 0..200 { + let mut b: [u8; Q4K_BYTES] = random_block(&mut seed); + b[1] = 0x30 | (b[1] & 0x03); + b[3] = 0x2c | (b[3] & 0x03); + let mut x = [0f32; QK_K]; + random_x(&mut seed, &mut x); + act.quantize(&x).unwrap(); + let mut xr = x; + crate::decode::q8k_round(&mut xr); + let mut w = [0f32; QK_K]; + dequant_q4k_block(&b, &mut w); + let want = serial_dot(&w, &xr); + let y: &[i8; QK_K] = act.values().try_into().unwrap(); + let ys: &[i32; 16] = act.group_sums().try_into().unwrap(); + let got = dot_q4k_q8k(&b, y, act.scales()[0], ys); + let scale = w.iter().zip(xr).map(|(a, b)| (a * b).abs()).sum::<f32>(); + assert!( + (got - want).abs() <= 1e-4 * scale.max(1e-3), + "got {got} want {want} (scale {scale})" + ); + } + } + + #[test] + fn q6k_int8_dot_matches_f32_dot_of_rounded_activations() { + let mut seed = 17u64; + let mut act = Q8Act::with_capacity(QK_K); + for _ in 0..200 { + let mut b: [u8; Q6K_BYTES] = random_block(&mut seed); + b[209] = 0x30 | (b[209] & 0x03); + let mut x = [0f32; QK_K]; + random_x(&mut seed, &mut x); + act.quantize(&x).unwrap(); + let mut xr = x; + crate::decode::q8k_round(&mut xr); + let mut w = [0f32; QK_K]; + dequant_q6k_block(&b, &mut w); + let want = serial_dot(&w, &xr); + let y: &[i8; QK_K] = act.values().try_into().unwrap(); + let ys: &[i32; 16] = act.group_sums().try_into().unwrap(); + let got = dot_q6k_q8k(&b, y, act.scales()[0], ys); + let scale = w.iter().zip(xr).map(|(a, b)| (a * b).abs()).sum::<f32>(); + assert!( + (got - want).abs() <= 1e-4 * scale.max(1e-3), + "got {got} want {want} (scale {scale})" + ); + } + } + + #[test] + fn int8_row_dot_matches_block_sum_and_checks_lengths() { + let mut seed = 19u64; + let mut x = [0f32; 2 * QK_K]; + random_x(&mut seed, &mut x); + let mut act = Q8Act::with_capacity(2 * QK_K); + act.quantize(&x).unwrap(); + let mut src = [0u8; 2 * Q4K_BYTES]; + for v in src.iter_mut() { + *v = lcg(&mut seed) as u8; + } + for blk in src.chunks_exact_mut(Q4K_BYTES) { + blk[1] = 0x30 | (blk[1] & 0x03); + blk[3] = 0x2c | (blk[3] & 0x03); + } + let got = dot_row_q8k(GgmlType::Q4K, &src, &act).unwrap(); + let mut want = 0f32; + for (i, blk) in src.chunks_exact(Q4K_BYTES).enumerate() { + let y: &[i8; QK_K] = act.values()[i * QK_K..(i + 1) * QK_K].try_into().unwrap(); + let ys: &[i32; 16] = act.group_sums()[16 * i..16 * i + 16].try_into().unwrap(); + want += dot_q4k_q8k(as_block(blk), y, act.scales()[i], ys); + } + assert_eq!(got, want); + assert_eq!( + dot_row_q8k(GgmlType::Q4K, &src[..Q4K_BYTES], &act), + Err(QuantError::BadLength) + ); + assert_eq!( + dot_row_q8k(GgmlType::F32, &src, &act), + Err(QuantError::Unsupported(GgmlType::F32)) + ); + } + #[test] fn length_checks() { let mut out = [0f32; QK_K]; @@ -261,4 +853,98 @@ mod tests { let x = [1f32; QK_K]; assert_eq!(dot_row(GgmlType::Q4K, &[0u8; Q4K_BYTES], &x), Ok(0.0)); } + + /// `y[i] = ((m i + c) mod 255) - 127`, the golden activation pattern. + fn golden_y(m: usize, c: usize) -> ([i8; QK_K], [i32; 16]) { + let mut y = [0i8; QK_K]; + for (i, v) in y.iter_mut().enumerate() { + *v = (((m * i + c) % 255) as i32 - 127) as i8; + } + let mut ys = [0i32; 16]; + for (g, s) in ys.iter_mut().enumerate() { + *s = y[16 * g..16 * g + 16].iter().map(|&v| v as i32).sum(); + } + (y, ys) + } + + /// Fixed block, expected values derived by hand-rolled arithmetic from the + /// ggml layout (see docs/l6b-int8-qualification.md), not from this crate. + #[test] + fn golden_q4k_q8k_i32_accumulations() { + let mut b = [0u8; Q4K_BYTES]; + b[0..2].copy_from_slice(&[0x00, 0x3c]); // d = 1.0 + b[2..4].copy_from_slice(&[0x00, 0x38]); // dmin = 0.5 + b[4..16].copy_from_slice(&[ + 0x41, 0x82, 0xC3, 0x14, 0x25, 0x76, 0x37, 0x08, 0x9A, 0x5B, 0xDC, 0x2D, + ]); + for i in 0..128 { + b[16 + i] = ((37 * i + 11) % 256) as u8; + } + let (y, ys) = golden_y(29, 7); + assert_eq!(q4k_q8k_accum(&b, &y, &ys), (-284188, -7913)); + // yd * (d * sumi - dmin * mins), all exact in f32. + assert_eq!(dot_q4k_q8k(&b, &y, 0.25, &ys), -70057.875); + } + + #[test] + fn golden_q6k_q8k_i32_accumulations() { + let mut b = [0u8; Q6K_BYTES]; + for i in 0..128 { + b[i] = ((53 * i + 5) % 256) as u8; + } + for i in 0..64 { + b[128 + i] = ((91 * i + 17) % 256) as u8; + } + for i in 0..16 { + b[192 + i] = (((23 * i + 3) % 61) as i32 - 30) as i8 as u8; + } + b[208..210].copy_from_slice(&[0x00, 0x34]); // d = 0.25 + let (y, ys) = golden_y(31, 5); + assert_eq!(q6k_q8k_isum(&b, &y, &ys), -275808); + assert_eq!(dot_q6k_q8k(&b, &y, 0.5, &ys), -34476.0); + } + + #[test] + fn q8k_properties_bounds_and_error() { + let mut seed = 23u64; + let mut act = Q8Act::with_capacity(QK_K); + let mut neg = Q8Act::with_capacity(QK_K); + let mut scaled = Q8Act::with_capacity(QK_K); + for _ in 0..100 { + let mut x = [0f32; QK_K]; + random_x(&mut seed, &mut x); + act.quantize(&x).unwrap(); + let d = act.scales()[0]; + // Bounds, and the largest-magnitude value lands on -127. + assert!(act.values().iter().all(|&v| v >= -127)); + let imax = (0..QK_K).fold(0, |m, i| if x[i].abs() > x[m].abs() { i } else { m }); + assert_eq!(act.values()[imax], -127); + // Reconstruction error is at most half a step (plus rounding slack). + for (&xi, &qi) in x.iter().zip(act.values()) { + let err = (xi - qi as f32 * d).abs(); + assert!(err <= 0.5 * d.abs() * 1.001 + 1e-6, "err {err} d {d}"); + } + // Group sums are the sums of the values. + for (g, &s) in act.group_sums().iter().enumerate() { + let want: i32 = act.values()[16 * g..16 * g + 16] + .iter() + .map(|&v| v as i32) + .sum(); + assert_eq!(s, want); + } + // Negating the input negates the values (ties to even is symmetric) + // and the scale. + let nx = x.map(|v| -v); + neg.quantize(&nx).unwrap(); + assert_eq!(neg.scales()[0], -d); + for (&a, &b) in act.values().iter().zip(neg.values()) { + assert_eq!(a, b); + } + // Scaling by a power of two keeps the values and scales d. + let sx = x.map(|v| v * 4.0); + scaled.quantize(&sx).unwrap(); + assert_eq!(scaled.values(), act.values()); + assert_eq!(scaled.scales()[0], d * 4.0); + } + } } diff --git a/crates/aienos-infer/tests/fixtures/ref_fr_idx12_logits.f32 b/crates/aienos-infer/tests/fixtures/ref_fr_idx12_logits.f32 new file mode 100644 index 00000000..92050b8a Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/ref_fr_idx12_logits.f32 differ diff --git a/crates/aienos-infer/tests/forward.rs b/crates/aienos-infer/tests/forward.rs index 156ad863..bc22d69a 100644 --- a/crates/aienos-infer/tests/forward.rs +++ b/crates/aienos-infer/tests/forward.rs @@ -8,7 +8,10 @@ //! 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, Gguf, Model, Tokenizer, Q8_ALL, Q8_DOWN, Q8_GATE_UP, Q8_OUTPUT, Q8_QKV, + Q8_WO, +}; use std::time::Instant; fn model_bytes() -> Option<Vec<u8>> { @@ -91,7 +94,7 @@ fn decode_round_trips_text() { } } -fn check(q8k: bool, max_logit_diff: f32) { +fn check(q8k: bool, int8: bool, max_logit_diff: f32) { let Some(bytes) = model_bytes() else { return }; let g = Gguf::parse(&bytes).unwrap(); let m = Model::new(&g).unwrap(); @@ -104,6 +107,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.int8_dot = int8; let t0 = Instant::now(); st.prefill(&m, &ids).unwrap(); if name == "cow" { @@ -177,6 +181,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.int8_dot = int8; st.prefill(&m, &ids).unwrap(); let mut hit = 0; for (i, &(t, gap)) in r.steps.iter().enumerate() { @@ -202,12 +207,380 @@ 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); } /// 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); +} + +/// Int8 activations with i32 dots (aienos#34 L6 speed path): the same +/// arithmetic ggml runs, so the same bound as the Q8_K emulation. +#[test] +fn forward_matches_llama_cpp_int8_dot() { + check(false, true, 1.0); +} + +/// Parity of the int8 path against the f32 path over the recorded 64-token +/// sequence (docs/l6b-int8-qualification.md, condition 2). PASS RULE: the +/// int8 tokens equal the f32 tokens. The per-position maximum absolute logit +/// difference is reported, not gated. Prints `PARITY_*` lines for +/// scripts/l6_host_receipt.sh. Run with: +/// `cargo test --release -p aienos-infer --test forward int8_parity -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "model-backed, minutes on one core; run locally"] +fn int8_parity_64_tokens_vs_f32() { + const N: usize = 64; + let Some(bytes) = model_bytes() else { + panic!("model file required"); + }; + let g = Gguf::parse(&bytes).unwrap(); + let m = Model::new(&g).unwrap(); + let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap(); + let ids = tok.encode_chat("What is the capital of France?").unwrap(); + // Same loop as examples/l6_host.rs: greedy, end-of-turn ignored. + let run = |int8: bool| -> (Vec<u32>, Vec<Vec<f32>>) { + let mut st = DecodeState::new(&m, ids.len() + N + 8); + st.int8_dot = int8; + st.prefill(&m, &ids).unwrap(); + let (mut out, mut logits) = (Vec::new(), Vec::new()); + loop { + let t = argmax(&st.logits); + out.push(t); + logits.push(st.logits.clone()); + if out.len() == N { + break; + } + st.forward(&m, t, true).unwrap(); + } + (out, logits) + }; + let (ft, fl) = run(false); + let (it, il) = run(true); + let first_div = ft.iter().zip(&it).position(|(a, b)| a != b); + // Positions after the first divergence have different histories. + let upto = first_div.map_or(N, |p| p + 1); + let per_pos: Vec<f32> = (0..upto) + .map(|p| { + fl[p] + .iter() + .zip(&il[p]) + .map(|(a, b)| (a - b).abs()) + .fold(0f32, f32::max) + }) + .collect(); + let (maxpos, maxdiff) = + per_pos.iter().enumerate().fold( + (0, 0f32), + |(bp, bv), (p, &v)| if v > bv { (p, v) } else { (bp, bv) }, + ); + let join = |v: &[String]| v.join(" "); + println!( + "PARITY_TOKENS_IDENTICAL: {}", + if first_div.is_none() { "yes" } else { "no" } + ); + println!( + "PARITY_FIRST_DIVERGENCE: {}", + first_div.map_or("none".to_string(), |p| p.to_string()) + ); + println!("PARITY_COMPARED_POSITIONS: {upto}"); + println!("PARITY_MAX_LOGIT_ABS_DIFF: {maxdiff}"); + println!("PARITY_MAX_LOGIT_ABS_DIFF_POSITION: {maxpos}"); + println!( + "PARITY_PER_POSITION_MAX: {}", + join(&per_pos.iter().map(|v| v.to_string()).collect::<Vec<_>>()) + ); + println!( + "PARITY_F32_TOKENS: {}", + join(&ft.iter().map(|v| v.to_string()).collect::<Vec<_>>()) + ); + println!( + "PARITY_INT8_TOKENS: {}", + join(&it.iter().map(|v| v.to_string()).collect::<Vec<_>>()) + ); + assert!( + first_div.is_none(), + "int8 tokens diverge from f32 at index {first_div:?}" + ); +} + +/// aienos#34 int8 parity diagnosis (2026-10-11). Diagnosis only: it does not +/// change the parity rule, the default path or `INT8_PROMOTION_DEFAULT`. +/// +/// The recorded parity run (`evidence/l6_host_3f5a22426976_l6b_parity.json`) +/// has f32 and int8 agree on indexes 0 to 11 and split at index 12 (f32 4897, +/// int8 53692). This test replays that common history teacher-forced (prompt +/// plus the 12 shared tokens) and compares the index-12 decision across paths: +/// plain f32, int8, f32 dots on Q8_K-rounded activations (`emulate_q8k`), int8 +/// restricted to one matvec class or one layer, and int8 everywhere except one +/// class or layer. It also compares against llama.cpp's logits for the same +/// history (`tests/fixtures/ref_fr_idx12_logits.f32`, from +/// `tests/ref/llama_ref_hist.c`). Prints `DIAG_*` lines; asserts only that the +/// recorded split reproduces and that the f32 path is deterministic. +/// `cargo test --release -p aienos-infer --test forward int8_divergence -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "model-backed, minutes on one core; run locally"] +fn int8_divergence_diagnosis_index_12() { + const F32_TOK: u32 = 4897; + const INT8_TOK: u32 = 53692; + const COMMON: [u32; 12] = [ + 791, 6864, 315, 9822, 374, 12366, 13, 128009, 128006, 78191, 128007, 271, + ]; + let Some(bytes) = model_bytes() else { + panic!("model file required"); + }; + let g = Gguf::parse(&bytes).unwrap(); + let m = Model::new(&g).unwrap(); + let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap(); + let ids = tok.encode_chat("What is the capital of France?").unwrap(); + assert_eq!(ids, reference("fr").ids, "prompt ids differ from llama.cpp"); + let n_layer = m.layers.len(); + assert!(n_layer <= 64); + + // Logits after every position of the history (13 decisions, indexes 0..=12). + let run = |int8: bool, round: bool, layers: u64, classes: u8| -> Vec<Vec<f32>> { + let mut st = DecodeState::new(&m, ids.len() + COMMON.len() + 1); + st.int8_dot = int8; + st.emulate_q8k = round; + st.q8_layers = layers; + st.q8_classes = classes; + st.prefill(&m, &ids).unwrap(); + let mut out = vec![st.logits.clone()]; + for &t in &COMMON { + st.forward(&m, t, true).unwrap(); + out.push(st.logits.clone()); + } + out + }; + let top2 = |l: &[f32]| -> (u32, f32) { + let (mut b1, mut b2, mut bi) = (f32::NEG_INFINITY, f32::NEG_INFINITY, 0u32); + for (i, &v) in l.iter().enumerate() { + if v > b1 { + (b2, b1, bi) = (b1, v, i as u32); + } else if v > b2 { + b2 = v; + } + } + (bi, b1 - b2) + }; + let maxdiff = |a: &[f32], b: &[f32]| { + a.iter() + .zip(b) + .map(|(x, y)| (x - y).abs()) + .fold(0f32, f32::max) + }; + let raw = std::fs::read(format!( + "{}/tests/fixtures/ref_fr_idx12_logits.f32", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(); + let llama: Vec<f32> = raw + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + + let f32l = run(false, false, u64::MAX, Q8_ALL); + let base = &f32l[12]; + assert_eq!(llama.len(), base.len()); + let report = |name: &str, l: &[f32]| { + let (am, gap) = top2(l); + println!( + "DIAG_MODE {name}: argmax {am} top1_top2_gap {gap:.6} logit_{F32_TOK} {:.6} logit_{INT8_TOK} {:.6} \ + f32tok_minus_int8tok {:.6} maxdiff_vs_f32 {:.6} maxdiff_vs_llama {:.6}", + l[F32_TOK as usize], + l[INT8_TOK as usize], + l[F32_TOK as usize] - l[INT8_TOK as usize], + maxdiff(l, base), + maxdiff(l, &llama), + ); + am + }; + + // Negative control: the f32 path is deterministic. + let again = run(false, false, u64::MAX, Q8_ALL); + let repeat_diff = maxdiff(&again[12], base); + println!("DIAG_F32_REPEAT_MAXDIFF: {repeat_diff}"); + + let i8l = run(true, false, u64::MAX, Q8_ALL); + let eml = run(false, true, u64::MAX, Q8_ALL); + for p in 0..=12 { + let (fa, fg) = top2(&f32l[p]); + let (ia, ig) = top2(&i8l[p]); + println!( + "DIAG_POS {p}: f32 argmax {fa} gap {fg:.6} | int8 argmax {ia} gap {ig:.6} | maxdiff {:.6} | emul_vs_int8 {:.6}", + maxdiff(&f32l[p], &i8l[p]), + maxdiff(&eml[p], &i8l[p]), + ); + } + let a_f32 = report("f32", base); + let a_int8 = report("int8", &i8l[12]); + report("emulate_q8k_f32_dots", &eml[12]); + report("llama_cpp", &llama); + + let classes = [ + ("qkv", Q8_QKV), + ("wo", Q8_WO), + ("gate_up", Q8_GATE_UP), + ("down", Q8_DOWN), + ("output", Q8_OUTPUT), + ]; + for (n, c) in classes { + report( + &format!("int8_only_{n}"), + &run(true, false, u64::MAX, c)[12], + ); + report( + &format!("int8_except_{n}"), + &run(true, false, u64::MAX, Q8_ALL & !c)[12], + ); + } + // Layer masks leave the output head on f32, so only layer effects show. + let no_out = Q8_ALL & !Q8_OUTPUT; + let all_layers = if n_layer == 64 { + u64::MAX + } else { + (1u64 << n_layer) - 1 + }; + report( + "int8_all_layers_f32_output", + &run(true, false, u64::MAX, no_out)[12], + ); + for l in 0..n_layer { + report( + &format!("int8_only_layer_{l:02}"), + &run(true, false, 1 << l, no_out)[12], + ); + report( + &format!("int8_except_layer_{l:02}"), + &run(true, false, all_layers & !(1 << l), no_out)[12], + ); + } + + assert_eq!(repeat_diff, 0.0, "f32 path not deterministic"); + assert_eq!( + a_f32, F32_TOK, + "recorded f32 choice at index 12 not reproduced" + ); + assert_eq!( + a_int8, INT8_TOK, + "recorded int8 choice at index 12 not reproduced" + ); +} + +/// Part of the aienos#34 int8 parity diagnosis: on a real activation (layer 0 +/// attention RMSNorm of the BOS embedding), the int8 matvec and the f32 +/// matvec over the same Q8_K-rounded activations both equal an f64 reference +/// of `row . round(x)` to rounding error, for every K-quant weight that layer +/// 0 feeds from that activation. So the int8 arithmetic itself adds nothing +/// beyond the activation rounding. +#[test] +fn int8_matvec_equals_rounded_f32_on_real_activation() { + use aienos_infer::decode::{q8k_round, rms_norm}; + use aienos_infer::quant::Q8Act; + let Some(bytes) = model_bytes() else { return }; + let g = Gguf::parse(&bytes).unwrap(); + let m = Model::new(&g).unwrap(); + let l0 = &m.layers[0]; + let e = m.params.embedding_length as usize; + let mut emb = vec![0f32; e]; + m.tok_embd.row_into(128000, &mut emb).unwrap(); + let mut h = vec![0f32; e]; + rms_norm(&emb, &l0.attn_norm, m.params.rms_norm_eps, &mut h); + let mut xr = h.clone(); + q8k_round(&mut xr); + let mut q8 = Q8Act::with_capacity(e); + q8.quantize(&h).unwrap(); + let ws = [ + ("wq", &l0.wq), + ("wk", &l0.wk), + ("wv", &l0.wv), + ("w_gate", &l0.w_gate), + ("w_up", &l0.w_up), + ]; + for (name, w) in ws { + assert!(w.is_kquant()); + let mut a = vec![0f32; w.rows]; + let mut scr = vec![0f32; w.cols]; + w.matvec(&xr, &mut a, &mut scr).unwrap(); + let mut b = vec![0f32; w.rows]; + w.matvec_q8(&q8, &mut b).unwrap(); + let mut row = vec![0f32; w.cols]; + let (mut da, mut db, mut mc) = (0f64, 0f64, 0f64); + for r in 0..w.rows { + w.row_into(r, &mut row).unwrap(); + let c: f64 = row + .iter() + .zip(&xr) + .map(|(p, q)| *p as f64 * *q as f64) + .sum(); + da = da.max((a[r] as f64 - c).abs()); + db = db.max((b[r] as f64 - c).abs()); + mc = mc.max(c.abs()); + } + println!("REAL_ACT {name}: max|f32-ref| {da:.3e} max|int8-ref| {db:.3e} max|ref| {mc:.3e}"); + assert!( + da <= 1e-5 * mc.max(1.0), + "{name}: f32 path off the f64 reference" + ); + assert!( + db <= 1e-5 * mc.max(1.0), + "{name}: int8 path off the f64 reference" + ); + } +} + +/// Part of the aienos#34 int8 parity diagnosis: int8 against the f32 path on +/// the same Q8_K-rounded activations (`emulate_q8k`), per matvec class, over +/// the first `n` prompt tokens. Prints `DRIFT` lines. The two compute the same +/// values per matvec (test above) but in a different summation order; the +/// rounding to the Q8_K grid is a step function, so a last-bit difference +/// upstream can move an activation to the neighbouring grid point. +/// `cargo test --release -p aienos-infer --test forward int8_vs_q8k_emulation_drift -- --ignored --nocapture` +#[test] +#[ignore = "model-backed, about a minute; run locally"] +fn int8_vs_q8k_emulation_drift() { + let Some(bytes) = model_bytes() else { + panic!("model file required"); + }; + let g = Gguf::parse(&bytes).unwrap(); + let m = Model::new(&g).unwrap(); + let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap(); + let ids = tok.encode_chat("What is the capital of France?").unwrap(); + let md = |a: &[f32], b: &[f32]| { + a.iter() + .zip(b) + .map(|(x, y)| (x - y).abs()) + .fold(0f32, f32::max) + }; + for n in [1usize, 2, 3, 8, ids.len()] { + let run = |int8: bool, round: bool, c: u8| { + let mut st = DecodeState::new(&m, ids.len() + 1); + st.int8_dot = int8; + st.emulate_q8k = round; + st.q8_classes = c; + st.prefill(&m, &ids[..n]).unwrap(); + st.logits.clone() + }; + let f = run(false, false, Q8_ALL); + for (name, c) in [ + ("qkv", Q8_QKV), + ("wo", Q8_WO), + ("gate_up", Q8_GATE_UP), + ("down", Q8_DOWN), + ("output", Q8_OUTPUT), + ("all", Q8_ALL), + ] { + let i = run(true, false, c); + let e = run(false, true, c); + println!( + "DRIFT tokens {n} class {name}: int8_vs_emul {:.3e} int8_vs_f32 {:.3e} emul_vs_f32 {:.3e}", + md(&i, &e), + md(&i, &f), + md(&e, &f) + ); + } + } } diff --git a/crates/aienos-infer/tests/golden.rs b/crates/aienos-infer/tests/golden.rs index ff533da5..d4336763 100644 --- a/crates/aienos-infer/tests/golden.rs +++ b/crates/aienos-infer/tests/golden.rs @@ -187,12 +187,21 @@ fn dot_helpers_match_dequant_then_dot() { let xa: &[f32; QK_K] = x.as_slice().try_into().unwrap(); let blk: &[u8; 144] = bin[..144].try_into().unwrap(); let want: f32 = w[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); - assert_eq!(dot_q4k_f32(blk, xa), want); + // Lane-summed, so only the f32 summation order differs from `want`. + let got = dot_q4k_f32(blk, xa); + assert!( + (got - want).abs() <= 1e-4 * want.abs().max(1.0), + "{got} vs {want}" + ); let bin6 = fx("q6k.bin"); let w6 = f32s(&fx("q6k.f32")); let blk6: &[u8; 210] = bin6[..210].try_into().unwrap(); let want6: f32 = w6[..QK_K].iter().zip(&x).map(|(a, b)| a * b).sum(); - assert_eq!(dot_q6k_f32(blk6, xa), want6); + let got6 = dot_q6k_f32(blk6, xa); + assert!( + (got6 - want6).abs() <= 1e-4 * want6.abs().max(1.0), + "{got6} vs {want6}" + ); // Row of 4 blocks. let x4: Vec<f32> = (0..4 * QK_K).map(|i| (i % 5) as f32 - 2.0).collect(); let w4: f32 = w[..4 * QK_K].iter().zip(&x4).map(|(a, b)| a * b).sum(); diff --git a/crates/aienos-infer/tests/ref/llama_ref_hist.c b/crates/aienos-infer/tests/ref/llama_ref_hist.c new file mode 100644 index 00000000..432cd6c9 --- /dev/null +++ b/crates/aienos-infer/tests/ref/llama_ref_hist.c @@ -0,0 +1,60 @@ +/* Reference harness for the int8 parity diagnosis (aienos#34, 2026-10-11). + * Links the locally built llama.cpp (libllama), single thread, CPU only, and + * replays a fixed token history exactly as llama_ref.c does: the first + * N_PROMPT ids decoded as one batch, every later id decoded one at a time, + * end-of-generation tokens NOT treated as a stop (the history is given). + * Prints, for the logits after the last id: + * argmax <id> gap <top1-top2> + * logit <id> <value> (for each WATCH id) + * and writes all n_vocab logits (f32 LE) to LOGITS_OUT. + * usage: llama_ref_hist MODEL.gguf LOGITS_OUT.bin N_PROMPT WATCH1,WATCH2 id... + * Build: cc -O2 llama_ref_hist.c -I$LLAMA/include -I$LLAMA/ggml/include \ + * -L$LLAMA/build/bin -lllama -lggml -lggml-base -Wl,-rpath,$LLAMA/build/bin */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "llama.h" +#include "ggml-backend.h" + +int main(int argc, char **argv) { + if (argc < 6) return 2; + int np = atoi(argv[3]); + int n = argc - 5; + if (np < 1 || np > n || n > 4096) return 2; + static llama_token toks[4096]; + for (int i = 0; i < n; i++) toks[i] = atoi(argv[5 + i]); + ggml_backend_load_all(); + llama_backend_init(); + struct llama_model_params mp = llama_model_default_params(); + mp.n_gpu_layers = 0; + struct llama_model *m = llama_model_load_from_file(argv[1], mp); + if (!m) return 3; + int nv = llama_vocab_n_tokens(llama_model_get_vocab(m)); + struct llama_context_params cp = llama_context_default_params(); + cp.n_ctx = 512; cp.n_batch = 512; cp.n_threads = 1; cp.n_threads_batch = 1; + struct llama_context *c = llama_init_from_model(m, cp); + if (!c) return 5; + if (llama_decode(c, llama_batch_get_one(toks, np))) return 6; + for (int i = np; i < n; i++) + if (llama_decode(c, llama_batch_get_one(&toks[i], 1))) return 7; + float *lg = llama_get_logits_ith(c, -1); + int b = 0; float b1 = lg[0], b2 = -1e30f; + for (int i = 1; i < nv; i++) { + if (lg[i] > b1) { b2 = b1; b1 = lg[i]; b = i; } else if (lg[i] > b2) { b2 = lg[i]; } + } + printf("argmax %d gap %.6f\n", b, b1 - b2); + char *w = argv[4]; + while (*w) { + int id = atoi(w); + if (id >= 0 && id < nv) printf("logit %d %.6f\n", id, lg[id]); + char *comma = strchr(w, ','); + if (!comma) break; + w = comma + 1; + } + FILE *f = fopen(argv[2], "wb"); + if (!f) return 8; + fwrite(lg, sizeof(float), nv, f); + fclose(f); + llama_free(c); llama_model_free(m); + return 0; +} diff --git a/docs/.crumb b/docs/.crumb index b9d2ead3..9c907866 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:55bcc89f5282eb2e3f4e86d882abdfb5f4ea39e427ef97ef620b2267e5701eb1", - "compiled_at": "2026-10-10T04:29:33Z", + "compiled_at": "2026-10-11T01:16:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:30f908b47375e088c78fe9123dac1ef2df0551c10de30c8c19ba7b053c065f91", + "digest": "sha256:98e2f17d73935a249d0048ff81b0e2a2d7e1ad23b0b5e91f63ffb51b153365af", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 66, - "generated_at_commit": "ed308de52ede1d4c8a211d88e0e4a3ac5c92ec23", - "source_tree": "sha256:4be513f71b655a5ddef8e3bb8bf5b15e77f9cb4ca5214a8e290af31a24b38cab" + "files": 68, + "generated_at_commit": "02edc84247d9ff8a06750ec885b3c7a006fc5dbe", + "source_tree": "sha256:3bf9c1dc1455ee38ce6bed7053dcf1dcb044f4c61bb84de05253165934c3eab6" }, "owner_lane": "", "provenance": { diff --git a/docs/l6b-int8-divergence-diagnosis.md b/docs/l6b-int8-divergence-diagnosis.md new file mode 100644 index 00000000..efcc9d45 --- /dev/null +++ b/docs/l6b-int8-divergence-diagnosis.md @@ -0,0 +1,85 @@ +# L6-B int8 vs f32 divergence at token index 12: diagnosis (aienos#34, PR #300) + +Diagnosis only (2026-10-11). Nothing here changes the parity rule in `docs/l6b-int8-qualification.md`, the +default path (f32), `INT8_PROMOTION_DEFAULT` (false) or the recorded FAIL. The int8 path stays unpromoted. + +Evidence: `evidence/l6b_int8_divergence_3f5a22426976.json` (commit a362beb, Spark spark-b87b, core 19 = +Cortex-X925 0xd85, release build with `+dotprod,+i8mm`, `quietlock check` clear). Reproduce with +`scripts/l6b_divergence_receipt.sh`. Every number below is read from that file unless marked otherwise. + +## Question + +The recorded parity run (`evidence/l6_host_3f5a22426976_l6b_parity.json`) has f32 and int8 agree on token +indexes 0 to 11 and split at index 12 (f32 4897, int8 53692). Is that an int8 defect (accumulation order, +saturation, rounding, one badly quantized tensor), or activation-quantization noise meeting a close decision? + +## Method + +All runs replay the same history teacher-forced: the 17 prompt ids plus the 12 tokens both paths agree on. +The decision at index 12 is the argmax of the logits after the last of those. Paths compared: + +- `f32`: the default path; run twice as a negative control (determinism). +- `int8`: the opt-in path (activations on ggml's Q8_K grid, i32 block dots). +- `emulate_q8k_f32_dots`: the existing `DecodeState::emulate_q8k`: the same Q8_K rounding of the same + activations, but f32 dots, so it differs from int8 only in summation order. +- int8 restricted to one matvec class or one layer, and int8 everywhere except one class or one layer, through + the new diagnostic selectors `DecodeState::q8_classes` / `q8_layers` (default: all; consulted only when + `int8_dot` or `emulate_q8k` is on, so the f32 path is untouched). Layer masks keep the output head on f32. +- llama.cpp 4a89937 (`~/llama.cpp-build`, CPU, 1 thread) on the same history through the new C harness + `crates/aienos-infer/tests/ref/llama_ref_hist.c` (prompt as one batch, later tokens one at a time, as + `llama_ref.c` does). Its logits are committed as `tests/fixtures/ref_fr_idx12_logits.f32`; the receipt + rebuilds the harness and checks the bytes match (`fixture_reproduced: true`; two runs bit-identical). + +Tests: `int8_divergence_diagnosis_index_12` and `int8_vs_q8k_emulation_drift` (ignored, model-backed) and +`int8_matvec_equals_rounded_f32_on_real_activation` (model-backed, skips without the model). + +## Findings + +1. **Reproduced.** Teacher-forced, f32 picks 4897 (top1-top2 gap 0.349) and int8 picks 53692 (gap 0.393). + The f32 repeat differs by exactly 0. +2. **Index 12 is the first close decision.** The f32 top1-top2 gap at indexes 0 to 11 is between 4.97 and + 14.40 logits; at index 12 it is 0.349. The int8-vs-f32 maximum logit difference is 0.43 to 1.29 at every + index, so index 12 is the first place where the noise is larger than the margin. Index 12 is the first token + of an unprompted second assistant turn (after end-of-turn, the assistant header and a blank line). +3. **llama.cpp makes the int8 choice.** On the same history llama.cpp picks 53692 with gap 0.091 (logit 4897: + 20.286, 53692: 20.377). llama.cpp also quantizes activations to Q8_K for these weight types. Max absolute + logit difference at index 12: our f32 vs llama.cpp 1.059, our int8 vs llama.cpp 1.304. +4. **The int8 arithmetic is exact for what it computes.** On a real activation (layer 0 attention RMSNorm of + BOS), the int8 matvec and the f32 matvec over the same Q8_K-rounded activation both equal an f64 reference + to within 6.6e-7 absolute for wq, wk, wv, w_gate and w_up (largest reference value 5.37). The unit tests + already pin the block dots and `q8k_properties_bounds_and_error` pins |q| <= 127 with the largest magnitude + at -127, so there is no saturation by construction. The i32 accumulators cannot overflow: per Q4_K block + |sumi| <= 8 x 32 x 15 x 128 x 63 < 2^28 (6-bit scales); per Q6_K block |isum| <= 16 x 16 x 32 x 128 x 128 + < 2^31 (arithmetic from the formats, not measured). +5. **No single layer or class carries the flip.** With int8 on only one class (5 runs) or only one layer (16 + runs) every run keeps the f32 choice 4897. With int8 everywhere except one class or layer, 19 of 21 runs keep + the int8 choice 53692; only "except qkv" and "except layer 3" go back to 4897. The output head alone moves + the logits by at most 0.077. The flip is the accumulated effect of activation rounding across most of the + network, not one tensor. +6. **Two implementations of the same Q8_K arithmetic also disagree here.** `emulate_q8k_f32_dots` keeps 4897 + (gap 0.124) while int8 picks 53692; the two differ by up to 1.42 logits at index 12 although each matvec + agrees to about 1e-6. The drift test shows how: after 1 prompt token int8 and emulation agree to within 6e-6 + for every class; from 2 to 3 tokens on, every class whose output is rounded again downstream drifts by 0.13 to + 0.67, while the output head (no rounding after it) stays within 4e-6 at every length. + Mechanism, INFERRED (confidence about 85%, not instrumented per activation): Q8_K rounding is a step + function, so a last-bit summation-order difference upstream can move a single activation to the neighbouring + grid point (a jump of one quantization step, about amax/127), and those jumps compound through later layers + and the cached keys and values. + +## Conclusion + +The index-12 divergence is activation-quantization noise (0.4 to 1.3 logits on this prompt) meeting a near-tie +(0.35 logits) in the f32 path. No defect was found in the int8 arithmetic: it computes exactly the Q8_K dot it +is defined to compute, llama.cpp makes the same choice at index 12, and our own f32-dot emulation of the same +rounding lands on the other side of the tie. Route (a) in the round-1 receipt ("an engineering cause found and +fixed in the int8 path") has no defect to fix on this evidence. Under the registered rule (64 identical token ids +against f32) any path that rounds activations to Q8_K, llama.cpp included, can fail wherever the f32 margin is +below that noise. Whether the rule should change is Drake's decision (route (b)); this document does not +propose or apply a new criterion. + +## Limits + +- One model, one prompt, one history, one machine. The llama.cpp comparison is the CPU backend at 4a89937, one + thread; other backends or thread counts may sum in a different order. +- The flip mechanism in finding 6 is inferred from the drift pattern, not from counting grid moves. +- The selectors and tests are diagnostic; they do not change any shipped path. The kernel crate still runs f32. diff --git a/docs/l6b-int8-qualification.md b/docs/l6b-int8-qualification.md new file mode 100644 index 00000000..2724933b --- /dev/null +++ b/docs/l6b-int8-qualification.md @@ -0,0 +1,151 @@ +# L6-B int8 dot path: qualification receipts (aienos#34, draft PR #300) + +Pre-registered before any test or code for this round (2026-10-10). Drake's ruling +(aien-architecture#190, last comment on PR #300): int8 promotion is approved for supported hardware, +gated, subject to native qualification. The PR stays a draft until the four conditions below have +receipts. The f32 path stays as the fallback. This round produces receipts only. It does not change +the kernel's default path, any kernel source outside `crates/aienos-infer`, or anything to do with +the accelerator. + +## Terms + +- f32 path: activations stay f32 (`DecodeState.int8_dot == false`). The default today. +- int8 path: activations on ggml's Q8_K grid, i32 dots (`int8_dot == true`). +- Features: `Features { dotprod, i8mm }`, supplied by the caller (the crate is `no_std` and + `forbid(unsafe_code)`, so it never reads CPU registers itself). + +## Condition 1: CPU-feature detection + +Design (all in new module `crates/aienos-infer/src/dotpath.rs`): + +- `pub struct Features { pub dotprod: bool, pub i8mm: bool }`, plus `Features::from_hwcap(hwcap, hwcap2)` + that decodes the Linux auxiliary-vector words (`HWCAP_ASIMDDP` = bit 20 of `AT_HWCAP`; + `HWCAP2_I8MM` = bit 13 of `AT_HWCAP2`, checked against `/usr/include/asm/hwcap.h`; the brief said + both are in `AT_HWCAP`, but I8MM is in `AT_HWCAP2`, so that is what the code and receipt use). +- `pub enum DotPath { F32, Int8 }`. +- `DotPath::select(features, requested)` calls `select_with(features, requested, INT8_PROMOTION_DEFAULT)`. + Rule: `Int8` iff `requested || (promotion && features.dotprod && features.i8mm)`, else `F32`. + An explicit request is honoured even without the features: the int8 path is correct on every CPU + (portable integer code), only slower than with `usdot`. +- Host harness (`examples/l6_host.rs`) fills `Features` from `/proc/self/auxv` (the same kernel + vector that `getauxval` returns, read through std so the example needs no `unsafe`), on aarch64 + only; other architectures report no features. +- Kernel side: a documented hook point only (a comment in `dotpath.rs` naming `ID_AA64ISAR0_EL1.DP` + and `ID_AA64ISAR1_EL1.I8MM`). Kernel register reads go through the manual-guard process and are + not implemented here. + +Tests (in `dotpath.rs`): + +| Test | Before | After | +|---|---|---| +| `dotpath::tests::select_matrix_all_combinations` (4 feature sets x requested x promotion, 16 rows) | absent (does not compile) | PASS | +| `dotpath::tests::features_from_hwcap_bits` | absent | PASS | + +## Condition 2: numerical parity + +Pre-registered criterion, stated before measuring: + +- Subject: the 64-token greedy sequence of the recorded f32 record (`evidence/l6_host_3f5a22426976_l6b.json`, + prompt "What is the capital of France?", Llama-3.2-1B-Instruct Q4_K_M, sha256 3f5a2242..., end-of-turn + ignored, same loop as `l6_host`). +- PASS RULE (gated): the int8 path produces the identical 64 token ids as the f32 path run in the same + process. A second reported check: the in-run f32 tokens equal the recorded f32 tokens in the evidence JSON. +- REPORTED, NOT GATED this round: the per-position maximum absolute difference between the int8 and + f32 logit vectors, and the overall maximum. Positions after a first token divergence are not + comparable (different histories), so the logit comparison covers positions 0 through the first + divergence index inclusive (all 64 if tokens are identical). +- If parity FAILS it is recorded as FAIL with the numbers. Nothing is tuned to make it pass. +- Expected result: unknown before the run. The existing llama.cpp-comparison tests show int8 stays + within the Q8_K bound against llama.cpp; they do not prove token identity against our own f32 path. + +Mechanism: ignored model-backed test `tests/forward.rs::int8_parity_64_tokens_vs_f32` prints +`PARITY_*` lines (`--nocapture`). `scripts/l6_host_receipt.sh` runs it (release build, pinned to one +core, 1 thread) and writes a `parity_int8_vs_f32` block: `{tokens_identical, first_divergence_index, +max_logit_abs_diff, max_logit_abs_diff_position, per_position_max_logit_abs_diff, compared_positions, +f32_matches_recorded, rule, verdict}`. The existing top-level string `parity` (first 8 ids against the golden +reply) is left unchanged. New flag `--parity-only` writes only +`evidence/l6_host_<sha12>_l6b_parity.json` without redoing the speed legs, so the committed speed +receipt is not overwritten. + +## Condition 3: rollback path + +- Default is f32. `pub const INT8_PROMOTION_DEFAULT: bool = false;` in `dotpath.rs` is the kernel's + build-time switch: with it `false`, `DotPath::select` returns `F32` unless the caller explicitly + requests int8, whatever the features say. Flipping it is the only change needed to promote, + flipping it back is the rollback. +- Host: `AIENOS_DOT=f32` forces f32 regardless of features and regardless of the constant; + `AIENOS_DOT=int8` forces int8; unset means `auto` (the selector with detected features). + Parsing lives in `DotSetting::parse` so it is testable without std. +- Operator rollback step (also in the PR body): set `AIENOS_DOT=f32` for a host run, or, for a kernel + build, make sure `INT8_PROMOTION_DEFAULT` is `false` (it is) and that the kernel does not request + int8, then rebuild. The kernel crate is untouched by this round and still runs f32. + +Tests: + +| Test | Before | After | +|---|---|---| +| `dotpath::tests::rollback_setting_f32_forces_f32_with_all_features` (setting f32, features present, promotion true gives F32) | absent | PASS | +| `dotpath::tests::default_constant_off_and_auto_is_f32_with_features` | absent | PASS | +| `dotpath::tests::setting_parse` (unset=auto, f32, int8, auto, garbage rejected) | absent | PASS | + +## Condition 4: native regression tests (CI, no model) + +Kept as they are: `quant::tests::q4k_int8_dot_matches_f32_dot_of_rounded_activations`, +`q6k_int8_dot_matches_f32_dot_of_rounded_activations`, `int8_row_dot_matches_block_sum_and_checks_lengths`, +`q8k_quantize_matches_q8k_round`. + +New: + +| Test | Checks | Before | After | +|---|---|---|---| +| the selector matrix and rollback tests above | selection rule | absent | PASS | +| `quant::tests::q8k_properties_bounds_and_error` | |q| <= 127; largest-magnitude value maps to -127; per-value error <= d/2 (+1 ulp slack); group sums equal sums of values; negation symmetry; scaling by a power of two scales d only and keeps q | absent | PASS | +| `quant::tests::golden_q4k_q8k_i32_accumulations` | fixed block, hardcoded (sumi, mins) | absent | PASS | +| `quant::tests::golden_q6k_q8k_i32_accumulations` | fixed block, hardcoded isum | absent | PASS | + +Golden blocks (derived independently with a throwaway awk script from the ggml block layout, +not from the crate's code, so an inner-loop change is caught): + +- Q4_K: d = 1.0, dmin = 0.5, scale bytes `41 82 C3 14 25 76 37 08 9A 5B DC 2D` (exercises the + high-bit extension for sub-blocks 4 to 7), `qs[i] = (37 i + 11) mod 256`, `y[i] = ((29 i + 7) mod 255) - 127`, + `yd = 0.25`. Expected `sumi = -284188`, `mins = -7913`, dot = `-70057.875`. +- Q6_K: `ql[i] = (53 i + 5) mod 256`, `qh[i] = (91 i + 17) mod 256`, scales `((23 i + 3) mod 61) - 30` as i8, + d = 0.25, `y[i] = ((31 i + 5) mod 255) - 127`, `yd = 0.5`. Expected `isum = -275808`, dot = `-34476.0`. + +To expose the accumulations without duplicating the loops, the golden tests call two small +`pub(crate)` helpers that the existing block dots are refactored to use (`q4k_q8k_accum`, +`q6k_q8k_isum`); the f32 results of the block dots must be bit-identical to before (the existing +tests plus the model-backed Q8_K comparison cover this). + +Model-backed parity test `int8_parity_64_tokens_vs_f32` stays `#[ignore]` in CI and is run locally once; +its output is pasted into the PR body. + +## What must not change + +- Default path stays f32. No kernel source outside `crates/aienos-infer`. Nothing about the accelerator. +- The f32 dot code and results stay bit-identical. No new dependencies. No Python. +- The speed receipt `evidence/l6_host_3f5a22426976_l6b.json` is not rewritten. + +## Results (appended after the run; the sections above are unchanged) + +Run on the Spark (spark-b87b) at commit b2c4710 plus the receipt-script parsing fix, release build, +`RUSTFLAGS="-C target-feature=+dotprod,+i8mm"`, pinned to cpu19 (Cortex-X925), `quietlock check` clear. +Evidence: `evidence/l6_host_3f5a22426976_l6b_parity.json`. The run was repeated once after fixing the script's +line parsing (libtest prints `test name ... ` without a newline); the numbers were identical both times. + +- Condition 2, parity: **FAIL**. The in-run f32 tokens equal the recorded f32 tokens (`f32_matches_recorded: true`). + The int8 tokens match for indexes 0 to 11 (the whole first reply, "The capital of France is Paris." and the + end-of-turn that follows) and diverge at index 12 (f32 4897, int8 53692). Max absolute logit difference over the + 13 comparable positions 0 to 12: 1.2880421 at position 11 (per position: 0.670, 0.676, 0.639, 0.501, 0.566, + 0.552, 0.434, 0.733, 0.597, 0.612, 0.781, 1.288, 1.068). Nothing was tuned. The same divergence is visible in + the already committed speed receipt (int8 text continues "Actually, ..." where f32 says "I apologize ..."). +- Conditions 1, 3 and 4: tests as registered, all PASS (`cargo test --release -p aienos-infer`: 32 library + tests, 4 model-backed forward tests (llama.cpp comparison, int8 included) and 15 other tests pass, 2 ignored). +- Therefore the PR stays a draft: condition 2 is not met. + +## Diagnosis of the condition 2 failure (appended 2026-10-11; the sections above are unchanged) + +`docs/l6b-int8-divergence-diagnosis.md`, evidence `evidence/l6b_int8_divergence_3f5a22426976.json`. Finding: +no int8 arithmetic defect; the split at index 12 is Q8_K activation-rounding noise against a 0.35-logit f32 +margin, and llama.cpp makes the int8 choice there. The verdict of condition 2 stays FAIL, the rule is unchanged +and the PR stays a draft. diff --git a/evidence/l6_host_3f5a22426976_l6b.json b/evidence/l6_host_3f5a22426976_l6b.json new file mode 100644 index 00000000..7addbcf0 --- /dev/null +++ b/evidence/l6_host_3f5a22426976_l6b.json @@ -0,0 +1,695 @@ +{ + "commit": "1855a0d41ba16c0845d67aa07496e686aeca7856", + "core_pinned": 0, + "cpu_part": "0xd85x10,0xd87x10", + "decode_tokens": 63, + "dot": "int8", + "generated_at_utc": "2026-10-10T10:24:58Z", + "golden_ids": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009 + ], + "governor": "performance", + "harness_command": "AIENOS_N=64 AIENOS_DOT=<f32|int8> taskset -c <core> cargo run --release -p aienos-infer --example l6_host", + "host": "spark-b87b", + "kernel": "7.0.0-1019-nvidia", + "legs": { + "core0": { + "core_pinned": 0, + "cpu_part": "0xd87", + "decode_tokens": 63, + "dot": "int8", + "exit_code": 0, + "mean_tok_us": 92830.6, + "parity": "PASS", + "prefill_us": 1164993, + "text": "The capital of France is Paris.assistant\\n\\nActually, the capital of France is Paris, but the official name of the capital is \\\"République de France\\\" (Republic of France). Paris is the largest city in France and is known for its rich history, art, fashion, and cuisine.\\n\\nHowever", + "tok_per_s": 10.772, + "tok_us": [ + 91891, + 91876, + 91945, + 92138, + 92448, + 92224, + 92188, + 92199, + 92170, + 92405, + 92514, + 92248, + 92210, + 92315, + 92566, + 92697, + 92389, + 92428, + 92391, + 92432, + 92408, + 92500, + 92461, + 92520, + 92547, + 92748, + 92656, + 92771, + 92772, + 92695, + 92707, + 92771, + 92784, + 92811, + 93021, + 92892, + 92934, + 92963, + 92991, + 93104, + 93029, + 93056, + 93049, + 93100, + 93137, + 93215, + 93177, + 93237, + 93230, + 93316, + 93413, + 93313, + 93368, + 93496, + 93438, + 93462, + 93474, + 93504, + 93599, + 93688, + 93776, + 93786, + 93734 + ], + "tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 53692, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 719, + 279, + 4033, + 836, + 315, + 279, + 6864, + 374, + 330, + 85936, + 9780, + 37526, + 409, + 9822, + 1, + 320, + 39963, + 315, + 9822, + 570, + 12366, + 374, + 279, + 7928, + 3363, + 304, + 9822, + 323, + 374, + 3967, + 369, + 1202, + 9257, + 3925, + 11, + 1989, + 11, + 11401, + 11, + 323, + 36105, + 382, + 11458 + ] + }, + "core19": { + "core_pinned": 19, + "cpu_part": "0xd85", + "decode_tokens": 63, + "dot": "int8", + "exit_code": 0, + "mean_tok_us": 38541.0, + "parity": "PASS", + "prefill_us": 486702, + "text": "The capital of France is Paris.assistant\\n\\nActually, the capital of France is Paris, but the official name of the capital is \\\"République de France\\\" (Republic of France). Paris is the largest city in France and is known for its rich history, art, fashion, and cuisine.\\n\\nHowever", + "tok_per_s": 25.946, + "tok_us": [ + 38126, + 38248, + 38180, + 38139, + 38224, + 38275, + 38282, + 38208, + 38179, + 38285, + 38299, + 38261, + 38262, + 38287, + 38280, + 38347, + 38392, + 38294, + 38357, + 38352, + 38328, + 38388, + 38360, + 38858, + 39534, + 38683, + 38472, + 38531, + 38535, + 38505, + 38512, + 38543, + 38543, + 38503, + 38527, + 38554, + 38477, + 38472, + 38537, + 38528, + 38574, + 38648, + 38676, + 38669, + 38714, + 38775, + 38572, + 38642, + 38723, + 38697, + 38724, + 38777, + 38856, + 38841, + 38849, + 38788, + 38812, + 38842, + 38849, + 38831, + 38847, + 38913, + 38800 + ], + "tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 53692, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 719, + 279, + 4033, + 836, + 315, + 279, + 6864, + 374, + 330, + 85936, + 9780, + 37526, + 409, + 9822, + 1, + 320, + 39963, + 315, + 9822, + 570, + 12366, + 374, + 279, + 7928, + 3363, + 304, + 9822, + 323, + 374, + 3967, + 369, + 1202, + 9257, + 3925, + 11, + 1989, + 11, + 11401, + 11, + 323, + 36105, + 382, + 11458 + ] + }, + "f32_core0": { + "core_pinned": 0, + "cpu_part": "0xd87", + "decode_tokens": 63, + "dot": "f32", + "exit_code": 0, + "mean_tok_us": 716826.7, + "parity": "PASS", + "prefill_us": 10086393, + "text": "The capital of France is Paris.assistant\\n\\nThat\\'s incorrect. The capital of France is actually Paris, not Rome (which is the capital of Italy). Rome is the capital of Italy.assistant\\n\\nYou are correct, the capital of France is Paris, not Rome. Paris is the largest", + "tok_per_s": 1.395, + "tok_us": [ + 716133, + 715917, + 715732, + 715884, + 715983, + 716051, + 715987, + 716165, + 716151, + 716371, + 716216, + 716243, + 716341, + 716275, + 716491, + 716308, + 716168, + 716454, + 716444, + 716578, + 716466, + 716713, + 716570, + 716641, + 716774, + 716736, + 716734, + 716661, + 716620, + 716722, + 716697, + 717042, + 716762, + 716754, + 716710, + 716651, + 717084, + 717157, + 716954, + 717220, + 717419, + 717107, + 717135, + 717098, + 717087, + 717285, + 717310, + 717325, + 717269, + 717479, + 717443, + 717401, + 717265, + 717218, + 717323, + 717421, + 717617, + 717573, + 717735, + 717742, + 717735, + 717769, + 717769 + ], + "tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 4897, + 596, + 15465, + 13, + 578, + 6864, + 315, + 9822, + 374, + 3604, + 12366, + 11, + 539, + 22463, + 320, + 8370, + 374, + 279, + 6864, + 315, + 15704, + 570, + 22463, + 374, + 279, + 6864, + 315, + 15704, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 2675, + 527, + 4495, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 539, + 22463, + 13, + 12366, + 374, + 279, + 7928 + ] + }, + "f32_core19": { + "core_pinned": 19, + "cpu_part": "0xd85", + "decode_tokens": 63, + "dot": "f32", + "exit_code": 0, + "mean_tok_us": 256174.9, + "parity": "PASS", + "prefill_us": 3678027, + "text": "The capital of France is Paris.assistant\\n\\nThat\\'s incorrect. The capital of France is actually Paris, not Rome (which is the capital of Italy). Rome is the capital of Italy.assistant\\n\\nYou are correct, the capital of France is Paris, not Rome. Paris is the largest", + "tok_per_s": 3.904, + "tok_us": [ + 255485, + 256404, + 255853, + 254901, + 255033, + 254990, + 254966, + 254946, + 255056, + 255136, + 254970, + 257773, + 255021, + 256287, + 255088, + 256642, + 255247, + 255198, + 255273, + 255841, + 255100, + 257142, + 259874, + 258718, + 255477, + 255192, + 255242, + 255225, + 255374, + 255322, + 255381, + 255321, + 255383, + 257012, + 259586, + 257732, + 261008, + 256295, + 255402, + 256627, + 255560, + 255454, + 255482, + 255581, + 256145, + 255531, + 256487, + 255422, + 260574, + 258687, + 258787, + 255848, + 255593, + 256567, + 255449, + 255681, + 257930, + 255617, + 255743, + 255646, + 256584, + 255856, + 256270 + ], + "tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 4897, + 596, + 15465, + 13, + 578, + 6864, + 315, + 9822, + 374, + 3604, + 12366, + 11, + 539, + 22463, + 320, + 8370, + 374, + 279, + 6864, + 315, + 15704, + 570, + 22463, + 374, + 279, + 6864, + 315, + 15704, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 2675, + 527, + 4495, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 539, + 22463, + 13, + 12366, + 374, + 279, + 7928 + ] + } + }, + "llama_cpp": { + "build": "4a89937 1", + "command": "taskset -c 0 /home/drakestapleton/llama.cpp-build/build/bin/llama-bench -m /home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf -ngl 0 -t 1 -p 0 -n 64 -r 3 -o json", + "threads": 1, + "tok_per_s": 6.640933, + "tok_per_s_core19": 20.197503 + }, + "load1_at_start": 1.88, + "mean_tok_us": 92830.6, + "model": { + "path": "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "sha256": "3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1", + "size_bytes": 807694368 + }, + "nproc": 20, + "parity": "PASS", + "prefill_us": 1164993, + "prompt": "What is the capital of France?", + "reference": { + "file": "evidence/config_a_reference_bundle.json", + "note": "20 threads, server; not like for like", + "tok_per_s": 54.2 + }, + "rustflags": "-C target-feature=+dotprod,+i8mm", + "summary_tok_per_s": { + "f32_core0": 1.395, + "f32_core19": 3.904, + "int8_core0": 10.772, + "int8_core19": 25.946, + "llama_cpp_1thread_core0": 6.640933, + "llama_cpp_1thread_core19": 20.197503 + }, + "threads": 1, + "tok_per_s": 10.772, + "tok_us": [ + 91891, + 91876, + 91945, + 92138, + 92448, + 92224, + 92188, + 92199, + 92170, + 92405, + 92514, + 92248, + 92210, + 92315, + 92566, + 92697, + 92389, + 92428, + 92391, + 92432, + 92408, + 92500, + 92461, + 92520, + 92547, + 92748, + 92656, + 92771, + 92772, + 92695, + 92707, + 92771, + 92784, + 92811, + 93021, + 92892, + 92934, + 92963, + 92991, + 93104, + 93029, + 93056, + 93049, + 93100, + 93137, + 93215, + 93177, + 93237, + 93230, + 93316, + 93413, + 93313, + 93368, + 93496, + 93438, + 93462, + 93474, + 93504, + 93599, + 93688, + 93776, + 93786, + 93734 + ] +} diff --git a/evidence/l6_host_3f5a22426976_l6b_parity.json b/evidence/l6_host_3f5a22426976_l6b_parity.json new file mode 100644 index 00000000..8e844950 --- /dev/null +++ b/evidence/l6_host_3f5a22426976_l6b_parity.json @@ -0,0 +1,175 @@ +{ + "commit": "b2c4710acec5c7eaf742bc4b73176a2b7620da81", + "cpu_part": "0xd85x10,0xd87x10", + "generated_at_utc": "2026-10-10T14:41:51Z", + "governor": "performance", + "host": "spark-b87b", + "kernel": "7.0.0-1019-nvidia", + "load1_at_start": 8.64, + "model": { + "path": "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "sha256": "3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1" + }, + "parity_int8_vs_f32": { + "command": "AIENOS_MODEL=<model> taskset -c 19 cargo test --release -p aienos-infer --test forward int8_parity -- --ignored --nocapture --test-threads=1", + "compared_positions": 13, + "core_pinned": 19, + "f32_matches_recorded": true, + "f32_tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 4897, + 596, + 15465, + 13, + 578, + 6864, + 315, + 9822, + 374, + 3604, + 12366, + 11, + 539, + 22463, + 320, + 8370, + 374, + 279, + 6864, + 315, + 15704, + 570, + 22463, + 374, + 279, + 6864, + 315, + 15704, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 2675, + 527, + 4495, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 539, + 22463, + 13, + 12366, + 374, + 279, + 7928 + ], + "first_divergence_index": 12, + "int8_tokens": [ + 791, + 6864, + 315, + 9822, + 374, + 12366, + 13, + 128009, + 128006, + 78191, + 128007, + 271, + 53692, + 11, + 279, + 6864, + 315, + 9822, + 374, + 12366, + 11, + 719, + 279, + 4033, + 836, + 315, + 279, + 6864, + 374, + 330, + 85936, + 9780, + 37526, + 409, + 9822, + 1, + 320, + 39963, + 315, + 9822, + 570, + 12366, + 374, + 279, + 7928, + 3363, + 304, + 9822, + 323, + 374, + 3967, + 369, + 1202, + 9257, + 3925, + 11, + 1989, + 11, + 11401, + 11, + 323, + 36105, + 382, + 11458 + ], + "max_logit_abs_diff": 1.2880421, + "max_logit_abs_diff_position": 11, + "per_position_max_logit_abs_diff": [ + 0.6702888, + 0.67553055, + 0.6392782, + 0.5013132, + 0.56553733, + 0.55216885, + 0.4337257, + 0.73328114, + 0.59707165, + 0.61226845, + 0.78101856, + 1.2880421, + 1.0683174 + ], + "recorded_file": "evidence/l6_host_3f5a22426976_l6b.json", + "rule": "PASS iff the int8 path produces the identical 64 token ids as the f32 path (gated). Max abs logit difference is reported, not gated, this round.", + "test_exit_code": 101, + "tokens_identical": false, + "verdict": "FAIL" + }, + "rustflags": "-C target-feature=+dotprod,+i8mm" +} diff --git a/evidence/l6b_int8_divergence_3f5a22426976.json b/evidence/l6b_int8_divergence_3f5a22426976.json new file mode 100644 index 00000000..c5094bc1 --- /dev/null +++ b/evidence/l6b_int8_divergence_3f5a22426976.json @@ -0,0 +1,863 @@ +{ + "commit": "a362beb416a06b93d79d09bc6448bbc44238ef17", + "core_pinned": 19, + "cpu_part": "0xd85", + "drift_int8_vs_emulation": [ + { + "class": "qkv:", + "emulation_vs_f32": 0.007108, + "int8_vs_emulation": 0.000005722, + "int8_vs_f32": 0.007111, + "tokens": 1 + }, + { + "class": "wo:", + "emulation_vs_f32": 0.005120, + "int8_vs_emulation": 0.000001907, + "int8_vs_f32": 0.005121, + "tokens": 1 + }, + { + "class": "gate_up:", + "emulation_vs_f32": 0.4916, + "int8_vs_emulation": 0.000001669, + "int8_vs_f32": 0.4916, + "tokens": 1 + }, + { + "class": "down:", + "emulation_vs_f32": 0.1292, + "int8_vs_emulation": 0.000002414, + "int8_vs_f32": 0.1292, + "tokens": 1 + }, + { + "class": "output:", + "emulation_vs_f32": 0.2276, + "int8_vs_emulation": 0.000001207, + "int8_vs_f32": 0.2276, + "tokens": 1 + }, + { + "class": "all:", + "emulation_vs_f32": 0.5775, + "int8_vs_emulation": 0.000002027, + "int8_vs_f32": 0.5775, + "tokens": 1 + }, + { + "class": "qkv:", + "emulation_vs_f32": 0.3234, + "int8_vs_emulation": 0.00001335, + "int8_vs_f32": 0.3234, + "tokens": 2 + }, + { + "class": "wo:", + "emulation_vs_f32": 0.1919, + "int8_vs_emulation": 0.000009418, + "int8_vs_f32": 0.1919, + "tokens": 2 + }, + { + "class": "gate_up:", + "emulation_vs_f32": 0.2215, + "int8_vs_emulation": 0.1270, + "int8_vs_f32": 0.2137, + "tokens": 2 + }, + { + "class": "down:", + "emulation_vs_f32": 0.4196, + "int8_vs_emulation": 0.000008583, + "int8_vs_f32": 0.4196, + "tokens": 2 + }, + { + "class": "output:", + "emulation_vs_f32": 0.06733, + "int8_vs_emulation": 0.000001907, + "int8_vs_f32": 0.06733, + "tokens": 2 + }, + { + "class": "all:", + "emulation_vs_f32": 0.5169, + "int8_vs_emulation": 0.3758, + "int8_vs_f32": 0.6659, + "tokens": 2 + }, + { + "class": "qkv:", + "emulation_vs_f32": 0.7561, + "int8_vs_emulation": 0.1570, + "int8_vs_f32": 0.7381, + "tokens": 3 + }, + { + "class": "wo:", + "emulation_vs_f32": 0.3303, + "int8_vs_emulation": 0.1541, + "int8_vs_f32": 0.2575, + "tokens": 3 + }, + { + "class": "gate_up:", + "emulation_vs_f32": 0.4036, + "int8_vs_emulation": 0.2154, + "int8_vs_f32": 0.4871, + "tokens": 3 + }, + { + "class": "down:", + "emulation_vs_f32": 0.7202, + "int8_vs_emulation": 0.00001454, + "int8_vs_f32": 0.7202, + "tokens": 3 + }, + { + "class": "output:", + "emulation_vs_f32": 0.07191, + "int8_vs_emulation": 0.000001907, + "int8_vs_f32": 0.07191, + "tokens": 3 + }, + { + "class": "all:", + "emulation_vs_f32": 1.488, + "int8_vs_emulation": 0.3826, + "int8_vs_f32": 1.463, + "tokens": 3 + }, + { + "class": "qkv:", + "emulation_vs_f32": 0.1840, + "int8_vs_emulation": 0.04784, + "int8_vs_f32": 0.1652, + "tokens": 8 + }, + { + "class": "wo:", + "emulation_vs_f32": 0.08392, + "int8_vs_emulation": 0.05367, + "int8_vs_f32": 0.09495, + "tokens": 8 + }, + { + "class": "gate_up:", + "emulation_vs_f32": 0.1501, + "int8_vs_emulation": 0.1454, + "int8_vs_f32": 0.1135, + "tokens": 8 + }, + { + "class": "down:", + "emulation_vs_f32": 0.2600, + "int8_vs_emulation": 0.2797, + "int8_vs_f32": 0.2249, + "tokens": 8 + }, + { + "class": "output:", + "emulation_vs_f32": 0.1228, + "int8_vs_emulation": 0.000002861, + "int8_vs_f32": 0.1228, + "tokens": 8 + }, + { + "class": "all:", + "emulation_vs_f32": 0.3264, + "int8_vs_emulation": 0.3486, + "int8_vs_f32": 0.3478, + "tokens": 8 + }, + { + "class": "qkv:", + "emulation_vs_f32": 0.5407, + "int8_vs_emulation": 0.1676, + "int8_vs_f32": 0.3965, + "tokens": 17 + }, + { + "class": "wo:", + "emulation_vs_f32": 0.2122, + "int8_vs_emulation": 0.1253, + "int8_vs_f32": 0.1813, + "tokens": 17 + }, + { + "class": "gate_up:", + "emulation_vs_f32": 0.2143, + "int8_vs_emulation": 0.3230, + "int8_vs_f32": 0.2502, + "tokens": 17 + }, + { + "class": "down:", + "emulation_vs_f32": 0.4431, + "int8_vs_emulation": 0.5574, + "int8_vs_f32": 0.4776, + "tokens": 17 + }, + { + "class": "output:", + "emulation_vs_f32": 0.08368, + "int8_vs_emulation": 0.000003815, + "int8_vs_f32": 0.08368, + "tokens": 17 + }, + { + "class": "all:", + "emulation_vs_f32": 0.6431, + "int8_vs_emulation": 0.6728, + "int8_vs_f32": 0.6703, + "tokens": 17 + } + ], + "exit_codes": { + "diagnosis": 0, + "drift": 0, + "real_activation": 0 + }, + "f32_repeat_max_logit_diff": 0, + "generated_at_utc": "2026-10-11T01:15:39Z", + "history": "prompt (17 ids) + recorded common tokens 0..11; decision at index 12", + "host": "spark-b87b", + "kernel": "7.0.0-1019-nvidia", + "llama_cpp": { + "argmax": 53692, + "commit": "4a89937", + "fixture_reproduced": true, + "top1_top2_gap": 0.090738 + }, + "load1_at_start": 7.79, + "model": { + "path": "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "sha256": "3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1" + }, + "modes_at_index_12": [ + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.349283, + "logit_4897": 20.681486, + "logit_53692": 20.332203, + "maxdiff_vs_f32": 0.000000, + "maxdiff_vs_llama": 1.059041, + "mode": "f32", + "top1_top2_gap": 0.349283 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.393490, + "logit_4897": 20.282204, + "logit_53692": 20.675694, + "maxdiff_vs_f32": 1.068317, + "maxdiff_vs_llama": 1.303616, + "mode": "int8", + "top1_top2_gap": 0.393490 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.124151, + "logit_4897": 20.614862, + "logit_53692": 20.490711, + "maxdiff_vs_f32": 0.785524, + "maxdiff_vs_llama": 1.397524, + "mode": "emulate_q8k_f32_dots", + "top1_top2_gap": 0.124151 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.090738, + "logit_4897": 20.286430, + "logit_53692": 20.377169, + "maxdiff_vs_f32": 1.059041, + "maxdiff_vs_llama": 0.000000, + "mode": "llama_cpp", + "top1_top2_gap": 0.090738 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.133486, + "logit_4897": 20.469990, + "logit_53692": 20.336504, + "maxdiff_vs_f32": 0.403699, + "maxdiff_vs_llama": 1.085854, + "mode": "int8_only_qkv", + "top1_top2_gap": 0.133486 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.473511, + "logit_4897": 20.743996, + "logit_53692": 20.270485, + "maxdiff_vs_f32": 0.884953, + "maxdiff_vs_llama": 1.242867, + "mode": "int8_except_qkv", + "top1_top2_gap": 0.473511 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.194111, + "logit_4897": 20.690647, + "logit_53692": 20.496536, + "maxdiff_vs_f32": 0.429628, + "maxdiff_vs_llama": 1.081858, + "mode": "int8_only_wo", + "top1_top2_gap": 0.194111 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.663363, + "logit_4897": 20.242369, + "logit_53692": 20.905731, + "maxdiff_vs_f32": 1.345973, + "maxdiff_vs_llama": 1.101498, + "mode": "int8_except_wo", + "top1_top2_gap": 0.663363 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.447498, + "logit_4897": 20.899208, + "logit_53692": 20.451710, + "maxdiff_vs_f32": 0.364813, + "maxdiff_vs_llama": 1.179406, + "mode": "int8_only_gate_up", + "top1_top2_gap": 0.447498 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.329693, + "logit_4897": 20.079603, + "logit_53692": 20.409296, + "maxdiff_vs_f32": 0.847629, + "maxdiff_vs_llama": 1.119980, + "mode": "int8_except_gate_up", + "top1_top2_gap": 0.329693 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.422346, + "logit_4897": 20.803083, + "logit_53692": 20.380737, + "maxdiff_vs_f32": 0.580110, + "maxdiff_vs_llama": 1.289439, + "mode": "int8_only_down", + "top1_top2_gap": 0.422346 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.217571, + "logit_4897": 20.441067, + "logit_53692": 20.658638, + "maxdiff_vs_f32": 0.715139, + "maxdiff_vs_llama": 1.491215, + "mode": "int8_except_down", + "top1_top2_gap": 0.217571 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.349512, + "logit_4897": 20.694056, + "logit_53692": 20.344543, + "maxdiff_vs_f32": 0.077365, + "maxdiff_vs_llama": 1.059503, + "mode": "int8_only_output", + "top1_top2_gap": 0.349512 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.391722, + "logit_4897": 20.270634, + "logit_53692": 20.662355, + "maxdiff_vs_f32": 1.082744, + "maxdiff_vs_llama": 1.314652, + "mode": "int8_except_output", + "top1_top2_gap": 0.391722 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.391722, + "logit_4897": 20.270634, + "logit_53692": 20.662355, + "maxdiff_vs_f32": 1.082744, + "maxdiff_vs_llama": 1.314652, + "mode": "int8_all_layers_f32_output", + "top1_top2_gap": 0.391722 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.294594, + "logit_4897": 20.636736, + "logit_53692": 20.342142, + "maxdiff_vs_f32": 0.307768, + "maxdiff_vs_llama": 0.950948, + "mode": "int8_only_layer_00", + "top1_top2_gap": 0.294594 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.188274, + "logit_4897": 20.348719, + "logit_53692": 20.536993, + "maxdiff_vs_f32": 0.824976, + "maxdiff_vs_llama": 1.768735, + "mode": "int8_except_layer_00", + "top1_top2_gap": 0.188274 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.396362, + "logit_4897": 20.689140, + "logit_53692": 20.292778, + "maxdiff_vs_f32": 0.093840, + "maxdiff_vs_llama": 1.065825, + "mode": "int8_only_layer_01", + "top1_top2_gap": 0.396362 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.299984, + "logit_4897": 20.147137, + "logit_53692": 20.447121, + "maxdiff_vs_f32": 0.998443, + "maxdiff_vs_llama": 1.142616, + "mode": "int8_except_layer_01", + "top1_top2_gap": 0.299984 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.205231, + "logit_4897": 20.596018, + "logit_53692": 20.390787, + "maxdiff_vs_f32": 0.160588, + "maxdiff_vs_llama": 1.110361, + "mode": "int8_only_layer_02", + "top1_top2_gap": 0.205231 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.049994, + "logit_4897": 20.554298, + "logit_53692": 20.604292, + "maxdiff_vs_f32": 0.948065, + "maxdiff_vs_llama": 1.040179, + "mode": "int8_except_layer_02", + "top1_top2_gap": 0.049994 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.288240, + "logit_4897": 20.719004, + "logit_53692": 20.430763, + "maxdiff_vs_f32": 0.277499, + "maxdiff_vs_llama": 1.180737, + "mode": "int8_only_layer_03", + "top1_top2_gap": 0.288240 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 1.136850, + "logit_4897": 21.099407, + "logit_53692": 19.962557, + "maxdiff_vs_f32": 0.816967, + "maxdiff_vs_llama": 1.371063, + "mode": "int8_except_layer_03", + "top1_top2_gap": 1.136850 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.429228, + "logit_4897": 20.693184, + "logit_53692": 20.263956, + "maxdiff_vs_f32": 0.190213, + "maxdiff_vs_llama": 1.145400, + "mode": "int8_only_layer_04", + "top1_top2_gap": 0.429228 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.265354, + "logit_4897": 20.210264, + "logit_53692": 20.475618, + "maxdiff_vs_f32": 0.940178, + "maxdiff_vs_llama": 1.188543, + "mode": "int8_except_layer_04", + "top1_top2_gap": 0.265354 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.195238, + "logit_4897": 20.612564, + "logit_53692": 20.417326, + "maxdiff_vs_f32": 0.197753, + "maxdiff_vs_llama": 1.077413, + "mode": "int8_only_layer_05", + "top1_top2_gap": 0.195238 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.045589, + "logit_4897": 20.263563, + "logit_53692": 20.309153, + "maxdiff_vs_f32": 0.766078, + "maxdiff_vs_llama": 1.087765, + "mode": "int8_except_layer_05", + "top1_top2_gap": 0.045589 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.392818, + "logit_4897": 20.645054, + "logit_53692": 20.252235, + "maxdiff_vs_f32": 0.220980, + "maxdiff_vs_llama": 1.058017, + "mode": "int8_only_layer_06", + "top1_top2_gap": 0.392818 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.068096, + "logit_4897": 20.833042, + "logit_53692": 20.901138, + "maxdiff_vs_f32": 1.026503, + "maxdiff_vs_llama": 1.322717, + "mode": "int8_except_layer_06", + "top1_top2_gap": 0.068096 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.410656, + "logit_4897": 20.738209, + "logit_53692": 20.327553, + "maxdiff_vs_f32": 0.246415, + "maxdiff_vs_llama": 1.146324, + "mode": "int8_only_layer_07", + "top1_top2_gap": 0.410656 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.277079, + "logit_4897": 20.286650, + "logit_53692": 20.563728, + "maxdiff_vs_f32": 0.874780, + "maxdiff_vs_llama": 1.170940, + "mode": "int8_except_layer_07", + "top1_top2_gap": 0.277079 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.189495, + "logit_4897": 20.710863, + "logit_53692": 20.521368, + "maxdiff_vs_f32": 0.407899, + "maxdiff_vs_llama": 1.163232, + "mode": "int8_only_layer_08", + "top1_top2_gap": 0.189495 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.547405, + "logit_4897": 20.526550, + "logit_53692": 21.073956, + "maxdiff_vs_f32": 1.092899, + "maxdiff_vs_llama": 1.192272, + "mode": "int8_except_layer_08", + "top1_top2_gap": 0.547405 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.120136, + "logit_4897": 20.441254, + "logit_53692": 20.321117, + "maxdiff_vs_f32": 0.346622, + "maxdiff_vs_llama": 1.108879, + "mode": "int8_only_layer_09", + "top1_top2_gap": 0.120136 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.558666, + "logit_4897": 20.276678, + "logit_53692": 20.835344, + "maxdiff_vs_f32": 0.961213, + "maxdiff_vs_llama": 1.419636, + "mode": "int8_except_layer_09", + "top1_top2_gap": 0.558666 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.257851, + "logit_4897": 20.652367, + "logit_53692": 20.394516, + "maxdiff_vs_f32": 0.285835, + "maxdiff_vs_llama": 1.143673, + "mode": "int8_only_layer_10", + "top1_top2_gap": 0.257851 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.143721, + "logit_4897": 20.516214, + "logit_53692": 20.659935, + "maxdiff_vs_f32": 1.062120, + "maxdiff_vs_llama": 1.329426, + "mode": "int8_except_layer_10", + "top1_top2_gap": 0.143721 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.280693, + "logit_4897": 20.663231, + "logit_53692": 20.382538, + "maxdiff_vs_f32": 0.251834, + "maxdiff_vs_llama": 1.078825, + "mode": "int8_only_layer_11", + "top1_top2_gap": 0.280693 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.677683, + "logit_4897": 20.014799, + "logit_53692": 20.692482, + "maxdiff_vs_f32": 1.133844, + "maxdiff_vs_llama": 1.425602, + "mode": "int8_except_layer_11", + "top1_top2_gap": 0.677683 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.391989, + "logit_4897": 20.747198, + "logit_53692": 20.355209, + "maxdiff_vs_f32": 0.155494, + "maxdiff_vs_llama": 1.110196, + "mode": "int8_only_layer_12", + "top1_top2_gap": 0.391989 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.252529, + "logit_4897": 20.377575, + "logit_53692": 20.630104, + "maxdiff_vs_f32": 1.162828, + "maxdiff_vs_llama": 1.525602, + "mode": "int8_except_layer_12", + "top1_top2_gap": 0.252529 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.288017, + "logit_4897": 20.684746, + "logit_53692": 20.396729, + "maxdiff_vs_f32": 0.214527, + "maxdiff_vs_llama": 1.098061, + "mode": "int8_only_layer_13", + "top1_top2_gap": 0.288017 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.397198, + "logit_4897": 20.203304, + "logit_53692": 20.600502, + "maxdiff_vs_f32": 1.011240, + "maxdiff_vs_llama": 1.245282, + "mode": "int8_except_layer_13", + "top1_top2_gap": 0.397198 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.352953, + "logit_4897": 20.665443, + "logit_53692": 20.312490, + "maxdiff_vs_f32": 0.221511, + "maxdiff_vs_llama": 1.072706, + "mode": "int8_only_layer_14", + "top1_top2_gap": 0.352953 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.353621, + "logit_4897": 20.264103, + "logit_53692": 20.617723, + "maxdiff_vs_f32": 0.995482, + "maxdiff_vs_llama": 1.218500, + "mode": "int8_except_layer_14", + "top1_top2_gap": 0.353621 + }, + { + "argmax": 4897, + "f32tok_minus_int8tok": 0.388020, + "logit_4897": 20.748285, + "logit_53692": 20.360266, + "maxdiff_vs_f32": 0.282944, + "maxdiff_vs_llama": 1.145030, + "mode": "int8_only_layer_15", + "top1_top2_gap": 0.388020 + }, + { + "argmax": 53692, + "f32tok_minus_int8tok": -0.486233, + "logit_4897": 20.289013, + "logit_53692": 20.775246, + "maxdiff_vs_f32": 1.093235, + "maxdiff_vs_llama": 1.257932, + "mode": "int8_except_layer_15", + "top1_top2_gap": 0.486233 + } + ], + "positions": [ + { + "emulation_vs_int8": 0.672785, + "f32_argmax": 791, + "f32_gap": 5.159847, + "index": 0, + "int8_argmax": 791, + "int8_gap": 5.141813, + "max_logit_abs_diff": 0.670289 + }, + { + "emulation_vs_int8": 0.781150, + "f32_argmax": 6864, + "f32_gap": 11.479628, + "index": 1, + "int8_argmax": 6864, + "int8_gap": 11.454018, + "max_logit_abs_diff": 0.675531 + }, + { + "emulation_vs_int8": 0.604889, + "f32_argmax": 315, + "f32_gap": 9.061489, + "index": 2, + "int8_argmax": 315, + "int8_gap": 9.070347, + "max_logit_abs_diff": 0.639278 + }, + { + "emulation_vs_int8": 0.684391, + "f32_argmax": 9822, + "f32_gap": 11.230284, + "index": 3, + "int8_argmax": 9822, + "int8_gap": 11.192930, + "max_logit_abs_diff": 0.501313 + }, + { + "emulation_vs_int8": 0.717548, + "f32_argmax": 374, + "f32_gap": 13.698101, + "index": 4, + "int8_argmax": 374, + "int8_gap": 13.801851, + "max_logit_abs_diff": 0.565537 + }, + { + "emulation_vs_int8": 0.604215, + "f32_argmax": 12366, + "f32_gap": 4.966125, + "index": 5, + "int8_argmax": 12366, + "int8_gap": 4.830284, + "max_logit_abs_diff": 0.552169 + }, + { + "emulation_vs_int8": 0.677788, + "f32_argmax": 13, + "f32_gap": 8.488819, + "index": 6, + "int8_argmax": 13, + "int8_gap": 8.504349, + "max_logit_abs_diff": 0.433726 + }, + { + "emulation_vs_int8": 0.873827, + "f32_argmax": 128009, + "f32_gap": 8.213617, + "index": 7, + "int8_argmax": 128009, + "int8_gap": 7.891104, + "max_logit_abs_diff": 0.733281 + }, + { + "emulation_vs_int8": 0.860786, + "f32_argmax": 128006, + "f32_gap": 13.969904, + "index": 8, + "int8_argmax": 128006, + "int8_gap": 13.897326, + "max_logit_abs_diff": 0.597072 + }, + { + "emulation_vs_int8": 0.956993, + "f32_argmax": 78191, + "f32_gap": 13.508966, + "index": 9, + "int8_argmax": 78191, + "int8_gap": 13.490692, + "max_logit_abs_diff": 0.612268 + }, + { + "emulation_vs_int8": 0.957607, + "f32_argmax": 128007, + "f32_gap": 12.665781, + "index": 10, + "int8_argmax": 128007, + "int8_gap": 12.587048, + "max_logit_abs_diff": 0.781019 + }, + { + "emulation_vs_int8": 1.180955, + "f32_argmax": 271, + "f32_gap": 14.398211, + "index": 11, + "int8_argmax": 271, + "int8_gap": 14.592617, + "max_logit_abs_diff": 1.288042 + }, + { + "emulation_vs_int8": 1.416652, + "f32_argmax": 4897, + "f32_gap": 0.349283, + "index": 12, + "int8_argmax": 53692, + "int8_gap": 0.393490, + "max_logit_abs_diff": 1.068317 + } + ], + "real_activation_matvec": [ + { + "f32_vs_f64_ref": 3.002E-7, + "int8_vs_f64_ref": 1.979E-7, + "max_abs_ref": 1.325, + "weight": "layer0.wq" + }, + { + "f32_vs_f64_ref": 6.562E-7, + "int8_vs_f64_ref": 4.389E-7, + "max_abs_ref": 5.369, + "weight": "layer0.wk" + }, + { + "f32_vs_f64_ref": 1.127E-8, + "int8_vs_f64_ref": 3.396E-8, + "max_abs_ref": 0.4167, + "weight": "layer0.wv" + }, + { + "f32_vs_f64_ref": 2.194E-7, + "int8_vs_f64_ref": 8.372E-8, + "max_abs_ref": 0.7062, + "weight": "layer0.w_gate" + }, + { + "f32_vs_f64_ref": 7.717E-8, + "int8_vs_f64_ref": 3.876E-8, + "max_abs_ref": 0.4384, + "weight": "layer0.w_up" + } + ], + "rustflags": "-C target-feature=+dotprod,+i8mm", + "scope": "diagnosis only; parity rule, default path and INT8_PROMOTION_DEFAULT unchanged" +} diff --git a/scripts/.crumb b/scripts/.crumb index 550a4868..7ea48eb9 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-10T02:47:01Z", + "compiled_at": "2026-10-11T01:16:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:d9cd564824903777dd323019bb8d5673331383e961bc3da703d5589be1eb6b4c", + "digest": "sha256:87580f35633fabdbc1d2d07a061b0022500dfcdf3499c815cce956d553eb9e59", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 78, - "generated_at_commit": "89fcc57c5bf7a5003eea52de0ac3bf2f752e2c04", - "source_tree": "sha256:14ef9ea3fcd3fdf3133ec04c2c401a2cc46321abd39bee7e1f54c7b199a5b4a8" + "files": 79, + "generated_at_commit": "02edc84247d9ff8a06750ec885b3c7a006fc5dbe", + "source_tree": "sha256:2823cab10add2eac96c4d863b7c0167c25942825db3ab0195588209624f74dad" }, "owner_lane": "", "provenance": { diff --git a/scripts/l6_host_receipt.sh b/scripts/l6_host_receipt.sh index 6e2dc3e5..f0a843dc 100755 --- a/scripts/l6_host_receipt.sh +++ b/scripts/l6_host_receipt.sh @@ -1,9 +1,11 @@ #!/usr/bin/env bash -# L6-A: host-side tokens-per-second receipt (aienos#34 lane 6). -# Runs the l6_host example pinned to cores 0 and 19 (core types are read from /proc/cpuinfo, not assumed; -# on this machine they interleave: cpu0=0xd87 A725, cpu19=0xd85 X925), -# runs llama.cpp single-thread on the same model, writes evidence/l6_host_<sha12>.json. -# Reproduce: scripts/l6_host_receipt.sh (env: AIENOS_MODEL, AIENOS_N, LLAMA_BENCH) +# L6-A/L6-B: host-side tokens-per-second receipt (aienos#34 lane 6). +# Builds the l6_host example with the GB10 dot-product features (RUSTFLAGS; override to compare), runs it on +# both dot paths (AIENOS_DOT=f32 and int8) pinned to cores 0 and 19 (core types are read from /proc/cpuinfo, +# not assumed; on this machine they interleave: cpu0=0xd87 A725, cpu19=0xd85 X925), +# runs llama.cpp single-thread on the same model, runs the int8-vs-f32 parity test (token identity is the pass rule), +# writes evidence/l6_host_<sha12>_l6b.json. `--parity-only` runs only the parity test and writes evidence/l6_host_<sha12>_l6b_parity.json. +# Reproduce: scripts/l6_host_receipt.sh (env: AIENOS_MODEL, AIENOS_N, LLAMA_BENCH, RUSTFLAGS) set -euo pipefail cd "$(dirname "$0")/.." MODEL="${AIENOS_MODEL:-$HOME/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" @@ -13,20 +15,71 @@ LB="${LLAMA_BENCH:-$HOME/llama.cpp-build/bin/llama-bench}" COMMIT="$(git rev-parse HEAD)" TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT export AIENOS_MODEL="$MODEL" AIENOS_N="$N" AIENOS_COMMIT="$COMMIT" +export RUSTFLAGS="${RUSTFLAGS:--C target-feature=+dotprod,+i8mm}" +LOAD1="$(cut -d' ' -f1 /proc/loadavg)" GOV="$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo unknown)" NPROC="$(nproc)" PARTS="$(grep -E '^CPU part' /proc/cpuinfo | awk '{print $4}' | sort | uniq -c | awk '{print $2 "x" $1}' | paste -sd, -)" HOST="$(hostname)"; KERNEL="$(uname -r)" -echo "commit=$COMMIT governor=$GOV nproc=$NPROC cpu_part=$PARTS host=$HOST kernel=$KERNEL" +echo "commit=$COMMIT governor=$GOV nproc=$NPROC cpu_part=$PARTS host=$HOST kernel=$KERNEL rustflags=$RUSTFLAGS load1=$LOAD1" + +# --- int8 vs f32 parity (docs/l6b-int8-qualification.md, condition 2) ------------------------------------------- +# PASS RULE (gated): the int8 path produces the identical 64 token ids as the f32 path. The per-position max +# absolute logit difference is reported, not gated. Runs the ignored model-backed test on one core (X925, cpu19), +# never killed. Writes a JSON object to $1. +PARITY_CORE=19 +run_parity() { + local out="$1" rc=0 sha12 rec + sha12="$(sha256sum "$MODEL" | cut -c1-12)" + rec="evidence/l6_host_${sha12}_l6b.json" + local pcmd="cargo test --release -p aienos-infer --test forward int8_parity -- --ignored --nocapture --test-threads=1" + cargo test --release -p aienos-infer --test forward --no-run + echo "RUN: AIENOS_MODEL=$MODEL taskset -c $PARITY_CORE $pcmd" + taskset -c "$PARITY_CORE" $pcmd >"$TMP/parity.txt" 2>"$TMP/parity.err" || rc=$? + # libtest prints "test name ... " without a newline, so the first PARITY line is not at line start. + grep -oE "PARITY_[A-Z0-9_]+: .*" "$TMP/parity.txt" >"$TMP/parity.lines" || true + echo "exit=$rc"; cut -c1-200 "$TMP/parity.lines" + grep -q "^PARITY_TOKENS_IDENTICAL:" "$TMP/parity.lines" || { echo "parity test produced no PARITY lines (see build/test error)"; tail -20 "$TMP/parity.err"; exit 3; } + local pv; pv() { sed -n "s/^$1: //p" "$TMP/parity.lines"; } + local recorded="[]"; [ -f "$rec" ] && recorded="$(jq -c '.legs.f32_core19.tokens' "$rec")" + jq -n --arg ident "$(pv PARITY_TOKENS_IDENTICAL)" --arg div "$(pv PARITY_FIRST_DIVERGENCE)" \ + --argjson cmp "$(pv PARITY_COMPARED_POSITIONS)" --argjson mx "$(pv PARITY_MAX_LOGIT_ABS_DIFF)" \ + --argjson mxp "$(pv PARITY_MAX_LOGIT_ABS_DIFF_POSITION)" --arg per "$(pv PARITY_PER_POSITION_MAX)" \ + --arg ft "$(pv PARITY_F32_TOKENS)" --arg it "$(pv PARITY_INT8_TOKENS)" --argjson recorded "$recorded" \ + --argjson rc "$rc" --arg cmd "AIENOS_MODEL=<model> taskset -c $PARITY_CORE $pcmd" --arg recfile "$rec" --argjson core "$PARITY_CORE" \ + '($ft|split(" ")|map(tonumber)) as $f | ($it|split(" ")|map(tonumber)) as $i | + {rule:"PASS iff the int8 path produces the identical 64 token ids as the f32 path (gated). Max abs logit difference is reported, not gated, this round.", + tokens_identical:($ident=="yes"), first_divergence_index:(if $div=="none" then null else ($div|tonumber) end), + compared_positions:$cmp, max_logit_abs_diff:$mx, max_logit_abs_diff_position:$mxp, + per_position_max_logit_abs_diff:($per|split(" ")|map(tonumber)), + f32_matches_recorded:($f==$recorded), recorded_file:$recfile, + f32_tokens:$f, int8_tokens:$i, test_exit_code:$rc, core_pinned:$core, command:$cmd, + verdict:(if $ident=="yes" and $rc==0 then "PASS" else "FAIL" end)}' >"$out" +} + +if [ "${1:-}" = "--parity-only" ]; then + # Writes only the parity record; the speed receipt is not touched. + run_parity "$TMP/parity.json" + SHA="$(sha256sum "$MODEL" | cut -d' ' -f1)" + OUT="evidence/l6_host_${SHA:0:12}_l6b_parity.json" + jq -n --arg commit "$COMMIT" --arg path "$MODEL" --arg sha "$SHA" --arg host "$HOST" --arg kernel "$KERNEL" \ + --arg cpu_part "$PARTS" --arg gov "$GOV" --arg rustflags "$RUSTFLAGS" --argjson load1 "$LOAD1" \ + --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --slurpfile p "$TMP/parity.json" \ + '{commit:$commit, model:{path:$path, sha256:$sha}, host:$host, kernel:$kernel, cpu_part:$cpu_part, governor:$gov, + rustflags:$rustflags, load1_at_start:$load1, parity_int8_vs_f32:$p[0], generated_at_utc:$now}' | jq -S . >"$OUT" + echo "wrote $OUT"; exit 0 +fi CMD="cargo run --release -p aienos-infer --example l6_host" cargo build --release -p aienos-infer --example l6_host -for core in 0 19; do - echo "RUN: AIENOS_MODEL=$MODEL AIENOS_N=$N taskset -c $core $CMD" - rc=0; taskset -c "$core" $CMD >"$TMP/run$core.txt" || rc=$? - echo "exit=$rc"; echo "$rc" >"$TMP/rc$core" - grep -E '^(prefill_us|decode_tokens|mean_tok_us|tok_per_s|PARITY):' "$TMP/run$core.txt" +for dot in f32 int8; do + for core in 0 19; do + echo "RUN: AIENOS_MODEL=$MODEL AIENOS_N=$N AIENOS_DOT=$dot taskset -c $core $CMD" + rc=0; AIENOS_DOT="$dot" taskset -c "$core" $CMD >"$TMP/run_${dot}_${core}.txt" || rc=$? + echo "exit=$rc"; echo "$rc" >"$TMP/rc_${dot}_${core}" + grep -E '^(prefill_us|decode_tokens|mean_tok_us|tok_per_s|PARITY):' "$TMP/run_${dot}_${core}.txt" + done done LLAMA_BUILD="NOT_RUN"; LLAMA_TPS="null"; LLAMA_TPS19="null" @@ -44,31 +97,36 @@ else fi cpart() { awk -v c="$1" '/^processor/{p=$3} /^CPU part/{if(p==c)print $4}' /proc/cpuinfo; } # 0xd85=Cortex-X925, 0xd87=Cortex-A725 -val() { sed -n "s/^$2: //p" "$TMP/run$1.txt"; } -leg() { # core -> JSON object - jq -n --arg core "$1" --arg parity "$(val "$1" PARITY)" --arg ids "$(val "$1" tokens)" \ - --arg us "$(val "$1" tok_us)" --arg text "$(val "$1" text)" \ - --argjson prefill "$(val "$1" prefill_us)" --argjson dt "$(val "$1" decode_tokens)" \ - --argjson mean "$(val "$1" mean_tok_us)" --argjson tps "$(val "$1" tok_per_s)" \ - --argjson rc "$(cat "$TMP/rc$1")" --arg part "$(cpart "$1")" \ - '{core_pinned:($core|tonumber), cpu_part:$part, exit_code:$rc, parity:$parity, prefill_us:$prefill, decode_tokens:$dt, - tokens:($ids|split(" ")|map(tonumber)), tok_us:($us|split(" ")|map(tonumber)), +val() { sed -n "s/^$3: //p" "$TMP/run_$1_$2.txt"; } +leg() { # <dot> <core> -> JSON object + jq -n --arg core "$2" --arg dot "$1" --arg parity "$(val "$1" "$2" PARITY)" --arg ids "$(val "$1" "$2" tokens)" \ + --arg us "$(val "$1" "$2" tok_us)" --arg text "$(val "$1" "$2" text)" \ + --argjson prefill "$(val "$1" "$2" prefill_us)" --argjson dt "$(val "$1" "$2" decode_tokens)" \ + --argjson mean "$(val "$1" "$2" mean_tok_us)" --argjson tps "$(val "$1" "$2" tok_per_s)" \ + --argjson rc "$(cat "$TMP/rc_$1_$2")" --arg part "$(cpart "$2")" \ + '{core_pinned:($core|tonumber), dot:$dot, cpu_part:$part, exit_code:$rc, parity:$parity, prefill_us:$prefill, + decode_tokens:$dt, tokens:($ids|split(" ")|map(tonumber)), tok_us:($us|split(" ")|map(tonumber)), mean_tok_us:$mean, tok_per_s:$tps, text:$text}' } -SHA="$(val 0 model_sha256)" -OUT="evidence/l6_host_${SHA:0:12}.json" -jq -n --arg commit "$COMMIT" --arg path "$MODEL" --arg sha "$SHA" --argjson size "$(val 0 model_size_bytes)" \ - --arg prompt "$(val 0 prompt)" --arg golden "$(val 0 golden_ids)" \ - --argjson c0 "$(leg 0)" --argjson c19 "$(leg 19)" \ +run_parity "$TMP/parity.json" +SHA="$(val int8 0 model_sha256)" +OUT="evidence/l6_host_${SHA:0:12}_l6b.json" +jq -n --arg commit "$COMMIT" --arg path "$MODEL" --arg sha "$SHA" --argjson size "$(val int8 0 model_size_bytes)" \ + --arg prompt "$(val int8 0 prompt)" --arg golden "$(val int8 0 golden_ids)" \ + --slurpfile par "$TMP/parity.json" --argjson c0 "$(leg int8 0)" --argjson c19 "$(leg int8 19)" --argjson f0 "$(leg f32 0)" --argjson f19 "$(leg f32 19)" \ + --arg rustflags "$RUSTFLAGS" --argjson load1 "$LOAD1" \ --arg cpu_part "$PARTS" --arg gov "$GOV" --arg host "$HOST" --arg kernel "$KERNEL" --argjson nproc "$NPROC" \ --arg lb "$LLAMA_BUILD" --arg llcmd "$LLCMD" --argjson lt0 "$LLAMA_TPS" --argjson lt19 "$LLAMA_TPS19" \ - --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg cmd "AIENOS_N=$N taskset -c <core> $CMD" \ + --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg cmd "AIENOS_N=$N AIENOS_DOT=<f32|int8> taskset -c <core> $CMD" \ '{commit:$commit, model:{path:$path, sha256:$sha, size_bytes:$size}, prompt:$prompt, - golden_ids:($golden|split(" ")|map(tonumber)), parity:($c0.parity), + golden_ids:($golden|split(" ")|map(tonumber)), parity:($c0.parity), parity_int8_vs_f32:$par[0], dot:"int8", prefill_us:$c0.prefill_us, decode_tokens:$c0.decode_tokens, tok_us:$c0.tok_us, mean_tok_us:$c0.mean_tok_us, tok_per_s:$c0.tok_per_s, core_pinned:0, cpu_part:$cpu_part, nproc:$nproc, governor:$gov, host:$host, kernel:$kernel, - legs:{core0:$c0, core19:$c19}, + legs:{core0:$c0, core19:$c19, f32_core0:$f0, f32_core19:$f19}, + summary_tok_per_s:{int8_core0:$c0.tok_per_s, int8_core19:$c19.tok_per_s, f32_core0:$f0.tok_per_s, f32_core19:$f19.tok_per_s, + llama_cpp_1thread_core0:$lt0, llama_cpp_1thread_core19:$lt19}, + rustflags:$rustflags, load1_at_start:$load1, harness_command:$cmd, threads:1, llama_cpp:{build:$lb, threads:1, tok_per_s:$lt0, tok_per_s_core19:$lt19, command:$llcmd}, reference:{file:"evidence/config_a_reference_bundle.json", tok_per_s:54.2, note:"20 threads, server; not like for like"}, diff --git a/scripts/l6b_divergence_receipt.sh b/scripts/l6b_divergence_receipt.sh new file mode 100755 index 00000000..43722cb1 --- /dev/null +++ b/scripts/l6b_divergence_receipt.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# L6-B int8 parity diagnosis receipt (aienos#34). Diagnosis only: it changes no pass rule and no default. +# 1. Rebuilds tests/ref/llama_ref_hist.c against the local llama.cpp, replays the recorded common history +# (prompt + the 12 tokens f32 and int8 agree on) and checks the logits against the committed fixture +# crates/aienos-infer/tests/fixtures/ref_fr_idx12_logits.f32. +# 2. Runs the ignored model-backed tests int8_divergence_diagnosis_index_12 and int8_vs_q8k_emulation_drift +# and the model-backed int8_matvec_equals_rounded_f32_on_real_activation, pinned to one X925 core, never killed. +# 3. Writes evidence/l6b_int8_divergence_<model sha12>.json. +# Reproduce: scripts/l6b_divergence_receipt.sh (env: AIENOS_MODEL, LLAMA_DIR, RUSTFLAGS, DIAG_CORE) +set -euo pipefail +cd "$(dirname "$0")/.." +MODEL="${AIENOS_MODEL:-$HOME/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" +LLAMA_DIR="${LLAMA_DIR:-$HOME/llama.cpp-build}" +CORE="${DIAG_CORE:-19}" +COMMIT="$(git rev-parse HEAD)" +TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT +export AIENOS_MODEL="$MODEL" +export RUSTFLAGS="${RUSTFLAGS:--C target-feature=+dotprod,+i8mm}" +LOAD1="$(cut -d' ' -f1 /proc/loadavg)" +HOST="$(hostname)"; KERNEL="$(uname -r)" +CPU_PART="$(awk -v c="$CORE" '/^processor/{p=$3} /^CPU part/{if (p==c) print $4}' /proc/cpuinfo)" +SHA="$(sha256sum "$MODEL" | cut -d' ' -f1)" +FIX=crates/aienos-infer/tests/fixtures/ref_fr_idx12_logits.f32 +HIST="128000 128006 882 128007 271 3923 374 279 6864 315 9822 30 128009 128006 78191 128007 271 791 6864 315 9822 374 12366 13 128009 128006 78191 128007 271" +echo "commit=$COMMIT host=$HOST core=$CORE cpu_part=$CPU_PART rustflags=$RUSTFLAGS load1=$LOAD1" + +# --- 1. llama.cpp reference for the same history ------------------------------------------------------------------- +LL_COMMIT="NOT_RUN"; LL_REPRO="null"; LL_LINES="" +if [ -f "$LLAMA_DIR/include/llama.h" ]; then + LL_COMMIT="$(git -C "$LLAMA_DIR" rev-parse --short HEAD 2>/dev/null || echo unknown)" + cc -O2 -Wall crates/aienos-infer/tests/ref/llama_ref_hist.c -o "$TMP/llama_ref_hist" \ + -I"$LLAMA_DIR/include" -I"$LLAMA_DIR/ggml/include" -L"$LLAMA_DIR/build/bin" \ + -lllama -lggml -lggml-base -Wl,-rpath,"$LLAMA_DIR/build/bin" + # shellcheck disable=SC2086 + LL_LINES="$(taskset -c "$CORE" "$TMP/llama_ref_hist" "$MODEL" "$TMP/ll.f32" 17 4897,53692 $HIST 2>/dev/null)" + echo "$LL_LINES" + if cmp -s "$TMP/ll.f32" "$FIX"; then LL_REPRO=true; else LL_REPRO=false; fi +fi +LL_ARGMAX="$(awk '/^argmax/{print $2}' <<<"$LL_LINES")"; LL_GAP="$(awk '/^argmax/{print $4}' <<<"$LL_LINES")" + +# --- 2. model-backed tests ---------------------------------------------------------------------------------------- +cargo test --release -p aienos-infer --test forward --no-run +run() { # name extra-args -> $TMP/<name>.txt, exit code on stdout + local rc=0 + taskset -c "$CORE" cargo test --release -p aienos-infer --test forward "$1" -- $2 --nocapture --test-threads=1 \ + >"$TMP/$1.txt" 2>"$TMP/$1.err" || rc=$? + echo "$rc" +} +RC_DIAG="$(run int8_divergence_diagnosis_index_12 --ignored)" +RC_DRIFT="$(run int8_vs_q8k_emulation_drift --ignored)" +RC_REAL="$(run int8_matvec_equals_rounded_f32_on_real_activation "")" +echo "exit codes: diagnosis=$RC_DIAG drift=$RC_DRIFT real_activation=$RC_REAL" + +# libtest prints "test name ... " without a newline, so take each tag from where it starts. +grep -o 'DIAG_POS.*' "$TMP/int8_divergence_diagnosis_index_12.txt" | tr -d '|' | awk '{ + printf "{\"index\":%d,\"f32_argmax\":%s,\"f32_gap\":%s,\"int8_argmax\":%s,\"int8_gap\":%s,\"max_logit_abs_diff\":%s,\"emulation_vs_int8\":%s}\n", + $2, $5, $7, $10, $12, $14, $16 }' | jq -s . >"$TMP/pos.json" +grep -o 'DIAG_MODE.*' "$TMP/int8_divergence_diagnosis_index_12.txt" | awk '{ + sub(":", "", $2); + printf "{\"mode\":\"%s\",\"argmax\":%s,\"top1_top2_gap\":%s,\"logit_4897\":%s,\"logit_53692\":%s,\"f32tok_minus_int8tok\":%s,\"maxdiff_vs_f32\":%s,\"maxdiff_vs_llama\":%s}\n", + $2, $4, $6, $8, $10, $12, $14, $16 }' | jq -s . >"$TMP/modes.json" +REPEAT="$(grep -o 'DIAG_F32_REPEAT_MAXDIFF: [^ ]*' "$TMP/int8_divergence_diagnosis_index_12.txt" | awk '{print $2}')" +grep -o 'DRIFT.*' "$TMP/int8_vs_q8k_emulation_drift.txt" | awk '{ + printf "{\"tokens\":%d,\"class\":\"%s\",\"int8_vs_emulation\":%s,\"int8_vs_f32\":%s,\"emulation_vs_f32\":%s}\n", $3, $5, $7, $9, $11 }' \ + | jq -s . >"$TMP/drift.json" +grep -o 'REAL_ACT.*' "$TMP/int8_matvec_equals_rounded_f32_on_real_activation.txt" | awk '{ + sub(":", "", $2); printf "{\"weight\":\"layer0.%s\",\"f32_vs_f64_ref\":%s,\"int8_vs_f64_ref\":%s,\"max_abs_ref\":%s}\n", $2, $4, $6, $8 }' \ + | jq -s . >"$TMP/real.json" + +OUT="evidence/l6b_int8_divergence_${SHA:0:12}.json" +jq -n --arg commit "$COMMIT" --arg path "$MODEL" --arg sha "$SHA" --arg host "$HOST" --arg kernel "$KERNEL" \ + --arg cpu_part "$CPU_PART" --argjson core "$CORE" --arg rustflags "$RUSTFLAGS" --argjson load1 "$LOAD1" \ + --arg ll_commit "$LL_COMMIT" --argjson ll_repro "$LL_REPRO" --arg ll_argmax "$LL_ARGMAX" --arg ll_gap "$LL_GAP" \ + --argjson rc_diag "$RC_DIAG" --argjson rc_drift "$RC_DRIFT" --argjson rc_real "$RC_REAL" --arg repeat "$REPEAT" \ + --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --slurpfile pos "$TMP/pos.json" --slurpfile modes "$TMP/modes.json" --slurpfile drift "$TMP/drift.json" \ + --slurpfile real "$TMP/real.json" \ + '{commit:$commit, model:{path:$path, sha256:$sha}, host:$host, kernel:$kernel, core_pinned:$core, cpu_part:$cpu_part, + rustflags:$rustflags, load1_at_start:$load1, generated_at_utc:$now, + scope:"diagnosis only; parity rule, default path and INT8_PROMOTION_DEFAULT unchanged", + history:"prompt (17 ids) + recorded common tokens 0..11; decision at index 12", + llama_cpp:{commit:$ll_commit, argmax:($ll_argmax|tonumber? // null), top1_top2_gap:($ll_gap|tonumber? // null), + fixture_reproduced:$ll_repro}, + exit_codes:{diagnosis:$rc_diag, drift:$rc_drift, real_activation:$rc_real}, + f32_repeat_max_logit_diff:($repeat|tonumber? // null), + positions:$pos[0], modes_at_index_12:$modes[0], drift_int8_vs_emulation:$drift[0], + real_activation_matvec:$real[0]}' | jq -S . >"$OUT" +echo "wrote $OUT"