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
//! The Kandinsky ImageSR transformer on CUDA: the `gpu::ksr_prepare` stepper,
//! one tile's forward a step. The patch tokens go up once and the velocity's
//! tokens come back once. A block is two row passes (`ks_row`: the gated
//! residual, the next LayerNorm and its modulation), the fused q|k|v product
//! with its bias, RMS norms and rotation straight into the flash attention's
//! layouts (`ks_heads`), `h3_flash`, the output product and the erf-GELU
//! feed-forward. The weights are the H3 store's: in their codec on the card
//! under `CMF_GPU_VRAM_MB`, expanded to an f16 plane for their product.
//! `CMF_KSR_CUDA=0` keeps the host path, `CMF_KSR_CUDA_PROF=1` times the parts.

use super::*;
use crate::gpu::KsrPrepareArgs;
use crate::ksr::{HEAD_DIM, MODS, RMS_EPS};

const KSR_SRC: &str = include_str!("ksr.cu");
const LN_EPS: f32 = 1e-5;
/// The feed-forward's middle is stored times this before its second product.
const MID_INV: f32 = 1.0 / 16.0;

#[derive(Clone, Copy)]
pub(super) struct KsFuncs {
    row: cs::CUfunction,
    heads: cs::CUfunction,
    gelu: cs::CUfunction,
    bias: cs::CUfunction,
}

fn funcs(st: &mut State, c: &Ctx) -> Res<KsFuncs> {
    if let Some(f) = st.h3.ksr_funcs {
        return Ok(f);
    }
    let module = compile(KSR_SRC, Vec::new(), c.arch)?;
    let f = KsFuncs {
        row: func(module, "ks_row")?,
        heads: func(module, "ks_heads")?,
        gelu: func(module, "ks_gelu")?,
        bias: func(module, "ks_bias")?,
    };
    st.h3.ksr_funcs = Some(f);
    Ok(f)
}

struct Blk {
    w: [usize; 6],
    o_b: usize,
    o_qn: usize,
    o_kn: usize,
    o_mods: usize,
    keep: bool,
}

pub struct KsrCuda {
    model: Arc<CmfModel>,
    n: usize,
    dim: usize,
    inner: usize,
    ff: usize,
    blocks: Vec<Blk>,
    consts: Buf,
    o_cos: usize,
    o_sin: usize,
    o_emb: usize,
    o_emb_b: usize,
    o_fin: usize,
    o_out_b: usize,
    out_w: Buf,
}

/// The device program, or `None` (said once) to run on the host.
pub fn ksr_prepare(a: &KsrPrepareArgs<'_>) -> Option<KsrCuda> {
    if std::env::var("CMF_KSR_CUDA").as_deref() == Ok("0") {
        return None;
    }
    let c = ctx()?;
    if c.current().is_err() {
        return None;
    }
    let mut st = c.st.lock().unwrap();
    match unsafe { prepare(c, &mut st, a) } {
        Ok(p) => Some(p),
        Err(e) => {
            let _ = c.sync();
            decline("kandinsky imagesr prepare", &e);
            None
        }
    }
}

