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
9.8 KiB187 linesraw
1"""tools/image/gate/run_set.py - TEST-ONLY (OWN-5 gate harness): run sd-cli for a set of prompt x seed pictures with exactly the command Strata's server runs
2(serve/images.py sd_cli_args + image_env from the repo copy), one process per picture, and record time and memory.
3
4    python3 -I -B run_set.py <root> <backend> <tag> <W>x<H> <quant> <models_dir> <prompt-indices e.g. 0-7> <seeds e.g. 42,1234>
5                             [--native] [--noise] [--threads N] [--min-free-gb N] [--steps N] [--build NAME]
6                             [--dump] [--cond-from TAG] [--latent-from TAG] [--noise-from DIR] [--exit-after K]
7                             [--env K=V ...] [--extra-args "sd-cli args"] [--model-arg K=V ...]
8--noise: the config's images "noise" is "strata" (--model-args strata_noise=1); the build must have the generator.
9--build NAME uses <root>/build-NAME.json (e.g. a stage_hooks.py variant); --dump/--cond-from/--latent-from/
10--noise-from/--exit-after drive that variant's hooks (OWN5_* variables, see stage_hooks.py), per picture.
11
12Writes <root>/pics/<tag>/p<i>_s<seed>.png, .log per picture and <root>/pics/<tag>/results.jsonl.
13Memory: peak RSS of sd-cli (wait4), GPU memory sampled every 0.2 s (nvidia-smi on NVIDIA with dedicated memory,
14amdgpu sysfs mem_info_vram_used on AMD; on unified-memory boxes the minimum MemAvailable is recorded instead)."""
15from __future__ import annotations
16
17import json
18import os
19import re
20import shutil
21import subprocess
22import sys
23import threading
24import time
25from pathlib import Path
26
27PROMPTS = [   # the I1/I2 gate set (p2006 ~/qimage/i2/qi_gate.py PROMPTS)
28    "a neon-lit ramen shop in a rainy Tokyo alley at night, reflections on wet pavement, cinematic",
29    "macro photograph of a honeybee on a sunflower, visible pollen grains, extreme detail",
30    "a chalkboard in a classroom with the words \"Photosynthesis: light + water + CO2\" written in white chalk",
31    "a medieval knight in ornate silver armor standing in a misty forest at dawn, oil painting",
32    "a cartoon sloth mascot waving, flat vector illustration, bright colours",
33    "portrait of an elderly fisherman with a weathered face and a knitted cap, soft window light, 85mm photo",
34    "a retro travel poster of a mountain lake with the text \"VISIT LAKE BLED\" in bold art deco letters",
35    "a still life of lemons, a glass carafe of water and a blue ceramic bowl on a linen tablecloth, morning light",
36]
37
38
39def gpu_mem_sampler(stop: threading.Event, out: dict):
40    nv = shutil.which("nvidia-smi")
41    amd = [p for p in Path("/sys/class/drm").glob("card*/device/mem_info_vram_used")]
42    peak, base, minavail, startavail = None, None, None, None
43    while not stop.is_set():
44        v = None
45        if nv:
46            try:
47                r = subprocess.run([nv, "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
48                                   capture_output=True, text=True, timeout=5)
49                v = sum(int(x) for x in r.stdout.split() if x.strip().isdigit()) or None
50            except Exception:
51                v = None
52        elif amd:
53            try:
54                v = max(int(p.read_text()) for p in amd) >> 20
55            except Exception:
56                v = None
57        if v is not None:
58            base = v if base is None else base
59            peak = v if peak is None else max(peak, v)
60        try:
61            for ln in open("/proc/meminfo"):
62                if ln.startswith("MemAvailable:"):
63                    a = int(ln.split()[1]) >> 10
64                    minavail = a if minavail is None else min(minavail, a)
65                    startavail = a if startavail is None else startavail
66        except OSError:
67            pass
68        stop.wait(0.2)
69    out.update(gpu_mib_start=base, gpu_mib_peak=peak, memavail_mib_start=startavail, memavail_mib_min=minavail)
70
71
72def main() -> int:
73    a = sys.argv[1:]
74    root, backend, tag, size, quant, models, pidx, seeds = a[:8]
75    root = Path(root).expanduser().resolve()
76    native = "--native" in a
77    threads = a[a.index("--threads") + 1] if "--threads" in a else None
78    min_free = float(a[a.index("--min-free-gb") + 1]) if "--min-free-gb" in a else 10.0
79    steps = int(a[a.index("--steps") + 1]) if "--steps" in a else 8
80    lo, _, hi = pidx.partition("-")
81    prompts = list(range(int(lo), int(hi or lo) + 1))
82    seed_list = [int(s) for s in seeds.split(",")]
83    w, h = (int(x) for x in size.lower().split("x"))
84    repo = root / "repo"
85    sys.path.insert(0, str(repo))
86    sys.path.insert(0, str(repo / "tools" / "image"))
87    import qimage as QI
88    from serve import images as IM
89    bname = a[a.index("--build") + 1] if "--build" in a else backend      # another build of the same backend
90    build = json.loads((root / f"build-{bname}.json").read_text())
91    md = Path(models).expanduser()
92    cfg = QI.image_config(backend, quant, Path(build["exe"]), md.parent if md.name == QI.MODEL_DIR else md,
93                          native=native, noise="--noise" in a)
94    if md.name != QI.MODEL_DIR:   # files sit directly in models_dir
95        for k, name in (("diffusion_model", quant), ("vae", "vae"), ("llm", "llm")):
96            cfg[k] = str(md / Path(QI.FILES[name][1]).name)
97    cfg["lib_dirs"] = [d for d in build.get("env_ld", "").split(os.pathsep) if d]
98    if threads:
99        cfg["args"] = list(cfg["args"]) + ["-t", threads]
100    outd = root / "pics" / tag
101    outd.mkdir(parents=True, exist_ok=True)
102    base_env = IM.image_env(cfg)
103    base_env["PATH"] = build.get("env_path") or base_env["PATH"]
104    for i, x in enumerate(a):
105        if x == "--env":
106            k, _, v = a[i + 1].partition("=")
107            base_env[k] = v
108    extra_args = a[a.index("--extra-args") + 1].split() if "--extra-args" in a else []
109    exit_after = a[a.index("--exit-after") + 1] if "--exit-after" in a else None
110    for pi in prompts:
111        for seed in seed_list:
112            if shutil.disk_usage(root).free / 1e9 < min_free:
113                raise SystemExit("ABORT: disk under the floor")
114            job = {"prompt": PROMPTS[pi], "width": w, "height": h, "n": 1, "steps": steps, "seed": seed}
115            work = outd / f"_work_p{pi}_s{seed}"
116            shutil.rmtree(work, ignore_errors=True)
117            work.mkdir()
118            pf = IM.write_prompt(work, job["prompt"])
119            cmd = IM.sd_cli_args(cfg, job, str(work / "img_%d.png"), str(pf)) + extra_args
120            for i, x in enumerate(a):                       # --model-arg K=V: into the one --model-args string
121                if x == "--model-arg":
122                    if "--model-args" in cmd:
123                        j = cmd.index("--model-args") + 1
124                        cmd[j] = cmd[j] + "," + a[i + 1]
125                    else:
126                        cmd += ["--model-args", a[i + 1]]
127            env = dict(base_env)
128            key = f"p{pi}_s{seed}"
129            if "--dump" in a:                                   # stage hooks (stage_hooks.py builds only)
130                dd = outd / f"dump_{key}"
131                dd.mkdir(exist_ok=True)
132                env["OWN5_DUMP_DIR"] = str(dd)
133            for opt, var, fname in (("--cond-from", "OWN5_COND_IN", "cond.bin"),
134                                    ("--latent-from", "OWN5_LATENT_IN", "latent.bin")):
135                if opt in a:
136                    env[var] = str(root / "pics" / a[a.index(opt) + 1] / f"dump_{key}" / fname)
137            if "--noise-from" in a:
138                env["OWN5_NOISE_DIR"] = str(Path(a[a.index("--noise-from") + 1]).expanduser())
139            if exit_after is not None:
140                env["OWN5_EXIT_AFTER"] = exit_after
141            stop, mem = threading.Event(), {}
142            th = threading.Thread(target=gpu_mem_sampler, args=(stop, mem), daemon=True)
143            th.start()
144            t0 = time.monotonic()
145            first_step = None
146            logp = outd / f"p{pi}_s{seed}.log"
147            with open(logp, "w") as lf:
148                proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
149                                        env=env, cwd=str(work), text=True, errors="replace", bufsize=1)
150                for line in proc.stdout:
151                    lf.write(line)
152                    if first_step is None and IM.STEP_LINE.search(line):
153                        first_step = time.monotonic() - t0
154                _, status, ru = os.wait4(proc.pid, 0)
155            secs = time.monotonic() - t0
156            stop.set()
157            th.join()
158            rc = os.waitstatus_to_exitcode(status)
159            log = logp.read_text(errors="replace")
160            rec = {"tag": tag, "backend": backend, "native": native, "quant": quant, "size": size, "steps": steps,
161                   "prompt": pi, "seed": seed, "rc": rc, "seconds": round(secs, 2),
162                   "first_step_s": round(first_step, 2) if first_step else None, "maxrss_mib": ru.ru_maxrss >> 10,
163                   "threads": threads, **mem}
164            for key, pat in (("text_encode_s", r"get_learned_condition completed, taking ([0-9.]+) ?s"),
165                             ("sampling_s", r"sampling completed, taking ([0-9.]+) ?s"),
166                             ("vae_decode_s", r"decode_first_stage completed, taking ([0-9.]+) ?s")):
167                m = re.findall(pat, log)
168                if m:
169                    rec[key] = float(m[-1])
170            png = work / "img_0.png"
171            if rc == 0 and png.is_file():
172                shutil.move(str(png), str(outd / f"p{pi}_s{seed}.png"))
173            elif rc == 0 and exit_after is not None:
174                rec["note"] = f"stopped after model call {exit_after} (stage run, no picture)"
175            else:
176                rec["error"] = "\n".join(log.strip().splitlines()[-8:])
177            shutil.rmtree(work, ignore_errors=True)
178            with open(outd / "results.jsonl", "a") as f:
179                f.write(json.dumps(rec) + "\n")
180            print(json.dumps(rec), flush=True)
181    (outd / "cmd.txt").write_text(" ".join(cmd) + "\n")
182    print("RUN-OK")
183    return 0
184
185
186if __name__ == "__main__":
187    sys.exit(main())