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)
}
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() }
}
#[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();
}
#[derive(Clone, Copy)]
struct Side {
off: u32,
stride: usize,
half: bool,
}
impl Side {
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()
}
}
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);
}
}
}
}
fn layout(act: &Buf, hgemm: bool, q_half: bool, t: usize, ts: usize, rng: &mut Rng) -> Vec<(LoraJob, Side, Side)> {
let mut next = 64u32; 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
}
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()
}
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");
}
}
#[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)]);
}
#[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() {
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);
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));
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));
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);
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);
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());
}
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()))
}
#[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);
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})"
);
}