cortiq-engine 0.9.25

Portable inference runtime for the CMF model format, with no ML framework underneath: runs on CPU, and on GPU (Vulkan / Metal / DX12) with the `gpu` feature; tokenizer, chat templates and dynamic per-skill weight overlay.
Documentation
//! Kandinsky ImageSR on native Metal: a tile's forward on the Kandinsky S2V
//! kernels (`s2v.rs`). The weights stay in the file mapping, the quantized
//! rows dequantized as the GEMM stages them; each block gets its own transient
//! view of the mapping. `CMF_KSR_METAL=0` keeps the host path.

use super::qi21::{Rec, buf_from, buf_zeroed, set_p, write_f32};
use super::s2v::{Aux, E, Pipes, Seq, Tens, pipes, span_of, tens};
use super::{Ctx, WeightArena};
use crate::gpu::{KsrPrepareArgs, KsrStepper};
use crate::ksr::{HEAD_DIM, MODS, RMS_EPS};
use cortiq_core::CmfModel;
use metal::{Buffer, MTLSize};
use std::sync::Arc;

struct Blk {
    q: Tens,
    k: Tens,
    v: Tens,
    o: Tens,
    w1: Tens,
    w2: Tens,
    b: [usize; 3],
    qn: usize,
    kn: usize,
}

pub struct KsrDev {
    c: &'static Ctx,
    p: &'static Pipes,
    model: Arc<CmfModel>,
    aux: Buffer,
    blocks: Vec<Blk>,
    s: Seq,
    tok: Buffer,
    emb: Buffer,
    head_w: Buffer,
    head_b: Buffer,
    out: Buffer,
    /// offsets in `aux`: the blocks' modulation, the output layer's (scale,
    /// shift), the embedder's bias, a row of zeros
    o_mods: usize,
    o_fin: usize,
    o_emb_b: usize,
    o_zero: usize,
    n: usize,
    h: usize,
    inner: usize,
    ff: usize,
}

unsafe impl Send for KsrDev {}

/// A tile's device program, or `None` to run on the host.
pub fn prepare(a: &KsrPrepareArgs<'_>) -> Option<KsrDev> {
    if std::env::var("CMF_KSR_METAL").as_deref() == Ok("0") {
        return None;
    }
    let c = super::ctx()?;
    let p = pipes(c)?;
    match build(c, p, a) {
        Ok(d) => Some(d),
        Err(e) => {
            eprintln!("upscale: no Metal program ({e}); the transformer runs on the CPU");
            None
        }
    }
}

fn build(c: &'static Ctx, p: &'static Pipes, a: &KsrPrepareArgs<'_>) -> Result<KsrDev, String> {
    let (n, h, inner, ff) = (a.n, a.dim, a.inner, a.ff);
    if n == 0 || n % 64 != 0 || h % 256 != 0 || h > 4096 || inner % 64 != 0 {
        return Err("a geometry outside its kernels".into());
    }
    let alloc = n.div_ceil(128) * 128 + 128;
    let total = alloc * (h * 10 + inner * 8 + ff * 2);
    if total as u64 > c._device.recommended_max_working_set_size() {
        return Err(format!("the activations need {:.1} GB", total as f64 / 1e9));
    }
    let mut aux = Aux::default();
    let o_mods = aux.push(a.mods);
    let mut fin: Vec<f32> = a.fin[..h].iter().map(|v| v - 1.0).collect();
    fin.extend_from_slice(&a.fin[h..]);
    let o_fin = aux.push(&fin);
    let o_emb_b = aux.push(a.embed.1);
    let o_zero = aux.push(&vec![0f32; h.max(inner)]);
    let mut blocks = Vec::with_capacity(a.blocks.len());
    for b in &a.blocks {
        let mut t = |i: usize, rows: usize, cols: usize| tens(a.model, &a.model.tensors[b.w[i]].name, rows, cols, &mut aux);
        let (q, k, v, o) = (t(0, inner, h)?, t(1, inner, h)?, t(2, inner, h)?, t(3, h, inner)?);
        let (w1, w2) = (t(4, ff, h)?, t(5, h, ff)?);
        blocks.push(Blk { q, k, v, o, w1, w2, b: b.b.map(|v| aux.push(v)), qn: aux.push(b.qn), kn: aux.push(b.kn) });
    }
    let s = Seq {
        x: buf_zeroed(c, alloc * h * 4),
        xn: buf_zeroed(c, alloc * h * 2),
        panel: buf_zeroed(c, alloc * 3 * inner * 2),
        att: buf_zeroed(c, alloc * inner * 2),
        y: buf_zeroed(c, alloc * h * 4),
        hid: buf_zeroed(c, alloc * ff * 2),
        cs: buf_zeroed(c, alloc * 64 * 4),
        sn: buf_zeroed(c, alloc * 64 * 4),
    };
    write_f32(&s.cs, 0, a.rope.0);
    write_f32(&s.sn, 0, a.rope.1);
    Ok(KsrDev {
        c,
        p,
        model: a.model.clone(),
        aux: buf_from(c, &aux.0),
        blocks,
        s,
        tok: buf_zeroed(c, n * 64 * 4),
        emb: buf_from(c, a.embed.0),
        head_w: buf_from(c, a.out.0),
        head_b: buf_from(c, a.out.1),
        out: buf_zeroed(c, n * 64 * 4),
        o_mods,
        o_fin,
        o_emb_b,
        o_zero,
        n,
        h,
        inner,
        ff,
    })
}

impl KsrDev {
    fn e<'r, 'a>(&'r self, rec: &'r mut Rec<'a>, weights: &'r WeightArena) -> E<'r, 'a> {
        E { rec, p: self.p, arena: weights, aux: &self.aux, h: self.h, inner: self.inner, nh: self.inner / HEAD_DIM, rms_eps: RMS_EPS }
    }
}

