interplane.Get Omega
Read in your language

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#249 (code only)

closed derived b5f65aa875375ad3 #249

Imported from GitHub aien-dev/aienux#249 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 1c318ea7bb618685b8165bc410a98b002113c866 · Head 7a7f5c1c8f3c949610a3a7fb9e092bdc1e912bd3

Apply it

git checkout -b patch-b5f65aa875375ad3 1c318ea7bb618685b8165bc410a98b002113c866
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/b5f65aa875375ad3.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
249
7a7f5c1c8f3c949610a3a7fb9e092bdc1e912bd3
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":249,"url":"https://github.com/aien-dev/aienux/pull/249","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:03Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-infer/src/decode.rs b/crates/aienos-infer/src/decode.rs
new file mode 100644
index 00000000..62553106
--- /dev/null
+++ b/crates/aienos-infer/src/decode.rs
@@ -0,0 +1,317 @@
+//! Forward pass, KV cache and greedy decode (aienos#34 lanes 2 and 3).
+//!
+//! Scalar f32, one token at a time. Graph per layer (llama.cpp
+//! `src/models/llama.cpp`): RMSNorm, Q/K/V, RoPE (adjacent pairs, base
+//! `rope_freq_base`, per-pair divisor from `rope_freqs.weight`), causal
+//! grouped-query attention over the cache (scale `1/sqrt(head_dim)`), output
+//! projection, residual, RMSNorm, SwiGLU (`silu(gate) * up -> down`), residual.
+
+use alloc::vec;
+use alloc::vec::Vec;
+
+use crate::math;
+use crate::model::{InferError, Model};
+
+/// KV cache plus scratch buffers for one sequence.
+pub struct DecodeState {
+    capacity: usize,
+    pos: usize,
+    kv_dim: usize,
+    /// `[layer][pos][kv_dim]`
+    k: Vec<f32>,
+    v: Vec<f32>,
+    x: Vec<f32>,
+    h: Vec<f32>,
+    q: Vec<f32>,
+    kk: Vec<f32>,
+    vv: Vec<f32>,
+    att: Vec<f32>,
+    scores: Vec<f32>,
+    gate: Vec<f32>,
+    up: Vec<f32>,
+    tmp: Vec<f32>,
+    scr: Vec<f32>,
+    rope_cos: Vec<f32>,
+    rope_sin: Vec<f32>,
+    /// Logits of the last position that asked for them.
+    pub logits: Vec<f32>,
+    /// Round matvec inputs to the Q8_K grid like ggml does (default off).
+    pub emulate_q8k: bool,
+}
+
+impl DecodeState {
+    /// Cache for up to `capacity` positions of `model`.
+    pub fn new(model: &Model<'_>, capacity: usize) -> Self {
+        let p = &model.params;
+        let (e, ff) = (p.embedding_length as usize, p.feed_forward_length as usize);
+        let n_layer = p.block_count as usize;
+        let kv = n_layer * capacity * model.kv_dim;
+        Self {
+            capacity,
+            pos: 0,
+            kv_dim: model.kv_dim,
+            k: vec![0.0; kv],
+            v: vec![0.0; kv],
+            x: vec![0.0; e],
+            h: vec![0.0; e],
+            q: vec![0.0; e],
+            kk: vec![0.0; model.kv_dim],
+            vv: vec![0.0; model.kv_dim],
+            att: vec![0.0; e],
+            scores: vec![0.0; capacity],
+            gate: vec![0.0; ff],
+            up: vec![0.0; ff],
+            tmp: vec![0.0; e.max(ff)],
+            scr: vec![0.0; e.max(ff)],
+            rope_cos: vec![0.0; model.head_dim / 2],
+            rope_sin: vec![0.0; model.head_dim / 2],
+            logits: vec![0.0; p.vocab_size as usize],
+            emulate_q8k: false,
+        }
+    }
+
+    /// Positions already in the cache.
+    pub fn len(&self) -> usize {
+        self.pos
+    }
+    pub fn is_empty(&self) -> bool {
+        self.pos == 0
+    }
+    pub fn capacity(&self) -> usize {
+        self.capacity
+    }
+    /// Forget the sequence (buffers are kept).
+    pub fn reset(&mut self) {
+        self.pos = 0;
+    }
+}
+
+/// `x * w / sqrt(mean(x^2) + eps)` into `out`.
+pub fn rms_norm(x: &[f32], w: &[f32], eps: f32, out: &mut [f32]) {
+    let ss: f32 = x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32;
+    let scale = 1.0 / math::sqrt(ss + eps);
+    for ((o, v), g) in out.iter_mut().zip(x).zip(w) {
+        *o = v * scale * g;
+    }
+}
+
+/// In-place softmax with max subtraction.
+pub fn softmax(x: &mut [f32]) {
+    let max = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+    let mut sum = 0.0;
+    for v in x.iter_mut() {
+        *v = math::exp(*v - max);
+        sum += *v;
+    }
+    for v in x.iter_mut() {
+        *v /= sum;
+    }
+}
+
+/// Fill cos/sin for one position as ggml's `ggml_rope_cache_init` does:
+/// `theta` starts at `pos`, is multiplied by `base^(-2/n_rot)` each pair and
+/// divided by that pair's factor.
+pub fn rope_cache(pos: usize, base: f32, factors: &[f32], cos: &mut [f32], sin: &mut [f32]) {
+    let n_rot = cos.len() * 2;
+    let theta_scale = math::powf(base, -2.0 / n_rot as f32);
+    let mut theta = pos as f32;
+    for i in 0..cos.len() {
+        let ff = factors.get(i).copied().unwrap_or(1.0);
+        let (s, c) = math::sin_cos(theta / ff);
+        cos[i] = c;
+        sin[i] = s;
+        theta *= theta_scale;
+    }
+}
+
+/// Rotate adjacent pairs of every head of `x` in place.
+pub fn rope_apply(x: &mut [f32], head_dim: usize, cos: &[f32], sin: &[f32]) {
+    for head in x.chunks_exact_mut(head_dim) {
+        for i in 0..head_dim / 2 {
+            let (a, b) = (head[2 * i], head[2 * i + 1]);
+            head[2 * i] = a * cos[i] - b * sin[i];
+            head[2 * i + 1] = a * sin[i] + b * cos[i];
+        }
+    }
+}
+
+impl DecodeState {
+    /// Run one token through the model at the next position, appending to
+    /// the cache. Logits are computed (into `self.logits`) only when
+    /// `want_logits`, since they cost as much as several layers.
+    pub fn forward(
+        &mut self,
+        m: &Model<'_>,
+        token: u32,
+        want_logits: bool,
+    ) -> Result<(), InferError> {
+        let p = &m.params;
+        if token >= p.vocab_size {
+            return Err(InferError::BadToken(token));
+        }
+        if self.pos >= self.capacity {
+            return Err(InferError::ContextFull);
+        }
+        let pos = self.pos;
+        let hd = m.head_dim;
+        let n_head = p.head_count as usize;
+        let group = n_head / p.head_count_kv as usize;
+        let eps = p.rms_norm_eps;
+        let scale = 1.0 / math::sqrt(hd as f32);
+
+        m.tok_embd.row_into(token as usize, &mut self.x)?;
+        rope_cache(
+            pos,
+            p.rope_freq_base,
+            &m.rope_factors,
+            &mut self.rope_cos,
+            &mut self.rope_sin,
+        );
+
+        for (l, layer) in m.layers.iter().enumerate() {
+            rms_norm(&self.x, &layer.attn_norm, eps, &mut self.h);
+            if self.emulate_q8k {
+                q8k_round(&mut self.h);
+            }
+            layer.wq.matvec(&self.h, &mut self.q, &mut self.scr)?;
+            layer.wk.matvec(&self.h, &mut self.kk, &mut self.scr)?;
+            layer.wv.matvec(&self.h, &mut self.vv, &mut self.scr)?;
+            rope_apply(&mut self.q, hd, &self.rope_cos, &self.rope_sin);
+            rope_apply(&mut self.kk, hd, &self.rope_cos, &self.rope_sin);
+
+            let base = l * self.capacity * self.kv_dim;
+            let at = base + pos * self.kv_dim;
+            self.k[at..at + self.kv_dim].copy_from_slice(&self.kk);
+            self.v[at..at + self.kv_dim].copy_from_slice(&self.vv);
+
+            for h in 0..n_head {
+                let kvh = (h / group) * hd;
+                let q = &self.q[h * hd..(h + 1) * hd];
+                let sc = &mut self.scores[..=pos];
+                for (t, s) in sc.iter_mut().enumerate() {
+                    let kt = &self.k[base + t * self.kv_dim + kvh..][..hd];
+                    *s = q.iter().zip(kt).map(|(a, b)| a * b).sum::<f32>() * scale;
+                }
+                softmax(sc);
+                let out = &mut self.att[h * hd..(h + 1) * hd];
+                out.fill(0.0);
+                for (t, &w) in sc.iter().enumerate() {
+                    let vt = &self.v[base + t * self.kv_dim + kvh..][..hd];
+                    for (o, v) in out.iter_mut().zip(vt) {
+                        *o += w * v;
+                    }
+                }
+            }
+            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)?;
+            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)?;
+            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)?;
+            for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) {
+                *x += d;
+            }
+        }
+        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)?;
+        }
+        Ok(())
+    }
+
+    /// Feed `ids` in order (prefill); logits are computed for the last one.
+    pub fn prefill(&mut self, m: &Model<'_>, ids: &[u32]) -> Result<(), InferError> {
+        for (i, &t) in ids.iter().enumerate() {
+            self.forward(m, t, i + 1 == ids.len())?;
+        }
+        Ok(())
+    }
+}
+
+/// Index of the largest logit (first on ties, like llama.cpp's greedy).
+pub fn argmax(logits: &[f32]) -> u32 {
+    let mut best = 0usize;
+    for (i, &v) in logits.iter().enumerate() {
+        if v > logits[best] {
+            best = i;
+        }
+    }
+    best as u32
+}
+
+/// Greedy generation: prefill `prompt`, then up to `max_new` tokens, stopping
+/// after any id in `stop` (that id is included in the result).
+pub fn generate_greedy(
+    m: &Model<'_>,
+    st: &mut DecodeState,
+    prompt: &[u32],
+    max_new: usize,
+    stop: &[u32],
+) -> Result<Vec<u32>, InferError> {
+    let mut out = Vec::new();
+    st.prefill(m, prompt)?;
+    for i in 0..max_new {
+        let t = argmax(&st.logits);
+        out.push(t);
+        if stop.contains(&t) || i + 1 == max_new {
+            break;
+        }
+        st.forward(m, t, true)?;
+    }
+    Ok(out)
+}
+
+/// 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
+/// the activations this way before every quantized dot; applying it makes
+/// results track llama.cpp more closely (see `DecodeState::emulate_q8k`).
+pub fn q8k_round(x: &mut [f32]) {
+    for blk in x.chunks_exact_mut(256) {
+        let mut amax = 0f32;
+        let mut max = 0f32;
+        for &v in blk.iter() {
+            if v.abs() > amax {
+                amax = v.abs();
+                max = v;
+            }
+        }
+        if amax == 0.0 {
+            continue;
+        }
+        let iscale = -127.0 / max;
+        let d = 1.0 / iscale;
+        for v in blk.iter_mut() {
+            let t = *v * iscale;
+            // nearest_int: magic-number rounding (ties to even), as ggml.
+            let q = ((t + 12_582_912.0) - 12_582_912.0).min(127.0);
+            *v = q * d;
+        }
+    }
+}
diff --git a/crates/aienos-infer/src/lib.rs b/crates/aienos-infer/src/lib.rs
index be51d20c..1217992c 100644
--- a/crates/aienos-infer/src/lib.rs
+++ b/crates/aienos-infer/src/lib.rs
@@ -20,8 +20,15 @@ extern crate alloc;
 #[cfg(test)]
 extern crate std;
 
