okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e4309aaf3
main
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 4python3 -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 ): 40nv = shutil .which ("nvidia-smi" ) 41amd = [p for p in Path ("/sys/class/drm" ).glob ("card*/device/mem_info_vram_used" )] 42peak ,base ,minavail ,startavail = None ,None ,None ,None 43while not stop .is_set (): 44v = None 45if nv : 46try : 47r = subprocess .run ([nv ,"--query-gpu=memory.used" ,"--format=csv,noheader,nounits" ], 48capture_output = True ,text = True ,timeout = 5 ) 49v = sum (int (x )for x in r .stdout .split ()if x .strip ().isdigit ())or None 50except Exception : 51v = None 52elif amd : 53try : 54v = max (int (p .read_text ())for p in amd )>> 20 55except Exception : 56v = None 57if v is not None : 58base = v if base is None else base 59peak = v if peak is None else max (peak ,v ) 60try : 61for ln in open ("/proc/meminfo" ): 62if ln .startswith ("MemAvailable:" ): 63a = int (ln .split ()[1 ])>> 10 64minavail = a if minavail is None else min (minavail ,a ) 65startavail = a if startavail is None else startavail 66except OSError : 67pass 68stop .wait (0.2 ) 69out .update (gpu_mib_start = base ,gpu_mib_peak = peak ,memavail_mib_start = startavail ,memavail_mib_min = minavail ) 70 71 72def main ()-> int : 73a = sys .argv [1 :] 74root ,backend ,tag ,size ,quant ,models ,pidx ,seeds = a [:8 ] 75root = Path (root ).expanduser ().resolve () 76native = "--native" in a 77threads = a [a .index ("--threads" )+ 1 ]if "--threads" in a else None 78min_free = float (a [a .index ("--min-free-gb" )+ 1 ])if "--min-free-gb" in a else 10.0 79steps = int (a [a .index ("--steps" )+ 1 ])if "--steps" in a else 8 80lo ,_ ,hi = pidx .partition ("-" ) 81prompts = list (range (int (lo ),int (hi or lo )+ 1 )) 82seed_list = [int (s )for s in seeds .split ("," )] 83w ,h = (int (x )for x in size .lower ().split ("x" )) 84repo = root / "repo" 85sys .path .insert (0 ,str (repo )) 86sys .path .insert (0 ,str (repo / "tools" / "image" )) 87import qimage as QI 88from serve import images as IM 89bname = a [a .index ("--build" )+ 1 ]if "--build" in a else backend # another build of the same backend 90build = json .loads ((root / f"build- { bname } .json" ).read_text ()) 91md = Path (models ).expanduser () 92cfg = QI .image_config (backend ,quant ,Path (build ["exe" ]),md .parent if md .name == QI .MODEL_DIR else md , 93native = native ,noise = "--noise" in a ) 94if md .name != QI .MODEL_DIR :# files sit directly in models_dir 95for k ,name in (("diffusion_model" ,quant ), ("vae" ,"vae" ), ("llm" ,"llm" )): 96cfg [k ]= str (md / Path (QI .FILES [name ][1 ]).name ) 97cfg ["lib_dirs" ]= [d for d in build .get ("env_ld" ,"" ).split (os .pathsep )if d ] 98if threads : 99cfg ["args" ]= list (cfg ["args" ])+ ["-t" ,threads ] 100outd = root / "pics" / tag 101outd .mkdir (parents = True ,exist_ok = True ) 102base_env = IM .image_env (cfg ) 103base_env ["PATH" ]= build .get ("env_path" )or base_env ["PATH" ] 104for i ,x in enumerate (a ): 105if x == "--env" : 106k ,_ ,v = a [i + 1 ].partition ("=" ) 107base_env [k ]= v 108extra_args = a [a .index ("--extra-args" )+ 1 ].split ()if "--extra-args" in a else [] 109exit_after = a [a .index ("--exit-after" )+ 1 ]if "--exit-after" in a else None 110for pi in prompts : 111for seed in seed_list : 112if shutil .disk_usage (root ).free / 1e9 < min_free : 113raise SystemExit ("ABORT: disk under the floor" ) 114job = {"prompt" :PROMPTS [pi ],"width" :w ,"height" :h ,"n" :1 ,"steps" :steps ,"seed" :seed } 115work = outd / f"_work_p { pi } _s { seed } " 116shutil .rmtree (work ,ignore_errors = True ) 117work .mkdir () 118pf = IM .write_prompt (work ,job ["prompt" ]) 119cmd = IM .sd_cli_args (cfg ,job ,str (work / "img_%d.png" ),str (pf ))+ extra_args 120for i ,x in enumerate (a ):# --model-arg K=V: into the one --model-args string 121if x == "--model-arg" : 122if "--model-args" in cmd : 123j = cmd .index ("--model-args" )+ 1 124cmd [j ]= cmd [j ]+ "," + a [i + 1 ] 125else : 126cmd += ["--model-args" ,a [i + 1 ]] 127env = dict (base_env ) 128key = f"p { pi } _s { seed } " 129if "--dump" in a :# stage hooks (stage_hooks.py builds only) 130dd = outd / f"dump_ { key } " 131dd .mkdir (exist_ok = True ) 132env ["OWN5_DUMP_DIR" ]= str (dd ) 133for opt ,var ,fname in (("--cond-from" ,"OWN5_COND_IN" ,"cond.bin" ), 134 ("--latent-from" ,"OWN5_LATENT_IN" ,"latent.bin" )): 135if opt in a : 136env [var ]= str (root / "pics" / a [a .index (opt )+ 1 ]/ f"dump_ { key } " / fname ) 137if "--noise-from" in a : 138env ["OWN5_NOISE_DIR" ]= str (Path (a [a .index ("--noise-from" )+ 1 ]).expanduser ()) 139if exit_after is not None : 140env ["OWN5_EXIT_AFTER" ]= exit_after 141stop ,mem = threading .Event (), {} 142th = threading .Thread (target = gpu_mem_sampler ,args = (stop ,mem ),daemon = True ) 143th .start () 144t0 = time .monotonic () 145first_step = None 146logp = outd / f"p { pi } _s { seed } .log" 147with open (logp ,"w" )as lf : 148proc = subprocess .Popen (cmd ,stdout = subprocess .PIPE ,stderr = subprocess .STDOUT ,stdin = subprocess .DEVNULL , 149env = env ,cwd = str (work ),text = True ,errors = "replace" ,bufsize = 1 ) 150for line in proc .stdout : 151lf .write (line ) 152if first_step is None and IM .STEP_LINE .search (line ): 153first_step = time .monotonic ()- t0 154_ ,status ,ru = os .wait4 (proc .pid ,0 ) 155secs = time .monotonic ()- t0 156stop .set () 157th .join () 158rc = os .waitstatus_to_exitcode (status ) 159log = logp .read_text (errors = "replace" ) 160rec = {"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 } 164for 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" )): 167m = re .findall (pat ,log ) 168if m : 169rec [key ]= float (m [- 1 ]) 170png = work / "img_0.png" 171if rc == 0 and png .is_file (): 172shutil .move (str (png ),str (outd / f"p { pi } _s { seed } .png" )) 173elif rc == 0 and exit_after is not None : 174rec ["note" ]= f"stopped after model call { exit_after } (stage run, no picture)" 175else : 176rec ["error" ]= "\n" .join (log .strip ().splitlines ()[- 8 :]) 177shutil .rmtree (work ,ignore_errors = True ) 178with open (outd / "results.jsonl" ,"a" )as f : 179f .write (json .dumps (rec )+ "\n" ) 180json .dumps (rec ),flush = True ) 181 (outd / "cmd.txt" ).write_text (" " .join (cmd )+ "\n" ) 182"RUN-OK" ) 183return 0 184 185 186if __name__ == "__main__" : 187sys .exit (main ())