Download scripts/verify.py from WeReCooking/DFlow2-4step-ONNX-WebGPU: direct link, hf CLI and curl.
- Browser
- Download file 5.13 kB
-
https://huggingface.co/WeReCooking/DFlow2-4step-ONNX-WebGPU/resolve/main/scripts/verify.py
- Command line
-
hf download hf://WeReCooking/DFlow2-4step-ONNX-WebGPU/scripts/verify.py
-
curl -L -o verify.py https://huggingface.co/WeReCooking/DFlow2-4step-ONNX-WebGPU/resolve/main/scripts/verify.py
5.13 kB
| """Run the ONNX chain on ORT CPU against the fp32 PyTorch reference. | |
| usage: verify.py ONNX_DIR REF_NPZ [--full] | |
| Reports cosine per stage; with --full it also runs all 4 steps and the decoder. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| from safetensors import safe_open | |
| import ropes | |
| SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad") | |
| root = Path(sys.argv[1]) | |
| ref = np.load(sys.argv[2]) | |
| full = "--full" in sys.argv | |
| tag = root.name | |
| def cos(a, b): | |
| a, b = a.astype(np.float64).ravel(), b.astype(np.float64).ravel() | |
| return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30)) | |
| def rel(a, b): | |
| return float(np.linalg.norm(a - b) / (np.linalg.norm(b) + 1e-30)) | |
| def sess(name, threads=4): | |
| so = ort.SessionOptions() | |
| so.intra_op_num_threads = threads | |
| p = next((root / name).glob("*.onnx")) | |
| t0 = time.time() | |
| s = ort.InferenceSession(str(p), so, providers=["CPUExecutionProvider"]) | |
| print(f" load {name}: {time.time()-t0:.1f}s", flush=True) | |
| return s | |
| def embeddings(ids): | |
| emb_file = SP / "emb" / "embed_int8.npy" | |
| if (root / "EMB_INT8").exists() and emb_file.exists(): | |
| q = np.load(emb_file, mmap_mode="r") | |
| sc = np.load(SP / "emb" / "embed_scale.npy") | |
| e = q[ids].astype(np.float32) * sc[ids][:, None] | |
| else: | |
| with safe_open(str(SP / "w/te.safetensors"), "pt") as f: | |
| w = f.get_tensor("embed_tokens.weight").float().numpy() | |
| e = w[ids] | |
| return (e * np.float32(math.sqrt(640.0))).astype(np.float32)[None] | |
| ids = ref["ids"].astype(np.int64) | |
| L = len(ids) | |
| feeds = {"emb": embeddings(ids), **ropes.gemma_tables(L)} | |
| rs, rc = ropes.dflow_rows(ropes.text_positions(L + 3)) | |
| feeds["r_sin"], feeds["r_cos"] = rs[None], rc[None] | |
| t0 = time.time() | |
| text = sess("text").run(None, feeds)[0] | |
| print(f"text cos={cos(text, ref['refined']):.6f} rel={rel(text, ref['refined']):.2e} {time.time()-t0:.1f}s") | |
| lat0 = ref["noise"] | |
| _, C, gh, gw = lat0.shape | |
| n = gh * gw | |
| lt = text.shape[1] | |
| js, jc = ropes.dflow_rows(ropes.joint_positions(lt, gh, gw)) | |
| rope = {"rope_sin": js[None], "rope_cos": jc[None], | |
| "qscale": np.array(math.exp(float(ref["gain"])), dtype=np.float32)} | |
| A, B, Cc, D = (sess(k) for k in ("dit_a", "dit_b", "dit_c", "dit_d")) | |
| def velocity(x, t): | |
| lat = x.reshape(1, C, n).transpose(0, 2, 1).copy() | |
| p, tact = A.run(None, {"lat": lat, "t": np.array([t], np.float32), "text": text, **rope}) | |
| m = B.run(None, {"x": p, "tact": tact, **rope})[0] | |
| m = Cc.run(None, {"x": m, "tact": tact, **rope})[0] | |
| v = D.run(None, {"prefix": p, "middle": m, "tact": tact, **rope})[0] | |
| return v[:, :n].transpose(0, 2, 1).reshape(1, C, gh, gw) | |
| times = ref["times"] | |
| t0 = time.time() | |
| v0 = velocity(lat0, float(times[0])) | |
| print(f"vel[0] cos={cos(v0, ref['vels'][0]):.6f} rel={rel(v0, ref['vels'][0]):.2e} {time.time()-t0:.1f}s/step") | |
| xs = [lat0] | |
| for i in range(len(times) - 2 if "--no-tf" not in sys.argv else 0): | |
| xs.append(xs[-1] + np.float32(times[i + 1] - times[i]) * ref["vels"][i]) | |
| tf = [cos(v0, ref["vels"][0])] + [cos(velocity(xs[i], float(times[i])), ref["vels"][i]) | |
| for i in range(1, len(xs))] | |
| print("teacher-forced vel cos:", " ".join(f"{c:.5f}" for c in tf), f"min={min(tf):.5f}") | |
| if not full: | |
| sys.exit() | |
| x = lat0.copy() | |
| for i in range(len(times) - 1): | |
| v = v0 if i == 0 else velocity(x, float(times[i])) | |
| if i: | |
| print(f"vel[{i}] cos={cos(v, ref['vels'][i]):.6f}") | |
| x = x + np.float32(times[i + 1] - times[i]) * v | |
| print(f"latent cos={cos(x, ref['latent']):.6f} rel={rel(x, ref['latent']):.2e}") | |
| name0 = next((a.split("=", 1)[1] for a in sys.argv if a.startswith("--name=")), f"onnx_{tag}") | |
| np.save(SP / "work" / f"{name0}_latent.npy", x) | |
| if "--no-decode" in sys.argv: | |
| sys.exit() | |
| vs, vc = ropes.vae_tables(gh, gw) | |
| t0 = time.time() | |
| rgb = sess("vae_dec").run(None, {"z": x.astype(np.float32), "v_sin": vs, "v_cos": vc})[0] | |
| want = (ref["rgb"] + 1) * 0.5 | |
| print(f"rgb cos={cos(rgb, want):.6f} maxabs={np.abs(rgb-want).max():.3f} " | |
| f"psnr={10*math.log10(1/np.mean((rgb-want)**2)):.1f}dB {time.time()-t0:.1f}s") | |
| img = (rgb[0].transpose(1, 2, 0) * 255).round().clip(0, 255).astype(np.uint8) | |
| name = next((a.split("=", 1)[1] for a in sys.argv if a.startswith("--name=")), f"onnx_{tag}") | |
| out = SP / "work" / f"{name}.png" | |
| Image.fromarray(img).save(out) | |
| print("saved", out) | |
| if "--dump" in sys.argv: | |
| d = SP / "web" / "test_data" | |
| d.mkdir(exist_ok=True) | |
| for k, v in {"noise": lat0, "ref_text": ref["refined"], "ort_text": text, "ort_v0": v0, | |
| "ref_v0": ref["vels"][0], "ort_latent": x, "ref_latent": ref["latent"], | |
| "ort_rgb": rgb, "ref_rgb": (ref["rgb"] + 1) * 0.5}.items(): | |
| np.ascontiguousarray(v, dtype=np.float32).tofile(d / f"{k}.f32") | |
| import json | |
| json.dump({"ids": ids.tolist(), "times": [float(t) for t in times], "gh": gh, "gw": gw, | |
| "gain": float(ref["gain"])}, open(d / "meta.json", "w")) | |
| print("dumped", d) | |