okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
4.8 KiB100 linesraw
1"""tools/image/gate/run_strata_image.py - TEST-ONLY (OWN-5 gate harness, step 5): run the test program strata-image
2(src/image/qi21_image_main.cpp) over a prompt x seed set, one process per picture, and write what run_set.py writes for
3sd-cli, so compare.py, floor_table.py and speed_table.py read both alike.
4
5    python3 -I -B run_strata_image.py <root> <tag> <W>x<H> <models_dir> <prompt-indices e.g. 0-7> <seeds e.g. 42,1234>
6                                      --exe PATH [--dump] [--min-free-gb N] [--threads N]
7
8models_dir holds the three files under their published names (tools/image/qimage.py FILES: the Q8_0 DiT, the VAE, the
9text encoder).  The prompts are run_set.py's PROMPTS (the I1/I2 gate set).
10Writes <root>/pics/<tag>/p<i>_s<seed>.png, .log and .json (strata-image --report) per picture, with --dump the stage
11tensors in <root>/pics/<tag>/dump_p<i>_s<seed>/ (stage_hooks.py names), and <root>/pics/<tag>/results.jsonl: rc,
12seconds, maxrss_mib, and from the report open_s, text_encode_s, sampling_s, vae_decode_s, png_s and the per-stage
13memory (ours_gb: the parts' own device memory; driver_gb: the driver's in-use peak above the start; host_gb)."""
14from __future__ import annotations
15
16import json
17import os
18import shutil
19import subprocess
20import sys
21import time
22from pathlib import Path
23
24HERE = Path(__file__).resolve().parent
25sys.path.insert(0, str(HERE))
26sys.path.insert(0, str(HERE.parent))
27from run_set import PROMPTS  # noqa: E402
28
29STAGE_KEYS = {"open": "open_s", "encode": "text_encode_s", "steps": "sampling_s", "decode": "vae_decode_s",
30              "png": "png_s"}
31
32
33def parse_range(text: str) -> list[int]:
34    lo, _, hi = text.partition("-")
35    return list(range(int(lo), int(hi or lo) + 1))
36
37
38def record(tag: str, size: str, pi: int, seed: int, rc: int, secs: float, maxrss_kib: int, report: dict | None) -> dict:
39    rec = {"tag": tag, "backend": "strata-image", "quant": "Q8_0", "size": size, "steps": 8, "prompt": pi,
40           "seed": seed, "rc": rc, "seconds": round(secs, 2), "maxrss_mib": maxrss_kib >> 10}
41    if report:
42        rec["plan"] = report.get("plan")
43        for st in report.get("stages", []):
44            k = STAGE_KEYS.get(st.get("name"))
45            if k:
46                rec[k] = round(st["wall_ms"] / 1000.0, 3)
47                stage = st["name"]
48                for m in ("ours_gb", "driver_gb", "host_gb"):
49                    rec[f"{stage}_{m}"] = round(st[m], 3)
50    return rec
51
52
53def main(argv: list[str]) -> int:
54    if len(argv) < 6 or "--exe" not in argv:
55        print(__doc__)
56        return 2
57    root, tag, size, models, pidx, seeds = argv[:6]
58    root = Path(root).expanduser().resolve()
59    exe = argv[argv.index("--exe") + 1]
60    min_free = float(argv[argv.index("--min-free-gb") + 1]) if "--min-free-gb" in argv else 10.0
61    threads = argv[argv.index("--threads") + 1] if "--threads" in argv else None
62    w, _, h = size.partition("x")
63    md = Path(models).expanduser()
64    files = {"dit": md / "qwen-image-2.1-turbo-Q8_0.gguf", "vae": md / "qwen_image_2.1_vae_bf16.safetensors",
65             "te": md / "Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf"}
66    outd = root / "pics" / tag
67    outd.mkdir(parents=True, exist_ok=True)
68    for pi in parse_range(pidx):
69        for seed in [int(s) for s in seeds.split(",") if s.strip()]:
70            if shutil.disk_usage(root).free / 1e9 < min_free:
71                raise SystemExit("ABORT: disk under the floor")
72            key = f"p{pi}_s{seed}"
73            rep = outd / f"{key}.json"
74            rep.unlink(missing_ok=True)
75            cmd = [exe, "--te", str(files["te"]), "--dit", str(files["dit"]), "--vae", str(files["vae"]),
76                   "--prompt", PROMPTS[pi], "--width", w, "--height", h, "--seed", str(seed), "--steps", "8",
77                   "-o", str(outd / f"{key}.png"), "--report", str(rep)]
78            if threads:
79                cmd += ["--threads", threads]
80            if "--dump" in argv:
81                cmd += ["--dump", str(outd / f"dump_{key}")]
82            t0 = time.monotonic()
83            with open(outd / f"{key}.log", "w") as lf:
84                proc = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
85                _, status, ru = os.wait4(proc.pid, 0)
86            secs = time.monotonic() - t0
87            rc = os.waitstatus_to_exitcode(status)
88            report = json.loads(rep.read_text()) if rc == 0 and rep.is_file() else None
89            rec = record(tag, size, pi, seed, rc, secs, ru.ru_maxrss, report)
90            if rc != 0:
91                rec["error"] = "\n".join((outd / f"{key}.log").read_text(errors="replace").strip().splitlines()[-8:])
92            with open(outd / "results.jsonl", "a") as f:
93                f.write(json.dumps(rec) + "\n")
94            print(json.dumps(rec), flush=True)
95    print("RUN-OK")
96    return 0
97
98
99if __name__ == "__main__":
100    sys.exit(main(sys.argv[1:]))