okami.mom/strata

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

Niko1221Merge f-029-par-harness1fb3e9a32

main
11.2 KiB215 linesraw
1#!/usr/bin/env python3
2"""par_run.py - start serve/server.py with one configuration variant on a test box, run par_load.py workloads, stop.
3
4Research tool for the parallelism program.  One call = one server start = one arm/variant.  Writes next to --out:
5  <tag>-cfg.json, <tag>-engine.log, <tag>-server.out, <tag>-<workload>.json (par_load ledgers), <tag>-run.json
6(effective engine lines, PSS/RSS of the engine tree, GPU memory, ready time, the cmd/env).
7
8    python3 tools/par_run.py --box boston --tag base1g --gpus 0 --work "w1;w2:4,8" --out /path/dir
9    python3 tools/par_run.py --box boston --tag s8g4 --gpus 0,1 --parallel 8 --groups 4 --env "STRATA_PIPED_CONCURRENT=1" \
10        --extra "--foo bar" --work "w2:4,8;w4:4" --out dir
11
12--work items are workload[:conc list] separated by ';', optionally with par_load flags after '@' (e.g. "w4:4@--joiner-tokens 16384").
13--default-config uses what the box's 0.2.8 launcher would write (no parallel key, layer_split auto when 2 GPUs).
14"""
15import argparse, json, os, shlex, signal, subprocess, sys, time, urllib.request
16
17BOXES = {
18    "boston": {
19        "py": "/data/external/niko/t027/venv/bin/python", "libs": ["/usr/local/cuda-13.1/lib64"],
20        "pack": "/data/external/niko/pm/pack/iq3_s", "mtp": "/data/external/niko/pm/mtp/rt",
21        "gguf1": "/data3/models/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
22        "gguf2": "/data3/models/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
23        "profile": "{repo}/data/expert-profile.bin",
24    },
25    "z440": {
26        "py": "/data/Strata/.venv/bin/python", "libs": ["/usr/local/cuda-12.9/lib64"],
27        "pack": "/data/strata-models/IQ3_S/pack", "mtp": "/data/Strata-data/mtp/rt",
28        "gguf1": "/data/strata-models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
29        "gguf2": "/data/strata-models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
30        "profile": "{repo}/data/expert-profile.bin",
31    },
32}
33
34
35def pss_tree(pid, exe=None):
36    """Sum of PSS (MB) and RSS of a process and all its descendants (Linux, via /proc ppid)."""
37    kids = {}
38    for d in os.listdir("/proc"):
39        if d.isdigit():
40            try:
41                st = open(f"/proc/{d}/stat").read()
42                ppid = int(st[st.rindex(")") + 2:].split()[1])
43                kids.setdefault(ppid, []).append(int(d))
44            except (OSError, ValueError):
45                pass
46    seen, todo = set(), [pid]
47    for d in os.listdir("/proc"):          # engines are started detached: also every process running our --exe
48        if d.isdigit() and exe:
49            try:
50                if exe in open(f"/proc/{d}/cmdline").read().replace("\0", " "):
51                    todo.append(int(d))
52            except OSError:
53                pass
54    while todo:
55        p = todo.pop()
56        if p not in seen:
57            seen.add(p)
58            todo += kids.get(p, [])
59    pss = rss = 0
60    for p in seen:
61        try:
62            for line in open(f"/proc/{p}/smaps_rollup"):
63                if line.startswith("Pss:"):
64                    pss += int(line.split()[1])
65                elif line.startswith("Rss:"):
66                    rss += int(line.split()[1])
67        except OSError:
68            pass
69    return {"pss_mb": pss // 1024, "rss_mb": rss // 1024, "procs": len(seen)}
70
71
72def gpu_mem():
73    try:
74        o = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used,memory.total", "--format=csv,noheader,nounits"],
75                           capture_output=True, text=True, timeout=20).stdout
76        return [[int(x) for x in l.split(",")] for l in o.strip().splitlines()]
77    except Exception:  # noqa: BLE001
78        return None
79
80
81def main():
82    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
83    ap.add_argument("--box", required=True, choices=list(BOXES))
84    ap.add_argument("--tag", required=True)
85    ap.add_argument("--out", required=True, help="output directory")
86    ap.add_argument("--exe", required=True)
87    ap.add_argument("--repo", required=True, help="source tree (serve/server.py, data/expert-profile.bin)")
88    ap.add_argument("--gpus", default="0,1")
89    ap.add_argument("--parallel", type=int, default=None)
90    ap.add_argument("--groups", default=None)
91    ap.add_argument("--replicas", type=int, default=None)
92    ap.add_argument("--split", default="auto")
93    ap.add_argument("--ctx", type=int, default=32768)
94    ap.add_argument("--prefill", default="auto")
95    ap.add_argument("--no-mtp", action="store_true")
96    ap.add_argument("--mtp-depth", type=int, default=4, help="--spec value (the default in setup configs is 4)")
97    ap.add_argument("--env", default="", help="K=V;K=V for the engine/server environment")
98    ap.add_argument("--extra", default="", help="extra engine args (one string)")
99    ap.add_argument("--server-extra", default="", help="extra server.py args")
100    ap.add_argument("--port", type=int, default=18930)
101    ap.add_argument("--work", default="w2:4,8")
102    ap.add_argument("--rounds", type=int, default=3)
103    ap.add_argument("--cap", type=int, default=1500, help="engine ready timeout (s)")
104    ap.add_argument("--min-free-gb", type=int, default=14)
105    ap.add_argument("--post-cmd", default=None, help="a shell command run after the work items; {url} is the server URL; its output goes to <tag>-post.txt")
106    a = ap.parse_args()
107    B = BOXES[a.box]
108    os.makedirs(a.out, exist_ok=True)
109    # memory guard: never start with too little RAM (the replicas and the 2-GPU engine each pin tens of GB)
110    avail = 0
111    for line in open("/proc/meminfo"):
112        if line.startswith("MemAvailable:"):
113            avail = int(line.split()[1]) // 1048576
114    if avail < a.min_free_gb:
115        print(f"ABORT: only {avail} GB RAM available (< {a.min_free_gb})")
116        return 3
117    log = os.path.join(a.out, f"{a.tag}-engine.log")
118    args = ["--pack", B["pack"], "--native", B["gguf1"], "--ple-gguf", B["gguf2"],
119            "--expert-profile", B["profile"].format(repo=a.repo), "--expert-cache", "auto", "--prefill", a.prefill,
120            "--spec", str(a.mtp_depth), "--spec-min-p", "0.5", "--layer-split", a.split, "--max-context", str(a.ctx), "--kv", "int8"]
121    if not a.no_mtp:
122        args += ["--mtp", B["mtp"]]
123    args += shlex.split(a.extra)
124    gpus = [int(x) for x in a.gpus.split(",")]
125    cfg = {"exe": a.exe, "args": args, "cwd": a.repo, "tokenizer": B["pack"] + "/tokenizer", "model_name": "qwen3.8-flash-next-iq3_s",
126           "log": log, "lib_dirs": B["libs"], "port": a.port, "gpu": gpus, "gpus_asked": True, "engine_ready_s": a.cap}
127    if len(gpus) == 1:
128        cfg["args"] = [x for i, x in enumerate(args) if x != "--layer-split" and (i == 0 or args[i - 1] != "--layer-split")]
129    if a.replicas:
130        cfg["replicas"] = a.replicas
131    cpath = os.path.join(a.out, f"{a.tag}-cfg.json")
132    json.dump(cfg, open(cpath, "w"), indent=1)
133    env = {k: v for k, v in os.environ.items() if not k.startswith("STRATA_")}
134    env["LD_LIBRARY_PATH"] = ":".join(B["libs"] + [env.get("LD_LIBRARY_PATH", "")])
135    for kv in a.env.split(";"):
136        if kv.strip():
137            k, v = kv.split("=", 1)
138            env[k.strip()] = v.strip()
139    cmd = [B["py"], f"{a.repo}/serve/server.py", "--engine", "strata", "--config", cpath, "--port", str(a.port)]
140    if a.parallel is not None:
141        cmd += ["--parallel", str(a.parallel)]
142    if a.groups:
143        cmd += ["--batch-groups", str(a.groups)]
144    cmd += shlex.split(a.server_extra)
145    srvout = open(os.path.join(a.out, f"{a.tag}-server.out"), "w")
146    t0 = time.time()
147    srv = subprocess.Popen(cmd, env=env, stdout=srvout, stderr=subprocess.STDOUT, start_new_session=True, cwd=a.repo)
148    ready = None
149    while time.time() - t0 < a.cap:
150        if srv.poll() is not None:
151            print("SERVER DIED", flush=True)
152            break
153        try:
154            urllib.request.urlopen(f"http://127.0.0.1:{a.port}/v1/models", timeout=5).read()
155            st = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{a.port}/v1/status", timeout=5).read())
156            if (st.get("state") or "ready") in ("ready", "idle", "serving") or st.get("ready"):
157                ready = time.time() - t0
158                break
159        except Exception:  # noqa: BLE001
160            pass
161        time.sleep(3)
162    print(f"[{a.tag}] ready after {ready}s", flush=True)
163    rec = {"tag": a.tag, "box": a.box, "cmd": cmd, "env": a.env, "args": args, "ready_s": ready, "work": {}, "mem": {}}
164    url = f"http://127.0.0.1:{a.port}"
165    if ready is not None:
166        time.sleep(2)
167        rec["mem"]["after_load"] = pss_tree(srv.pid, a.exe)
168        rec["gpu_after_load"] = gpu_mem()
169        here = os.path.dirname(os.path.abspath(__file__))
170        # a short unmeasured warmup so that lazy code objects/JIT and the first expert-cache fills are out of the way
171        subprocess.run([sys.executable, f"{here}/par_load.py", url, "--workload", "w2", "--conc", "2", "--rounds", "1", "--max-tokens", "48",
172                        "--nonce", "warm", "--out", os.path.join(a.out, f"{a.tag}-warm.json")], capture_output=True)
173        for item in a.work.split(";"):
174            if not item.strip():
175                continue
176            main_part, _, extra = item.partition("@")
177            wl, _, conc = main_part.partition(":")
178            wl = wl.strip()
179            outj = os.path.join(a.out, f"{a.tag}-{wl}{conc.replace(',', '_')}.json")
180            c2 = [sys.executable, f"{here}/par_load.py", url, "--workload", wl, "--rounds", str(a.rounds), "--arm", a.tag, "--pair", "0",
181                  "--label", a.tag, "--settings", log, "--out", outj]
182            if conc:
183                c2 += ["--conc", conc]
184            c2 += shlex.split(extra)
185            r = subprocess.run(c2, capture_output=True, text=True)
186            print(r.stdout[-1500:], flush=True)
187            if r.returncode:
188                print("par_load rc", r.returncode, r.stderr[-300:], flush=True)
189            rec["work"][item] = outj
190            rec["mem"][item] = pss_tree(srv.pid, a.exe)
191        if a.post_cmd:
192            r = subprocess.run(a.post_cmd.format(url=url), shell=True, capture_output=True, text=True)
193            open(os.path.join(a.out, f"{a.tag}-post.txt"), "w").write(r.stdout + r.stderr)
194            print(r.stdout[-1500:], flush=True)
195        rec["gpu_after_work"] = gpu_mem()
196    try:
197        os.killpg(srv.pid, signal.SIGTERM)
198        srv.wait(120)
199    except Exception:  # noqa: BLE001
200        try:
201            os.killpg(srv.pid, signal.SIGKILL)
202        except Exception:  # noqa: BLE001
203            pass
204    text = open(log, errors="replace").read() if os.path.exists(log) else ""
205    keys = ("batch_slots", "batch_groups", "expert cache", "slot sessions", "groups of", "pipelined", "VRAM free", "layer split", "layer-split",
206            "strata p4", "strata par", "mtp", "adapt")
207    rec["engine_lines"] = [l[:220] for l in text.splitlines() if any(k in l for k in keys)][:60]
208    rec["errors_in_log"] = len([1 for l in text.splitlines() if any(k in l for k in ("illegal instruction", "Traceback", " ERR ", "segfault", "Segmentation", "out of memory"))])
209    json.dump(rec, open(os.path.join(a.out, f"{a.tag}-run.json"), "w"), indent=1)
210    print("DONE", a.tag, "errors_in_log", rec["errors_in_log"])
211    return 0
212
213
214if __name__ == "__main__":
215    sys.exit(main())