impl KsrStepper for KsrDev {
    fn step(&mut self, tok: &[f32]) -> Result<Vec<f32>, String> {
        let (n, h, inner, ff) = (self.n, self.h, self.inner, self.ff);
        if tok.len() != n * 64 {
            return Err("tokens of the wrong size".into());
        }
        write_f32(&self.tok, 0, tok);
        let s = &self.s;
        let aux = &self.aux;
        let mut rec = Rec::new(self.c);
        {
            #[repr(C)]
            #[derive(Clone, Copy)]
            struct Em {
                h: u32,
                n: u32,
                p0: u32,
                p1: u32,
            }
            let pe = Em { h: h as u32, n: n as u32, p0: 0, p1: 0 };
            let p = self.p;
            let enc = rec.enc("embed");
            enc.set_compute_pipeline_state(&p.embed);
            enc.set_buffer(0, Some(&self.tok), 0);
            enc.set_buffer(1, Some(&self.emb), 0);
            enc.set_buffer(2, Some(&s.x), 0);
            set_p(enc, 3, &pe);
            enc.dispatch_threads(MTLSize::new(h as u64, n as u64, 1), MTLSize::new(256, 1, 1));
            enc.set_compute_pipeline_state(&p.addv);
            enc.set_buffer(0, Some(&s.x), 0);
            enc.set_buffer(1, Some(aux), (self.o_emb_b * 4) as u64);
            enc.set_buffer(2, Some(aux), (self.o_zero * 4) as u64);
            set_p(enc, 3, &pe);
            enc.dispatch_threads(MTLSize::new(h as u64, n as u64, 1), MTLSize::new(256, 1, 1));
        }
        let qmul = std::f32::consts::LOG2_E / (HEAD_DIM as f32).sqrt();
        // row modes: 1 residual, 2 gated, 64 the constant after the gate,
        // 16 the next LayerNorm times a scale plus a shift
        for (i, b) in self.blocks.iter().enumerate() {
            let weights = super::file_page_buffer(self.c, &self.model, span_of([b.q, b.k, b.v, b.o, b.w1, b.w2]).0, span_of([b.q, b.k, b.v, b.o, b.w1, b.w2]).1)
                .map(|w| w.0)
                .ok_or("Metal refused a view of a block's weights")?;
            let mut e = self.e(&mut rec, &weights);
            let m = |b: usize, k: usize| (aux, self.o_mods + (b * MODS + k) * h);
            if i == 0 {
                e.row(s, 0, 0, n, 16, m(0, 0), m(0, 1), m(0, 0), self.o_zero, 1.0);
            }
            e.gemm(&[b.q, b.k, b.v], &s.xn, h, &s.panel, &[0, inner, 2 * inner], 3 * inner, n, true, 1.0);
            e.norm(&s.panel, &s.cs, &s.sn, n, 3 * inner, 0, 3, b.qn, b.b[0], qmul);
            e.norm(&s.panel, &s.cs, &s.sn, n, 3 * inner, inner, 3, b.kn, b.b[1], 1.0);
            e.norm(&s.panel, &s.cs, &s.sn, n, 3 * inner, 2 * inner, 0, b.qn, b.b[2], 1.0);
            e.flash_self(&s.panel, 3 * inner, &s.att, n);
            e.gemm(&[b.o], &s.att, inner, &s.y, &[0], h, n, false, 1.0);
            e.row(s, 0, 0, n, 1 | 2 | 64 | 16, m(i, 2), m(i, 5), m(i, 4), m(i, 3).1, 1.0);
            e.gemm(&[b.w1], &s.xn, h, &s.hid, &[0], ff, n, true, 1.0);
            e.gelu(&s.hid, n * ff / 4);
            e.gemm(&[b.w2], &s.hid, ff, &s.y, &[0], h, n, false, 1.0);
            if i + 1 < self.blocks.len() {
                e.row(s, 0, 0, n, 1 | 2 | 64 | 16, m(i, 6), m(i + 1, 1), m(i + 1, 0), self.o_zero, 1.0);
            } else {
                e.row(s, 0, 0, n, 1 | 2 | 64, m(i, 6), m(i, 6), m(i, 6), self.o_zero, 1.0);
            }
            rec.cut();
        }
        {
            #[repr(C)]
            #[derive(Clone, Copy)]
            struct Hd {
                h: u32,
                row0: u32,
                eps: f32,
                outs: u32,
            }
            let ph = Hd { h: h as u32, row0: 0, eps: 1e-5, outs: 64 };
            let p = self.p;
            let enc = rec.enc("head");
            enc.set_compute_pipeline_state(&p.head);
            enc.set_buffer(0, Some(&s.x), 0);
            enc.set_buffer(1, Some(aux), ((self.o_fin + h) * 4) as u64);
            enc.set_buffer(2, Some(aux), (self.o_fin * 4) as u64);
            enc.set_buffer(3, Some(&self.head_w), 0);
            enc.set_buffer(4, Some(&self.head_b), 0);
            enc.set_buffer(5, Some(&self.out), 0);
            set_p(enc, 6, &ph);
            enc.dispatch_thread_groups(MTLSize::new(n as u64, 1, 1), MTLSize::new(256, 1, 1));
        }
        if !rec.finish("tile") {
            return Err("a Metal command buffer failed".into());
        }
        let y = unsafe { std::slice::from_raw_parts(self.out.contents() as *const f32, n * 64) }.to_vec();
        if y.iter().any(|v| !v.is_finite()) {
            return Err("the forward produced a value that is not finite".into());
        }
        Ok(y)
    }
}