unsafe fn prepare(c: &Ctx, st: &mut State, a: &KsrPrepareArgs<'_>) -> Res<KsrCuda> {
    let (n, dim, inner, ff) = (a.n, a.dim, a.inner, a.ff);
    if n == 0 || !n.is_multiple_of(16) || !inner.is_multiple_of(HEAD_DIM) || a.mods.len() != a.blocks.len() * MODS * dim {
        return Err(format!("{n} rows of {dim} ({inner}) outside the program"));
    }
    if a.embed.0.len() != dim * 64 || a.out.0.len() != 64 * dim || a.rope.0.len() != n * HEAD_DIM / 2 {
        return Err("an embedder, output layer or rotation table of the wrong size".into());
    }
    funcs(st, c)?;
    st.h3.flash(c, HEAD_DIM, false).ok_or("no flash attention kernel for this head width")?;
    let mut cv: Vec<f32> = Vec::new();
    let mut put = |v: &[f32]| -> usize {
        let at = cv.len();
        cv.extend_from_slice(v);
        at
    };
    let o_mods = put(a.mods);
    let mut blocks = Vec::with_capacity(a.blocks.len());
    for (i, b) in a.blocks.iter().enumerate() {
        let o_b = put(b.b[0]);
        put(b.b[1]);
        put(b.b[2]);
        if b.b.iter().any(|v| v.len() != inner) {
            return Err("a bias of the wrong size".into());
        }
        blocks.push(Blk { w: b.w, o_b, o_qn: put(b.qn), o_kn: put(b.kn), o_mods: o_mods + i * MODS * dim, keep: false });
    }
    let (o_cos, o_sin) = (put(a.rope.0), put(a.rope.1));
    let (o_emb, o_emb_b) = (put(a.embed.0), put(a.embed.1));
    let (o_fin, o_out_b) = (put(a.fin), put(a.out.1));
    let consts = Buf::direct(cv.len() * 4)?;
    let out_w = Buf::direct(a.out.0.len() * 2)?;
    let to_half = st.h3.funcs(c)?.to_half;
    let stage = st.h3.buf(c, "ks stage", a.out.0.len() * 4)?;
    unsafe {
        cu::memcpy_htod_async(consts.ptr, &cv, c.stream).map_err(derr)?;
        cu::memcpy_htod_async(stage, a.out.0, c.stream).map_err(derr)?;
        let k = a.out.0.len() as u64;
        c.launch(to_half, (k.div_ceil(256) as u32, 1), 256, 0, kargs!(stage, out_w.ptr, k))?;
    }
    c.sync()?;

    // which blocks keep their weights on the card: what is free after the
    // step's own buffers and the autoencoder's (its widest tensors)
    let uid = a.model.uid();
    let (free, total) = cu::mem_get_info().map_err(derr)?;
    let acts = (n * (dim * 4 + dim * 2 + 3 * inner * 4 + 3 * inner * 2 + inner * 2 + ff * 4 + ff * 2) + 2 * ff * dim * 2) as i64;
    let vae = 5i64 << 30;
    let mut room = match ceiling() {
        Some(b) => b as i64 - (total - free) as i64,
        None => free as i64 - vae,
    } - acts
        - (256 << 20);
    for b in &mut blocks {
        let mut need = 0u64;
        for &ix in &b.w {
            if !st.h3.mats.contains_key(&(uid, ix)) {
                let (kind, r, co, _) = packed(a.model, ix)?;
                need += packed_dev_bytes(kind, r, co);
            }
        }
        if room >= need as i64 {
            room -= need as i64;
            b.keep = true;
        }
    }
    Ok(KsrCuda { model: a.model.clone(), n, dim, inner, ff, blocks, consts, o_cos, o_sin, o_emb, o_emb_b, o_fin, o_out_b, out_w })
}

impl KsrCuda {
    fn at(&self, o: usize) -> u64 {
        self.consts.ptr + (o * 4) as u64
    }

