okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
3.7 KiB72 linesraw
1"""tools/image/gate/vae_decode_set.py - TEST-ONLY (OWN-5 gate harness): decode the fixed latents of a stage set with
2Strata's own VAE decoder (strata-vae-decode, src/image/vae) and write the pictures as sd-cli would, so compare.py and
3check_limits.py can put them next to sd.cpp's decode of the same latents.
4
5    python -I -B vae_decode_set.py <strata-vae-decode> <vae.safetensors> <pics root> <latent tag> <out tag> [--repeat N] [--stream off]
6
7<pics root>/<latent tag>/dump_<name>/latent.bin (run_set.py --dump) -> <pics root>/<out tag>/<name>.png (RGBA, sd.cpp's
88-bit conversion) and results.jsonl (decode ms, peak MiB, run-to-run identity when --repeat > 1).
9The gate for the VAE stage (limits.py vae_same_tiling, PSNR >= 45 dB and SSIM >= 0.998 on every picture):
10    python -I -B compare.py <pics root> <sd.cpp tag> <out tag>   then   check_limits.py vae_same_tiling <cmp json>
11where <sd.cpp tag> is run_set.py --latent-from <latent tag> --steps 1 (sd.cpp's VAE on the same latents)."""
12from __future__ import annotations
13
14import json
15import re
16import subprocess
17import sys
18import tempfile
19from pathlib import Path
20
21import numpy as np
22from PIL import Image
23
24sys.path.insert(0, str(Path(__file__).resolve().parent))
25import vae_ref as V  # noqa: E402
26
27LINE = re.compile(r"decode (\d+)x(\d+) run (\d+): ([\d.]+) ms, peak (\d+) MiB \(weights\+work (\d+) MiB\)(.*)")
28OPEN = re.compile(r"open ([\d.]+) ms")
29
30
31def main(argv) -> int:
32    if len(argv) < 5:
33        print(__doc__)
34        return 2
35    exe, vae, root, src, dst = argv[0], argv[1], Path(argv[2]), argv[3], argv[4]
36    repeat = int(argv[argv.index("--repeat") + 1]) if "--repeat" in argv else 1
37    stream = argv[argv.index("--stream") + 1] if "--stream" in argv else "on"
38    out = root / dst
39    out.mkdir(parents=True, exist_ok=True)
40    rc_all = 0
41    with open(out / "results.jsonl", "w", encoding="utf-8") as res, tempfile.TemporaryDirectory() as tmp:
42        for d in sorted((root / src).glob("dump_p*_s*")):
43            name = d.name[len("dump_"):]
44            f32 = Path(tmp) / f"{name}.f32"
45            r = subprocess.run([exe, vae, str(d / "latent.bin"), str(f32), "--repeat", str(repeat),
46                                "--stream", stream],
47                               capture_output=True, text=True)
48            runs = [m.groups() for m in map(LINE.match, r.stdout.splitlines()) if m]
49            opened = [float(m.group(1)) for m in map(OPEN.match, r.stdout.splitlines()) if m]
50            rec = {"name": name, "rc": r.returncode, "open_ms": opened[0] if opened else None, "runs": [
51                {"ms": float(g[3]), "peak_mib": int(g[4]), "weights_work_mib": int(g[5]),
52                 "identical_to_run0": None if g[2] == "0" else "identical" in g[6]} for g in runs]}
53            if r.returncode != 0 or not runs:
54                rec["stderr"] = r.stderr[-2000:]
55                rc_all = 1
56                res.write(json.dumps(rec) + "\n")
57                print(f"{name}: FAILED rc {r.returncode} {r.stderr.strip()[-300:]}")
58                continue
59            W, H = int(runs[0][0]), int(runs[0][1])
60            img = np.fromfile(f32, dtype=np.float32).reshape(4, H, W).transpose(1, 2, 0)
61            Image.fromarray(V.to_u8(img), "RGBA").save(out / f"{name}.png")
62            res.write(json.dumps(rec) + "\n")
63            print(f"{name}: open {rec['open_ms']} ms, decode " + ", ".join(f"{x['ms']:.0f} ms" for x in rec["runs"]) +
64                  f", peak {rec['runs'][0]['peak_mib']} MiB" +
65                  ("" if repeat == 1 else f", run to run {'identical' if all(x['identical_to_run0'] for x in rec['runs'][1:]) else 'DIFFERENT'}"))
66            if repeat > 1 and not all(x["identical_to_run0"] for x in rec["runs"][1:]):
67                rc_all = 1
68    return rc_all
69
70
71if __name__ == "__main__":
72    sys.exit(main(sys.argv[1:]))