inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! `last_tg` (kernels.metal): the last threadgroup of a dispatch reads what every other threadgroup stored.
//!
//! `k_ctrl_apply` (the decode loop controller) writes its outputs and a per-threadgroup sum of squares, and its
//! last threadgroup rescales every output in place by the RMSNorm. With plain `device` pointers the last
//! threadgroup could read another threadgroup's outputs before they were visible, rescale the stale values and
//! write them back over the fresh ones: on an M3 Ultra whole 32-channel blocks came out as their stale zeros, at a
//! different place on every run, so `inky check` (single-stream decode) gave different logits from run to run.
//! This runs the kernel many times on random data, each into fresh zeroed outputs, and requires every repeat to be
//! bit-identical to the first and to agree with a CPU reference. No model file is needed.

use super::*;

struct Rng(u64);

impl Rng {
    fn unit(&mut self) -> f32 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^= z >> 31;
        ((z >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
    }
}

/// a bf16 value and its exact f32 reading
fn bf16(x: f32) -> (u16, f32) {
    let b = (x.to_bits() >> 16) as u16;
    (b, f32::from_bits((b as u32) << 16))
}

const JOBS: usize = 3; // a decode step's attention controllers run three at once
const REPEATS: usize = 64; // per command buffer
const ROUNDS: usize = 8;

/// One controller's inputs: `u`, `m`, `g` (64), gain and forget (E x 64, as bf16 and as f32), norm weight (E).
struct Job {
    u: Vec<f32>,
    m: Vec<f32>,
    g: Vec<f32>,
    gain: Vec<f32>,
    forget: Vec<f32>,
    gain_b: Vec<u16>,
    forget_b: Vec<u16>,
    norm: Vec<f32>,
}

impl Job {
    fn random(rng: &mut Rng) -> Job {
        let mut v = |n: usize, s: f32| (0..n).map(|_| rng.unit() * s).collect::<Vec<f32>>();
        let (u, m, g, gw, fw) = (v(E, 2.0), v(E, 2.0), v(64, 1.0), v(E * 64, 0.25), v(E * 64, 0.25));
        let norm = v(E, 1.0).into_iter().map(|x| 1.0 + 0.5 * x).collect();
        let (gain_b, gain) = gw.iter().map(|&x| bf16(x)).unzip();
        let (forget_b, forget) = fw.iter().map(|&x| bf16(x)).unzip();
        Job { u, m, g, gain, forget, gain_b, forget_b, norm }
    }