+pub mod decode;
 pub mod gguf;
 pub mod half;
+pub mod math;
+pub mod model;
 pub mod quant;
+pub mod tokenizer;
 
+pub use decode::{argmax, generate_greedy, DecodeState};
 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/math.rs b/crates/aienos-infer/src/math.rs
new file mode 100644
index 00000000..c1ad0813
--- /dev/null
+++ b/crates/aienos-infer/src/math.rs
@@ -0,0 +1,148 @@
+//! Scalar f32 math without libm (no_std).
+//!
+//! `exp_approx`, `sqrt_approx` and `sin_cos` are adapted from the retired
+//! kernel crate's `crates/aienos-kernel/src/infer/{gemm,rope}.rs` (same
+//! authors, Apache-2.0); `exp` got one more series term and `ln` is new.
+
+use core::f32::consts::{FRAC_PI_2, LN_2, LOG2_E, PI, TAU};
+
+/// Cody-Waite split of ln 2: the high part is exact in f32 (355/512), so the
+/// reduction `x - n*LN_2_HI` is exact for large |n|; the low part restores precision.
+#[allow(clippy::excessive_precision)] // exact f32 (355/512), written in full on purpose
+const LN_2_HI: f32 = 0.693_359_375;
+const LN_2_LO: f32 = -2.121_944_4e-4;
+
+/// Newton square root from a bit-trick seed (error ~1 ulp).
+pub fn sqrt(x: f32) -> f32 {
+    if x <= 0.0 {
+        return 0.0;
+    }
+    let mut y = f32::from_bits((x.to_bits() >> 1) + 0x1fc0_0000);
+    for _ in 0..5 {
+        y = 0.5 * (y + x / y);
+    }
+    y
+}
+
+/// `e^x` by range reduction to `|r| <= ln2/2` and a degree-6 series
+/// (relative error below 2e-7 on [-87, 88]).
+pub fn exp(x: f32) -> f32 {
+    let x = x.clamp(-87.0, 88.0);
+    let scaled = x * LOG2_E;
+    let n = if scaled >= 0.0 {
+        (scaled + 0.5) as i32
+    } else {
+        (scaled - 0.5) as i32
+    };
+    // Cody-Waite two-part ln2 keeps the reduction exact for large |n|.
+    let r = (x - n as f32 * LN_2_HI) - n as f32 * LN_2_LO;
+    let p = 1.0
+        + r * (1.0
+            + r * (0.5 + r * (1.0 / 6.0 + r * (1.0 / 24.0 + r * (1.0 / 120.0 + r / 720.0)))));
+    p * f32::from_bits(((n + 127) as u32) << 23)
+}
+
+/// Natural log for positive normal `x` (frexp then atanh series on
+/// the mantissa folded to [sqrt(1/2), sqrt(2)]; error below 1e-7).
+pub fn ln(x: f32) -> f32 {
+    let bits = x.to_bits();
+    let mut e = ((bits >> 23) & 0xff) as i32 - 127;
+    let mut m = f32::from_bits((bits & 0x7f_ffff) | (127 << 23));
+    if m > core::f32::consts::SQRT_2 {
+        m *= 0.5;
+        e += 1;
+    }
+    let y = (m - 1.0) / (m + 1.0);
+    let y2 = y * y;
+    let s = y
+        * (1.0
+            + y2 * (1.0 / 3.0
+                + y2 * (1.0 / 5.0 + y2 * (1.0 / 7.0 + y2 * (1.0 / 9.0 + y2 / 11.0)))));
+    2.0 * s + e as f32 * LN_2
+}
+
+/// `base^e` for positive `base`.
+pub fn powf(base: f32, e: f32) -> f32 {
+    exp(e * ln(base))
+}
+
+/// `(sin, cos)`. Reduce to [-pi, pi], fold to [-pi/2, pi/2], Taylor series
+/// (about 1e-6 absolute).
+pub fn sin_cos(angle: f32) -> (f32, f32) {
+    let mut r = (angle + PI) % TAU;
+    if r < 0.0 {
+        r += TAU;
+    }
+    let mut x = r - PI;
+    let mut cos_sign = 1.0;
+    if x > FRAC_PI_2 {
+        x = PI - x;
+        cos_sign = -1.0;
+    } else if x < -FRAC_PI_2 {
+        x = -PI - x;
+        cos_sign = -1.0;
+    }
+    let x2 = x * x;
+    let sin = x
+        * (1.0
+            + x2 * (-1.0 / 6.0
+                + x2 * (1.0 / 120.0 + x2 * (-1.0 / 5040.0 + x2 * (1.0 / 362_880.0)))));
+    let cos = 1.0
+        + x2 * (-1.0 / 2.0
+            + x2 * (1.0 / 24.0 + x2 * (-1.0 / 720.0 + x2 * (1.0 / 40_320.0 - x2 / 3_628_800.0))));
+    (sin, cos_sign * cos)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn rel(a: f32, b: f32) -> f32 {
+        (a - b).abs() / b.abs().max(1e-30)
+    }
+
+    #[test]
+    fn exp_matches_std() {
+        let mut x = -80.0f32;
+        while x < 80.0 {
+            assert!(rel(exp(x), x.exp()) < 5e-7, "exp({x})");
+            x += 0.173;
+        }
+    }
+
+    #[test]
+    fn ln_matches_std() {
+        let mut x = 1e-6f32;
+        while x < 1e6 {
+            let (a, b) = (ln(x), x.ln());
+            assert!((a - b).abs() < 2e-6 * b.abs().max(1.0), "ln({x}) {a} {b}");
+            x *= 1.37;
+        }
+    }
+
+    #[test]
+    fn powf_rope_theta_scale() {
+        // llama.cpp: theta_scale = powf(freq_base, -2/n_rot)
+        let (a, b) = (powf(500000.0, -2.0 / 64.0), 500000f32.powf(-2.0 / 64.0));
+        assert!(rel(a, b) < 1e-6, "{a} {b}");
+    }
+
+    #[test]
+    fn sqrt_matches_std() {
+        for &x in &[1e-8f32, 0.25, 1.0, 2.0, 1234.5, 1e9] {
+            assert!(rel(sqrt(x), x.sqrt()) < 2e-7, "sqrt({x})");
+        }
+    }
+
+    #[test]
+    fn sin_cos_matches_std_and_unit_norm() {
+        let mut a = -50.0f32;
+        while a < 600.0 {
+            let (s, c) = sin_cos(a);
+            assert!((s - a.sin()).abs() < 3e-5, "sin({a})");
+            assert!((c - a.cos()).abs() < 3e-5, "cos({a})");
+            assert!((s * s + c * c - 1.0).abs() < 1e-5);
+            a += 0.37;
+        }
+    }
+}
diff --git a/crates/aienos-infer/src/model.rs b/crates/aienos-infer/src/model.rs
new file mode 100644
index 00000000..8c7dc8fe
--- /dev/null
+++ b/crates/aienos-infer/src/model.rs
@@ -0,0 +1,219 @@
+//! Llama weights bound to a GGUF slice (aienos#34 lane 2).
+//!
+//! Nothing is copied except the small f32 vectors (norm weights, rope
+//! frequency factors). Matrices stay quantized inside the borrowed file and
+//! are read one row at a time.
+
+use alloc::format;
+use alloc::string::String;
+use alloc::vec;
+use alloc::vec::Vec;
+
+use crate::gguf::{plain_to_f32, GgmlType, Gguf, GgufError, LlamaParams};
+use crate::quant::{self, QuantError};
+
+/// Why a model could not be bound or run.
+#[derive(Debug, Clone, PartialEq)]
+pub enum InferError {
+    Gguf(GgufError),
+    Quant(QuantError),
+    /// Required tensor absent.
+    MissingTensor(String),
+    /// Tensor shape or type does not fit this architecture.
+    BadTensor(String),
+    /// Hyperparameters are inconsistent (head sizes, odd rope dim, ...).
+    BadParams(&'static str),
+    /// Token id outside the vocabulary.
+    BadToken(u32),
+    /// The KV cache is full.
+    ContextFull,
+}
+
+impl From<GgufError> for InferError {
+    fn from(e: GgufError) -> Self {
+        Self::Gguf(e)
+    }
+}
+impl From<QuantError> for InferError {
+    fn from(e: QuantError) -> Self {
+        Self::Quant(e)
+    }
+}
+
+/// A 2-D weight matrix inside the GGUF data: `rows` rows of `cols` weights.
+#[derive(Clone, Copy)]
+pub struct Weight<'a> {
+    data: &'a [u8],
+    ty: GgmlType,
+    pub rows: usize,
+    pub cols: usize,
+    row_bytes: usize,
+}
+
+impl<'a> Weight<'a> {
+    fn bind(g: &Gguf<'a>, name: &str, rows: usize, cols: usize) -> Result<Self, InferError> {
+        let t = g
+            .tensor(name)
+            .ok_or_else(|| InferError::MissingTensor(String::from(name)))?;
+        let bad = || InferError::BadTensor(format!("{name}: want {cols}x{rows}"));
+        if t.n_dims != 2 || t.dims[0] as usize != cols || t.dims[1] as usize != rows {
+            return Err(bad());
+        }
+        let (bw, _) = t.ty.block();
+        if cols % bw != 0 {
+            return Err(bad());
+        }
+        match t.ty {
+            GgmlType::Q4K | GgmlType::Q6K | GgmlType::F32 | GgmlType::F16 | GgmlType::BF16 => {}
+            _ => return Err(bad()),
+        }
+        let data = g.tensor_data(t);
+        let row_bytes = t.row_bytes() as usize;
+        if data.len() != row_bytes * rows {
+            return Err(bad());
+        }
+        Ok(Self {
+            data,
+            ty: t.ty,
+            rows,
+            cols,
+            row_bytes,
+        })
+    }
+
+    fn row(&self, i: usize) -> &'a [u8] {
+        &self.data[i * self.row_bytes..(i + 1) * self.row_bytes]
+    }
+
+    /// Dequantize row `i` into `out` (`cols` long).
+    pub fn row_into(&self, i: usize, out: &mut [f32]) -> Result<(), InferError> {
+        if i >= self.rows || out.len() != self.cols {
+            return Err(InferError::BadToken(i as u32));
+        }
+        if !plain_to_f32(self.ty, self.row(i), out) {
+            quant::dequantize(self.ty, self.row(i), out)?;
+        }
+        Ok(())
+    }
+
+    /// `out[r] = row_r . x` for every row. `scratch` is `cols` long and is
+    /// used only for the plain float types.
+    pub fn matvec(
+        &self,
+        x: &[f32],
+        out: &mut [f32],
+        scratch: &mut [f32],
+    ) -> Result<(), InferError> {
+        if x.len() != self.cols || out.len() != self.rows || scratch.len() < self.cols {
+            return Err(InferError::BadParams("matvec shape"));
+        }
+        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)?,
+                _ => {
+                    let s = &mut scratch[..self.cols];
+                    plain_to_f32(self.ty, self.row(r), s);
+                    s.iter().zip(x).map(|(a, b)| a * b).sum()
+                }
+            };
+        }
+        Ok(())
+    }
+}
+
+/// One transformer block's tensors.
+pub struct Layer<'a> {
+    pub attn_norm: Vec<f32>,
+    pub wq: Weight<'a>,
+    pub wk: Weight<'a>,
+    pub wv: Weight<'a>,
+    pub wo: Weight<'a>,
+    pub ffn_norm: Vec<f32>,
+    pub w_gate: Weight<'a>,
+    pub w_up: Weight<'a>,
+    pub w_down: Weight<'a>,
+}
+
+/// A Llama model bound to a GGUF file.
+pub struct Model<'a> {
+    pub params: LlamaParams,
+    pub head_dim: usize,
+    pub kv_dim: usize,
+    pub layers: Vec<Layer<'a>>,
+    pub tok_embd: Weight<'a>,
+    /// Output projection: `output.weight` if present, else tied `token_embd`.
+    pub output: Weight<'a>,
+    pub output_norm: Vec<f32>,
+    /// Per rope pair divisors from `rope_freqs.weight` (llama3 scaling as
+    /// precomputed by the converter), or empty when absent.
+    pub rope_factors: Vec<f32>,
+}
+
+fn load_vec(g: &Gguf<'_>, name: &str, n: usize) -> Result<Vec<f32>, InferError> {
+    let t = g
+        .tensor(name)
+        .ok_or_else(|| InferError::MissingTensor(String::from(name)))?;
+    if t.n_dims != 1 || t.dims[0] as usize != n || t.ty != GgmlType::F32 {
+        return Err(InferError::BadTensor(format!("{name}: want f32[{n}]")));
+    }
+    let mut v = vec![0f32; n];
+    plain_to_f32(t.ty, g.tensor_data(t), &mut v);
+    Ok(v)
+}
+
+impl<'a> Model<'a> {
+    pub fn new(g: &Gguf<'a>) -> Result<Self, InferError> {
+        let p = g.llama_params()?;
+        let (n_embd, n_head, n_kv, n_ff, vocab) = (
+            p.embedding_length as usize,
+            p.head_count as usize,
+            p.head_count_kv as usize,
+            p.feed_forward_length as usize,
+            p.vocab_size as usize,
+        );
+        if n_head == 0 || n_kv == 0 || n_embd % n_head != 0 || n_head % n_kv != 0 {
+            return Err(InferError::BadParams("head counts"));
+        }
+        let head_dim = n_embd / n_head;
+        if head_dim % 2 != 0 {
+            return Err(InferError::BadParams("odd head dim"));
+        }
+        let kv_dim = n_kv * head_dim;
+        let tok_embd = Weight::bind(g, "token_embd.weight", vocab, n_embd)?;
+        let output = if g.tensor("output.weight").is_some() {
+            Weight::bind(g, "output.weight", vocab, n_embd)?
+        } else {
+            tok_embd
+        };
+        let mut layers = Vec::with_capacity(p.block_count as usize);
+        for l in 0..p.block_count {
+            let n = |s: &str| format!("blk.{l}.{s}.weight");
+            layers.push(Layer {
+                attn_norm: load_vec(g, &n("attn_norm"), n_embd)?,
+                wq: Weight::bind(g, &n("attn_q"), n_embd, n_embd)?,
+                wk: Weight::bind(g, &n("attn_k"), kv_dim, n_embd)?,
+                wv: Weight::bind(g, &n("attn_v"), kv_dim, n_embd)?,
+                wo: Weight::bind(g, &n("attn_output"), n_embd, n_embd)?,
+                ffn_norm: load_vec(g, &n("ffn_norm"), n_embd)?,
+                w_gate: Weight::bind(g, &n("ffn_gate"), n_ff, n_embd)?,
+                w_up: Weight::bind(g, &n("ffn_up"), n_ff, n_embd)?,
+                w_down: Weight::bind(g, &n("ffn_down"), n_embd, n_ff)?,
+            });
+        }
+        let rope_factors = if g.tensor("rope_freqs.weight").is_some() {
+            load_vec(g, "rope_freqs.weight", head_dim / 2)?
+        } else {
+            Vec::new()
+        };
+        Ok(Self {
+            params: p,
+            head_dim,
+            kv_dim,
+            layers,
+            tok_embd,
+            output,
+            output_norm: load_vec(g, "output_norm.weight", n_embd)?,
+            rope_factors,
+        })
+    }
+}
diff --git a/crates/aienos-infer/src/tokenizer.rs b/crates/aienos-infer/src/tokenizer.rs
new file mode 100644
index 00000000..d64617d3
--- /dev/null
+++ b/crates/aienos-infer/src/tokenizer.rs
@@ -0,0 +1,495 @@
+//! Llama-3 byte-level BPE tokenizer built from the GGUF `tokenizer.ggml.*`
+//! arrays (pre-tokenizer `llama-bpe`).
+//!
+//! Adapted in structure from `crates/aienos-kernel/src/infer/tokenizer.rs`
+//! (that one reads a custom text vocabulary; this one reads GGUF tokens and
+//! merges and adds the llama-bpe pre-tokenizer split and the GPT-2 byte map).
+//! No regex engine: the llama-bpe split is a hand-written matcher with the
+//! same alternatives and backtracking as llama.cpp's regex
+//! (`llama-vocab.cpp`, `LLAMA_VOCAB_PRE_TYPE_LLAMA3`).
+
+use alloc::string::String;
+use alloc::vec::Vec;
+
+use crate::gguf::TokenizerData;
+
+/// Why a tokenizer could not be built or a text could not be encoded.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TokenizerError {
+    /// `tokenizer.ggml.tokens` is empty or too large for u32 ids.
+    BadVocab,
+    /// A byte-level symbol is missing from the vocabulary.
+    MissingSymbol,
+    /// A token id is outside the vocabulary.
+    BadId(u32),
+}
+
+/// Longest pre-token fed to the BPE merge loop (keeps it bounded).
+const MAX_WORD_BYTES: usize = 1024;
+/// Longest `<|...|>` special token string recognised in text.
+const MAX_SPECIAL_BYTES: usize = 64;
+
+const TYPE_CONTROL: i32 = 3;
+const TYPE_USER_DEFINED: i32 = 4;
+
+/// GPT-2 `bytes_to_unicode`: printable bytes map to themselves, the rest to
+/// U+0100 upward in byte order.
+fn byte_to_char(b: u8) -> char {
+    let keep = (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b);
+    if keep {
+        return b as char;
+    }
+    // Rank of this byte among the non-kept bytes.
+    let mut n = 0u32;
+    for x in 0..b {
+        let k = (33..=126).contains(&x) || (161..=172).contains(&x) || (174..=255).contains(&x);
+        if !k {
+            n += 1;
+        }
+    }
+    char::from_u32(256 + n).expect("valid scalar")
+}
+
+fn char_to_byte(c: char) -> Option<u8> {
+    let cp = c as u32;
+    if cp < 256 {
+        let b = cp as u8;
+        let keep = (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b);
+        return if keep { Some(b) } else { None };
+    }
+    if cp >= 256 {
+        let n = cp - 256;
+        let mut seen = 0u32;
+        for b in 0..=255u8 {
+            let keep =
+                (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b);
+            if !keep {
+                if seen == n {
+                    return Some(b);
+                }
+                seen += 1;
+            }
+        }
+    }
+    None
+}
+
+/// Byte-level BPE tokenizer borrowing the GGUF strings.
+pub struct Tokenizer<'a> {
+    tokens: Vec<&'a str>,
+    types: Vec<i32>,
+    /// `(token text, id)` sorted by text.
+    by_text: Vec<(&'a str, u32)>,
+    /// `(merge "left right", rank)` sorted by text.
+    merges: Vec<(&'a str, u32)>,
+    pub bos_id: Option<u32>,
+    pub eos_id: Option<u32>,
+    /// `<|eot_id|>` if present.
+    pub eot_id: Option<u32>,
+    /// Dense table: GPT-2 mapped char of every byte.
+    byte_chars: [char; 256],
+}
+
+impl<'a> Tokenizer<'a> {
+    pub fn new(data: &TokenizerData<'a>) -> Result<Self, TokenizerError> {
+        let tokens: Vec<&'a str> = data.tokens.strings().collect();
+        if tokens.is_empty()
+            || tokens.len() != data.tokens.len()
+            || tokens.len() > u32::MAX as usize
+        {
+            return Err(TokenizerError::BadVocab);
+        }
+        let types: Vec<i32> = match data.token_type {
+            Some(a) => a.i32s().collect(),
+            None => Vec::new(),
+        };
+        let mut by_text: Vec<(&'a str, u32)> = tokens
+            .iter()
+            .enumerate()
+            .map(|(i, t)| (*t, i as u32))
+            .collect();
+        // Duplicate texts: keep the lowest id (stable sort + dedup below).
+        by_text.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(&b.1)));
+        by_text.dedup_by(|b, a| a.0 == b.0);
+        let mut merges: Vec<(&'a str, u32)> = match data.merges {
+            Some(m) => m
+                .strings()
+                .enumerate()
+                .map(|(i, s)| (s, i as u32))
+                .collect(),
+            None => Vec::new(),
+        };
+        merges.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(&b.1)));
+        merges.dedup_by(|b, a| a.0 == b.0);
+        let mut byte_chars = ['\0'; 256];
+        for b in 0..=255u8 {
+            byte_chars[b as usize] = byte_to_char(b);
+        }
+        let mut t = Tokenizer {
+            tokens,
+            types,
+            by_text,
+            merges,
+            bos_id: data.bos_id,
+            eos_id: data.eos_id,
+            eot_id: None,
+            byte_chars,
+        };
+        t.eot_id = t.lookup("<|eot_id|>");
+        Ok(t)
+    }
+
+    pub fn vocab_size(&self) -> usize {
+        self.tokens.len()
+    }
+
+    /// Token text as stored (GPT-2 mapped).
+    pub fn token_text(&self, id: u32) -> Option<&'a str> {
+        self.tokens.get(id as usize).copied()
+    }
+
+    /// Id of an exact token text.
+    pub fn lookup(&self, text: &str) -> Option<u32> {
+        self.by_text
+            .binary_search_by(|p| p.0.cmp(text))
+            .ok()
+            .map(|i| self.by_text[i].1)
+    }
+
+    fn merge_rank(&self, buf: &mut String, left: &str, right: &str) -> Option<u32> {
+        buf.clear();
+        buf.push_str(left);
+        buf.push(' ');
+        buf.push_str(right);
+        self.merges
+            .binary_search_by(|p| p.0.cmp(buf.as_str()))
+            .ok()
+            .map(|i| self.merges[i].1)
+    }
+
+    fn is_special(&self, id: u32) -> bool {
+        matches!(
+            self.types.get(id as usize),
+            Some(&TYPE_CONTROL) | Some(&TYPE_USER_DEFINED)
+        )
+    }
+
+    /// True for control tokens (printed as nothing).
+    pub fn is_control(&self, id: u32) -> bool {
+        self.types.get(id as usize) == Some(&TYPE_CONTROL)
+    }
+
+    /// Encode `text`. With `parse_special`, `<|name|>` strings that are
+    /// control or user-defined tokens become their single id. No BOS is
+    /// added (the chat template carries it).
+    pub fn encode(&self, text: &str, parse_special: bool) -> Result<Vec<u32>, TokenizerError> {
+        let mut out = Vec::new();
+        let mut rest = text;
+        loop {
+            let hit = if parse_special {
+                self.find_special(rest)
+            } else {
+                None
+            };
+            match hit {
+                Some((at, len, id)) => {
+                    self.encode_plain(&rest[..at], &mut out)?;
+                    out.push(id);
+                    rest = &rest[at + len..];
+                }
+                None => {
+                    self.encode_plain(rest, &mut out)?;
+                    return Ok(out);
+                }
+            }
+        }
+    }
+
+    /// First special token string in `s`: (byte offset, byte length, id).
+    fn find_special(&self, s: &str) -> Option<(usize, usize, u32)> {
+        let b = s.as_bytes();
+        let mut i = 0;
+        while i + 1 < b.len() {
+            if b[i] == b'<' && b[i + 1] == b'|' {
+                let end = (i + MAX_SPECIAL_BYTES).min(b.len());
+                let mut j = i + 2;
+                while j + 1 < end + 1 && j + 1 < b.len() {
+                    if b[j] == b'|' && b[j + 1] == b'>' {
+                        let cand = &s[i..j + 2];
+                        if let Some(id) = self.lookup(cand) {
+                            if self.is_special(id) {
+                                return Some((i, cand.len(), id));
+                            }
+                        }
+                        break;
+                    }
+                    j += 1;
+                }
+            }
+            i += 1;
+        }
+        None
+    }
+
+    fn encode_plain(&self, text: &str, out: &mut Vec<u32>) -> Result<(), TokenizerError> {
+        let mut mapped = String::new();
+        let mut buf = String::new();
+        for word in pretokenize(text) {
+            for chunk in word.as_bytes().chunks(MAX_WORD_BYTES) {
+                mapped.clear();
+                for &b in chunk {
+                    mapped.push(self.byte_chars[b as usize]);
+                }
+                self.bpe_word(&mapped, &mut buf, out)?;
+            }
+        }
+        Ok(())
+    }
+
+    fn bpe_word(
+        &self,
+        word: &str,
+        buf: &mut String,
+        out: &mut Vec<u32>,
+    ) -> Result<(), TokenizerError> {
+        // llama-bpe sets ignore_merges: a whole pre-token in the vocab wins.
+        if let Some(id) = self.lookup(word) {
+            out.push(id);
+            return Ok(());
+        }
+        // Symbols as (start, end) byte ranges of `word`.
+        let mut syms: Vec<(usize, usize)> = word
+            .char_indices()
+            .map(|(i, c)| (i, i + c.len_utf8()))
+            .collect();
+        loop {
+            let mut best: Option<(u32, usize)> = None;
+            for i in 0..syms.len().saturating_sub(1) {
+                let l = &word[syms[i].0..syms[i].1];
+                let r = &word[syms[i + 1].0..syms[i + 1].1];
+                if let Some(rank) = self.merge_rank(buf, l, r) {
+                    if best.is_none_or(|(br, _)| rank < br) {
+                        best = Some((rank, i));
+                    }
+                }
+            }
+            match best {
+                Some((_, i)) => {
+                    syms[i].1 = syms[i + 1].1;
+                    syms.remove(i + 1);
+                }
+                None => break,
+            }
+        }
+        for (s, e) in syms {
+            out.push(
+                self.lookup(&word[s..e])
+                    .ok_or(TokenizerError::MissingSymbol)?,
+            );
+        }
+        Ok(())
+    }
+
+    /// Append the raw bytes of token `id` (control tokens add nothing).
+    pub fn decode_token(&self, id: u32, out: &mut Vec<u8>) -> Result<(), TokenizerError> {
+        let t = self.token_text(id).ok_or(TokenizerError::BadId(id))?;
+        if self.is_control(id) {
+            return Ok(());
+        }
+        for c in t.chars() {
+            match char_to_byte(c) {
+                Some(b) => out.push(b),
+                None => {
+                    let mut tmp = [0u8; 4];
+                    out.extend_from_slice(c.encode_utf8(&mut tmp).as_bytes());
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// Bytes for a whole id sequence.
+    pub fn decode(&self, ids: &[u32]) -> Result<Vec<u8>, TokenizerError> {
+        let mut out = Vec::new();
+        for &id in ids {
+            self.decode_token(id, &mut out)?;
+        }
+        Ok(out)
+    }
+
+    /// Llama-3 instruct chat template for one user turn, ending at the
+    /// assistant header so generation starts the reply.
+    pub fn encode_chat(&self, user: &str) -> Result<Vec<u32>, TokenizerError> {
+        let mut s = String::from("<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n");
+        s.push_str(user);
+        s.push_str("<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n");
+        self.encode(&s, true)
+    }
+}
+
+fn is_letter(c: char) -> bool {
+    c.is_alphabetic()
+}
+fn is_number(c: char) -> bool {
+    c.is_numeric()
+}
+fn is_nl(c: char) -> bool {
+    c == '\r' || c == '\n'
+}
+
+/// Split `text` like the llama-bpe regex:
+/// `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])
+///  |[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*
+///  |\s*[\r\n]+|\s+(?!\S)|\s+`
+/// `\p{L}` is approximated by `char::is_alphabetic` (a superset: also
+/// letter-numbers and a few combining marks), `\p{N}` by `char::is_numeric`.
+pub fn pretokenize(text: &str) -> Vec<&str> {
+    let mut parts = Vec::new();
+    let mut i = 0;
+    while i < text.len() {
+        let end = i + match_one(&text[i..]);
+        parts.push(&text[i..end]);
+        i = end;
+    }
+    parts
+}
+
+/// Length in bytes of the first match at the start of `s` (always >= 1).
+fn match_one(s: &str) -> usize {
+    let mut it = s.chars();
+    let c0 = it.next().expect("non-empty");
+    // 1: contractions
+    if c0 == '\'' {
+        let rest = &s[1..];
+        let low = |n: usize| -> Option<[u8; 2]> {
+            let b = rest.as_bytes();
+            if b.len() < n {
+                return None;
+            }
+            Some([
+                b[0].to_ascii_lowercase(),
+                if n > 1 { b[1].to_ascii_lowercase() } else { 0 },
+            ])
+        };
+        if let Some([a, b]) = low(2) {
+            if (a == b'r' && b == b'e') || (a == b'v' && b == b'e') || (a == b'l' && b == b'l') {
+                return 3;
+            }
+        }
+        if let Some([a, _]) = low(1) {
+            if matches!(a, b's' | b't' | b'm' | b'd') {
+                return 2;
+            }
+        }
+    }
+    // 2: optional one char, then letters
+    if is_letter(c0) {
+        return c0.len_utf8() + run(&s[c0.len_utf8()..], is_letter);
+    }
+    if !is_nl(c0) && !is_number(c0) {
+        let l0 = c0.len_utf8();
+        if s[l0..].chars().next().is_some_and(is_letter) {
+            return l0 + run(&s[l0..], is_letter);
+        }
+    }
+    // 3: 1..=3 digits
+    if is_number(c0) {
+        let mut len = 0;
+        for (n, c) in s.chars().enumerate() {
+            if n == 3 || !is_number(c) {
+                break;
+            }
+            len += c.len_utf8();
+        }
+        return len;
+    }
+    // 4: optional space, symbols, trailing newlines
+    let sym = |c: char| !c.is_whitespace() && !is_letter(c) && !is_number(c);
+    {
+        let skip = if c0 == ' ' { 1 } else { 0 };
+        let body = run(&s[skip..], sym);
+        if body > 0 {
+            let tail = run(&s[skip + body..], is_nl);
+            return skip + body + tail;
+        }
+    }
+    // 5-7: whitespace handling (c0 is whitespace here)
+    let ws = run(s, char::is_whitespace);
+    let w = &s[..ws];
+    // 5: \s*[\r\n]+  -> through the last newline of the run
+    if let Some(p) = w.rfind(is_nl) {
+        return p + 1; // \r and \n are one byte
+    }
+    // 6: \s+(?!\S)
+    if ws == s.len() {
+        return ws;
+    }
+    let n_chars = w.chars().count();
+    if n_chars > 1 {
+        let last = w.chars().next_back().expect("non-empty").len_utf8();
+        return ws - last;
+    }
+    // 7: \s+
+    ws
+}
+
+/// Byte length of the longest prefix whose chars all satisfy `f`.
+fn run(s: &str, f: impl Fn(char) -> bool) -> usize {
+    let mut len = 0;
+    for c in s.chars() {
+        if !f(c) {
+            break;
+        }
+        len += c.len_utf8();
+    }
+    len
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn byte_map_is_gpt2() {
+        assert_eq!(byte_to_char(b'A'), 'A');
+        assert_eq!(byte_to_char(b' '), 'Ġ');
+        assert_eq!(byte_to_char(b'\n'), 'Ċ');
+        assert_eq!(byte_to_char(0), 'Ā');
+        assert_eq!(byte_to_char(127), 'ġ');
+        assert_eq!(byte_to_char(173), 'Ń');
+        for b in 0..=255u8 {
+            assert_eq!(char_to_byte(byte_to_char(b)), Some(b));
+        }
+    }
+
+    fn split(s: &str) -> Vec<&str> {
+        pretokenize(s)
+    }
+
+    #[test]
+    fn pretokenize_cases() {
+        assert_eq!(split("Hello world"), ["Hello", " world"]);
+        assert_eq!(
+            split("it's I'M we'LL"),
+            ["it", "'s", " I", "'M", " we", "'LL"]
+        );
+        assert_eq!(split("a1234b"), ["a", "123", "4", "b"]);
+        assert_eq!(split("x  y"), ["x", " ", " y"]);
+        assert_eq!(split("end.\n\nnext"), ["end", ".\n\n", "next"]);
+        assert_eq!(split("a \n b"), ["a", " \n", " b"]);
+        assert_eq!(split("a   "), ["a", "   "]);
+        assert_eq!(split(" ,x"), [" ,", "x"]);
+        assert_eq!(split("(abc"), ["(abc"]);
+        assert_eq!(split("\n\n"), ["\n\n"]);
+        assert_eq!(split("é à"), ["é", " à"]);
+        assert_eq!(split("don't"), ["don", "'t"]);
+        assert_eq!(split("'x"), ["'x"]);
+        assert_eq!(split("1 2"), ["1", " ", "2"]);
+    }
+
+    #[test]
+    fn pretokenize_covers_input() {
+        let s = "Mixed: 12345, \t tabs\r\n\r\n  and ünïcode… ok'd 99 \u{3000} end ";
+        assert_eq!(split(s).concat(), s);
+    }
+}
diff --git a/crates/aienos-infer/tests/fixtures/ref_cow.txt b/crates/aienos-infer/tests/fixtures/ref_cow.txt
new file mode 100644
index 00000000..5794fa08
--- /dev/null
+++ b/crates/aienos-infer/tests/fixtures/ref_cow.txt
@@ -0,0 +1,33 @@
+ids 128000 128006 882 128007 271 849 21435 3048 10539 63162 304 832 11914 13 128009 128006 78191 128007 271
+step 0 12379 3.018305
+step 1 10539 8.020454
+step 2 63162 4.909622
+step 3 320 0.772867
+step 4 7489 2.132778
+step 5 54 7.287212
+step 6 8 6.522385
+step 7 374 3.995619
+step 8 264 3.739115
+step 9 15840 1.504683
+step 10 15105 1.208258
+step 11 430 2.521580
+step 12 6276 2.440145
+step 13 5361 0.675491
+step 14 13707 1.253502
+step 15 311 4.391739
+step 16 4430 0.382343
+step 17 279 0.663177
+step 18 1890 4.572191
+step 19 2592 0.107500
+step 20 2082 7.167053
+step 21 11 1.506186
+step 22 449 0.898439
+step 23 1855 2.261843
+step 24 16131 3.873367
+step 25 3339 1.772791
+step 26 1193 0.297949
+step 27 9099 0.622007
+step 28 4442 1.832527
+step 29 11 0.976486
+step 30 2085 0.002346
+step 31 3515 0.382198
diff --git a/crates/aienos-infer/tests/fixtures/ref_cow_logits0.f32 b/crates/aienos-infer/tests/fixtures/ref_cow_logits0.f32
new file mode 100644
index 00000000..bbbf0d47
Binary files /dev/null and b/crates/aienos-infer/tests/fixtures/ref_cow_logits0.f32 differ
diff --git a/crates/aienos-infer/tests/fixtures/ref_fr.txt b/crates/aienos-infer/tests/fixtures/ref_fr.txt
new file mode 100644
index 00000000..53c64174
--- /dev/null
+++ b/crates/aienos-infer/tests/fixtures/ref_fr.txt
@@ -0,0 +1,10 @@
+ids 128000 128006 882 128007 271 3923 374 279 6864 315 9822 30 128009 128006 78191 128007 271
+step 0 791 5.114677
+step 1 6864 11.351259
+step 2 315 9.189505
+step 3 9822 11.255690
+step 4 374 13.750587
+step 5 12366 4.883307
+step 6 13 8.523685
+step 7 128009 7.994570
+eog
diff --git a/crates/aienos-infer/tests/fixtures/ref_uni.txt b/crates/aienos-infer/tests/fixtures/ref_uni.txt
new file mode 100644
index 00000000..7dc95584
--- /dev/null
+++ b/crates/aienos-infer/tests/fixtures/ref_uni.txt
@@ -0,0 +1,11 @@
+ids 128000 128006 882 128007 271 46864 15960 304 220 18 15823 25 53050 11 105180 102158 11 91416 320 275 596 220 1041 4 7060 3677 220 11361 0 128009 128006 78191 128007 271
+step 0 34 0.943712
+step 1 2642 1.054420
+step 2 978 7.168729
+step 3 0 0.430935
+step 4 91416 0.158345
+step 5 220 0.209386
+step 6 38641 0.218408
+step 7 1811 0.958755
+step 8 128009 0.299834
+eog
diff --git a/crates/aienos-infer/tests/forward.rs b/crates/aienos-infer/tests/forward.rs
new file mode 100644
index 00000000..156ad863
--- /dev/null
+++ b/crates/aienos-infer/tests/forward.rs
@@ -0,0 +1,213 @@
+#![allow(clippy::chunks_exact_to_as_chunks)]
+//! Golden tests for the Llama-3.2-1B forward pass, tokenizer and greedy decode
+//! against llama.cpp (aienos#34 lanes 2+3).
+//!
+//! Reference fixtures `tests/fixtures/ref_*.txt` were produced by
+//! `tests/ref/llama_ref.c` linked against the local llama.cpp build
+//! (command in the header of that file and in the PR body). The tests need the frozen
+//! 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 std::time::Instant;
+
+fn model_bytes() -> Option<Vec<u8>> {
+    let p = std::env::var("AIENOS_MODEL").unwrap_or_else(|_| {
+        format!(
+            "{}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
+            std::env::var("HOME").unwrap_or_default()
+        )
+    });
+    match std::fs::read(&p) {
+        Ok(b) => Some(b),
+        Err(_) => {
+            eprintln!("SKIPPED: model file {p} not present");
+            None
+        }
+    }
+}
+
+struct Reference {
+    ids: Vec<u32>,
+    /// (token, top1-top2 logit gap)
+    steps: Vec<(u32, f32)>,
+}
+
+fn reference(name: &str) -> Reference {
+    let path = format!(
+        "{}/tests/fixtures/ref_{name}.txt",
+        env!("CARGO_MANIFEST_DIR")
+    );
+    let text = std::fs::read_to_string(path).unwrap();
+    let mut r = Reference {
+        ids: vec![],
+        steps: vec![],
+    };
+    for line in text.lines() {
+        let f: Vec<&str> = line.split_whitespace().collect();
+        match f.first() {
+            Some(&"ids") => r.ids = f[1..].iter().map(|s| s.parse().unwrap()).collect(),
+            Some(&"step") => r.steps.push((f[2].parse().unwrap(), f[3].parse().unwrap())),
+            _ => {}
+        }
+    }
+    r
+}
+
+const PROMPTS: [(&str, &str); 3] = [
+    ("cow", "Explain copy-on-write in one sentence."),
+    ("fr", "What is the capital of France?"),
+    (
+        "uni",
+        "Say hi in 3 languages: caf\u{e9}, \u{65e5}\u{672c}\u{8a9e}, \u{1F600} (it's 100% fine).\n\n  Thanks!",
+    ),
+];
+
+#[test]
+fn tokenization_matches_llama_cpp() {
+    let Some(bytes) = model_bytes() else { return };
+    let g = Gguf::parse(&bytes).unwrap();
+    let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
+    assert_eq!(tok.vocab_size(), 128256);
+    assert_eq!(tok.eot_id, Some(128009));
+    for (name, prompt) in PROMPTS {
+        let want = reference(name).ids;
+        assert_eq!(tok.encode_chat(prompt).unwrap(), want, "prompt {name}");
+    }
+}
+
+#[test]
+fn decode_round_trips_text() {
+    let Some(bytes) = model_bytes() else { return };
+    let g = Gguf::parse(&bytes).unwrap();
+    let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
+    for s in [
+        "Hello, world!",
+        "  caf\u{e9} \u{65e5}\u{672c}\u{8a9e} \u{1F600}\n\n",
+        "a\tb\r\nc 12345",
+    ] {
+        let ids = tok.encode(s, false).unwrap();
+        assert_eq!(tok.decode(&ids).unwrap(), s.as_bytes(), "{s:?}");
+    }
+}
+
+fn check(q8k: bool, max_logit_diff: f32) {
+    let Some(bytes) = model_bytes() else { return };
+    let g = Gguf::parse(&bytes).unwrap();
+    let m = Model::new(&g).unwrap();
+    let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
+    let mut total_match = 0;
+    let mut total = 0;
+    for (name, prompt) in PROMPTS {
+        let r = reference(name);
+        let ids = tok.encode_chat(prompt).unwrap();
+        // (c) free-running greedy
+        let mut st = DecodeState::new(&m, 256);
+        st.emulate_q8k = q8k;
+        let t0 = Instant::now();
+        st.prefill(&m, &ids).unwrap();
+        if name == "cow" {
+            // (b)+(d) first-position logits vs llama.cpp
+            let raw = std::fs::read(format!(
+                "{}/tests/fixtures/ref_cow_logits0.f32",
+                env!("CARGO_MANIFEST_DIR")
+            ))
+            .unwrap();
+            let want: Vec<f32> = raw
+                .chunks_exact(4)
+                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
+                .collect();
+            assert_eq!(want.len(), st.logits.len());
+            let maxdiff = st
+                .logits
+                .iter()
+                .zip(&want)
+                .map(|(a, b)| (a - b).abs())
+                .fold(0f32, f32::max);
+            eprintln!("q8k={q8k} first-position logits: max abs diff vs llama.cpp = {maxdiff}");
+            let n = want.len() as f32;
+            let mean = st
+                .logits
+                .iter()
+                .zip(&want)
+                .map(|(a, b)| (a - b).abs())
+                .sum::<f32>()
+                / n;
+            let top = argmax(&want) as usize;
+            let rms_ref = (want.iter().map(|v| v * v).sum::<f32>() / n).sqrt();
+            eprintln!(
+                "mean abs diff {mean}, diff at top token {} (ref {}), ref logit rms {rms_ref}",
+                st.logits[top] - want[top],
+                want[top]
+            );
+            assert_eq!(argmax(&st.logits), argmax(&want));
+            assert!(maxdiff < max_logit_diff, "max abs logit diff {maxdiff}");
+        }
+        let mut free = Vec::new();
+        for i in 0..r.steps.len() {
+            let t = argmax(&st.logits);
+            free.push(t);
+            if t == 128009 || i + 1 == r.steps.len() {
+                break;
+            }
+            st.forward(&m, t, true).unwrap();
+        }
+        let secs = t0.elapsed().as_secs_f64();
+        let want: Vec<u32> = r.steps.iter().map(|s| s.0).collect();
+        let first_div = free.iter().zip(&want).position(|(a, b)| a != b);
+        eprintln!(
+            "{name}: {} tokens in {secs:.2}s (prefill {} + decode) {:.2} tok/s overall; free-run divergence at {:?}{}",
+            free.len(),
+            ids.len(),
+            (free.len() + ids.len()) as f64 / secs,
+            first_div,
+            first_div
+                .map(|p| format!(" (ref gap there {:.4}, ours {} vs ref {})", r.steps[p].1, free[p], want[p]))
+                .unwrap_or_default()
+        );
+        match first_div {
+            None => assert_eq!(free.len(), want.len()),
+            // A divergence is only acceptable at a near-tie in llama.cpp's own logits.
+            Some(p) => assert!(
+                r.steps[p].1 < 0.05,
+                "diverged at {p} with gap {}",
+                r.steps[p].1
+            ),
+        }
+        // teacher-forced top-1 match rate
+        let mut st = DecodeState::new(&m, 256);
+        st.emulate_q8k = q8k;
+        st.prefill(&m, &ids).unwrap();
+        let mut hit = 0;
+        for (i, &(t, gap)) in r.steps.iter().enumerate() {
+            let mine = argmax(&st.logits);
+            if mine == t {
+                hit += 1;
+            } else {
+                eprintln!("{name}: teacher-forced mismatch at {i}: ours {mine} ref {t} (ref gap {gap:.4})");
+                assert!(gap < 0.05, "mismatch at {i} with gap {gap}");
+            }
+            if t == 128009 {
+                break;
+            }
+            st.forward(&m, t, true).unwrap();
+        }
+        total_match += hit;
+        total += r.steps.len();
+    }
+    eprintln!("teacher-forced top-1 match {total_match}/{total}");
+}
+
+/// Plain f32 activations (more accurate than ggml's int8 activations, so a
+/// small, bounded logit difference is expected).
+#[test]
+fn forward_matches_llama_cpp_f32_activations() {
+    check(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);
+}
diff --git a/crates/aienos-infer/tests/ref/llama_ref.c b/crates/aienos-infer/tests/ref/llama_ref.c
new file mode 100644
index 00000000..76832e33
--- /dev/null
+++ b/crates/aienos-infer/tests/ref/llama_ref.c
@@ -0,0 +1,65 @@
+/* Reference harness for aienos-infer golden tests (aienos#34 lane 2+3).
+ * Links the locally built llama.cpp (libllama) and prints, for one raw prompt
+ * string (special tokens parsed, BOS NOT added: the string carries it):
+ *   ids <prompt token ids>
+ *   step <i> <token id> <logit gap top1-top2>   (greedy = argmax, n_predict steps)
+ * and writes the first-position logits (f32 LE, n_vocab values) to argv[4].
+ * usage: llama_ref MODEL.gguf "PROMPT" N_PREDICT LOGITS_OUT.bin [teacher ids...]
+ * Single thread, CPU only (n_gpu_layers = 0). */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "llama.h"
+#include "ggml-backend.h"
+
+static int argmax2(const float *l, int n, float *gap) {
+    int b = 0; float b1 = l[0], b2 = -1e30f;
+    for (int i = 1; i < n; i++) {
+        if (l[i] > b1) { b2 = b1; b1 = l[i]; b = i; } else if (l[i] > b2) { b2 = l[i]; }
+    }
+    *gap = b1 - b2;
+    return b;
+}
+
+int main(int argc, char **argv) {
+    if (argc < 5) return 2;
+    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;
+    const struct llama_vocab *v = llama_model_get_vocab(m);
+    int nv = llama_vocab_n_tokens(v);
+    const char *p = argv[2];
+    llama_token toks[4096];
+    int n = llama_tokenize(v, p, (int)strlen(p), toks, 4096, /*add_special*/ 0, /*parse_special*/ 1);
+    if (n < 0) return 4;
+    printf("ids");
+    for (int i = 0; i < n; i++) printf(" %d", toks[i]);
+    printf("\n");
+    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;
+    int npred = atoi(argv[3]);
+    int nteach = argc - 5;
+    struct llama_batch b = llama_batch_get_one(toks, n);
+    if (llama_decode(c, b)) return 6;
+    for (int i = 0; i < npred; i++) {
+        float *lg = llama_get_logits_ith(c, -1);
+        if (i == 0) {
+            FILE *f = fopen(argv[4], "wb");
+            fwrite(lg, sizeof(float), nv, f);
+            fclose(f);
+        }
+        float gap; int t = argmax2(lg, nv, &gap);
+        printf("step %d %d %.6f\n", i, t, gap);
+        if (llama_vocab_is_eog(v, t)) { printf("eog\n"); break; }
+        llama_token nt = (i < nteach) ? atoi(argv[5 + i]) : t;
+        struct llama_batch b1 = llama_batch_get_one(&nt, 1);
+        if (llama_decode(c, b1)) return 7;
+    }
+    llama_free(c); llama_model_free(m);
+    return 0;
+}