use std::path::Path;
pub struct StTensor {
pub shape: Vec<usize>,
pub data: Vec<f32>,
}
pub fn read_safetensors_each(
path: &Path,
f: &mut dyn FnMut(&str, Vec<usize>, Vec<f32>) -> Result<(), String>,
) -> Result<(), String> {
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
if bytes.len() < 8 {
return Err("safetensors: truncated header".into());
}
let hlen = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize;
let header: serde_json::Value = serde_json::from_slice(&bytes[8..8 + hlen])
.map_err(|e| format!("safetensors header: {e}"))?;
let base = 8 + hlen;
let obj = header
.as_object()
.ok_or("safetensors: header not an object")?;
for (name, meta) in obj {
if name == "__metadata__" {
continue;
}
let dtype = meta["dtype"].as_str().ok_or("dtype")?;
let shape: Vec<usize> = meta["shape"]
.as_array()
.ok_or("shape")?
.iter()
.map(|v| v.as_u64().unwrap_or(0) as usize)
.collect();
let offs = meta["data_offsets"].as_array().ok_or("offsets")?;
let (s, e) = (
offs[0].as_u64().unwrap_or(0) as usize + base,
offs[1].as_u64().unwrap_or(0) as usize + base,
);
let raw = bytes.get(s..e).ok_or("safetensors: span out of file")?;
let n: usize = shape.iter().product::<usize>().max(1);
let mut data = Vec::with_capacity(n);
match dtype {
"F32" => {
for c in raw.chunks_exact(4) {
data.push(f32::from_le_bytes(c.try_into().unwrap()));
}
}
"F16" => {
for c in raw.chunks_exact(2) {
data.push(cortiq_core::quant::f16_to_f32(u16::from_le_bytes(
c.try_into().unwrap(),
)));
}
}
"BF16" => {
for c in raw.chunks_exact(2) {
let b = u16::from_le_bytes(c.try_into().unwrap());
data.push(f32::from_bits((b as u32) << 16));
}
}
other => return Err(format!("safetensors: unsupported dtype {other}")),
}
f(name, shape, data)?;
}
Ok(())
}
pub fn read_safetensors(
path: &Path,
) -> Result<std::collections::HashMap<String, StTensor>, String> {
let mut out = std::collections::HashMap::new();
read_safetensors_each(path, &mut |name, shape, data| {
out.insert(name.to_string(), StTensor { shape, data });
Ok(())
})?;
Ok(out)
}
fn gemm(x: &[f32], w: &[f32], y: &mut [f32], n: usize, k: usize, m: usize) {
if crate::gpu::enabled_here() {
return crate::fcd_ops::gemm_nt(x, w, y, n, k, m, None);
}
static POOL: std::sync::OnceLock<Option<std::sync::Mutex<std::sync::Arc<crate::pool::Pool>>>> = std::sync::OnceLock::new();
let guard = POOL
.get_or_init(|| crate::pool::Pool::from_env().map(std::sync::Mutex::new))
.as_ref()
.map(|p| p.lock().unwrap_or_else(|e| e.into_inner()));
let pool = guard.as_deref().map(|p| p.as_ref());
#[cfg(target_arch = "x86_64")]
if std::arch::is_x86_feature_detected!("avx512f") {
return crate::fcd_ops::gemm_nt_host(x, w, y, n, k, m, pool);
}
crate::zimage::host_gemm::gemm_nt(x, w, y, n, k, m, pool);
}
fn par_chunks(v: &mut [f32], len: usize, f: impl Fn(usize, &mut [f32]) + Sync) {
let nt = std::thread::available_parallelism().map_or(4, |n| n.get());
let n = v.len().div_ceil(len.max(1));
let per = n.div_ceil(nt).max(1) * len;
std::thread::scope(|s| {
for (t, part) in v.chunks_mut(per.max(1)).enumerate() {
let f = &f;
s.spawn(move || {
for (i, c) in part.chunks_mut(len).enumerate() {
f(t * (per / len) + i, c);
}
});
}
});
}
pub struct Conv2d {
pub w: Vec<f32>, pub b: Vec<f32>, pub oc: usize,
pub ic: usize,
pub k: usize,
}
impl Conv2d {
fn from(t: &StTensor, bias: &StTensor) -> Self {
let (oc, ic, k) = (t.shape[0], t.shape[1], t.shape[2]);
Self {
w: t.data.clone(),
b: bias.data.clone(),
oc,
ic,
k,
}
}
pub fn apply(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
debug_assert_eq!(x.len(), self.ic * h * w);
self.apply_at(x, h, w, h, w, false)
}
pub fn apply_down(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
self.apply_at(x, h, w, h / 2, w / 2, true)
}
fn apply_at(&self, x: &[f32], sh: usize, sw: usize, h: usize, w: usize, down: bool) -> Vec<f32> {
if !down && h * w * self.ic * self.oc >= 1 << 26 && crate::gpu::enabled_here() {
let mut out = vec![0f32; self.oc * h * w];
if std::env::var("CMF_VAE_CONV_COOP").as_deref() == Ok("1")
&& crate::gpu::vae_conv2d_coop(
&self.w,
Some(&self.b[..]),
x,
self.ic,
self.oc,
h,
w,
self.k,
&mut out,
)
{
return out;
}
if crate::gpu::vae_conv2d(
&self.w, &self.b, x, self.ic, self.oc, h, w, self.k, &mut out,
) {
return out;
}
}
if !down && self.k == 3 && h >= 16 && w >= 16 && self.ic >= 16 && self.oc >= 16 && std::env::var("CMF_VAE_WINO").as_deref() != Ok("0") {
return self.winograd(x, h, w);
}
let pad = self.k / 2;
let ick2 = self.ic * self.k * self.k;
let mut out = vec![0f32; self.oc * h * w];
let band = (128 << 20) / (ick2 * w * 4).max(1);
let band = band.clamp(1, h);
let mut cols = vec![0f32; band * w * ick2];
let mut yt = vec![0f32; band * w * self.oc];
let mut y0 = 0usize;
while y0 < h {
let rows = band.min(h - y0);
let hw_band = rows * w;
let nt = std::thread::available_parallelism().map_or(4, |n| n.get());
let per = rows.div_ceil(nt).max(1);
let (ic, k) = (self.ic, self.k);
std::thread::scope(|s| {
for (t, part) in cols[..hw_band * ick2].chunks_mut(per * w * ick2).enumerate() {
s.spawn(move || {
for (dy, colrow) in part.chunks_mut(w * ick2).enumerate() {
let y = y0 + t * per + dy;
for (xx, patch) in colrow.chunks_mut(ick2).enumerate() {
let mut i = 0;
for c in 0..ic {
let img = &x[c * sh * sw..(c + 1) * sh * sw];
for ky in 0..k {
let sy = if down { (2 * y + ky) as isize } else { y as isize + ky as isize - pad as isize };
for kx in 0..k {
let sx = if down { (2 * xx + kx) as isize } else { xx as isize + kx as isize - pad as isize };
patch[i] = if sy >= 0 && sy < sh as isize && sx >= 0 && sx < sw as isize {
img[sy as usize * sw + sx as usize]
} else {
0.0
};
i += 1;
}
}
}
}
}
});
}
});
gemm(&cols[..hw_band * ick2], &self.w, &mut yt[..hw_band * self.oc], hw_band, ick2, self.oc);
let (oc, yt, bias) = (self.oc, &yt, &self.b);
par_chunks(&mut out, h * w, |o, plane| {
for (p, d) in plane[y0 * w..][..hw_band].iter_mut().enumerate() {
*d = yt[p * oc + o] + bias[o];
}
});
y0 += rows;
}
out
}
fn winograd(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let (ic, oc) = (self.ic, self.oc);
let (th, tw) = (h.div_ceil(4), w.div_ceil(4));
let tp = std::time::Instant::now();
let mut u = vec![0f32; 36 * oc * ic];
{
let up = SharedPtr(u.as_mut_ptr());
par_for(oc, |o| {
for c in 0..ic {
let k = &self.w[(o * ic + c) * 9..(o * ic + c + 1) * 9];
let mut t = [[0f32; 3]; 6];
for (r, g) in WINO_G.iter().enumerate() {
for j in 0..3 {
t[r][j] = g[0] * k[j] + g[1] * k[3 + j] + g[2] * k[6 + j];
}
}
for a in 0..6 {
for (b, g) in WINO_G.iter().enumerate() {
let v = t[a][0] * g[0] + t[a][1] * g[1] + t[a][2] * g[2];
unsafe { *up.at((a * 6 + b) * oc * ic + o * ic + c) = v };
}
}
}
});
}
let mut out = vec![0f32; oc * h * w];
let band = ((32 << 20) / (36 * ic.max(oc) * 4 * tw)).clamp(1, th);
let mut v = vec![0f32; 36 * band * tw * ic];
let mut m = vec![0f32; 36 * band * tw * oc];
prof_add(0, tp);
let mut t0 = 0;
while t0 < th {
let rows = band.min(th - t0);
let nt = rows * tw;
let tp = std::time::Instant::now();
{
let vp = SharedPtr(v.as_mut_ptr());
par_for(rows, |tr| wide(|| {
let ty = t0 + tr;
let pw = tw * 4 + 2;
let mut pad = vec![0f32; 6 * pw];
let mut e = vec![0f32; 6 * pw];
for c in 0..ic {
let plane = &x[c * h * w..(c + 1) * h * w];
for (i, dst) in pad.chunks_mut(pw).enumerate() {
let sy = (ty * 4 + i) as isize - 1;
dst.fill(0.0);
if sy >= 0 && sy < h as isize {
let row = &plane[sy as usize * w..(sy as usize + 1) * w];
let n = w.min(pw - 1);
dst[1..1 + n].copy_from_slice(&row[..n]);
}
}
wino_in_rows(&pad, &mut e, pw);
for tx in 0..tw {
let t = tr * tw + tx;
let o = tx * 4;
let mut d = [[0f32; 6]; 6];
for (j, dj) in d.iter_mut().enumerate() {
for (i, v) in dj.iter_mut().enumerate() {
*v = e[i * pw + o + j];
}
}
for (j, col) in wino_lanes_in(&d).iter().enumerate() {
for (i, val) in col.iter().enumerate() {
unsafe { *vp.at((i * 6 + j) * nt * ic + t * ic + c) = *val };
}
}
}
}
}));
}
prof_add(1, tp);
let tp = std::time::Instant::now();
for f in 0..36 {
gemm(&v[f * nt * ic..(f + 1) * nt * ic], &u[f * oc * ic..(f + 1) * oc * ic], &mut m[f * nt * oc..(f + 1) * nt * oc], nt, ic, oc);
}
prof_add(2, tp);
let tp = std::time::Instant::now();
{
let op = SharedPtr(out.as_mut_ptr());
let mp = &m;
par_for(rows, |tr| wide(|| {
let ty = t0 + tr;
for tx in 0..tw {
let t = tr * tw + tx;
let (ow, ohh) = (w - tx * 4, h - ty * 4);
for o in 0..oc {
let mut d = [[0f32; 6]; 6];
for (j, dj) in d.iter_mut().enumerate() {
for (i, v) in dj.iter_mut().enumerate() {
*v = mp[(i * 6 + j) * nt * oc + t * oc + o];
}
}
let a = wino_lanes_out(&d);
let bias = self.b[o];
for (j, aj) in a.iter().enumerate().take(ow.min(4)) {
let v = wino_out(*aj);
for (i, val) in v.iter().enumerate().take(ohh.min(4)) {
unsafe { *op.at(o * h * w + (ty * 4 + i) * w + tx * 4 + j) = val + bias };
}
}
}
}
}));
}
prof_add(3, tp);
t0 += rows;
}
out
}
}
const WINO_G: [[f32; 3]; 6] = [
[0.25, 0.0, 0.0],
[-1.0 / 6.0, -1.0 / 6.0, -1.0 / 6.0],
[-1.0 / 6.0, 1.0 / 6.0, -1.0 / 6.0],
[1.0 / 24.0, 1.0 / 12.0, 1.0 / 6.0],
[1.0 / 24.0, -1.0 / 12.0, 1.0 / 6.0],
[0.0, 0.0, 1.0],
];
#[inline(always)]
fn wide<R>(f: impl FnOnce() -> R) -> R {
#[cfg(target_arch = "x86_64")]
{
#[target_feature(enable = "avx2,fma")]
unsafe fn go<R>(f: impl FnOnce() -> R) -> R {
f()
}
if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
return unsafe { go(f) };
}
}
f()
}
#[inline(always)]
fn wino_in_rows(p: &[f32], e: &mut [f32], pw: usize) {
let (r0, rest) = p.split_at(pw);
let (r1, rest) = rest.split_at(pw);
let (r2, rest) = rest.split_at(pw);
let (r3, rest) = rest.split_at(pw);
let (r4, r5) = rest.split_at(pw);
let mut it = e.chunks_exact_mut(pw);
let mut rows: [&mut [f32]; 6] = std::array::from_fn(|_| it.next().unwrap());
let [o0, o1, o2, o3, o4, o5] = &mut rows;
for x in 0..pw {
let (d0, d1, d2, d3, d4, d5) = (r0[x], r1[x], r2[x], r3[x], r4[x], r5[x]);
o0[x] = 4.0 * d0 - 5.0 * d2 + d4;
o1[x] = -4.0 * d1 - 4.0 * d2 + d3 + d4;
o2[x] = 4.0 * d1 - 4.0 * d2 - d3 + d4;
o3[x] = -2.0 * d1 - d2 + 2.0 * d3 + d4;
o4[x] = 2.0 * d1 - d2 - 2.0 * d3 + d4;
o5[x] = 4.0 * d1 - 5.0 * d3 + d5;
}
}
#[inline(always)]
fn wino_lanes_in(d: &[[f32; 6]; 6]) -> [[f32; 6]; 6] {
let mut o = [[0f32; 6]; 6];
for i in 0..6 {
let r = wino_in([d[0][i], d[1][i], d[2][i], d[3][i], d[4][i], d[5][i]]);
for (j, v) in r.into_iter().enumerate() {
o[j][i] = v;
}
}
o
}
#[inline(always)]
fn wino_lanes_out(d: &[[f32; 6]; 6]) -> [[f32; 6]; 4] {
let mut o = [[0f32; 6]; 4];
for i in 0..6 {
let r = wino_out([d[0][i], d[1][i], d[2][i], d[3][i], d[4][i], d[5][i]]);
for (j, v) in r.into_iter().enumerate() {
o[j][i] = v;
}
}
o
}
#[inline(always)]
fn wino_in(d: [f32; 6]) -> [f32; 6] {
[
4.0 * d[0] - 5.0 * d[2] + d[4],
-4.0 * d[1] - 4.0 * d[2] + d[3] + d[4],
4.0 * d[1] - 4.0 * d[2] - d[3] + d[4],
-2.0 * d[1] - d[2] + 2.0 * d[3] + d[4],
2.0 * d[1] - d[2] - 2.0 * d[3] + d[4],
4.0 * d[1] - 5.0 * d[3] + d[5],
]
}
#[inline(always)]
fn wino_out(m: [f32; 6]) -> [f32; 4] {
let (a, b, c, d) = (m[1] + m[2], m[1] - m[2], m[3] + m[4], m[3] - m[4]);
[m[0] + a + c, b + 2.0 * d, a + 4.0 * c, b + 8.0 * d + m[5]]
}
static PROF: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
fn prof_add(i: usize, t: std::time::Instant) {
PROF[i].fetch_add(t.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
}
struct SharedPtr(*mut f32);
unsafe impl Send for SharedPtr {}
unsafe impl Sync for SharedPtr {}
impl SharedPtr {
unsafe fn at(&self, i: usize) -> *mut f32 {
unsafe { self.0.add(i) }
}
}
fn par_for(n: usize, f: impl Fn(usize) + Sync) {
let nt = std::thread::available_parallelism().map_or(4, |t| t.get()).min(n.max(1));
let next = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|s| {
for _ in 0..nt {
s.spawn(|| {
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= n {
break;
}
f(i);
}
});
}
});
}
pub struct GroupNorm {
pub g: usize,
pub w: Vec<f32>,
pub b: Vec<f32>,
}
impl GroupNorm {
fn from(w: &StTensor, b: &StTensor, groups: usize) -> Self {
Self {
g: groups,
w: w.data.clone(),
b: b.data.clone(),
}
}
fn apply_from(&self, x: &[f32], h: usize, w: usize, act: bool) -> Vec<f32> {
let tp = std::time::Instant::now();
let mut y = vec![0f32; x.len()];
let per = self.w.len() / self.g;
let hw = h * w;
par_chunks(&mut y, per * hw, |gi, span| wide(|| {
let src = &x[gi * per * hw..(gi + 1) * per * hw];
let (m, inv) = self.stats(src);
for (ci, (ch, sc)) in span.chunks_mut(hw).zip(src.chunks(hw)).enumerate() {
let cc = gi * per + ci;
let (sw, sb) = (self.w[cc] * inv, self.b[cc]);
for (v, q) in ch.iter_mut().zip(sc) {
*v = (*q - m) * sw + sb;
}
if act {
crate::gigaam::ops::silu(ch);
}
}
}));
prof_add(4, tp);
y
}
#[inline(always)]
fn stats(&self, span: &[f32]) -> (f32, f32) {
let (mut sum, mut sq) = (0f64, 0f64);
for c in span.chunks(1024) {
let (mut s, mut q) = ([0f32; 8], [0f32; 8]);
let it = c.chunks_exact(8);
let tail = it.remainder();
for v in it {
for k in 0..8 {
s[k] += v[k];
q[k] += v[k] * v[k];
}
}
sum += s.iter().map(|v| *v as f64).sum::<f64>();
sq += q.iter().map(|v| *v as f64).sum::<f64>();
for v in tail {
sum += *v as f64;
sq += (*v as f64) * (*v as f64);
}
}
let n = span.len() as f64;
let mean = sum / n;
let var = (sq / n - mean * mean).max(0.0);
(mean as f32, (1.0 / (var + 1e-6).sqrt()) as f32)
}
pub fn apply(&self, x: &mut [f32], h: usize, w: usize) {
let tp = std::time::Instant::now();
let c = self.w.len();
let per = c / self.g;
let hw = h * w;
par_chunks(x, per * hw, |gi, span| wide(|| {
let (m, inv) = self.stats(span);
for (ci, ch) in span.chunks_mut(hw).enumerate() {
let cc = gi * per + ci;
let (sw, sb) = (self.w[cc] * inv, self.b[cc]);
for v in ch.iter_mut() {
*v = (*v - m) * sw + sb;
}
}
}));
prof_add(4, tp);
}
}
fn silu(x: &mut [f32]) {
let tp = std::time::Instant::now();
let nt = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
let chunk = x.len().div_ceil(nt).max(1 << 14);
std::thread::scope(|s| {
for part in x.chunks_mut(chunk) {
s.spawn(move || {
crate::gigaam::ops::silu(part);
});
}
});
prof_add(5, tp);
}
fn upsample2x(x: &[f32], c: usize, h: usize, w: usize) -> Vec<f32> {
let mut out = vec![0f32; c * 4 * h * w];
par_chunks(&mut out, 4 * h * w, |ci, dst| {
let src = &x[ci * h * w..(ci + 1) * h * w];
for (y, row) in dst.chunks_mut(2 * w).enumerate() {
let sr = &src[(y / 2) * w..(y / 2 + 1) * w];
for (xx, d) in row.iter_mut().enumerate() {
*d = sr[xx / 2];
}
}
});
out
}
struct ResnetBlock {
norm1: GroupNorm,
conv1: Conv2d,
norm2: GroupNorm,
conv2: Conv2d,
shortcut: Option<Conv2d>,
}
impl ResnetBlock {
fn apply(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let (ic, oc) = (self.conv1.ic, self.conv1.oc);
if h * w * ic * oc >= 1 << 26 && crate::gpu::enabled_here() {
let mut out = vec![0f32; oc * h * w];
let args = crate::gpu::VaeResnetArgs {
groups: self.norm1.g,
ic,
oc,
h,
w,
n1w: &self.norm1.w,
n1b: &self.norm1.b,
c1w: &self.conv1.w,
c1b: &self.conv1.b,
c1k: self.conv1.k,
n2w: &self.norm2.w,
n2b: &self.norm2.b,
c2w: &self.conv2.w,
c2b: &self.conv2.b,
c2k: self.conv2.k,
shortcut: self
.shortcut
.as_ref()
.map(|s| (s.w.as_slice(), s.b.as_slice(), s.k)),
};
if std::env::var("CMF_VAE_RESNET").as_deref() != Ok("split")
&& crate::gpu::vae_resnet(&args, x, &mut out)
{
return out;
}
}
let t = self.norm1.apply_from(x, h, w, true);
let t = self.conv1.apply(&t, h, w);
let t = self.norm2.apply_from(&t, h, w, true);
let mut y = self.conv2.apply(&t, h, w);
let sc;
let skip: &[f32] = match &self.shortcut {
Some(s) => {
sc = s.apply(x, h, w);
&sc
}
None => x,
};
par_chunks(&mut y, h * w, |c, plane| {
for (a, b) in plane.iter_mut().zip(&skip[c * h * w..]) {
*a += b;
}
});
y
}
}
struct AttnBlock {
norm: GroupNorm,
q: (Vec<f32>, Vec<f32>), k: (Vec<f32>, Vec<f32>),
v: (Vec<f32>, Vec<f32>),
out: (Vec<f32>, Vec<f32>),
c: usize,
}
impl AttnBlock {
fn proj(w: &[f32], b: &[f32], x: &[f32], hw: usize, c: usize) -> Vec<f32> {
let mut y = vec![0f32; hw * c];
gemm(x, w, &mut y, hw, c, c);
for row in y.chunks_mut(c) {
for (v, bb) in row.iter_mut().zip(b) {
*v += bb;
}
}
y
}
fn apply(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let (c, hw) = (self.c, h * w);
let mut n = x.to_vec();
self.norm.apply(&mut n, h, w);
let mut nt = vec![0f32; hw * c];
for ci in 0..c {
for p in 0..hw {
nt[p * c + ci] = n[ci * hw + p];
}
}
let mut q = Self::proj(&self.q.0, &self.q.1, &nt, hw, c);
let k = Self::proj(&self.k.0, &self.k.1, &nt, hw, c);
let v = Self::proj(&self.v.0, &self.v.1, &nt, hw, c);
let scale = 1.0 / (c as f32).sqrt();
if std::env::var("CMF_VAE_ATTN").as_deref() != Ok("cpu")
&& crate::gpu::enabled_here()
&& hw >= 256
{
let mut got = vec![0f32; hw * c];
if crate::gpu::dit_attention(&q, &k, &v, 1, 1, hw, c, scale, &mut got) {
return Self::finish(self, x, &got, h, w);
}
}
for qv in q.iter_mut() {
*qv *= scale;
}
let mut scores = vec![0f32; hw * hw];
gemm(&q, &k, &mut scores, hw, c, hw);
par_chunks(&mut scores, hw, |_, row| wide(|| {
crate::attention::softmax_row(row);
for v in row.iter_mut() {
*v = if *v < 1e-30 { 0.0 } else { *v };
}
}));
let mut vt = vec![0f32; c * hw];
for p in 0..hw {
for ci in 0..c {
vt[ci * hw + p] = v[p * c + ci];
}
}
let mut ot = vec![0f32; hw * c];
gemm(&scores, &vt, &mut ot, hw, hw, c);
Self::finish(self, x, &ot, h, w)
}
fn finish(&self, x: &[f32], ot: &[f32], h: usize, w: usize) -> Vec<f32> {
let (c, hw) = (self.c, h * w);
let o = Self::proj(&self.out.0, &self.out.1, ot, hw, c);
let mut y = x.to_vec();
for p in 0..hw {
for ci in 0..c {
y[ci * hw + p] += o[p * c + ci];
}
}
y
}
}
struct UpBlock {
resnets: Vec<ResnetBlock>,
upsample: Option<Conv2d>,
}
pub struct VaeDecoder {
conv_in: Conv2d,
mid_res1: ResnetBlock,
mid_attn: AttnBlock,
mid_res2: ResnetBlock,
ups: Vec<UpBlock>,
norm_out: GroupNorm,
conv_out: Conv2d,
pub latent_channels: usize,
pub scaling_factor: f32,
pub shift_factor: f32,
pub keep: bool,
uid: u64,
}
#[derive(Clone, Copy)]
pub struct VaeConvRef<'a> {
pub w: &'a [f32],
pub b: &'a [f32],
pub oc: usize,
pub ic: usize,
pub k: usize,
}
#[derive(Clone, Copy)]
pub struct VaeNormRef<'a> {
pub w: &'a [f32],
pub b: &'a [f32],
pub groups: usize,
}
#[derive(Clone, Copy)]
pub struct VaeResnetRef<'a> {
pub norm1: VaeNormRef<'a>,
pub conv1: VaeConvRef<'a>,
pub norm2: VaeNormRef<'a>,
pub conv2: VaeConvRef<'a>,
pub shortcut: Option<VaeConvRef<'a>>,
}
#[derive(Clone, Copy)]
pub struct VaeAttnRef<'a> {
pub norm: VaeNormRef<'a>,
pub q: (&'a [f32], &'a [f32]),
pub k: (&'a [f32], &'a [f32]),
pub v: (&'a [f32], &'a [f32]),
pub out: (&'a [f32], &'a [f32]),
pub c: usize,
}
pub struct VaeUpRef<'a> {
pub resnets: Vec<VaeResnetRef<'a>>,
pub upsample: Option<VaeConvRef<'a>>,
}
pub struct VaeChainArgs<'a> {
pub key: u64,
pub conv_in: VaeConvRef<'a>,
pub downs: Vec<VaeUpRef<'a>>,
pub mid_res1: VaeResnetRef<'a>,
pub mid_attn: VaeAttnRef<'a>,
pub mid_res2: VaeResnetRef<'a>,
pub ups: Vec<VaeUpRef<'a>>,
pub norm_out: VaeNormRef<'a>,
pub conv_out: VaeConvRef<'a>,
pub latent_channels: usize,
pub scaling_factor: f32,
pub shift_factor: f32,
pub keep: bool,
}
impl Conv2d {
fn chain_ref(&self) -> VaeConvRef<'_> {
VaeConvRef {
w: &self.w,
b: &self.b,
oc: self.oc,
ic: self.ic,
k: self.k,
}
}
}
impl GroupNorm {
fn chain_ref(&self) -> VaeNormRef<'_> {
VaeNormRef {
w: &self.w,
b: &self.b,
groups: self.g,
}
}
}
impl ResnetBlock {
fn chain_ref(&self) -> VaeResnetRef<'_> {
VaeResnetRef {
norm1: self.norm1.chain_ref(),
conv1: self.conv1.chain_ref(),
norm2: self.norm2.chain_ref(),
conv2: self.conv2.chain_ref(),
shortcut: self.shortcut.as_ref().map(Conv2d::chain_ref),
}
}
}
impl AttnBlock {
fn chain_ref(&self) -> VaeAttnRef<'_> {
VaeAttnRef {
norm: self.norm.chain_ref(),
q: (&self.q.0, &self.q.1),
k: (&self.k.0, &self.k.1),
v: (&self.v.0, &self.v.1),
out: (&self.out.0, &self.out.1),
c: self.c,
}
}
}
impl UpBlock {
fn chain_ref(&self) -> VaeUpRef<'_> {
VaeUpRef {
resnets: self.resnets.iter().map(ResnetBlock::chain_ref).collect(),
upsample: self.upsample.as_ref().map(Conv2d::chain_ref),
}
}
}
static VAE_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl VaeDecoder {
pub fn chain_args(&self) -> VaeChainArgs<'_> {
VaeChainArgs {
key: self.uid,
conv_in: self.conv_in.chain_ref(),
downs: Vec::new(),
mid_res1: self.mid_res1.chain_ref(),
mid_attn: self.mid_attn.chain_ref(),
mid_res2: self.mid_res2.chain_ref(),
ups: self.ups.iter().map(UpBlock::chain_ref).collect(),
norm_out: self.norm_out.chain_ref(),
conv_out: self.conv_out.chain_ref(),
latent_channels: self.latent_channels,
scaling_factor: self.scaling_factor,
shift_factor: self.shift_factor,
keep: self.keep,
}
}
pub fn decode_fast(&self, z: &[f32], h: usize, w: usize) -> Vec<f32> {
if crate::gpu::enabled_here() {
let zin: Vec<f32> = z
.iter()
.map(|&v| v / self.scaling_factor + self.shift_factor)
.collect();
let mut out = vec![0f32; 3 * 64 * h * w];
if crate::gpu::vae_decode_chain(&self.chain_args(), &zin, h, w, &mut out) {
return out;
}
}
self.decode(z, h, w)
}
}
impl VaeDecoder {
pub fn load_dir(dir: &Path) -> Result<Self, String> {
let cfg: serde_json::Value = serde_json::from_slice(
&std::fs::read(dir.join("config.json")).map_err(|e| format!("config.json: {e}"))?,
)
.map_err(|e| format!("config.json: {e}"))?;
let t = read_safetensors(&dir.join("diffusion_pytorch_model.safetensors"))?;
Self::from_tensors(t, &cfg)
}
pub fn from_cmf(model: &cortiq_core::CmfModel) -> Result<Self, String> {
let (t, cfg) = cmf_vae_tensors(model, "vae.decoder.")?;
Self::from_tensors(t, &cfg)
}
fn from_tensors(
t: std::collections::HashMap<String, StTensor>,
cfg: &serde_json::Value,
) -> Result<Self, String> {
let r = TensorReader { t: &t, groups: cfg["norm_num_groups"].as_u64().unwrap_or(32) as usize };
let mut ups = Vec::new();
for b in 0.. {
if !t.contains_key(&format!("decoder.up_blocks.{b}.resnets.0.conv1.weight")) {
break;
}
ups.push(UpBlock {
resnets: r.resnets(&format!("decoder.up_blocks.{b}"))?,
upsample: r.opt_conv(&format!("decoder.up_blocks.{b}.upsamplers.0.conv"))?,
});
}
Ok(Self {
conv_in: r.conv("decoder.conv_in")?,
mid_res1: r.resnet("decoder.mid_block.resnets.0")?,
mid_attn: r.attn("decoder.mid_block.attentions.0")?,
mid_res2: r.resnet("decoder.mid_block.resnets.1")?,
ups,
norm_out: r.gnorm("decoder.conv_norm_out")?,
conv_out: r.conv("decoder.conv_out")?,
latent_channels: cfg["latent_channels"].as_u64().unwrap_or(16) as usize,
scaling_factor: cfg["scaling_factor"].as_f64().unwrap_or(1.0) as f32,
shift_factor: cfg["shift_factor"].as_f64().unwrap_or(0.0) as f32,
keep: false,
uid: VAE_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
})
}
pub fn decode(&self, z: &[f32], h: usize, w: usize) -> Vec<f32> {
let prof = std::env::var("CMF_VAE_PROF").is_ok();
macro_rules! stage {
($name:expr, $e:expr) => {{
let t = std::time::Instant::now();
let r = $e;
if prof {
eprintln!("vae {}: {:.2}s", $name, t.elapsed().as_secs_f64());
}
r
}};
}
let z: Vec<f32> = z
.iter()
.map(|&v| v / self.scaling_factor + self.shift_factor)
.collect();
let mut x = stage!("conv_in", self.conv_in.apply(&z, h, w));
x = stage!("mid_res1", self.mid_res1.apply(&x, h, w));
x = stage!("mid_attn", self.mid_attn.apply(&x, h, w));
x = stage!("mid_res2", self.mid_res2.apply(&x, h, w));
let (mut h, mut w) = (h, w);
for (ui, up) in self.ups.iter().enumerate() {
for (ri, r) in up.resnets.iter().enumerate() {
x = stage!(format!("up{ui}.res{ri} ({h}x{w})"), r.apply(&x, h, w));
}
if let Some(upc) = &up.upsample {
let c = upc.ic;
let (h2, w2) = (h * 2, w * 2);
x = stage!(format!("up{ui}.conv ({h2}x{w2})"), {
let mut fused = None;
if h2 * w2 * upc.ic * upc.oc >= 1 << 26 && crate::gpu::enabled_here() {
let mut o = vec![0f32; upc.oc * h2 * w2];
if crate::gpu::vae_upsample_conv(
&upc.w, &upc.b, &x, upc.ic, upc.oc, h, w, upc.k, &mut o,
) {
fused = Some(o);
}
}
match fused {
Some(o) => o,
None => {
let xu = upsample2x(&x, c, h, w);
upc.apply(&xu, h2, w2)
}
}
});
h = h2;
w = w2;
}
}
self.norm_out.apply(&mut x, h, w);
silu(&mut x);
let y = stage!("conv_out", self.conv_out.apply(&x, h, w));
prof_report("decoder");
y
}
}
pub struct VaeEncoder {
conv_in: Conv2d,
downs: Vec<UpBlock>,
mid_res1: ResnetBlock,
mid_attn: AttnBlock,
mid_res2: ResnetBlock,
norm_out: GroupNorm,
conv_out: Conv2d,
pub latent_channels: usize,
uid: u64,
}
impl VaeEncoder {
pub fn from_cmf(model: &cortiq_core::CmfModel) -> Result<Self, String> {
let (t, cfg) = cmf_vae_tensors(model, "vae.encoder.")?;
let r = TensorReader { t: &t, groups: cfg["norm_num_groups"].as_u64().unwrap_or(32) as usize };
let mut downs = Vec::new();
for b in 0.. {
if !t.contains_key(&format!("encoder.down_blocks.{b}.resnets.0.conv1.weight")) {
break;
}
downs.push(UpBlock {
resnets: r.resnets(&format!("encoder.down_blocks.{b}"))?,
upsample: r.opt_conv(&format!("encoder.down_blocks.{b}.downsamplers.0.conv"))?,
});
}
Ok(Self {
conv_in: r.conv("encoder.conv_in")?,
downs,
mid_res1: r.resnet("encoder.mid_block.resnets.0")?,
mid_attn: r.attn("encoder.mid_block.attentions.0")?,
mid_res2: r.resnet("encoder.mid_block.resnets.1")?,
norm_out: r.gnorm("encoder.conv_norm_out")?,
conv_out: r.conv("encoder.conv_out")?,
latent_channels: cfg["latent_channels"].as_u64().unwrap_or(16) as usize,
uid: VAE_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
})
}
pub fn chain_args(&self) -> VaeChainArgs<'_> {
VaeChainArgs {
key: self.uid,
conv_in: self.conv_in.chain_ref(),
downs: self.downs.iter().map(UpBlock::chain_ref).collect(),
mid_res1: self.mid_res1.chain_ref(),
mid_attn: self.mid_attn.chain_ref(),
mid_res2: self.mid_res2.chain_ref(),
ups: Vec::new(),
norm_out: self.norm_out.chain_ref(),
conv_out: self.conv_out.chain_ref(),
latent_channels: self.conv_in.ic,
scaling_factor: 1.0,
shift_factor: 0.0,
keep: true,
}
}
pub fn encode_fast(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let n = self.latent_channels * (h / 8) * (w / 8);
let mut out = vec![0f32; self.conv_out.oc * (h / 8) * (w / 8)];
if !(crate::gpu::enabled_here() && crate::gpu::vae_decode_chain(&self.chain_args(), x, h, w, &mut out)) {
out = self.encode(x, h, w);
}
out.truncate(n);
out
}
pub fn encode(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let prof = std::env::var("CMF_VAE_PROF").is_ok();
let mut tl = std::time::Instant::now();
let mut lap = |name: &str| {
if prof {
eprintln!("vae encoder {name}: {:.2}s", tl.elapsed().as_secs_f64());
tl = std::time::Instant::now();
}
};
let (mut h, mut w) = (h, w);
let mut x = self.conv_in.apply(x, h, w);
lap("conv_in");
for d in &self.downs {
for r in &d.resnets {
x = r.apply(&x, h, w);
lap("resnet");
}
if let Some(c) = &d.upsample {
x = c.apply_down(&x, h, w);
h /= 2;
w /= 2;
lap("down");
}
}
x = self.mid_res1.apply(&x, h, w);
x = self.mid_attn.apply(&x, h, w);
lap("mid");
x = self.mid_res2.apply(&x, h, w);
self.norm_out.apply(&mut x, h, w);
silu(&mut x);
let y = self.conv_out.apply(&x, h, w);
prof_report("encoder");
y
}
}
fn prof_report(name: &str) {
if std::env::var("CMF_VAE_PROF").is_ok() {
let names = ["kernels", "input", "products", "output", "norm", "silu"];
let s: Vec<String> = names.iter().zip(&PROF).map(|(n, p)| format!("{n} {:.2}", p.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 * 1e-9)).collect();
eprintln!("vae {name} host, s: {}", s.join(" · "));
}
}
fn cmf_vae_tensors(model: &cortiq_core::CmfModel, prefix: &str) -> Result<(std::collections::HashMap<String, StTensor>, serde_json::Value), String> {
let cfg = serde_json::from_slice(model.tensor_bytes("vae.config_json").map_err(|e| e.to_string())?)
.map_err(|e| format!("vae.config_json: {e}"))?;
let mut t = std::collections::HashMap::new();
for e in model.tensors.iter().filter(|e| e.name.starts_with(prefix) && e.name != "vae.config_json") {
let data = crate::dit::cmf_f32(model, &e.name)?;
t.insert(e.name["vae.".len()..].to_string(), StTensor { shape: e.shape.clone(), data });
}
Ok((t, cfg))
}
struct TensorReader<'a> {
t: &'a std::collections::HashMap<String, StTensor>,
groups: usize,
}
impl TensorReader<'_> {
fn get(&self, n: &str) -> Result<&StTensor, String> {
self.t.get(n).ok_or_else(|| format!("missing tensor {n}"))
}
fn conv(&self, n: &str) -> Result<Conv2d, String> {
Ok(Conv2d::from(self.get(&format!("{n}.weight"))?, self.get(&format!("{n}.bias"))?))
}
fn opt_conv(&self, n: &str) -> Result<Option<Conv2d>, String> {
if self.t.contains_key(&format!("{n}.weight")) { self.conv(n).map(Some) } else { Ok(None) }
}
fn gnorm(&self, n: &str) -> Result<GroupNorm, String> {
Ok(GroupNorm::from(self.get(&format!("{n}.weight"))?, self.get(&format!("{n}.bias"))?, self.groups))
}
fn resnet(&self, n: &str) -> Result<ResnetBlock, String> {
Ok(ResnetBlock {
norm1: self.gnorm(&format!("{n}.norm1"))?,
conv1: self.conv(&format!("{n}.conv1"))?,
norm2: self.gnorm(&format!("{n}.norm2"))?,
conv2: self.conv(&format!("{n}.conv2"))?,
shortcut: self.opt_conv(&format!("{n}.conv_shortcut"))?,
})
}
fn resnets(&self, n: &str) -> Result<Vec<ResnetBlock>, String> {
let mut v = Vec::new();
while self.t.contains_key(&format!("{n}.resnets.{}.conv1.weight", v.len())) {
v.push(self.resnet(&format!("{n}.resnets.{}", v.len()))?);
}
Ok(v)
}
fn attn(&self, n: &str) -> Result<AttnBlock, String> {
let lin = |m: &str| -> Result<(Vec<f32>, Vec<f32>), String> {
Ok((self.get(&format!("{n}.{m}.weight"))?.data.clone(), self.get(&format!("{n}.{m}.bias"))?.data.clone()))
};
Ok(AttnBlock {
norm: self.gnorm(&format!("{n}.group_norm"))?,
q: lin("to_q")?,
k: lin("to_k")?,
v: lin("to_v")?,
out: lin("to_out.0")?,
c: self.get(&format!("{n}.to_q.weight"))?.shape[0],
})
}
}
pub struct Flux2VaeDecoder {
decoder: VaeDecoder,
post_quant_conv: Option<Conv2d>,
bn_mean: Vec<f32>,
bn_var: Vec<f32>,
bn_eps: f32,
packed_channels: usize,
}
impl Flux2VaeDecoder {
pub fn from_cmf(model: &cortiq_core::CmfModel) -> Result<Self, String> {
let cfg: serde_json::Value = serde_json::from_slice(
model
.tensor_bytes("vae.config_json")
.map_err(|e| e.to_string())?,
)
.map_err(|e| format!("vae.config_json: {e}"))?;
let decoder = VaeDecoder::from_cmf(model)?;
let f = |name: &str| crate::dit::cmf_f32(model, name);
let mean = f("vae.bn.running_mean")?;
let var = f("vae.bn.running_var")?;
if mean.is_empty() || mean.len() != var.len() || mean.len() % 4 != 0 {
return Err(format!(
"Flux2 VAE BN must have a nonempty channel count divisible by 4 (mean {}, var {})",
mean.len(),
var.len()
));
}
let post_quant_conv = if model.tensor("vae.post_quant_conv.weight").is_some() {
let w = f("vae.post_quant_conv.weight")?;
let b = f("vae.post_quant_conv.bias")?;
let e = model
.tensor("vae.post_quant_conv.weight")
.ok_or("missing vae.post_quant_conv.weight")?;
if e.shape.len() != 4 || e.shape[2] != e.shape[3] {
return Err("Flux2 post_quant_conv must be square 2-D convolution".into());
}
let (oc, ic, k) = (e.shape[0], e.shape[1], e.shape[2]);
if w.len() != oc * ic * k * k || b.len() != oc {
return Err("Flux2 post_quant_conv shape/bias mismatch".into());
}
Some(Conv2d { w, b, oc, ic, k })
} else {
None
};
Ok(Self {
decoder,
post_quant_conv,
bn_mean: mean,
bn_var: var,
bn_eps: cfg["batch_norm_eps"].as_f64().unwrap_or(1e-4) as f32,
packed_channels: cfg["latent_channels"].as_u64().unwrap_or(32) as usize,
})
}
pub fn prewarm(&self) -> bool {
crate::gpu::vae_prewarm(&self.decoder.chain_args())
}
pub fn decode_fast(&self, packed: &[f32], h: usize, w: usize) -> Result<Vec<f32>, String> {
let channels = self.bn_mean.len();
let hw = h.checked_mul(w).ok_or("Flux2 latent dimensions overflow")?;
if packed.len() != channels * hw || channels != self.packed_channels * 4 {
return Err(format!(
"Flux2 packed latent has {} values; expected {} channels × {}×{}",
packed.len(),
channels,
h,
w
));
}
let mut z = vec![0f32; self.packed_channels * 4 * hw];
for c4 in 0..channels {
let scale = (self.bn_var[c4] + self.bn_eps).sqrt();
let src = &packed[c4 * hw..(c4 + 1) * hw];
let c = c4 / 4;
let rem = c4 % 4;
let dy = rem / 2;
let dx = rem % 2;
for yy in 0..h {
for xx in 0..w {
z[c * (4 * hw) + (2 * yy + dy) * (2 * w) + 2 * xx + dx] =
src[yy * w + xx] * scale + self.bn_mean[c4];
}
}
}
let (h2, w2) = (h * 2, w * 2);
if let Some(conv) = &self.post_quant_conv {
if conv.ic != self.packed_channels {
return Err(format!(
"Flux2 post_quant_conv expects {} channels, unpatch produced {}",
conv.ic, self.packed_channels
));
}
z = conv.apply(&z, h2, w2);
}
Ok(self.decoder.decode_fast(&z, h2, w2))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn conv2d_matches_hand_reference() {
let c = Conv2d {
w: vec![1.0; 9],
b: vec![0.5],
oc: 1,
ic: 1,
k: 3,
};
let x = vec![1., 2., 3., 4., 5., 6., 7., 8., 9.];
let y = c.apply(&x, 3, 3);
assert_eq!(y[4], 45.5);
assert_eq!(y[0], 12.5);
assert_eq!(y[8], 5. + 6. + 8. + 9. + 0.5);
}
#[test]
fn group_norm_standardizes() {
let gn = GroupNorm {
g: 2,
w: vec![2.0, 1.0],
b: vec![0.0, 3.0],
};
let mut x = vec![1., 3., 5., 7., 10., 10., 10., 10.];
gn.apply(&mut x, 2, 2);
let s = 5f64.sqrt();
assert!((x[0] as f64 - (-3.0 / s * 2.0)).abs() < 1e-5);
assert!((x[4] - 3.0).abs() < 1e-4);
}
#[test]
fn conv2d_down_matches_hand_reference() {
let c = Conv2d { w: vec![1.0; 9], b: vec![0.0], oc: 1, ic: 1, k: 3 };
let x: Vec<f32> = (1..=16).map(|v| v as f32).collect();
assert_eq!(c.apply_down(&x, 4, 4), vec![54.0, 3. + 4. + 7. + 8. + 11. + 12., 9. + 10. + 11. + 13. + 14. + 15., 11. + 12. + 15. + 16.]);
}
fn rnd(seed: &mut u64, n: usize, scale: f32) -> Vec<f32> {
(0..n)
.map(|_| {
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(((*seed >> 40) as f32) / (1u64 << 23) as f32 - 1.0) * scale
})
.collect()
}
fn rconv(s: &mut u64, ic: usize, oc: usize, k: usize) -> Conv2d {
Conv2d { w: rnd(s, oc * ic * k * k, 1.7 / ((ic * k * k) as f32).sqrt()), b: rnd(s, oc, 0.2), oc, ic, k }
}
fn rnorm(s: &mut u64, c: usize) -> GroupNorm {
GroupNorm { g: 32, w: rnd(s, c, 0.2).iter().map(|v| 1.0 + v).collect(), b: rnd(s, c, 0.2) }
}
fn rres(s: &mut u64, ic: usize, oc: usize) -> ResnetBlock {
ResnetBlock {
norm1: rnorm(s, ic),
conv1: rconv(s, ic, oc, 3),
norm2: rnorm(s, oc),
conv2: rconv(s, oc, oc, 3),
shortcut: (ic != oc).then(|| rconv(s, ic, oc, 1)),
}
}
fn rattn(s: &mut u64, c: usize) -> AttnBlock {
let mut lin = || (rnd(s, c * c, 1.7 / (c as f32).sqrt()), rnd(s, c, 0.2));
let (q, k, v, out) = (lin(), lin(), lin(), lin());
AttnBlock { norm: rnorm(s, c), q, k, v, out, c }
}
fn near(name: &str, a: &[f32], b: &[f32]) {
let e: f64 = a.iter().zip(b).map(|(x, y)| ((x - y) as f64).powi(2)).sum();
let n: f64 = b.iter().map(|y| (*y as f64).powi(2)).sum();
assert!((e / n).sqrt() < 5e-3, "{name}: the device chain is {:.2e} from the host", (e / n).sqrt());
}
#[test]
fn winograd_matches_im2col() {
let mut s = 21u64;
let c = rconv(&mut s, 20, 24, 3);
let (h, w) = (37, 50);
let x = rnd(&mut s, 20 * h * w, 1.0);
let a = c.winograd(&x, h, w);
let mut plain = vec![0f32; 24 * h * w];
for o in 0..24 {
for y in 0..h as isize {
for xx in 0..w as isize {
let mut v = c.b[o];
for i in 0..20 {
for (k, wt) in c.w[(o * 20 + i) * 9..(o * 20 + i + 1) * 9].iter().enumerate() {
let (sy, sx) = (y + k as isize / 3 - 1, xx + k as isize % 3 - 1);
if sy >= 0 && sx >= 0 && sy < h as isize && sx < w as isize {
v += wt * x[i * h * w + sy as usize * w + sx as usize];
}
}
}
plain[o * h * w + y as usize * w + xx as usize] = v;
}
}
}
let d = a.iter().zip(&plain).map(|(p, q)| (p - q).abs()).fold(0f32, f32::max);
assert!(d < 2e-4, "max |Δ| {d}");
}
#[test]
fn the_device_chain_matches_the_host() {
let mut s = 11u64;
let uid = || VAE_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dec = VaeDecoder {
conv_in: rconv(&mut s, 16, 256, 3),
mid_res1: rres(&mut s, 256, 256),
mid_attn: rattn(&mut s, 256),
mid_res2: rres(&mut s, 256, 256),
ups: vec![
UpBlock { resnets: vec![rres(&mut s, 256, 256)], upsample: Some(rconv(&mut s, 256, 256, 3)) },
UpBlock { resnets: vec![rres(&mut s, 256, 128)], upsample: Some(rconv(&mut s, 128, 128, 3)) },
UpBlock { resnets: vec![rres(&mut s, 128, 128)], upsample: Some(rconv(&mut s, 128, 128, 3)) },
],
norm_out: rnorm(&mut s, 128),
conv_out: rconv(&mut s, 128, 3, 3),
latent_channels: 16,
scaling_factor: 1.0,
shift_factor: 0.0,
keep: true,
uid: uid(),
};
let z = rnd(&mut s, 16 * 16 * 16, 1.0);
let mut out = vec![0f32; 3 * 128 * 128];
if crate::gpu::vae_decode_chain(&dec.chain_args(), &z, 16, 16, &mut out) {
near("decoder", &out, &crate::gpu::cpu_scope(|| dec.decode(&z, 16, 16)));
}
let enc = VaeEncoder {
conv_in: rconv(&mut s, 3, 128, 3),
downs: vec![
UpBlock { resnets: vec![rres(&mut s, 128, 128)], upsample: Some(rconv(&mut s, 128, 128, 3)) },
UpBlock { resnets: vec![rres(&mut s, 128, 256)], upsample: Some(rconv(&mut s, 256, 256, 3)) },
],
mid_res1: rres(&mut s, 256, 256),
mid_attn: rattn(&mut s, 256),
mid_res2: rres(&mut s, 256, 256),
norm_out: rnorm(&mut s, 256),
conv_out: rconv(&mut s, 256, 32, 3),
latent_channels: 16,
uid: uid(),
};
let x = rnd(&mut s, 3 * 64 * 64, 1.0);
let mut out = vec![0f32; 32 * 16 * 16];
if crate::gpu::vae_decode_chain(&enc.chain_args(), &x, 64, 64, &mut out) {
near("encoder", &out, &crate::gpu::cpu_scope(|| enc.encode(&x, 64, 64)));
}
}
#[cfg(feature = "cuda")]
#[test]
fn the_device_chain_takes_192_and_96_channels() {
let mut s = 5u64;
let dec = VaeDecoder {
conv_in: rconv(&mut s, 16, 192, 3),
mid_res1: rres(&mut s, 192, 192),
mid_attn: rattn(&mut s, 192),
mid_res2: rres(&mut s, 192, 192),
ups: vec![UpBlock { resnets: vec![rres(&mut s, 192, 96)], upsample: Some(rconv(&mut s, 96, 96, 3)) }],
norm_out: rnorm(&mut s, 96),
conv_out: rconv(&mut s, 96, 3, 3),
latent_channels: 16,
scaling_factor: 1.0,
shift_factor: 0.0,
keep: false,
uid: VAE_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
};
let z = rnd(&mut s, 16 * 16 * 16, 1.0);
let mut out = vec![0f32; 3 * 32 * 32];
if crate::gpu_cuda::flux_vae_chain(&dec.chain_args(), &z, 16, 16, &mut out) {
near("decoder", &out, &crate::gpu::cpu_scope(|| dec.decode(&z, 16, 16)));
}
}
#[test]
fn upsample_nearest() {
let x = vec![1., 2., 3., 4.];
let y = upsample2x(&x, 1, 2, 2);
assert_eq!(
y,
vec![
1., 1., 2., 2., 1., 1., 2., 2., 3., 3., 4., 4., 3., 3., 4., 4.,
]
);
}
}