    /// `k_ctrl_apply`'s output, in f64
    fn reference(&self) -> Vec<f64> {
        let o: Vec<f64> = (0..E)
            .map(|ch| {
                let dot = |w: &[f32]| (0..64).map(|i| w[ch * 64 + i] as f64 * self.g[i] as f64).sum::<f64>();
                let (dg, df) = (dot(&self.gain), dot(&self.forget));
                let (u, m) = (self.u[ch] as f64, self.m[ch] as f64);
                u - df.tanh() * u + dg.tanh() * m
            })
            .collect();
        let r = 1.0 / (o.iter().map(|x| x * x).sum::<f64>() / E as f64 + 1e-6).sqrt();
        o.iter().zip(&self.norm).map(|(x, &w)| x * r * w as f64).collect()
    }
}

/// Run `k_ctrl_apply` from `src` `ROUNDS * REPEATS` times; returns every repeat's outputs (`JOBS * E` each).
fn run_ctrl_apply(src: &str, jobs: &[Job]) -> Vec<Vec<f32>> {
    let gpu = Gpu::new_with_lang(src, &["k_ctrl_apply"], false);
    // PB: per job gain, forget (E rows of 64 bf16 = 128 bytes), norm (E f32)
    let mut pb: Vec<u8> = Vec::new();
    let mut offs = Vec::new();
    for j in jobs {
        let gain_off = pb.len() as u32;
        pb.extend(j.gain_b.iter().flat_map(|x| x.to_le_bytes()));
        let forget_off = pb.len() as u32;
        pb.extend(j.forget_b.iter().flat_map(|x| x.to_le_bytes()));
        let norm_off = pb.len() as i32;
        pb.extend(j.norm.iter().flat_map(|x| x.to_le_bytes()));
        offs.push((gain_off, forget_off, norm_off));
    }
    let pb = gpu.buffer_with(&pb);
    // A: per job u, m, g (64), then per repeat and job the outputs (E) and the partial sums (128)
    let mut a: Vec<f32> = Vec::new();
    let mut inputs = Vec::new();
    for j in jobs {
        let u = a.len() as u32;
        a.extend(&j.u);
        let m = a.len() as u32;
        a.extend(&j.m);
        let g = a.len() as u32;
        a.extend(&j.g);
        inputs.push((u, m, g));
    }
    let out0 = a.len();
    let per_rep = JOBS * (E + 128);
    let ctr = gpu.buffer(64 * 4);
    let mut all = Vec::new();
    for _ in 0..ROUNDS {
        let mut words = a.clone();
        words.resize(out0 + REPEATS * per_rep, 0.0); // fresh zeroed outputs: what a stale read sees
        let abuf = gpu.buffer_with(&words.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
        let cb = gpu.cmd();
        let e = Enc::new(&cb);
        e.pso(&gpu.pso("k_ctrl_apply"));
        e.buf(&pb, 0, 1);
        e.buf(&abuf, 0, 2);
        e.buf(&ctr, 0, 7);
        for rep in 0..REPEATS {
            let mut args = CtrlArgs { n_c: JOBS as u32, ..Default::default() };
            for (i, (&(u, m, g), &(gain_off, forget_off, norm_w))) in inputs.iter().zip(&offs).enumerate() {
                let base = (out0 + rep * per_rep + i * (E + 128)) as u32;
                args.job[i] = CtrlJob {
                    u_off: u,
                    m_off: m,
                    d_off: 0,
                    out_off: g,
                    gain_off,
                    forget_off,
                    res_out: base,
                    ss_off: base + E as u32,
                    norm_w,
                    ctr: 8 + i as u32,
                };
            }
            e.bytes(&args, 5);
            e.dispatch((E / 32, JOBS, 1), 256);
            e.barrier();
        }
        e.end();
        cb.commit();
        cb.waitUntilCompleted();
        assert!(cb.error().is_none(), "k_ctrl_apply failed: {:?}", cb.error());
        let got = unsafe { std::slice::from_raw_parts(abuf.contents().as_ptr().cast::<f32>(), words.len()) };
        for rep in 0..REPEATS {
            let r = &got[out0 + rep * per_rep..out0 + (rep + 1) * per_rep];
            all.push((0..JOBS).flat_map(|i| r[i * (E + 128)..i * (E + 128) + E].to_vec()).collect());
        }
        let counters = unsafe { std::slice::from_raw_parts(ctr.contents().as_ptr().cast::<u32>(), 64) };
        assert!(counters.iter().all(|&c| c == 0), "k_ctrl_apply left a counter set: {counters:?}");
    }
    all
}

/// (repeats that differ in any bit from the first, repeats with an output off the CPU reference by more than 1e-3)
fn audit(src: &str) -> (usize, usize, String) {
    let mut rng = Rng(0x6c61_7374_5f74_67);
    let jobs: Vec<Job> = (0..JOBS).map(|_| Job::random(&mut rng)).collect();
    let want: Vec<f64> = jobs.iter().flat_map(Job::reference).collect();
    let reps = run_ctrl_apply(src, &jobs);
    let differ = reps.iter().filter(|r| r.iter().zip(&reps[0]).any(|(x, y)| x.to_bits() != y.to_bits())).count();
    let mut wrong = 0;
    let mut first = String::new();
    for (k, r) in reps.iter().enumerate() {
        if let Some(i) = (0..r.len()).find(|&i| !((r[i] as f64 - want[i]).abs() <= 1e-3 * (1.0 + want[i].abs()))) {
            if wrong == 0 {
                first = format!("repeat {k}: job {} channel {}: got {}, want {}", i / E, i % E, r[i], want[i]);
            }
            wrong += 1;
        }
    }
    (differ, wrong, first)
}

fn kernels_src(edit: impl Fn(&str) -> String) -> String {
    format!("#define NO_MPP 1\n{}", edit(include_str!("../kernels.metal")))
}

#[test]
fn ctrl_apply_last_threadgroup_norm_is_the_same_on_every_repeat() {
    if objc2_metal::MTLCreateSystemDefaultDevice().is_none() {
        return;
    }
    let (differ, wrong, first) = audit(&kernels_src(str::to_string));
    let n = ROUNDS * REPEATS;
    assert!(differ == 0 && wrong == 0, "k_ctrl_apply: {differ}/{n} repeats differ from the first, {wrong}/{n} off the reference ({first})");
}

/// The test above has teeth: the same kernel with plain `device` pointers (the race) is reported, on hardware where
/// the race shows (an M3 Ultra shows it within a few hundred repeats). Where it does not show this says so and passes:
/// a race that does not fire is no evidence either way.
#[test]
fn ctrl_apply_with_plain_pointers_is_reported_where_the_race_shows() {
    if objc2_metal::MTLCreateSystemDefaultDevice().is_none() {
        return;
    }
    let plain = kernels_src(|s| {
        let fixed = "k_ctrl_apply(device const uchar * PB [[buffer(1)]], coherent(device) device float * A";
        assert!(s.contains(fixed), "k_ctrl_apply's signature moved: update this negative control");
        s.replace(fixed, "k_ctrl_apply(device const uchar * PB [[buffer(1)]], device float * A")
    });
    let (differ, wrong, first) = audit(&plain);
    let n = ROUNDS * REPEATS;
    eprintln!("[last_tg] plain-pointer k_ctrl_apply: {differ}/{n} repeats differ, {wrong}/{n} off the reference {first}");
    // a stale read is always a wrong value, never a merely different rounding
    assert!(differ == 0 || wrong > 0, "repeats differ without leaving the reference: {first}");
}