    unsafe fn run(&self, c: &Ctx, st: &mut State, tok_in: &[f32]) -> Res<Vec<f32>> {
        let f = funcs(st, c)?;
        let (n, d, inner, ff, hd) = (self.n, self.dim, self.inner, self.ff, HEAD_DIM);
        let nh = inner / hd;
        if tok_in.len() != n * 64 {
            return Err("tokens of the wrong size".into());
        }
        let fl = st.h3.flash(c, hd, false).ok_or("no flash attention kernel")?;
        let x = st.h3.buf(c, "ks x", n * d * 4)?;
        let xn = st.h3.buf(c, "ks xn", n * d * 2)?;
        let y = st.h3.buf(c, "ks y", n * (3 * inner).max(ff).max(d) * 4)?;
        let q = st.h3.buf(c, "ks q", n * inner * 2)?;
        let k = st.h3.buf(c, "ks k", n * inner * 2)?;
        let v = st.h3.buf(c, "ks v", n * inner * 2 + 64)?;
        let ao = st.h3.buf(c, "ks ao", n * inner * 2)?;
        let act = st.h3.buf(c, "ks act", n * ff * 2)?;
        let w = st.h3.buf(c, "ks w", (3 * inner).max(ff) * d * 2)?;
        let tok = st.h3.buf(c, "ks tok", n * 64 * 4)?;
        let ob = st.h3.buf(c, "ks out", n * 64 * 4)?;
        let (ni, di, nhi, hdi) = (n as i32, d as i32, nh as i32, hd as i32);
        let rows = (n as u32, 1);
        let nul = 0u64;
        let scale = 1.0 / (hd as f32).sqrt();
        let prof = std::env::var("CMF_KSR_CUDA_PROF").as_deref() == Ok("1");
        let mut times = [0f64; 8];
        let mut tt = std::time::Instant::now();
        let mut lap = |i: usize| {
            if prof {
                let _ = c.sync();
                times[i] += tt.elapsed().as_secs_f64();
                tt = std::time::Instant::now();
            }
        };
        unsafe {
            cu::memcpy_htod_async(tok, tok_in, c.stream).map_err(derr)?;
            c.gemm(true, false, d, n, 64, 1.0, self.at(self.o_emb), 64, tok, 64, 0.0, x, d, Gemm::F32)?;
            let tot = (n * d) as u64;
            c.launch(f.bias, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(x, self.at(self.o_emb_b), di, tot))?;
            lap(0);
            let fin = self.at(self.o_fin);
            for (i, b) in self.blocks.iter().enumerate() {
                let m = |i: usize| self.at(b.o_mods + i * d);
                if i == 0 {
                    c.launch(f.row, rows, 256, 0, kargs!(x, nul, xn, nul, nul, m(0), m(1), di, LN_EPS))?;
                }
                lap(1);
                for (i, &ix) in b.w[..3].iter().enumerate() {
                    expand(c, st, &self.model, ix, w + (i * inner * d * 2) as u64, b.keep, true)?;
                }
                lap(2);
                c.gemm(true, false, 3 * inner, n, d, 1.0, w, d, xn, d, 0.0, y, 3 * inner, Gemm::Half)?;
                lap(3);
                c.launch(f.heads, (n as u32, 3 * nh as u32), 32, 0, kargs!(y, self.at(b.o_b), q, k, v, self.at(b.o_qn), self.at(b.o_kn), self.at(self.o_cos), self.at(self.o_sin), ni, nhi, hdi, RMS_EPS))?;
                lap(4);
                c.launch(fl, (n.div_ceil(64) as u32, nh as u32), 128, 0, kargs!(q, k, v, ao, ni, ni, nhi, scale, 1i32))?;
                lap(5);
                expand(c, st, &self.model, b.w[3], w, b.keep, true)?;
                lap(2);
                c.gemm(true, false, d, n, inner, 1.0, w, inner, ao, inner, 0.0, y, d, Gemm::Half)?;
                lap(3);
                c.launch(f.row, rows, 256, 0, kargs!(x, y, xn, m(2), m(3), m(4), m(5), di, LN_EPS))?;
                lap(1);
                expand(c, st, &self.model, b.w[4], w, b.keep, true)?;
                lap(2);
                c.gemm(true, false, ff, n, d, 1.0, w, d, xn, d, 0.0, y, ff, Gemm::Half)?;
                lap(6);
                let tot = (n * ff) as u64;
                c.launch(f.gelu, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(y, act, MID_INV, tot))?;
                lap(4);
                expand(c, st, &self.model, b.w[5], w, b.keep, true)?;
                lap(2);
                c.gemm(true, false, d, n, ff, 1.0 / MID_INV, w, ff, act, ff, 0.0, y, d, Gemm::Half)?;
                lap(6);
                // the residual with the next LayerNorm: the next block's, or the output layer's
                let (sc, sh) = match self.blocks.get(i + 1) {
                    Some(n) => (self.at(n.o_mods), self.at(n.o_mods + d)),
                    None => (fin, fin + (d * 4) as u64),
                };
                c.launch(f.row, rows, 256, 0, kargs!(x, y, xn, m(6), nul, sc, sh, di, LN_EPS))?;
                lap(1);
            }
            c.gemm(true, false, 64, n, d, 1.0, self.out_w.ptr, d, xn, d, 0.0, ob, 64, Gemm::Half)?;
            let tot = (n * 64) as u64;
            c.launch(f.bias, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(ob, self.at(self.o_out_b), 64i32, tot))?;
            let mut out = vec![0f32; n * 64];
            cu::memcpy_dtoh_async(&mut out, ob, c.stream).map_err(derr)?;
            c.sync()?;
            lap(7);
            if prof {
                let names = ["embed", "row", "expand", "attn gemm", "heads+gelu", "flash", "ffn gemm", "head"];
                let s: Vec<String> = names.iter().zip(times).map(|(n, t)| format!("{n} {:.1}", t * 1e3)).collect();
                eprintln!("ksr cuda forward, ms: {}", s.join(" ยท "));
            }
            if out.iter().any(|v| !v.is_finite()) {
                return Err("the forward produced a value that is not finite".into());
            }
            Ok(out)
        }
    }
}

impl crate::gpu::KsrStepper for KsrCuda {
    fn step(&mut self, tok: &[f32]) -> Result<Vec<f32>, String> {
        let c = ctx().ok_or("no CUDA context")?;
        c.current().map_err(|e| format!("{e:?}"))?;
        let mut st = c.st.lock().unwrap();
        let r = unsafe { self.run(c, &mut st, tok) };
        if r.is_err() {
            let _ = c.sync();
        }
        r
    }
}