use super::*;
use crate::vae::{VaeChainArgs, VaeConvRef, VaeNormRef, VaeResnetRef};
const FV_SRC: &str = include_str!("flux_vae.cu");
const GN_EPS: f32 = 1e-6;
const FV_TN: usize = 128;
const GN_ROWS: usize = 1024;
const PANEL: usize = 256 << 20;
#[derive(Clone, Copy)]
pub(super) struct FvFuncs {
conv: Option<(cs::CUfunction, usize)>,
cols: cs::CUfunction,
weights: cs::CUfunction,
input: cs::CUfunction,
output: cs::CUfunction,
cast: cs::CUfunction,
part: cs::CUfunction,
fin: cs::CUfunction,
apply: cs::CUfunction,
bias_rows: cs::CUfunction,
rms_ch: cs::CUfunction,
dupup: cs::CUfunction,
}
fn funcs(st: &mut State, c: &Ctx) -> Res<FvFuncs> {
if let Some(f) = st.h3.flux_vae {
return Ok(f);
}
let mma = !matches!(c.arch, None | Some("compute_70") | Some("compute_75")) && std::env::var("CMF_FLUX_VAE_CONV").as_deref() != Ok("gemm");
let wide = std::env::var("CMF_FLUX_VAE_TN").ok().and_then(|v| v.parse().ok()).unwrap_or(FV_TN);
let module = compile(FV_SRC, if mma { vec!["-DMMA".into(), format!("-DTN={wide}")] } else { Vec::new() }, c.arch)?;
let f = FvFuncs {
conv: if mma { Some((func(module, "fv_conv")?, wide)) } else { None },
cols: func(module, "fv_cols")?,
weights: func(module, "fv_weights")?,
input: func(module, "fv_in")?,
output: func(module, "fv_out")?,
cast: func(module, "fv_cast")?,
part: func(module, "fv_gn_part_l")?,
fin: func(module, "fv_gn_fin")?,
apply: func(module, "fv_gn_apply_l")?,
bias_rows: func(module, "fv_bias_rows")?,
rms_ch: func(module, "fv_rms_ch")?,
dupup: func(module, "fv_dupup_add")?,
};
st.h3.flux_vae = Some(f);
Ok(f)
}
#[derive(Default)]
pub(super) struct FvWeights {
keys: Vec<u64>,
convs: HashMap<(u64, usize), Buf>,
}
pub(super) fn release_weights(st: &mut State) {
st.h3.fv_weights.keys.clear();
st.h3.fv_weights.convs.clear();
}
pub fn flux_vae_chain(a: &VaeChainArgs<'_>, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
let Some(c) = ctx() else { return false };
if c.current().is_err() || std::env::var("CMF_FLUX_VAE_CUDA").as_deref() == Ok("0") {
return false;
}
let mut st = c.st.lock().unwrap();
match unsafe { run(c, &mut st, a, z, h, w, out) } {
Ok(()) => true,
Err(e) => {
let _ = c.sync();
decline("flux vae chain", &e);
false
}
}
}
const SAME: i32 = 0;
const UP: i32 = 1;
const DOWN: i32 = 2;
#[allow(clippy::too_many_arguments)]
unsafe fn conv_kept(c: &Ctx, st: &mut State, f: &FvFuncs, key: u64, cv: &VaeConvRef<'_>, src: u64, h: usize, w: usize, mode: i32, y: u64, acc: bool) -> Res<()> {
let (wt, bias, ci, co, k) = (cv.w, cv.b, cv.ic, cv.oc, cv.k);
let (oh, ow) = match mode {
UP => (2 * h, 2 * w),
DOWN => (h / 2, w / 2),
_ => (h, w),
};
let taps = k * k;
if !(k == 1 && mode == SAME || k == 3) || wt.len() != co * ci * taps || bias.len() != co {
return Err("a convolution of an unexpected shape".into());
}
let (cip, cop) = (ci.next_multiple_of(16), co.next_multiple_of(128));
let nw = cop * taps * cip;
let id = (key, wt.as_ptr() as usize);
let (tapsi, cii, coi) = (taps as i32, cip as i32, co as i32);
let wh = match st.h3.fv_weights.convs.get(&id) {
Some(b) => b.ptr,
None => {
let b = Buf::direct(nw * 2 + co * 4 + 64)?;
let ptr = b.ptr;
let wf = st.h3.buf(c, "fv wf", wt.len() * 4)?;
let (ci0, total) = (ci as i32, nw as u32);
unsafe {
cu::memcpy_htod_async(wf, wt, c.stream).map_err(derr)?;
c.launch(f.weights, (total.div_ceil(256), 1), 256, 0, kargs!(wf, ptr, coi, ci0, cii, tapsi, total))?;
cu::memcpy_htod_async(ptr + (nw * 2) as u64, bias, c.stream).map_err(derr)?;
}
st.h3.fv_weights.convs.insert(id, b);
ptr
}
};
let bb = wh + (nw * 2) as u64;
let (ohi, owi, hi, wi, acci) = (oh as i32, ow as i32, h as i32, w as i32, acc as i32);
if let Some((conv, tn)) = f.conv {
let grid = ((oh * ow).div_ceil(64) as u32, co.div_ceil(tn) as u32);
return unsafe { c.launch(conv, grid, 128, 0, kargs!(src, wh, bb, y, ohi, owi, hi, wi, cii, coi, tapsi, mode, acci)) };
}
let (p, kk) = (oh * ow, taps * cip);
let chunk = ((16 << 20) / (kk * 2)).clamp(64, p.max(64));
let cols = st.h3.buf(c, "fv cols", chunk * kk * 2)?;
let mut p0 = 0usize;
while p0 < p {
let np = chunk.min(p - p0);
let (p0u, total) = (p0 as u32, (np * kk) as u32);
unsafe {
c.launch(f.cols, (total.div_ceil(256), 1), 256, 0, kargs!(src, cols, ohi, owi, hi, wi, cii, tapsi, mode, p0u, total))?;
c.gemm(true, false, co, np, kk, 1.0, wh, kk, cols, kk, if acc { 1.0 } else { 0.0 }, y + (p0 * co * 4) as u64, co, Gemm::Half)?;
}
p0 += np;
}
let total = (p * co) as u64;
unsafe { c.launch(f.bias_rows, (total.div_ceil(256) as u32, 1), 256, 0, kargs!(y, bb, coi, total)) }
}
#[allow(clippy::too_many_arguments)]
unsafe fn conv2d(
c: &Ctx,
st: &mut State,
lx: &super::ltx::LxFuncs,
to_half: cs::CUfunction,
cv: (&[f32], &[f32], usize, usize, usize),
src: u64,
h: usize,
w: usize,
up: bool,
y: u64,
acc: bool,
) -> Res<()> {
let (wt, bias, ci, co, k) = cv;
let (oh, ow) = if up { (2 * h, 2 * w) } else { (h, w) };
let (p, kk) = (oh * ow, ci * k * k);
if k.is_multiple_of(2) || wt.len() != co * kk || bias.len() != co {
return Err("a convolution of an unexpected shape".into());
}
let wf = st.h3.buf(c, "fv wf", co * kk * 4)?;
let wh = st.h3.buf(c, "fv wh", co * kk * 2 + 64)?;
let bb = st.h3.buf(c, "fv b", co * 4 + 64)?;
let chunk = (PANEL / (kk * 2)).clamp(1, p);
let cols = st.h3.buf(c, "fv cols", chunk * kk * 2)?;
let nw = (co * kk) as u64;
let (cii, hi, wi, owi, ohi, ki, upi) = (ci as i32, h as i32, w as i32, ow as i32, oh as i32, k as i32, up as i32);
let nul = 0u64;
unsafe {
cu::memcpy_htod_async(wf, wt, c.stream).map_err(derr)?;
c.launch(to_half, (nw.div_ceil(256) as u32, 1), 256, 0, kargs!(wf, wh, nw))?;
cu::memcpy_htod_async(bb, bias, c.stream).map_err(derr)?;
let beta = if acc { 1.0 } else { 0.0 };
let mut p0 = 0usize;
while p0 < p {
let np = chunk.min(p - p0);
let (p0u, total) = (p0 as u64, (np * ci) as u64);
c.launch(lx.im2col2d, (total.div_ceil(256) as u32, 1), 256, 0, kargs!(src, cols, cii, hi, wi, owi, ohi, ki, upi, p0u, total))?;
c.gemm(true, false, np, co, kk, 1.0, cols, kk, wh, kk, beta, y + (p0 * 4) as u64, p, Gemm::Half)?;
p0 += np;
}
let (pu, n) = (p as u64, (co * p) as u64);
c.launch(lx.bias, (n.div_ceil(256) as u32, 1), 256, 0, kargs!(y, bb, nul, pu, n))
}
}
struct Plan {
most: usize,
mid_most: usize,
mh: usize,
mw: usize,
oh: usize,
ow: usize,
}
fn plan(a: &VaeChainArgs<'_>, h: usize, w: usize) -> Plan {
let (mut hh, mut ww) = (h, w);
let mut most = a.latent_channels.max(a.conv_in.oc) * h * w;
let mut mid = 0;
let mut res = |r: &VaeResnetRef<'_>, hw: usize, most: &mut usize| {
*most = (*most).max(r.conv1.ic.max(r.conv2.oc) * hw);
mid = mid.max(r.conv1.oc * hw);
};
for d in &a.downs {
for r in &d.resnets {
res(r, hh * ww, &mut most);
}
if d.upsample.is_some() {
hh /= 2;
ww /= 2;
}
}
let (mh, mw) = (hh, ww);
res(&a.mid_res1, hh * ww, &mut most);
res(&a.mid_res2, hh * ww, &mut most);
for up in &a.ups {
for r in &up.resnets {
res(r, hh * ww, &mut most);
}
if let Some(u) = &up.upsample {
hh *= 2;
ww *= 2;
most = most.max(u.ic.max(u.oc) * hh * ww);
}
}
most = most.max(a.conv_out.ic * hh * ww);
let mid_most = mid.max(a.conv_out.oc * hh * ww).max(a.mid_attn.c * mh * mw);
Plan { most, mid_most, mh, mw, oh: hh, ow: ww }
}
unsafe fn run(c: &Ctx, st: &mut State, a: &VaeChainArgs<'_>, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> Res<()> {
let Plan { most, mid_most, mh, mw, oh, ow } = plan(a, h, w);
if z.len() != a.latent_channels * h * w || a.conv_in.ic != a.latent_channels || out.len() != a.conv_out.oc * oh * ow {
return Err("a latent or picture of the wrong size".into());
}
let halvings = a.downs.iter().filter(|d| d.upsample.is_some()).count();
if mh << halvings != h || mw << halvings != w {
return Err("a picture whose sides the down blocks do not halve".into());
}
let keys = &mut st.h3.fv_weights.keys;
if keys.last() != Some(&a.key) {
keys.retain(|k| *k != a.key);
keys.push(a.key);
if keys.len() > 2 {
let old = keys.remove(0);
c.sync()?;
st.h3.fv_weights.convs.retain(|k, _| k.0 != old);
}
}
let f = funcs(st, c)?;
let lx = super::ltx::funcs(st, c)?;
let mut x = st.h3.buf(c, "fv x", most * 4)?;
let mut s = st.h3.buf(c, "fv s", most * 4)?;
let t = st.h3.buf(c, "fv t", most.max(a.conv_in.ic.next_multiple_of(16) * h * w) * 2)?;
let u = st.h3.buf(c, "fv u", mid_most * 4)?;
if most > u32::MAX as usize {
return Err("a tensor past the kernels' 32-bit index".into());
}
let prof = std::env::var("CMF_FLUX_VAE_PROF").as_deref() == Ok("1");
let mut times = [0f64; 4];
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();
}
};
let conv = |st: &mut State, cv: &VaeConvRef<'_>, src: u64, h: usize, w: usize, mode: i32, y: u64, acc: bool| -> Res<()> {
unsafe { conv_kept(c, st, &f, a.key, cv, src, h, w, mode, y, acc) }
};
let cast = |src: u64, dst: u64, n: usize| -> Res<()> {
let total = n as u32;
unsafe { c.launch(f.cast, (total.div_ceil(256), 1), 256, 0, kargs!(src, dst, total)) }
};
let gn = |st: &mut State, nr: &VaeNormRef<'_>, src: u64, dst: u64, ch: usize, hw: usize, silu: bool, half: bool| -> Res<()> {
let g = nr.groups;
if g == 0 || g > 256 || !ch.is_multiple_of(g) || ch > 512 || nr.w.len() != ch || nr.b.len() != ch {
return Err("a GroupNorm of an unexpected shape".into());
}
let nchunk = hw.div_ceil(GN_ROWS);
let part = st.h3.buf(c, "fv part", g * nchunk * 16)?;
let stats = st.h3.buf(c, "fv stats", g * 8 + 64)?;
let nw = st.h3.buf(c, "fv nw", 2 * ch * 4)?;
let (chi, gi, hwu, rows, nci) = (ch as i32, g as i32, hw as u32, GN_ROWS as i32, nchunk as i32);
let (count, peri, silui, hf, total) = ((ch / g * hw) as f64, (ch / g) as i32, silu as i32, half as i32, (ch * hw) as u32);
unsafe {
cu::memcpy_htod_async(nw, nr.w, c.stream).map_err(derr)?;
cu::memcpy_htod_async(nw + (ch * 4) as u64, nr.b, c.stream).map_err(derr)?;
c.launch(f.part, (nchunk as u32, 1), 256, 0, kargs!(src, part, chi, gi, hwu, rows, nci))?;
c.launch(f.fin, (g as u32, 1), 32, 0, kargs!(part, stats, nci, count, GN_EPS))?;
let (wo, bo) = (nw, nw + (ch * 4) as u64);
c.launch(f.apply, (total.div_ceil(256), 1), 256, 0, kargs!(src, dst, stats, wo, bo, chi, peri, silui, hf, total))
}
};
let mut resnet = |st: &mut State, r: &VaeResnetRef<'_>, x: &mut u64, s: &mut u64, h: usize, w: usize, lap: &mut dyn FnMut(usize)| -> Res<()> {
let hw = h * w;
let into = match &r.shortcut {
Some(sc) => {
cast(*x, t, sc.ic * hw)?;
conv(st, sc, t, h, w, SAME, *s, false)?;
lap(1);
*s
}
None => *x,
};
gn(st, &r.norm1, *x, t, r.conv1.ic, hw, true, true)?;
lap(0);
conv(st, &r.conv1, t, h, w, SAME, u, false)?;
lap(1);
gn(st, &r.norm2, u, t, r.conv1.oc, hw, true, true)?;
lap(0);
conv(st, &r.conv2, t, h, w, SAME, into, true)?;
lap(1);
if r.shortcut.is_some() {
std::mem::swap(x, s);
}
Ok(())
};
unsafe {
cu::memcpy_htod_async(s, z, c.stream).map_err(derr)?;
let (ci, cip, n) = (a.conv_in.ic as i32, a.conv_in.ic.next_multiple_of(16) as i32, (h * w) as u32);
let total = n * cip as u32;
c.launch(f.input, (total.div_ceil(256), 1), 256, 0, kargs!(s, t, ci, cip, n, total))?;
}
conv(st, &a.conv_in, t, h, w, SAME, x, false)?;
lap(1);
let (mut hh, mut ww) = (h, w);
for d in &a.downs {
for r in &d.resnets {
resnet(st, r, &mut x, &mut s, hh, ww, &mut lap)?;
}
if let Some(cv) = &d.upsample {
cast(x, t, cv.ic * hh * ww)?;
conv(st, cv, t, hh, ww, DOWN, s, false)?;
lap(1);
std::mem::swap(&mut x, &mut s);
hh /= 2;
ww /= 2;
}
}
let (h, w) = (hh, ww);
resnet(st, &a.mid_res1, &mut x, &mut s, h, w, &mut lap)?;
{
let at = &a.mid_attn;
let (ch, n) = (at.c, h * w);
gn(st, &at.norm, x, u, ch, n, false, false)?;
let wq = st.h3.buf(c, "fv aw", 4 * ch * ch * 4)?;
let ab = st.h3.buf(c, "fv ab", 4 * ch * 4)?;
let qkv = st.h3.buf(c, "fv qkv", 4 * n * ch * 4)?;
let cq = (PANEL / (n * 4)).clamp(1, n);
let sb = st.h3.buf(c, "fv sc", cq * n * 4)?;
let (q, k, v, o) = (qkv, qkv + (n * ch * 4) as u64, qkv + (2 * n * ch * 4) as u64, qkv + (3 * n * ch * 4) as u64);
let mats = [at.q, at.k, at.v, at.out];
if mats.iter().any(|(m, b)| m.len() != ch * ch || b.len() != ch) {
return Err("a mid-block attention of an unexpected shape".into());
}
let wm = |i: usize| wq + (i * ch * ch * 4) as u64;
let bm = |i: usize| ab + (i * ch * 4) as u64;
let (ci, ni, total) = (ch as i32, n as i32, (n * ch) as u64);
unsafe {
for (i, (m, b)) in mats.iter().enumerate() {
cu::memcpy_htod_async(wm(i), m, c.stream).map_err(derr)?;
cu::memcpy_htod_async(bm(i), b, c.stream).map_err(derr)?;
}
for (i, dst) in [q, k, v].into_iter().enumerate() {
c.gemm(true, false, ch, n, ch, 1.0, wm(i), ch, u, ch, 0.0, dst, ch, Gemm::Tf32)?;
c.launch(f.bias_rows, (total.div_ceil(256) as u32, 1), 256, 0, kargs!(dst, bm(i), ci, total))?;
}
let scale = 1.0 / (ch as f32).sqrt();
let mut q0 = 0usize;
while q0 < n {
let rows = cq.min(n - q0);
c.gemm(true, false, n, rows, ch, scale, k, ch, q + (q0 * ch * 4) as u64, ch, 0.0, sb, n, Gemm::Tf32)?;
c.launch(lx.softmax_f32, (rows as u32, 1), 256, 0, kargs!(sb, ni))?;
c.gemm(false, false, ch, rows, n, 1.0, v, ch, sb, n, 0.0, o + (q0 * ch * 4) as u64, ch, Gemm::Tf32)?;
q0 += rows;
}
c.gemm(true, false, ch, n, ch, 1.0, wm(3), ch, o, ch, 1.0, x, ch, Gemm::Tf32)?;
c.launch(f.bias_rows, (total.div_ceil(256) as u32, 1), 256, 0, kargs!(x, bm(3), ci, total))?;
}
lap(2);
}
resnet(st, &a.mid_res2, &mut x, &mut s, h, w, &mut lap)?;
for up in &a.ups {
for r in &up.resnets {
resnet(st, r, &mut x, &mut s, hh, ww, &mut lap)?;
}
if let Some(cv) = &up.upsample {
cast(x, t, cv.ic * hh * ww)?;
conv(st, cv, t, hh, ww, UP, s, false)?;
lap(1);
std::mem::swap(&mut x, &mut s);
hh *= 2;
ww *= 2;
}
}
gn(st, &a.norm_out, x, t, a.norm_out.w.len(), hh * ww, true, true)?;
conv(st, &a.conv_out, t, hh, ww, SAME, u, false)?;
unsafe {
let (oc, n) = (a.conv_out.oc as i32, (hh * ww) as u32);
let total = oc as u32 * n;
c.launch(f.output, (total.div_ceil(256), 1), 256, 0, kargs!(u, s, oc, n, total))?;
cu::memcpy_dtoh_async(out, s, c.stream).map_err(derr)?;
}
c.sync()?;
lap(3);
if prof {
eprintln!(
"flux vae chain, ms: norms {:.0} · convolutions {:.0} · attention {:.0} · ends {:.0}",
times[0] * 1e3,
times[1] * 1e3,
times[2] * 1e3,
times[3] * 1e3
);
}
if out.iter().any(|v| !v.is_finite()) {
return Err("the picture came back with a value that is not finite".into());
}
Ok(())
}
pub fn qi21_vae_decode(a: &crate::gpu::Qi21VaeDecodeArgs<'_>, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> bool {
let Some(c) = ctx() else { return false };
if c.current().is_err() || std::env::var("CMF_QI21_VAE_CUDA").as_deref() == Ok("0") {
return false;
}
let mut st = c.st.lock().unwrap();
match unsafe { run_qi21(c, &mut st, a, z, h, w, out) } {
Ok(()) => true,
Err(e) => {
let _ = c.sync();
decline("qwen-image-2.1 vae chain", &e);
false
}
}
}
unsafe fn run_qi21(c: &Ctx, st: &mut State, a: &crate::gpu::Qi21VaeDecodeArgs<'_>, z: &[f32], h: usize, w: usize, out: &mut [f32]) -> Res<()> {
use crate::gpu::{Qi21VaeConvRef, Qi21VaeResRef};
let (mut hh, mut ww) = (h, w);
let mut most = a.post_quant.ci.max(a.post_quant.co).max(a.conv_in.co) * h * w;
let res_most = |r: &Qi21VaeResRef<'_>, hw: usize| r.c1.ci.max(r.c1.co).max(r.c2.co) * hw;
for r in &a.mid_res {
most = most.max(res_most(r, h * w));
}
most = most.max(3 * a.attn_qkv.ci * h * w);
for up in &a.ups {
for r in &up.resnets {
most = most.max(res_most(r, hh * ww));
}
if let Some((u, _)) = &up.up {
hh *= 2;
ww *= 2;
most = most.max(u.ci.max(u.co).max(up.out_dim) * hh * ww);
}
}
most = most.max(a.conv_out.ci.max(a.conv_out.co) * hh * ww);
if z.len() != a.post_quant.ci * h * w || out.len() != a.conv_out.co * hh * ww {
return Err("a latent or picture of the wrong size".into());
}
let f = funcs(st, c)?;
let lx = super::ltx::funcs(st, c)?;
let to_half = st.h3.funcs(c)?.to_half;
let b = [
st.h3.buf(c, "fv x", most * 4)?,
st.h3.buf(c, "fv t", most * 4)?,
st.h3.buf(c, "fv u", most * 4)?,
st.h3.buf(c, "fv s", most * 4)?,
st.h3.buf(c, "fv copy", most * 4)?,
];
let (mut x, mut t, u, mut s, cp) = (b[0], b[1], b[2], b[3], b[4]);
let gam = st.h3.buf(c, "fv gamma", 4096 * 4)?;
unsafe { cu::memcpy_htod_async(t, z, c.stream).map_err(derr)? };
let conv = |st: &mut State, cv: &Qi21VaeConvRef<'_>, src: u64, h: usize, w: usize, up: bool, y: u64, acc: bool| -> Res<()> {
unsafe { conv2d(c, st, &lx, to_half, (cv.w, cv.b, cv.ci, cv.co, cv.k), src, h, w, up, y, acc) }
};
let rms = |gamma: &[f32], src: u64, dst: u64, ch: usize, hw: usize, silu: bool| -> Res<()> {
if gamma.len() != ch || ch > 4096 {
return Err("an RMS norm of an unexpected width".into());
}
let (chi, hwu, si) = (ch as i32, hw as u64, silu as i32);
unsafe {
cu::memcpy_htod_async(gam, gamma, c.stream).map_err(derr)?;
c.launch(f.rms_ch, (hwu.div_ceil(256) as u32, 1), 256, 0, kargs!(src, dst, gam, chi, hwu, si))
}
};
let resnet = |st: &mut State, r: &Qi21VaeResRef<'_>, x: &mut u64, s: &mut u64, t: u64, h: usize, w: usize| -> Res<()> {
let hw = h * w;
rms(r.g1, *x, t, r.c1.ci, hw, true)?;
conv(st, &r.c1, t, h, w, false, u, false)?;
rms(r.g2, u, u, r.c1.co, hw, true)?;
match &r.shortcut {
Some(sc) => {
conv(st, sc, *x, h, w, false, *s, false)?;
conv(st, &r.c2, u, h, w, false, *s, true)?;
std::mem::swap(x, s);
}
None => conv(st, &r.c2, u, h, w, false, *x, true)?,
}
Ok(())
};
conv(st, &a.post_quant, t, h, w, false, x, false)?;
conv(st, &a.conv_in, x, h, w, false, t, false)?;
std::mem::swap(&mut x, &mut t);
resnet(st, &a.mid_res[0], &mut x, &mut s, t, h, w)?;
{
let (ch, n) = (a.attn_qkv.ci, h * w);
if a.attn_qkv.co != 3 * ch {
return Err("a mid attention of an unexpected shape".into());
}
rms(a.attn_gamma, x, u, ch, n, false)?;
conv(st, &a.attn_qkv, u, h, w, false, t, false)?;
let (q, k, v) = (t, t + (ch * n * 4) as u64, t + (2 * ch * n * 4) as u64);
let cq = (PANEL / (n * 4)).clamp(1, n);
let sb = st.h3.buf(c, "fv sc", cq * n * 4)?;
let scale = 1.0 / (ch as f32).sqrt();
let ni = n as i32;
let mut q0 = 0usize;
while q0 < n {
let rows = cq.min(n - q0);
unsafe {
c.gemm(false, true, n, rows, ch, scale, k, n, q + (q0 * 4) as u64, n, 0.0, sb, n, Gemm::Tf32)?;
c.launch(lx.softmax_f32, (rows as u32, 1), 256, 0, kargs!(sb, ni))?;
c.gemm(true, false, rows, ch, n, 1.0, sb, n, v, n, 0.0, u + (q0 * 4) as u64, n, Gemm::Tf32)?;
}
q0 += rows;
}
conv(st, &a.attn_proj, u, h, w, false, x, true)?;
}
resnet(st, &a.mid_res[1], &mut x, &mut s, t, h, w)?;
let (mut hh, mut ww) = (h, w);
for up in &a.ups {
if up.up.is_some() {
unsafe { cu::memcpy_dtod_async(cp, x, up.in_dim * hh * ww * 4, c.stream).map_err(derr)? };
}
for r in &up.resnets {
resnet(st, r, &mut x, &mut s, t, hh, ww)?;
}
if let Some((cv, ft)) = &up.up {
conv(st, cv, x, hh, ww, true, t, false)?;
if cv.co != up.out_dim || up.in_dim == 0 || !(up.out_dim * ft * 4).is_multiple_of(up.in_dim) {
return Err("an up block's shortcut of an unexpected shape".into());
}
let total = (up.out_dim * 4 * hh * ww) as u64;
let (ci, co, fti, hi, wi) = (up.in_dim as i32, up.out_dim as i32, *ft as i32, hh as i32, ww as i32);
unsafe { c.launch(f.dupup, (total.div_ceil(256) as u32, 1), 256, 0, kargs!(t, cp, ci, co, fti, hi, wi, total))? };
std::mem::swap(&mut x, &mut t);
hh *= 2;
ww *= 2;
}
}
rms(a.norm_out, x, t, a.conv_out.ci, hh * ww, true)?;
conv(st, &a.conv_out, t, hh, ww, false, u, false)?;
unsafe { cu::memcpy_dtoh_async(out, u, c.stream).map_err(derr)? };
c.sync()?;
if out.iter().any(|v| !v.is_finite()) {
return Err("the picture came back with a value that is not finite".into());
}
Ok(())
}