"""CPU float32 reference for the VAE decoder with REAL latents: encode real images with the VAE encoder, decode in fp32. Also checks the host glue (bn de-normalisation + unpatchify in numpy) against the pipeline's torch formula. Usage: python ref_vae.py IMAGE.webp [--sizes 512,1024] -> /opt/mossimage/work/vae_ref_.npz """ import argparse import sys import numpy as np import torch from PIL import Image sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__))) from common import VAE_DIR, WORK, Timer, cmp, psnr # noqa: E402 def bn_unpatchify_np(latents, mean, var, eps): """latents [b,128,h,w] (DiT/sampler space) -> z [b,32,2h,2w] for vae.decode, exactly as in the pipeline.""" z = latents * np.sqrt(var + eps).reshape(1, -1, 1, 1) + mean.reshape(1, -1, 1, 1) b, c, h, w = z.shape return z.reshape(b, c // 4, 2, 2, h, w).transpose(0, 1, 4, 2, 5, 3).reshape(b, c // 4, 2 * h, 2 * w).astype(np.float32) def main(): ap = argparse.ArgumentParser() ap.add_argument("image") ap.add_argument("--sizes", default="512,1024") args = ap.parse_args() from diffusers import AutoencoderKLFlux2 torch.set_num_threads(8) vae = AutoencoderKLFlux2.from_pretrained(VAE_DIR, torch_dtype=torch.float32).eval() img = Image.open(args.image).convert("RGB") print("source image", img.size) bn = vae.bn # host glue check with random latents lat = torch.randn(1, 128, 8, 8) zt = lat * (bn.running_var + vae.config.batch_norm_eps).sqrt().view(1, -1, 1, 1) + bn.running_mean.view(1, -1, 1, 1) b, c, h, w = zt.shape zt = zt.reshape(b, c // 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3).reshape(b, c // 4, 2 * h, 2 * w) zn = bn_unpatchify_np(lat.numpy(), bn.running_mean.numpy(), bn.running_var.numpy(), vae.config.batch_norm_eps) print("host bn+unpatchify vs torch: max abs diff", float(np.abs(zt.numpy() - zn).max()), flush=True) out = {} for s in [int(x) for x in args.sizes.split(",")]: W, H = img.size if min(W, H) < s: im = img.resize((s, s), Image.LANCZOS) else: left, top = (W - s) // 2, (H - s) // 2 im = img.crop((left, top, left + s, top + s)) x = torch.from_numpy(np.asarray(im).astype(np.float32) / 127.5 - 1.0).permute(2, 0, 1)[None] with torch.no_grad(): with Timer(f"encode {s}"): z = vae.encode(x).latent_dist.mode() with Timer(f"decode fp32 {s}"): dec = vae.decode(z, return_dict=False)[0].clamp(-1, 1) u8 = ((dec[0].permute(1, 2, 0).numpy() + 1) * 127.5).round().clip(0, 255).astype(np.uint8) print(f"size {s}: z {tuple(z.shape)} absmax {float(z.abs().max()):.2f}; fp32 round-trip PSNR vs source: {psnr(np.asarray(im), u8):.2f} dB", flush=True) np.savez(f"{WORK}/vae_ref_{s}.npz", z=z.numpy(), dec=dec.numpy(), src=np.asarray(im)) Image.fromarray(u8).save(f"{WORK}/vae_ref_{s}_decoded.png") Image.fromarray(np.asarray(im)).save(f"{WORK}/vae_ref_{s}_source.png") if __name__ == "__main__": main()