inky-engine 3.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Runtime LoRA kernels (`k_lora_a`, `k_lora_b` in `lora.metal`) against a CPU reference, on the model's real layer
//! shapes (q 2304 -> 3072, k / v 2304 -> 1024, o 3072 -> 2304, rank 32, scale 2), in both activation layouts the
//! batched layer hands them: fp16 inputs with q written as half (`hgemm`) and fp32 everywhere (the fp32 GEMM path).
//!
//! Tolerance, per output: |got - want| <= 1e-5 * scale * sum_i |B[o][i]| * sum_c |A[i][c] x[c]| + 2^-22 |want|,
//! plus half an fp16 ulp of `want` when y is half. `want` is computed in f64 from the inputs as the kernel reads them.
//! The first term is the fp32 summation bound for the kernels' chains (<= 36 + 8 + 8 + 32 terms deep). Measured: fp32
//! outputs land within ~2e-7 of the largest update of their matrix; half outputs within half an fp16 ulp.

use super::*;
use crate::blocks::{f16_bits_to_f32, f32_to_f16_bits};
use crate::lora::{reference_delta, LoraAdapter, LoraMat, Proj, KSPLIT, MAX_RANK, PROJS, ROWS_PER_TG};
use crate::metal::{Buf, Enc, Gpu};
use objc2_metal::{MTLBuffer, MTLCommandBuffer};

const R: usize = 32;
const QD: usize = NH * HD;
const KVD: usize = NKV * HD;

