P-Q-Image-2.1-DWD / scripts /benchmark_latency.py
johnrachwanpruna's picture
Release P-Q-Image-2.1-Turbo-DWD
baa0a0e verified
Raw History Blame Contribute Delete
10.7 kB
#!/usr/bin/env python
"""Latency and peak memory: Qwen-Image-2.1-Turbo with the VAE decode vs the DWD head, same GPU, same code.
Both paths: batch 1, text-to-image, 8 steps, no CFG, prompt encode -> 7 stock transformer steps (prefix KV cache, as
the stock pipeline) -> last step -> uint8 image on the host.
VAE path: last step through the stock transformer, Euler update to t = 0, VAE decode (this is the stock
QwenImage21Pipeline computation; --stock-pipeline also times the diffusers pipeline object itself)
DWD path: last step through the stock prefix (blocks 1-28, no KV cache), the DWD tail and head, Oklab -> sRGB
(no proj_out, no Euler update, no VAE decode)
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. Peak memory is
the peak allocated during one end-to-end run minus what was allocated before it (activations, not weights); resident
weights are listed separately. Modes: eager, and compile (torch.compile of every transformer block, stock and tail;
the VAE stays eager unless --compile-vae).
Before timing, a PSNR check compares the DWD image with the VAE image (same seed); a broken or mismatched tail lands
far below --min-psnr and the script exits with status 1.
python scripts/benchmark_latency.py --sizes 1024x1024,2048x2048 --modes eager,compile --out benchmark.json
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
import os
import random
import statistics
import sys
import time
import torch
if importlib.util.find_spec("pq_image_dwd") 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 pq_image_dwd.pipeline import DEFAULT_TAIL, DWDPipeline # noqa: E402
PROMPTS = ["a red fox standing in fresh snow at sunrise, professional wildlife photograph",
"a close-up portrait of an elderly fisherman with a grey beard, soft window light, 85mm photo",
"a hand-painted wooden storefront sign that reads \"FRESH BREAD\" above a small bakery door"]
def _sync():
if torch.cuda.is_available():
torch.cuda.synchronize()
def _med(v: list[float]) -> float:
return round(statistics.median(v), 2)
def _boot_ci(d: list[float], n: int = 2000, seed: int = 0) -> list[float]:
rng = random.Random(seed)
meds = sorted(statistics.median(rng.choices(d, k=len(d))) for _ in range(n))
return [round(meds[int(0.025 * n)], 2), round(meds[int(0.975 * n) - 1], 2)]
def _psnr(a: torch.Tensor, b: torch.Tensor) -> float:
mse = ((a.float() - b.float()) ** 2).mean().item()
return 99.0 if mse == 0 else 10 * math.log10(255.0 ** 2 / mse)
def _gb(m) -> float:
return round(sum(p.numel() * p.element_size() for p in m.parameters()) / 1e9, 3)
class _Ev:
"""CUDA-event timer for one region (ms)."""
def __init__(self):
self.s = torch.cuda.Event(enable_timing=True)
self.e = torch.cuda.Event(enable_timing=True)
def __enter__(self):
self.s.record()
return self
def __exit__(self, *a):
self.e.record()
def ms(self) -> float:
return self.s.elapsed_time(self.e)
def e2e(pipe: DWDPipeline, prompt: str, h: int, w: int, seed: int, path: str):
"""One end-to-end run until the uint8 image is on the host."""
cond = pipe.encode(prompt)
lat, cache = pipe.denoise(cond, h, w, seed)
img = pipe.last_step_dwd(lat, cond, h, w) if path == "dwd" else pipe.last_step_vae(lat, cond, h, w, cache)
return img.cpu()
def components(pipe: DWDPipeline, prompt: str, h: int, w: int, seed: int) -> dict:
"""CUDA-event timings (ms) of the parts of one run."""
ev = {k: _Ev() for k in ("encode", "steps_1_7", "last_dwd", "last_vae", "vae_decode")}
with ev["encode"]:
cond = pipe.encode(prompt)
with ev["steps_1_7"]:
lat, cache = pipe.denoise(cond, h, w, seed)
with ev["last_dwd"]:
pipe.last_step_dwd(lat, cond, h, w)
with ev["last_vae"]:
pipe.last_step_vae(lat, cond, h, w, cache)
lat0 = lat.clone()
vae = pipe._get_vae(decoder=True)
with ev["vae_decode"]:
vae.decode(lat0, h, w)
_sync()
return {k: e.ms() for k, e in ev.items()}
def peak_activation_gb(fn) -> float:
_sync()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
fn()
_sync()
return round((torch.cuda.max_memory_allocated() - base) / 1e9, 3)
def bench_size(pipe: DWDPipeline, w: int, h: int, reps: int, warmup: int, stock_pipe=None) -> dict:
th, tw = h // 16, w // 16
prompt = PROMPTS[0]
for i in range(warmup):
for path in ("dwd", "vae"):
e2e(pipe, prompt, th, tw, i, path)
t = {"dwd": [], "vae": []}
for r in range(reps):
order = ("dwd", "vae") if r % 2 == 0 else ("vae", "dwd")
for path in order:
_sync()
a = time.perf_counter()
e2e(pipe, prompt, th, tw, 100 + r, path)
_sync()
t[path].append((time.perf_counter() - a) * 1000)
diff = [v - d for v, d in zip(t["vae"], t["dwd"])]
comp = [components(pipe, prompt, th, tw, 200 + r) for r in range(max(3, reps // 2))]
out = {"width": w, "height": h, "reps": reps,
"e2e_ms": {"vae": _med(t["vae"]), "dwd": _med(t["dwd"])},
"saved_ms": _med(diff), "saved_ms_ci95": _boot_ci(diff),
"speedup": round(statistics.median(t["vae"]) / statistics.median(t["dwd"]), 3),
"components_ms": {k: _med([c[k] for c in comp]) for k in comp[0]},
"peak_activation_gb": {
"vae": peak_activation_gb(lambda: e2e(pipe, prompt, th, tw, 7, "vae")),
"dwd": peak_activation_gb(lambda: e2e(pipe, prompt, th, tw, 7, "dwd"))}}
c = out["components_ms"]
out["last_step_saved_ms"] = round(c["last_vae"] - c["last_dwd"], 2)
out["peak_activation_saved_gb"] = round(out["peak_activation_gb"]["vae"] - out["peak_activation_gb"]["dwd"], 3)
if stock_pipe is not None:
st = []
for r in range(warmup + reps):
g = torch.Generator(pipe.dev).manual_seed(300 + r)
_sync()
a = time.perf_counter()
stock_pipe(prompt=prompt, width=w, height=h, generator=g, output_type="pil")
_sync()
if r >= warmup:
st.append((time.perf_counter() - a) * 1000)
out["e2e_ms"]["stock_pipeline"] = _med(st)
return out
def quality_check(pipe: DWDPipeline, w: int, h: int, n: int = 2) -> list[float]:
out = []
for i in range(n):
cond = pipe.encode(PROMPTS[i % len(PROMPTS)])
o = pipe.generate(cond, h // 16, w // 16, seed=i, dwd=True, vae=True)
out.append(round(_psnr(o["dwd"], o["vae"]), 2))
return out
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--tail", default=DEFAULT_TAIL)
ap.add_argument("--base", default="Qwen/Qwen-Image-2.1-Turbo")
ap.add_argument("--sizes", default="1024x1024,2048x2048")
ap.add_argument("--modes", default="eager,compile")
ap.add_argument("--reps", type=int, default=10)
ap.add_argument("--warmup", type=int, default=2)
ap.add_argument("--min-psnr", type=float, default=30.0)
ap.add_argument("--compile-vae", action="store_true", help="in compile mode, also torch.compile the VAE decoder")
ap.add_argument("--stock-pipeline", action="store_true",
help="also time the diffusers QwenImage21Pipeline object (eager only)")
ap.add_argument("--out", default="benchmark.json")
a = ap.parse_args(argv)
if not torch.cuda.is_available():
ap.error("a CUDA GPU is needed")
sizes = [tuple(int(v) for v in s.split("x")) for s in a.sizes.split(",")]
pipe = DWDPipeline.from_pretrained(a.tail, base=a.base, device="cuda", load_vae=True)
res = {"gpu": torch.cuda.get_device_name(), "torch": torch.__version__, "batch": 1, "steps": 8,
"dtype": "bfloat16", "task": "text-to-image",
"weights_gb": {"transformer": _gb(pipe.transformer), "text_encoder": _gb(pipe.text_encoder.te),
"vae_decoder": round(_gb(pipe.vae.vae.decoder) + _gb(pipe.vae.vae.post_quant_conv), 3),
"vae_encoder": round(_gb(pipe.vae.vae.encoder) + _gb(pipe.vae.vae.quant_conv), 3),
"dwd_tail": _gb(pipe.tail)}}
import diffusers
import transformers
res["diffusers"], res["transformers"] = diffusers.__version__, transformers.__version__
w0, h0 = sizes[0]
res["psnr_dwd_vs_vae"] = quality_check(pipe, w0, h0)
print("PSNR DWD vs VAE", res["psnr_dwd_vs_vae"], flush=True)
if min(res["psnr_dwd_vs_vae"]) < a.min_psnr:
print(f"DWD image is far from the VAE image (< {a.min_psnr} dB): wrong or broken tail", flush=True)
with open(a.out, "w") as fh:
json.dump(res, fh, indent=1)
return 1
stock_pipe = None
if a.stock_pipeline:
from diffusers import QwenImage21Pipeline
stock_pipe = QwenImage21Pipeline(scheduler=pipe.scheduler, vae=pipe.vae.vae, text_encoder=pipe.text_encoder.te,
processor=pipe.text_encoder.pipe.processor, transformer=pipe.transformer,
sample_sigmas=pipe.sigmas)
stock_pipe.set_progress_bar_config(disable=True)
res["modes"] = {}
for mode in a.modes.split(","):
rows = {}
try:
if mode == "compile":
pipe.enable_compile()
if a.compile_vae:
pipe.vae.vae.decoder = torch.compile(pipe.vae.vae.decoder, dynamic=False)
elif mode != "eager":
raise ValueError(f"unknown mode {mode}")
for w, h in sizes:
warm = a.warmup + (2 if mode == "compile" else 0)
rows[f"{w}x{h}"] = bench_size(pipe, w, h, a.reps, warm,
stock_pipe if mode == "eager" else None)
print(mode, w, h, json.dumps(rows[f"{w}x{h}"]), flush=True)
except Exception as e: # report and go on with the next mode
rows["error"] = f"{type(e).__name__}: {e}"[:500]
print(mode, "FAILED", rows["error"], flush=True)
res["modes"][mode] = rows
with open(a.out, "w") as fh:
json.dump(res, fh, indent=1)
print(json.dumps(res, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())