#!/usr/bin/env python """Latency: FLUX.2 [klein] 4B with the VAE decode vs the DWD head (no VAE), on the same GPU and the same code. Both paths: batch 1, 4 steps, no CFG (klein is distilled), text encode -> 4 transformer steps -> uint8 image on the host. VAE path: prefix + the ORIGINAL last-K blocks (pure bf16, i.e. the stock model) at every step, Euler update, VAE decode, uint8. DWD path: DWDKleinPipeline: prefix + trained tail at every step (proj_out velocity at steps 0-2); at the last step the head reads norm_out's image tokens (no proj_out, no Euler update, no VAE), Oklab -> sRGB, uint8. Both tails recompute their own time embedding + single-block modulation every step, so both paths are a hair slower than the stock pipeline by the same amount. Timing: the two end-to-end paths run INTERLEAVED (order alternates every rep), wall clock with a device sync; the saving is the median of the paired differences with a bootstrap 95% CI. Component rows use CUDA events. Modes: eager (cudnn benchmark off, the PyTorch default), eager_cudnn (cudnn benchmark on: autotuned VAE convs), compile (torch.compile default mode) and reduce-overhead (CUDA graphs); a mode that fails is reported and skipped. Before timing, a PSNR check compares the DWD image with the VAE image for a few prompts (same seed); a broken or mismatched tail lands far below --min-psnr and the script exits with status 1. Usage: python scripts/benchmark_latency.py --out latency.json # the released tail; --tail for a local export """ from __future__ import annotations import argparse import importlib.util import json import math import os import random import statistics import subprocess import sys import time import torch if importlib.util.find_spec("dwd_klein") is None: # running from a source checkout without installing the package sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) from dwd_klein.color import to_uint8 # noqa: E402 from dwd_klein.model import Tail, pure_bf16_copy # noqa: E402 from dwd_klein.pipeline import DEFAULT_REPO # noqa: E402 SIZES = [(1024, 1024), (1344, 768), (512, 512), (1440, 1440)] # (width, height); the first two are training sizes PROMPTS = ["a close-up portrait of an elderly fisherman with a grey beard, soft window light, 85mm photo", "a purple and white ice cream shop with a purple and white striped awning", "a red fox standing in fresh snow at sunrise, professional wildlife photograph", "a hand-painted wooden storefront sign that reads \"FRESH BREAD\" above a small bakery door"] MODES = ("eager", "eager_cudnn", "compile", "reduce-overhead") # -- timing helpers --------------------------------------------------------------------------------------------------- def _sync(): if torch.cuda.is_available(): torch.cuda.synchronize() def _stats(v: list[float]) -> dict: s = sorted(v) q = lambda f: round(s[min(len(s) - 1, int(round(f * (len(s) - 1))))], 3) # noqa: E731 return {"median": round(statistics.median(v), 3), "mean": round(statistics.mean(v), 3), "p10": q(0.1), "p90": q(0.9), "min": round(s[0], 3), "n": len(v)} def _boot_ci(v: list[float], n: int = 2000, seed: int = 0) -> list[float]: rng = random.Random(seed) meds = sorted(statistics.median(rng.choices(v, k=len(v))) for _ in range(n)) return [round(meds[int(0.025 * n)], 3), round(meds[int(0.975 * n)], 3)] def _sync_call(fn) -> float: t = time.perf_counter() fn() _sync() return (time.perf_counter() - t) * 1000 def wall_ms(fn, warmup: int, reps: int) -> dict: for _ in range(warmup): fn() _sync() return _stats([_sync_call(fn) for _ in range(reps)]) def paired_ms(fa, fb, warmup: int, reps: int) -> dict: """a = VAE path, b = DWD path, interleaved (order alternates) so drift hits both equally.""" for _ in range(warmup): fa() fb() _sync() ta, tb = [], [] for i in range(reps): if i % 2 == 0: ta.append(_sync_call(fa)) tb.append(_sync_call(fb)) else: tb.append(_sync_call(fb)) ta.append(_sync_call(fa)) d = [x - y for x, y in zip(ta, tb)] sa, sb = statistics.median(ta), statistics.median(tb) return {"vae": _stats(ta), "head": _stats(tb), "saving_ms": _stats(d), "saving_ms_ci95": _boot_ci(d), "saving_pct": round(100 * statistics.median(d) / sa, 2), "speedup": round(sa / sb, 4)} def event_ms(fn, warmup: int, reps: int) -> dict: """GPU time per call (CUDA events); wall clock on CPU.""" if not torch.cuda.is_available(): return wall_ms(fn, warmup, reps) for _ in range(warmup): fn() torch.cuda.synchronize() out = [] for _ in range(reps): e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) e0.record() fn() e1.record() e1.synchronize() out.append(e0.elapsed_time(e1)) return _stats(out) def peak_extra_gb(fn) -> float | None: """Peak memory above what is already resident (model weights), i.e. activations + workspace.""" if not torch.cuda.is_available(): return None torch.cuda.synchronize() base = torch.cuda.memory_allocated() torch.cuda.reset_peak_memory_stats() fn() torch.cuda.synchronize() return round((torch.cuda.max_memory_allocated() - base) / 1e9, 3) def gpu_state() -> dict: q = "clocks.sm,clocks.mem,clocks.max.sm,power.draw,temperature.gpu,clocks_throttle_reasons.active,utilization.gpu" try: out = subprocess.run(["nvidia-smi", f"--query-gpu={q}", "--format=csv,noheader"], capture_output=True, text=True, timeout=20).stdout.strip() return dict(zip(q.split(","), [x.strip() for x in out.split(",")])) except Exception as e: # noqa: BLE001 return {"error": type(e).__name__} def psnr_u8(a: torch.Tensor, b: torch.Tensor) -> float: mse = ((a.float() - b.float()) ** 2).mean().item() return 99.0 if mse == 0 else round(10 * math.log10(255.0 ** 2 / mse), 3) # -- the two paths ---------------------------------------------------------------------------------------------------- def stock_tail(transformer, k: int) -> Tail: """Pure bf16 copy of the transformer's original last-k single blocks + norm_out + proj_out (the stock model's computation on the prefix states). Call before the pipeline moves those blocks out.""" return pure_bf16_copy(Tail(transformer, k, head=False)) class Bench: """pipe: DWDKleinPipeline; stock: stock_tail(...) of the same base; vae: an object with decode(lat, h, w) -> image [B, 3, H, W] in [-1, 1] (dwd_klein.encoders.VAE).""" def __init__(self, pipe, stock: Tail, vae): self.pipe, self.vae = pipe, vae self.stock = stock.to(pipe.dev) inner = getattr(vae, "vae", None) # the diffusers VAE (compiled per mode) self._orig = (inner.decoder, inner.post_quant_conv) if inner is not None else None self.mode = "eager" self.stock_vel = self._stock_vel def _stock_vel(self, hs, t, rot, n): return self.stock(hs, t, rot, n)[0] def set_mode(self, mode: str): """eager | compile | reduce-overhead. Rebuilds every compiled piece from the eager originals.""" self.mode = mode inner = getattr(self.vae, "vae", None) if self._orig is not None: inner.decoder, inner.post_quant_conv = self._orig if mode == "eager": self.pipe.disable_compile() self.stock_vel = self._stock_vel return cmode = None if mode == "compile" else mode self.pipe.enable_compile(cmode) # resets dynamo, compiles prefix / tail / head kw = {"dynamic": False} if cmode is None else {"dynamic": False, "mode": cmode} self.stock_vel = torch.compile(self._stock_vel, **kw) if self._orig is not None: inner.decoder = torch.compile(self._orig[0], **kw) if self._orig[1] is not None: inner.post_quant_conv = torch.compile(self._orig[1], **kw) def decode_u8(self, lat, h, w): return to_uint8(self.vae.decode(lat, h, w)) @torch.no_grad() def run_vae(self, pe, h, w, seed) -> torch.Tensor: p = self.pipe if self.mode == "reduce-overhead": torch.compiler.cudagraph_mark_step_begin() ts, dts, iid, tid = p.schedule(h, w, pe.shape[1]) lat = p.noise(h, w, seed) for i in range(len(ts)): hs, rot, n = p.prefix(lat, pe, ts[i], iid, tid) v = self.stock_vel(hs, ts[i], rot, n) lat = (lat.float() + v.float() * dts[i]).to(torch.bfloat16) return self.decode_u8(lat, h, w).clone() @torch.no_grad() def run_head(self, pe, h, w, seed) -> torch.Tensor: return self.pipe.generate_uint8(pe, h, w, seed) def bench(b: Bench, warmup: int, reps: int, sizes=SIZES, tag: str = "eager", components: bool = True, log=print) -> dict: p = b.pipe out, seed, prompt = {}, 1234, PROMPTS[0] for (W, H) in sizes: h, w = H // 16, W // 16 r = {"gpu_before": gpu_state()} pe = p.encode_prompt([prompt]) r["e2e"] = paired_ms(lambda: b.run_vae(p.encode_prompt([prompt]), h, w, seed).cpu(), lambda: b.run_head(p.encode_prompt([prompt]), h, w, seed).cpu(), warmup, reps) r["no_text"] = paired_ms(lambda: b.run_vae(pe, h, w, seed), lambda: b.run_head(pe, h, w, seed), warmup, reps) r["text_encode_ms"] = wall_ms(lambda: p.encode_prompt([prompt]), warmup, reps) if components: ts, dts, iid, tid = p.schedule(h, w, pe.shape[1]) with torch.no_grad(): lat = p.noise(h, w, seed) hs, rot, n = p.prefix(lat, pe, ts[-1], iid, tid) hs = hs.clone() y = p.head_tokens(hs, ts[-1], rot, n).clone() c = {"vae_decode_to_u8": event_ms(lambda: b.decode_u8(lat, h, w), warmup, reps), "head_color_to_u8": event_ms(lambda: p.head_image(y, h, w), warmup, reps), "prefix_step": event_ms(lambda: p.prefix(lat, pe, ts[-1], iid, tid), warmup, reps), "stock_tail_step": event_ms(lambda: b.stock_vel(hs, ts[-1], rot, n), warmup, reps), "dwd_tail_step": event_ms(lambda: p.velocity(hs, ts[-1], rot, n), warmup, reps), "dwd_last_step_tail_plus_head": event_ms(lambda: p.head_tokens(hs, ts[-1], rot, n), warmup, reps)} r["components_ms"] = c with torch.no_grad(): r["peak_extra_gb"] = {"vae": peak_extra_gb(lambda: b.run_vae(pe, h, w, seed)), "head": peak_extra_gb(lambda: b.run_head(pe, h, w, seed))} r["gpu_after"] = gpu_state() e, nt = r["e2e"], r["no_text"] log(f"{tag} {W}x{H}: e2e {e['vae']['median']} -> {e['head']['median']} ms (saving {e['saving_ms']['median']} " f"ms, CI {e['saving_ms_ci95']}, {e['saving_pct']}%) | without text encode {nt['vae']['median']} -> " f"{nt['head']['median']} ms ({nt['saving_pct']}%)") out[f"{W}x{H}"] = r return out @torch.no_grad() def psnr_check(b: Bench, prompts=PROMPTS, width: int = 1024, height: int = 1024, log=print) -> tuple[dict, dict]: """PSNR (uint8) of the DWD image vs the VAE image of the same prompt and seed -> (results, first image pair).""" h, w = height // 16, width // 16 vals, imgs = [], {} for i, prompt in enumerate(prompts): pe = b.pipe.encode_prompt([prompt]) hv, hd = b.run_vae(pe, h, w, 1000 + i), b.run_head(pe, h, w, 1000 + i) vals.append(psnr_u8(hd, hv)) if i == 0: imgs = {"vae": hv[0].cpu().numpy(), "dwd": hd[0].cpu().numpy()} res = {"size": f"{width}x{height}", "psnr_dwd_vs_vae": vals, "mean": round(statistics.mean(vals), 3)} log(f"PSNR DWD vs VAE at {width}x{height}: mean {res['mean']} dB {vals}") return res, imgs def build(tail: str, base: str, device, full_text_encoder: bool = True) -> Bench: from diffusers import FlowMatchEulerDiscreteScheduler, Flux2Transformer2DModel from dwd_klein.encoders import VAE, TextEncoder, resolve from dwd_klein.pipeline import DWDKleinPipeline, load_tail_weights sd, meta = load_tail_weights(tail) path = resolve(base) transformer = Flux2Transformer2DModel.from_pretrained(path, subfolder="transformer", torch_dtype=torch.bfloat16) stock = stock_tail(transformer, meta["k"]) text = TextEncoder(path, device=device, truncate=not full_text_encoder) sched = FlowMatchEulerDiscreteScheduler.from_pretrained(path, subfolder="scheduler") pipe = DWDKleinPipeline.from_components(transformer, (sd, meta), text, sched, device=device) return Bench(pipe, stock, VAE(path, device=device)) def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--tail", default=DEFAULT_REPO, help=f"exported tail (.safetensors), a directory holding it, or a repo id (default {DEFAULT_REPO})") ap.add_argument("--base", default="black-forest-labs/FLUX.2-klein-4B") ap.add_argument("--device", default="cuda") ap.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES), help="WxH list, comma separated") ap.add_argument("--modes", default=",".join(MODES), help=f"subset of {','.join(MODES)}") ap.add_argument("--warmup", type=int, default=5) ap.add_argument("--reps", type=int, default=50) ap.add_argument("--min-psnr", type=float, default=20.0, help="fail if the mean DWD vs VAE PSNR is below this") ap.add_argument("--truncated-text-encoder", action="store_true", help="time the truncated Qwen3 text encoder (same embeddings) instead of the full one the stock " "pipeline runs") ap.add_argument("--out", default="latency.json") ap.add_argument("--save-images", default="", help="directory for one VAE / DWD image pair from the PSNR check") a = ap.parse_args(argv) sizes = [tuple(int(x) for x in s.lower().split("x")) for s in a.sizes.split(",") if s.strip()] modes = [m.strip() for m in a.modes.split(",") if m.strip()] for m in modes: if m not in MODES: ap.error(f"unknown mode {m}") log = lambda m: print(m, flush=True) # noqa: E731 t0 = time.perf_counter() torch.backends.cudnn.benchmark = False b = build(a.tail, a.base, torch.device(a.device), not a.truncated_text_encoder) res = {"device": torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu", "torch": torch.__version__, "warmup": a.warmup, "reps": a.reps, "sizes": [f"{w}x{h}" for w, h in sizes], "gpu_start": gpu_state(), "load_s": round(time.perf_counter() - t0, 1), "modes": {}, "errors": {}} res["psnr"], imgs = psnr_check(b, log=log) if a.save_images: from PIL import Image os.makedirs(a.save_images, exist_ok=True) for k, arr in imgs.items(): Image.fromarray(arr).save(os.path.join(a.save_images, f"{k}.png")) ok = res["psnr"]["mean"] >= a.min_psnr if not ok: log(f"PSNR check FAILED: {res['psnr']['mean']} < {a.min_psnr} dB (wrong base model or a broken tail?)") with open(a.out, "w") as fh: json.dump(res, fh, indent=1) log(f"wrote {a.out}") return 1 for mode in modes: tm = time.perf_counter() try: torch.backends.cudnn.benchmark = mode != "eager" b.set_mode("eager" if mode.startswith("eager") else mode) res["modes"][mode] = bench(b, a.warmup, a.reps, sizes, tag=mode, components=mode != "reduce-overhead", log=log) except Exception as e: # noqa: BLE001 import traceback res["errors"][mode] = f"{type(e).__name__}: {str(e)[:400]}" log(f"mode {mode} failed: {res['errors'][mode]}\n{traceback.format_exc()[-1500:]}") res.setdefault("mode_wall_s", {})[mode] = round(time.perf_counter() - tm, 1) b.set_mode("eager") res["wall_s"] = round(time.perf_counter() - t0, 1) with open(a.out, "w") as fh: json.dump(res, fh, indent=1) log(f"wrote {a.out}") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())