struct Rng(u64);
impl Rng {
    fn f(&mut self, amp: f32) -> f32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        ((self.0 >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp
    }
}

fn gpu() -> Gpu {
    let src = format!("#include <metal_stdlib>\nusing namespace metal;\n{}", include_str!("../lora.metal"));
    Gpu::new_with_lang(&src, &["k_lora_a", "k_lora_b"], false)
}

/// One layer of adapter at the real shapes, with weights of the trained adapter's magnitudes.
fn adapter(seed: u64) -> LoraAdapter {
    let mut rng = Rng(seed);
    let mats = PROJS.map(|p| {
        let (k, nout) = p.dims(E, QD, KVD);
        LoraMat {
            k,
            nout,
            a: (0..R * k).map(|_| rng.f(0.03)).collect(),
            b: (0..nout * R).map(|_| rng.f(0.01)).collect(),
        }
    });
    LoraAdapter { rank: R, alpha: 64.0, scale: 2.0, layers: vec![mats], source: "test".into() }
}

// a shared Metal buffer's contents (the GPU is idle whenever a test reads or writes them)
#[allow(clippy::mut_from_ref)]
fn floats(b: &Buf) -> &mut [f32] {
    unsafe { std::slice::from_raw_parts_mut(b.contents().as_ptr().cast::<f32>(), b.length() / 4) }
}
#[allow(clippy::mut_from_ref)]
fn halves(b: &Buf) -> &mut [u16] {
    unsafe { std::slice::from_raw_parts_mut(b.contents().as_ptr().cast::<u16>(), b.length() / 2) }
}

fn run(g: &Gpu, w: &Buf, scratch: &Buf, act: &Buf, plan: &LoraPlan) {
    let cb = g.cmd();
    let e = Enc::new(&cb);
    e.buf(act, 0, 2);
    e.buf(w, 0, 15);
    e.buf(scratch, 0, 16);
    e.pso(&g.pso("k_lora_a"));
    e.bytes(&plan.a, 5);
    e.dispatch(plan.grid_a(), 256);
    e.barrier();
    e.pso(&g.pso("k_lora_b"));
    e.bytes(&plan.b, 5);
    e.dispatch(plan.grid_b(), 256);
    e.barrier();
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
}

/// A side of a job in the arena: offset in floats, row stride in elements, half or not.
#[derive(Clone, Copy)]
struct Side {
    off: u32,
    stride: usize,
    half: bool,
}

impl Side {
    /// `rows` rows of `width` values, read in one pass.
    fn rows(&self, act: &Buf, rows: usize, width: usize) -> Vec<f32> {
        let n = rows * self.stride;
        if self.half {
            let h = &halves(act)[self.off as usize * 2..][..n];
            (0..rows).flat_map(|r| h[r * self.stride..][..width].iter().map(|&b| f16_bits_to_f32(b))).collect()
        } else {
            let f = &floats(act)[self.off as usize..][..n];
            (0..rows).flat_map(|r| f[r * self.stride..][..width].iter().copied()).collect()
        }
    }
    /// Write `rows` rows of `width` values in one pass.
    fn write(&self, act: &Buf, rows: usize, width: usize, v: &[f32]) {
        for r in 0..rows {
            let src = &v[r * width..][..width];
            if self.half {
                let h = &mut halves(act)[self.off as usize * 2 + r * self.stride..][..width];
                h.iter_mut().zip(src).for_each(|(d, &x)| *d = f32_to_f16_bits(x));
            } else {
                floats(act)[self.off as usize + r * self.stride..][..width].copy_from_slice(src);
            }
        }
    }
}

/// Jobs laid out the way `layer_b_ex` lays them out for `t` rows with query tail `ts` (q covers rows [ts, t)),
/// x and y filled with random values; returns the jobs and their (x, y) sides.
fn layout(act: &Buf, hgemm: bool, q_half: bool, t: usize, ts: usize, rng: &mut Rng) -> Vec<(LoraJob, Side, Side)> {
    let mut next = 64u32; // floats; keep everything 16-byte aligned
    let mut alloc = |rows: usize, width: usize, half: bool| {
        let off = next;
        let fl = if half { rows * width / 2 } else { rows * width };
        next += (fl as u32).div_ceil(4) * 4 + 4;
        Side { off, stride: width, half }
    };
    let mut out = Vec::new();
    let specs: [(Proj, usize, usize, bool, bool); 4] = [
        (Proj::Q, E, QD, hgemm, hgemm && q_half),
        (Proj::K, E, KVD, hgemm, false),
        (Proj::V, E, KVD, hgemm, false),
        (Proj::O, QD, E, hgemm, false),
    ];
    for (proj, k, nout, xh, yh) in specs {
        let (x, y) = (alloc(t, k, xh), alloc(t, nout, yh));
        x.write(act, t, k, &(0..t * k).map(|_| rng.f(1.0)).collect::<Vec<_>>());
        y.write(act, t, nout, &(0..t * nout).map(|_| rng.f(0.05)).collect::<Vec<_>>());
        let r0 = if proj == Proj::Q { ts } else { 0 };
        let shift = |s: Side, w: usize| Side { off: s.off + (r0 * w / if s.half { 2 } else { 1 }) as u32, ..s };
        let (xs, ys) = (shift(x, k), shift(y, nout));
        let job = LoraJob {
            proj,
            x_off: xs.off,
            x_stride: k as u32,
            x_half: xh,
            y_off: ys.off,
            y_stride: nout as u32,
            y_half: yh,
            rows: t - r0,
        };
        out.push((job, xs, ys));
    }
    assert!((next as usize) * 4 <= act.length(), "test arena too small");
    out
}

/// Check every output of `jobs` (after the kernels ran) against base + reference delta; returns the largest error
/// relative to the bound, the largest |delta| / |base| seen (the update must not be negligible), and the largest fp32
/// error relative to the largest update of its matrix.
fn check(act: &Buf, ad: &LoraAdapter, jobs: &[(LoraJob, Side, Side)], before: &[Vec<f32>]) -> (f64, f64, f64) {
    let (mut worst, mut weight, mut rel) = (0.0f64, 0.0f64, 0.0f64);
    for ((job, xs, ys), y0) in jobs.iter().zip(before) {
        let m = &ad.layers[0][job.proj.index()];
        let x = xs.rows(act, job.rows, m.k);
        let y = ys.rows(act, job.rows, m.nout);
        let delta = reference_delta(m, R, ad.scale as f64, &x, job.rows);
        let babs: Vec<f64> = m.b.iter().map(|b| b.abs() as f64).collect();
        let dmax = delta.iter().fold(0.0f64, |a, d| a.max(d.abs()));
        for r in 0..job.rows {
            let xr = &x[r * m.k..][..m.k];
            let ax: Vec<f64> =
                m.a.chunks_exact(m.k).map(|a| a.iter().zip(xr).map(|(a, x)| (a * x).abs() as f64).sum()).collect();
            for o in 0..m.nout {
                let base = y0[r * m.nout + o] as f64;
                let want = base + delta[r * m.nout + o];
                let got = y[r * m.nout + o] as f64;
                let cond: f64 = babs[o * R..][..R].iter().zip(&ax).map(|(b, a)| b * a).sum::<f64>() * ad.scale as f64;
                let mut tol = 1e-5 * cond + want.abs() * 2f64.powi(-22);
                if ys.half {
                    tol += want.abs() * 2f64.powi(-11) + 2f64.powi(-25);
                }
                let err = (got - want).abs();
                assert!(err <= tol, "{:?} row {r} out {o}: got {got}, want {want} (base {base}), tol {tol}", job.proj);
                worst = worst.max(err / tol);
                weight = weight.max(delta[r * m.nout + o].abs() / base.abs().max(1e-3));
                if !ys.half {
                    rel = rel.max(err / dmax);
                }
            }
        }
    }
    (worst, weight, rel)
}

fn snapshot(act: &Buf, jobs: &[(LoraJob, Side, Side)], ad: &LoraAdapter) -> Vec<Vec<f32>> {
    jobs.iter().map(|(job, _, ys)| ys.rows(act, job.rows, ad.layers[0][job.proj.index()].nout)).collect()
}

/// Run q / k / v in one plan (one batched dispatch pair, as `layer_b_ex` issues it) then o, and check every output.
fn kernel_cases(cases: &[(bool, bool, usize, usize)]) {
    let g = gpu();
    let ad = adapter(0x1234_5678_9abc_def1);
    let (img, slots) = ad.pack();
    let w = g.buffer_with(&img.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
    let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
    for &(hgemm, q_half, t, ts) in cases {
        let act = g.buffer((64 + 2 * t * (2 * E + QD + 2 * KVD) + 4096) * 4);
        let scratch = g.buffer(crate::lora::scratch_floats(t) * 4);
        let jobs = layout(&act, hgemm, q_half, t, ts, &mut rng);
        let before = snapshot(&act, &jobs, &ad);
        let qkv: Vec<LoraJob> = jobs[..3].iter().map(|j| j.0).collect();
        let plan = LoraPlan::new(&slots[0], ad.scale, &qkv);
        assert!(plan.u_floats <= crate::lora::scratch_floats(t));
        run(&g, &w, &scratch, &act, &plan);
        run(&g, &w, &scratch, &act, &LoraPlan::new(&slots[0], ad.scale, &[jobs[3].0]));
        let (worst, weight, rel) = check(&act, &ad, &jobs, &before);
        assert!(weight > 0.5, "the update must be visible against the base output (largest ratio {weight})");
        eprintln!("hgemm {hgemm} q_half {q_half} t {t} ts {ts}: worst error {worst:.3} of the bound, fp32 outputs within {rel:.2e} of the largest update");
    }
}

/// (hgemm, q written as half, rows, query tail): the fp16 layout with and without half q, and the fp32 layout; one row
/// (a decode step), a partial row tile with a query tail, a whole tile.
#[test]
fn lora_kernels_match_the_cpu_reference_on_real_layer_shapes() {
    kernel_cases(&[(true, true, 1, 0), (true, true, 13, 5), (true, false, 3, 2), (false, false, 8, 0)]);
}

/// Longer batches: a 64-row prefill whose last layer keeps only the final query row, and 130 rows of each layout.
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn lora_kernels_match_the_cpu_reference_on_long_batches() {
    kernel_cases(&[(true, true, 64, 63), (true, true, 130, 0), (true, false, 130, 0), (false, false, 130, 0)]);
}

#[test]
fn lora_rows_are_batch_invariant() {
    // A row's update is the same bits alone or in a batch of 37 (fixed k-split, fixed reduction order).
    let g = gpu();
    let ad = adapter(77);
    let (img, slots) = ad.pack();
    let w = g.buffer_with(&img.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
    let t = 37;
    for (hgemm, q_half) in [(true, true), (false, false)] {
        let act = g.buffer((64 + 2 * t * (2 * E + QD + 2 * KVD) + 4096) * 4);
        let scratch = g.buffer(crate::lora::scratch_floats(t) * 4);
        let jobs = layout(&act, hgemm, q_half, t, 0, &mut Rng(5));
        let before = snapshot(&act, &jobs, &ad);
        let all: Vec<LoraJob> = jobs.iter().map(|j| j.0).collect();
        run(&g, &w, &scratch, &act, &LoraPlan::new(&slots[0], ad.scale, &all));
        let batched = snapshot(&act, &jobs, &ad);
        // put the base outputs back and run every row on its own
        for ((_, _, ys), y0) in jobs.iter().zip(&before) {
            ys.write(&act, t, y0.len() / t, y0);
        }
        for r in 0..t {
            let one: Vec<LoraJob> = jobs
                .iter()
                .map(|(j, xs, ys)| {
                    let k = ad.layers[0][j.proj.index()].k;
                    let n = ad.layers[0][j.proj.index()].nout;
                    let adv = |s: &Side, w: usize| s.off + (r * w / if s.half { 2 } else { 1 }) as u32;
                    LoraJob { x_off: adv(xs, k), y_off: adv(ys, n), rows: 1, ..*j }
                })
                .collect();
            run(&g, &w, &scratch, &act, &LoraPlan::new(&slots[0], ad.scale, &one));
        }
        let alone = snapshot(&act, &jobs, &ad);
        for (p, (a, b)) in batched.iter().zip(&alone).enumerate() {
            assert!(
                a.iter().zip(b).all(|(a, b)| a.to_bits() == b.to_bits()),
                "projection {p}: batched and solo rows differ"
            );
        }
    }
}

#[test]
fn lora_plan_lays_out_partials_and_tiles() {
    let ad = adapter(3);
    let (_, slots) = ad.pack();
    let job =
        |proj, rows| LoraJob { proj, x_off: 0, x_stride: 0, x_half: false, y_off: 0, y_stride: 0, y_half: false, rows };
    let p = LoraPlan::new(&slots[0], 2.0, &[job(Proj::Q, 5), job(Proj::K, 13), job(Proj::V, 13)]);
    assert_eq!(p.grid_a(), (2, 3, KSPLIT));
    // q: 3072 / 256 = 12 output tiles, k and v 4 each
    assert_eq!(p.grid_b(), (20, 2, 1));
    assert_eq!((p.b.job[0].tile0, p.b.job[1].tile0, p.b.job[2].tile0), (0, 12, 16));
    // partials: [ksplit][rows rounded to a tile][32] per job, back to back
    let (r5, r13) = (ROWS_PER_TG, 2 * ROWS_PER_TG);
    assert_eq!(
        (p.a.job[0].u_off, p.a.job[1].u_off, p.a.job[2].u_off),
        (0, (KSPLIT * r5 * MAX_RANK) as u32, (KSPLIT * (r5 + r13) * MAX_RANK) as u32)
    );
    assert_eq!(p.u_floats, KSPLIT * (r5 + 2 * r13) * MAX_RANK);
    assert!(p.u_floats <= crate::lora::scratch_floats(13));
    assert_eq!(p.b.scale, 2.0);
}

#[test]
fn registry_ids_start_at_one_and_zero_is_the_base_model() {
    use crate::lora::{LoraGpu, Registry, NO_ADAPTER};
    let g = gpu();
    let mut reg = Registry::default();
    assert!(reg.is_empty() && reg.get(NO_ADAPTER).is_none() && reg.default_fingerprint() == 0);
    // an empty registry allocates no scratch
    reg.reserve_rows(&g, 4096);
    assert!(reg.scratch.borrow().is_none());
    let (a, b) = (adapter(1), adapter(2));
    let id_a = reg.add(&g, LoraGpu::new(&g, &a), 64);
    let id_b = reg.add(&g, LoraGpu::new(&g, &b), 64);
    assert_eq!((id_a, id_b), (1, 2));
    assert_eq!(reg.get(id_b).unwrap().fingerprint, b.fingerprint());
    assert_ne!(reg.get(id_a).unwrap().fingerprint, reg.get(id_b).unwrap().fingerprint);
    // one scratch for every adapter, grown with the batch
    assert_eq!(reg.scratch_cap.get(), crate::lora::scratch_floats(64));
    reg.reserve_rows(&g, 512);
    assert_eq!(reg.scratch_cap.get(), crate::lora::scratch_floats(512));
    assert_eq!(reg.default_fingerprint(), 0, "no default until one is chosen");
    reg.default_id = id_a;
    assert_eq!(reg.default_fingerprint(), a.fingerprint());
}

/// Prefill `n` tokens then decode one more through the serving path; the two steps' logits.
fn prefill_then_decode(eng: &Engine, toks: &[u32]) -> (Vec<f32>, Vec<f32>) {
    use crate::poolgate::{Layer3Pool, StepPath};
    let pool = Layer3Pool::new(eng, 1);
    let n = toks.len() - 1;
    let lane = pool.new_lane(toks, 256);
    pool.prefill(&[(lane, 0, n)]);
    let pf = pool.logits(0);
    pool.decode(&[(lane, n)]);
    let dec = pool.logits(0);
    pool.end_lane(lane);
    (pf, dec)
}

fn same_bits(a: &[f32], b: &[f32]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.to_bits() == b.to_bits())
}

fn max_diff(a: &[f32], b: &[f32]) -> f32 {
    a.iter().zip(b).fold(0.0f32, |m, (a, b)| m.max((a - b).abs()))
}

/// On the real model, through the serving path (paged prefill, then a decode step):
/// - no adapter, an adapter whose update is exactly zero, and an adapter loaded but not selected (lane id 0) give
///   the same bits: the runtime LoRA is off bit for bit, and the extra dispatches add exactly zero;
/// - a nonzero adapter moves the logits, and moves prefill and decode the same way: prefilling the decoded token
///   instead gives logits within the engine's own prefill/decode spread, far below the adapter's effect (a path
///   that skipped the update would differ by the whole effect). `INKY_TEST_LORA=<adapter dir>` uses that adapter
///   (the harness-hub one) for the last part; otherwise a random one of the trained adapter's magnitudes.
#[test]
#[ignore = "requires local Inkling-2-Mini GGUF on M5"]
fn lora_off_is_bit_identical_and_on_moves_prefill_and_decode_alike() {
    use crate::lora::{LoraGpu, Registry};
    let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    let mut eng = Engine::load(&model, 256);
    let toks: Vec<u32> = (0..41).map(|i| (i * 7919 + 13) % 50_000).collect();
    let (off_pf, off_dec) = prefill_then_decode(&eng, &toks);
    // the decode step's input, prefilled instead: the engine's own prefill/decode spread
    let (off_pf41, _) = prefill_then_decode(&eng, &[&toks[..], &[toks[0]]].concat());
    let spread = max_diff(&off_pf41, &off_dec);

    let layers = |seed: u64, zero_b: bool| {
        let one = adapter(seed);
        let mut ad = LoraAdapter { layers: Vec::new(), ..one.clone() };
        for l in 0..N_PHYS {
            let mut m = adapter(seed + l as u64).layers.remove(0);
            if zero_b {
                m.iter_mut().for_each(|m| m.b.iter_mut().for_each(|b| *b = 0.0));
            }
            ad.layers.push(m);
        }
        ad
    };
    let install = |eng: &mut Engine, ad: &LoraAdapter, default: bool| {
        let mut reg = Registry::default();
        let id = reg.add(&eng.gpu, LoraGpu::new(&eng.gpu, ad), eng.ba.get().cap.max(256));
        reg.default_id = if default { id } else { crate::lora::NO_ADAPTER };
        eng.lora = reg;
    };

    install(&mut eng, &layers(11, true), true);
    let (z_pf, z_dec) = prefill_then_decode(&eng, &toks);
    assert!(same_bits(&z_pf, &off_pf) && same_bits(&z_dec, &off_dec), "a zero update must leave every bit");

    let real = match std::env::var_os("INKY_TEST_LORA") {
        Some(dir) => LoraAdapter::load(std::path::Path::new(&dir), N_PHYS, E, QD, KVD).expect("INKY_TEST_LORA"),
        None => layers(29, false),
    };
    install(&mut eng, &real, false);
    let (n_pf, n_dec) = prefill_then_decode(&eng, &toks);
    assert!(same_bits(&n_pf, &off_pf) && same_bits(&n_dec, &off_dec), "lanes on adapter 0 must run the base model");

    install(&mut eng, &real, true);
    let (on_pf, on_dec) = prefill_then_decode(&eng, &toks);
    let (on_pf41, _) = prefill_then_decode(&eng, &[&toks[..], &[toks[0]]].concat());
    let effect = max_diff(&on_dec, &off_dec).max(max_diff(&on_pf, &off_pf));
    let on_spread = max_diff(&on_pf41, &on_dec);
    eprintln!("LoRA effect on logits {effect:.4}; prefill/decode spread off {spread:.4}, on {on_spread:.4}");
    assert!(effect > 0.05, "the adapter must move the logits (moved {effect})");
    assert!(
        on_spread <= (4.0 * spread).max(0.1 * effect),
        "prefill and decode disagree with the adapter on: {on_spread} (off {spread}, effect {effect})"
    );
}