#!/usr/bin/env python3 """State sampler for the baseline-pair A/B (ours against vanilla Strata). Stdlib only, read-only: it never writes to /proc or /sys. python3 -I baseline-sampler.py OUT.jsonl [--full-s 15] [--fast-s 2] [--once] One JSON object per line, two kinds: kind=full every --full-s seconds (and at start): uptime, loadavg, PSI, per-CPU scaling_cur_freq (kHz) and utilisation, cpufreq governor / driver / EPP / boost, /proc/meminfo (AnonHugePages, HugePages_*, MemAvailable, Cached, Shmem ...), THP enabled / defrag / khugepaged knobs, /proc/vmstat THP + compaction + allocstall counters, /proc/buddyinfo (raw), nvidia-smi (SM / mem clocks, temperature, power, pstate, throttle reasons, utilisation, memory), for every process that uses the GPU: Cpus_allowed_list, smaps_rollup (Rss, Pss, AnonHugePages, ...), every thread (tid, comm, last cpu, cpu ticks, allowed list), and the top 5 other CPU consumers of the interval (so a foreign CPU job is visible). kind=fast every --fast-s seconds: per-CPU scaling_cur_freq and utilisation only (cheap, to see the clocks of the cores in use during a decode window). --once writes a single full sample and exits (the pre-run state record). SIGTERM / SIGINT stop it cleanly. """ import json, os, signal, subprocess, sys, time OUT = sys.argv[1] ARGS = sys.argv[2:] def opt(name, default): return float(ARGS[ARGS.index(name) + 1]) if name in ARGS else default FULL_S, FAST_S, ONCE = opt("--full-s", 15.0), opt("--fast-s", 2.0), "--once" in ARGS CPUS = sorted(int(d[3:]) for d in os.listdir("/sys/devices/system/cpu") if d.startswith("cpu") and d[3:].isdigit()) MEM_KEYS = {"MemTotal", "MemFree", "MemAvailable", "Cached", "Buffers", "Active(file)", "Inactive(file)", "Shmem", "ShmemHugePages", "AnonPages", "AnonHugePages", "FileHugePages", "FilePmdMapped", "Mlocked", "Unevictable", "Dirty", "SwapFree", "HugePages_Total", "HugePages_Free", "HugePages_Rsvd", "HugePages_Surp"} VM_PREFIX = ("thp_", "compact_", "allocstall", "pgmajfault", "pgfault", "pswpin", "pswpout", "pgscan_direct", "pgscan_kswapd", "pgsteal_direct", "pgsteal_kswapd", "numa_", "kswapd_low_wmark") STOP = False def _stop(*_): global STOP STOP = True signal.signal(signal.SIGTERM, _stop) signal.signal(signal.SIGINT, _stop) def rd(path, default=None): try: with open(path) as f: return f.read().strip() except Exception: return default def read_stat(): cpu, total = {}, {} try: for ln in open("/proc/stat"): if ln.startswith("cpu") and ln[3:4].isdigit(): p = ln.split() v = [int(x) for x in p[1:9]] idle = v[3] + v[4] cpu[int(p[0][3:])] = (sum(v), idle) except Exception: pass return cpu def freqs(): out = [] for c in CPUS: v = rd("/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq" % c) out.append(int(v) if v and v.isdigit() else None) return out def util(prev, cur): if prev is None: return None out = [] for c in CPUS: if c in prev and c in cur: dt, di = cur[c][0] - prev[c][0], cur[c][1] - prev[c][1] out.append(round(100.0 * (dt - di) / dt, 1) if dt > 0 else None) else: out.append(None) return out def kv_file(path, keys=None, prefix=None): d = {} try: for ln in open(path): p = ln.replace(":", " ").split() if len(p) < 2: continue k = p[0] if (keys and k in keys) or (prefix and k.startswith(prefix)): d[k] = int(p[1]) except Exception: pass return d def nvsmi(): q = "temperature.gpu,clocks.sm,clocks.mem,power.draw,power.limit,utilization.gpu,memory.used,pstate,%s" names = "temp_c sm_mhz mem_mhz power_w power_limit_w util_pct mem_used_mib pstate throttle".split() for reasons in ("clocks_event_reasons.active", "clocks_throttle_reasons.active"): try: r = subprocess.run(["nvidia-smi", "--query-gpu=" + q % reasons, "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8) if r.returncode == 0 and r.stdout.strip(): return dict(zip(names, [x.strip() for x in r.stdout.strip().splitlines()[0].split(",")])) except Exception: pass return {} def gpu_pids(): try: r = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8) return [int(l.split(",")[0]) for l in r.stdout.strip().splitlines() if l.strip()] except Exception: return [] def proc_info(pid): d = {"pid": pid, "exe": os.path.basename(os.readlink("/proc/%d/exe" % pid)) if os.path.exists("/proc/%d/exe" % pid) else None} st = rd("/proc/%d/status" % pid, "") for ln in st.splitlines(): if ln.startswith("Cpus_allowed_list:"): d["allowed"] = ln.split(":", 1)[1].strip() elif ln.startswith("Threads:"): d["threads"] = int(ln.split(":", 1)[1]) d["smaps_rollup_kb"] = kv_file("/proc/%d/smaps_rollup" % pid, keys={"Rss", "Pss", "Pss_Anon", "Pss_File", "Pss_Shmem", "Shared_Clean", "Shared_Dirty", "Private_Clean", "Private_Dirty", "Anonymous", "AnonHugePages", "ShmemPmdMapped", "FilePmdMapped", "Shared_Hugetlb", "Private_Hugetlb", "Swap", "Locked"}) ths = [] try: for t in os.listdir("/proc/%d/task" % pid): s = rd("/proc/%d/task/%s/stat" % (pid, t)) if not s: continue comm = s[s.index("(") + 1:s.rindex(")")] f = s[s.rindex(")") + 2:].split() # f[0]=state, utime=f[11], stime=f[12], processor=f[36] allowed = None for ln in (rd("/proc/%d/task/%s/status" % (pid, t), "") or "").splitlines(): if ln.startswith("Cpus_allowed_list:"): allowed = ln.split(":", 1)[1].strip() break ths.append([int(t), comm, int(f[36]), int(f[11]) + int(f[12]), allowed]) except Exception: pass d["thr"] = ths return d def all_proc_ticks(): out = {} for p in os.listdir("/proc"): if p.isdigit(): s = rd("/proc/%s/stat" % p) if s: try: comm = s[s.index("(") + 1:s.rindex(")")] f = s[s.rindex(")") + 2:].split() out[int(p)] = (comm, int(f[11]) + int(f[12])) except Exception: pass return out def full(prev_stat, prev_ticks, gpids_hint): now = read_stat() ticks = all_proc_ticks() s = {"kind": "full", "t": round(time.time(), 3), "uptime_s": float(rd("/proc/uptime", "0 0").split()[0]), "loadavg": rd("/proc/loadavg", "").split()[:3]} s["cpu_khz"], s["cpu_util"] = freqs(), util(prev_stat, now) s["cpufreq"] = {"governor": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"), "driver": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver"), "epp": rd("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"), "boost": rd("/sys/devices/system/cpu/cpufreq/boost"), "max_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"), "min_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"), "pstate_status": rd("/sys/devices/system/cpu/amd_pstate/status")} s["meminfo_kb"] = kv_file("/proc/meminfo", keys=MEM_KEYS) thp = "/sys/kernel/mm/transparent_hugepage/" s["thp"] = {"enabled": rd(thp + "enabled"), "defrag": rd(thp + "defrag"), "shmem_enabled": rd(thp + "shmem_enabled"), "khugepaged_defrag": rd(thp + "khugepaged/defrag"), "khugepaged_pages_collapsed": rd(thp + "khugepaged/pages_collapsed"), "nr_hugepages": rd("/proc/sys/vm/nr_hugepages")} s["vmstat"] = {} try: for ln in open("/proc/vmstat"): k, v = ln.split() if k.startswith(VM_PREFIX): s["vmstat"][k] = int(v) except Exception: pass s["buddy"] = rd("/proc/buddyinfo") s["psi"] = {n: (rd("/proc/pressure/" + n, "").splitlines() or [None])[0] for n in ("cpu", "memory", "io")} s["gpu"] = nvsmi() pids = gpu_pids() s["gpu_pids"] = pids s["procs"] = [proc_info(p) for p in pids if os.path.exists("/proc/%d" % p)] if prev_ticks is not None: d = [] for p, (comm, t) in ticks.items(): if p in pids or p == os.getpid(): continue pt = prev_ticks.get(p) if pt and t - pt[1] > 0: d.append((t - pt[1], p, comm)) d.sort(reverse=True) s["others_top"] = [[p, c, tk] for tk, p, c in d[:5]] return s, now, ticks def main(): prev_stat, prev_ticks = read_stat(), None out = open(OUT, "a", buffering=1) nxt_full, nxt_fast = 0.0, 0.0 while not STOP: t = time.time() if t >= nxt_full: s, prev_stat, prev_ticks = full(prev_stat, prev_ticks, None) out.write(json.dumps(s, separators=(",", ":")) + "\n") nxt_full = t + FULL_S nxt_fast = t + FAST_S if ONCE: break elif t >= nxt_fast: now = read_stat() out.write(json.dumps({"kind": "fast", "t": round(t, 3), "cpu_khz": freqs(), "cpu_util": util(prev_stat, now)}, separators=(",", ":")) + "\n") prev_stat = now nxt_fast = t + FAST_S time.sleep(max(0.05, min(nxt_full, nxt_fast) - time.time())) out.close() main()