Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/gpu-head-to-head/blob/main/coldstart/run.py # gpu-head-to-head aien-dev/gpu-head-to-head Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `gpu-head-to-head / coldstart / run.py` 278 lines ยท 12800 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """coldstart/run.py: driver of the cold-start chip microbenchmark (coldstart/PROTOCOL.md section 5). 3 4 Measurement tooling, not first-party product code. It runs inside one spark-window and writes 5 results/coldstart/{raw.jsonl,session.json,rows.wl}. --dry-run runs the same schedule on the host with 6 --build-only (no GPU opened) into a scratch directory; dry-run output is never a result. 7 """ 8 import argparse, datetime, hashlib, itertools, json, os, subprocess, sys, time 9 10 ARMS = ("CUDAPP", "PTXC", "NVRTC") 11 BIN = {"CUDAPP": "cs_cudapp", "PTXC": "cs_ptxc", "NVRTC": "cs_nvrtc"} 12 ORDERS = list(itertools.permutations(ARMS)) # the 6 orders, round r uses ORDERS[r % 6] 13 ARM_CORES = (9, 8, 7) # X925 (A2), first one free of the nvidia-modeset kthreads 14 DRIVER_CORE = 12 # A725 (A2) 15 N_TOTAL = 1 << 20 16 CUDAPP_CODE_SHA = "`9e28bd9c46f80584d77238a752e99cecddbc8d622ffbe320885ed2f499e1f075`" # hello_gpu --sim at `cc0908bd` 17 FORBIDDEN = ("libcuda", "libcudart", "libnvrtc", "libnvptx", "libnvidia") 18 CAP_S = 15 * 60 19 20 here = os.path.dirname(os.path.abspath(__file__)) 21 repo = os.path.dirname(here) 22 23 24 def mono(): 25 return time.clock_gettime_ns(time.CLOCK_MONOTONIC) 26 27 28 def utc(): 29 return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") 30 31 32 def sha256(path): 33 h = hashlib.sha256() 34 with open(path, "rb") as f: 35 for b in iter(lambda: f.read(1 << 20), b""): 36 h.update(b) 37 return h.hexdigest() 38 39 40 def load1(): 41 with open("/proc/loadavg") as f: 42 return float(f.read().split()[0]) 43 44 45 def kthread_cpus(): 46 """CPU (stat field 39) of every nvidia-modeset kernel thread.""" 47 cpus = {} 48 for d in os.listdir("/proc"): 49 if not d.isdigit(): 50 continue 51 try: 52 with open(f"/proc/{d}/comm") as f: 53 comm = f.read().strip() 54 if not comm.startswith("nvidia-modeset"): 55 continue 56 with open(f"/proc/{d}/stat") as f: 57 rest = f.read().rsplit(")", 1)[1].split() 58 cpus[f"{d}:{comm}"] = int(rest[36]) 59 except (OSError, IndexError, ValueError): 60 continue 61 return cpus 62 63 64 def gpu_apps(): 65 r = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"], 66 capture_output=True, text=True, timeout=30) 67 return {"rc": r.returncode, "apps": [l.strip() for l in r.stdout.splitlines() if l.strip()]} 68 69 70 def spawn(path, args, core, cwd): 71 env = dict(os.environ, CUDA_CACHE_DISABLE="1") 72 l1 = load1() 73 t0 = mono() 74 p = subprocess.Popen([path] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env, 75 preexec_fn=lambda: os.sched_setaffinity(0, {core})) 76 out, err = p.communicate(timeout=120) 77 t1 = mono() 78 row = {"exit": p.returncode, "load1": l1, "spawn_ns": t0, "proc_ns": t1 - t0} 79 try: 80 rep = json.loads(out.decode().strip().splitlines()[-1]) 81 row.update(rep) 82 row["exec_ns"] = rep["t_main_ns"] - t0 83 except (ValueError, IndexError, KeyError): 84 row["stdout"] = out.decode(errors="replace")[-400:] 85 if p.returncode != 0: 86 row["stderr"] = err.decode(errors="replace")[-400:] 87 return row 88 89 90 def main(): 91 ap = argparse.ArgumentParser() 92 ap.add_argument("--build", default="/tmp/h2h-coldstart-build", help="output directory of coldstart/build.sh") 93 ap.add_argument("--out", default=os.path.join(repo, "results", "coldstart")) 94 ap.add_argument("--rounds", type=int, default=30) 95 ap.add_argument("--warmup", type=int, default=2) 96 ap.add_argument("--warm-rounds", type=int, default=10) 97 ap.add_argument("--gap", type=float, default=1.0) 98 ap.add_argument("--dry-run", action="store_true", help="host only: --build-only, scratch output, no GPU") 99 a = ap.parse_args() 100 101 t_start = mono() 102 if a.dry_run: 103 if a.out == os.path.join(repo, "results", "coldstart"): 104 sys.exit("run: --dry-run needs --out outside results/") 105 elif os.environ.get("AIEN_GB10_LOCK_HELD") != "1" or not os.environ.get("SPARK_WINDOW"): 106 sys.exit("run: not inside a spark-window holding the chip lock (spark-window run coldstart/run.py ...)") 107 os.makedirs(a.out, exist_ok=True) 108 os.sched_setaffinity(0, {DRIVER_CORE}) 109 110 session = {"started_utc": utc(), "dry_run": a.dry_run, "spark_window": os.environ.get("SPARK_WINDOW"), 111 "rounds": a.rounds, "warmup": a.warmup, "warm_rounds": a.warm_rounds, "gap_s": a.gap, "driver_core": DRIVER_CORE, 112 "uname": " ".join(os.uname()), "CUDA_CACHE_DISABLE": "1"} 113 with open(os.path.join(a.build, "build.txt")) as f: 114 build = f.read() 115 session["build_txt"] = build 116 want = {l.split()[1]: l.split()[2] for l in build.splitlines() if l.startswith("sha256 ")} 117 paths = {arm: os.path.join(a.build, BIN[arm]) for arm in ARMS} 118 for arm, p in paths.items(): 119 got = sha256(p) 120 if got != want.get(BIN[arm]): 121 sys.exit(f"run: {p} sha256 {got} is not the one in build.txt") 122 ptx = os.path.join(here, "vecadd.ptx") 123 if sha256(ptx) != want.get("vecadd.ptx"): 124 sys.exit("run: coldstart/vecadd.ptx is not the one in build.txt") 125 extra = {"CUDAPP": [], "PTXC": ["--ptx", ptx], "NVRTC": []} 126 127 kt = kthread_cpus() 128 session["nvidia_modeset_kthread_cpus"] = kt 129 core = next((c for c in ARM_CORES if c not in kt.values()), None) 130 if core is None: 131 sys.exit(f"run: every arm core {ARM_CORES} hosts an nvidia-modeset kthread {kt}") 132 session["arm_core"] = core 133 134 if not a.dry_run: 135 q = subprocess.run([sys.executable, os.path.join(repo, "bench", "quiet.py"), "--window", "60", "--max-load", "6", 136 "--exclude-tree", str(os.getpid())], capture_output=True, text=True) 137 session["quiet"] = {"rc": q.returncode, "out": q.stdout.strip()} 138 if q.returncode != 0: 139 sys.exit(f"run: machine not quiet: {q.stdout.strip()}") 140 session["gpu_apps_before"] = gpu_apps() 141 if session["gpu_apps_before"]["apps"]: 142 sys.exit(f"run: GPU compute apps present: {session['gpu_apps_before']}") 143 144 raw = open(os.path.join(a.out, "raw.jsonl"), "w") 145 146 def record(row): 147 raw.write(json.dumps(row, sort_keys=True) + "\n") 148 raw.flush() 149 150 # Section 6 controls. Any failure stops the study before a measured process runs. 151 fails = [] 152 codes = {} 153 for arm in ARMS: 154 cf = os.path.join(a.out, f"code.{arm}.bin") 155 r = spawn(paths[arm], extra[arm] + ["--build-only", "--emit-code", cf], core, repo) 156 r.update(arm=arm, phase="control_code") 157 record(r) 158 codes[arm] = sha256(cf) if r["exit"] == 0 else None 159 if r["exit"] != 0: 160 fails.append(f"{arm} --build-only exit {r['exit']}") 161 session["code_sha256"] = codes 162 if codes["CUDAPP"] != CUDAPP_CODE_SHA: 163 fails.append(f"CUDAPP code sha {codes['CUDAPP']} != hello_gpu --sim {CUDAPP_CODE_SHA}") 164 if codes["PTXC"] is None or codes["PTXC"] != codes["NVRTC"]: 165 fails.append(f"PTXC cubin {codes['PTXC']} != NVRTC cubin {codes['NVRTC']} (like-for-like broken)") 166 if not a.dry_run: 167 outs = {} 168 for arm in ARMS: 169 r = spawn(paths[arm], extra[arm] + ["--skip-run"], core, repo) 170 r.update(arm=arm, phase="control_skip_run") 171 record(r) 172 if not (r["exit"] == 1 and r.get("unwritten") == N_TOTAL and r.get("wrong") == N_TOTAL): 173 fails.append(f"{arm} --skip-run not caught: exit {r['exit']} unwritten {r.get('unwritten')}") 174 mf = os.path.join(a.out, f"maps.{arm}.txt") 175 r = spawn(paths[arm], extra[arm] + ["--maps", mf], core, repo) 176 r.update(arm=arm, phase="control_maps") 177 record(r) 178 if r["exit"] != 0 or r.get("wrong") != 0 or r.get("unwritten") != 0: 179 fails.append(f"{arm} maps run exit {r['exit']}") 180 outs[arm] = r.get("out_fnv") 181 maps = "" 182 if os.path.exists(mf): 183 with open(mf) as f: 184 maps = f.read() 185 libs = sorted({l.split()[-1] for l in maps.splitlines() if any(x in l.split()[-1] for x in FORBIDDEN)} if maps else []) 186 dev = [l for l in maps.splitlines() if "/dev/nvidia" in l] 187 if arm == "CUDAPP" and (libs or not dev): 188 fails.append(f"CUDAPP maps: NVIDIA user libraries {libs}, /dev/nvidia mappings {len(dev)}") 189 if arm != "CUDAPP" and not any("libcuda" in l for l in libs): 190 fails.append(f"{arm} maps: libcuda absent, the library check checks nothing") 191 session["out_fnv"] = outs 192 if len(set(outs.values())) != 1 or None in outs.values(): 193 fails.append(f"output differs between arms {outs}") 194 session["control_failures"] = fails 195 if fails: 196 session["verdict"] = "CONTROLS_FAILED" 197 _finish(a, session, raw) 198 sys.exit("run: controls failed: " + "; ".join(fails)) 199 200 # Cold processes run the cold path only (--warm 0), so proc_ns holds no warm builds. 201 mode = (["--build-only"] if a.dry_run else []) + ["--warm", "0"] 202 n = 0 203 for w in range(a.warmup): 204 for arm in ARMS: 205 r = spawn(paths[arm], extra[arm] + mode, core, repo) 206 r.update(arm=arm, phase="warmup", round=w) 207 record(r) 208 complete = True 209 210 def timed_out(): 211 return (mono() - t_start) / 1e9 > CAP_S 212 213 for rnd in range(a.rounds): 214 order = ORDERS[rnd % len(ORDERS)] 215 for slot, arm in enumerate(order): 216 if timed_out(): 217 complete = False 218 break 219 time.sleep(a.gap) 220 r = spawn(paths[arm], extra[arm] + mode, core, repo) 221 r.update(arm=arm, phase="measured", round=rnd, slot=slot, order="".join(x[0] for x in order)) 222 record(r) 223 n += 1 224 if not complete: 225 break 226 # Warm builds (descriptive W): separate --build-only processes, 10 builds each after the cold one. 227 for rnd in range(a.warm_rounds if complete else 0): 228 order = ORDERS[rnd % len(ORDERS)] 229 for slot, arm in enumerate(order): 230 if timed_out(): 231 complete = False 232 break 233 time.sleep(a.gap) 234 r = spawn(paths[arm], extra[arm] + ["--build-only"], core, repo) 235 r.update(arm=arm, phase="warm", round=rnd, slot=slot, order="".join(x[0] for x in order)) 236 record(r) 237 if not complete: 238 break 239 session["measured_processes"] = n 240 session["complete"] = complete 241 session["verdict"] = "DRY_RUN" if a.dry_run else ("MEASURED" if complete else "INCOMPLETE_CAP") 242 if not a.dry_run: 243 session["gpu_apps_after"] = gpu_apps() 244 _finish(a, session, raw) 245 print(json.dumps({"verdict": session["verdict"], "measured": n, "out": a.out})) 246 247 248 def _finish(a, session, raw): 249 raw.close() 250 session["finished_utc"] = utc() 251 with open(os.path.join(a.out, "session.json"), "w") as f: 252 json.dump(session, f, indent=1, sort_keys=True) 253 # Wolfram input (coldstart/analysis.wl), every time in ns. csRows: one row per measured cold process. 254 # csWarm: one row per warm-phase process with its 10 warm build times; analysis.wl takes each one's median. 255 rows, warm = [], [] 256 with open(os.path.join(a.out, "raw.jsonl")) as f: 257 for l in f: 258 r = json.loads(l) 259 g = lambda k: r.get(k, 0) 260 if r.get("phase") == "warm": 261 warm.append('{"%s",%d,%s,{%s}}' % (r["arm"], r["round"], "True" if r["exit"] == 0 else "False", 262 ",".join(str(x) for x in r.get("warm_build_ns", [])))) 263 if r.get("phase") != "measured": 264 continue 265 ok = r["exit"] == 0 and (r.get("build_only") == 1 or (r.get("wrong") == 0 and r.get("unwritten") == 0)) 266 first = g("exec_ns") + g("prep_ns") + g("build_ns") + g("open_ns") + g("load_ns") + g("data_ns") + g("run_ns") + g("check_ns") 267 rows.append('{"%s",%d,%s,%s,%d,%d,%d,%d,%d}' % ( 268 r["arm"], r["round"], "True" if ok else "False", repr(r["load1"]), g("build_ns"), 269 g("build_ns") + g("open_ns") + g("load_ns"), first, r["proc_ns"], g("exec_ns"))) 270 with open(os.path.join(a.out, "rows.wl"), "w") as f: 271 f.write("(* csRows: {arm, round, ok, load1, build, ready, firstResult, proc, exec}; ns *)\n") 272 f.write("csRows = {" + ",\n ".join(rows) + "};\n") 273 f.write("(* csWarm: {arm, round, ok, {warm build ns ...}} *)\n") 274 f.write("csWarm = {" + ",\n ".join(warm) + "};\n") 275 276 277 if __name__ == "__main__": 278 main()