interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

branch main Branches Tags History

gpu-head-to-head / bench / coremon.py

124 lines · 4593 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Per-core monitor for one timed cell (PROTOCOL.md amendment A2, void rule).
3
4 coremon.py --cpus 5-9,15-17,19 --exclude-tree PID ... --out FILE (runs until SIGTERM)
5
6Every second it appends one JSON line to FILE: the busy share of each watched core (from
7/proc/stat, integer jiffies) and, per foreign process, the CPU ticks its threads spent on each
8watched core in that second (a thread's ticks are attributed to the core it is on at the end of the
9second, field 39 of /proc/<pid>/task/<tid>/stat). Foreign = not in the excluded process trees
10(re-resolved every second, so server children count as ours) and not the nvidia-modeset kthread,
11which the session log tracks separately. On SIGTERM it appends a summary line and exits:
12 {"summary": true, "elapsed_ticks": E, "offenders": [{pid, comm, cpu, ticks}, ...]}
13An offender is a foreign process with more than 20% of one watched core over the run
14(ticks * 5 > elapsed_ticks). Exit status: 0 clean, 1 offenders (the cell is VOID).
15"""
16import argparse
17import json
18import os
19import signal
20import sys
21import time
22
23ap = argparse.ArgumentParser()
24ap.add_argument("--cpus", required=True)
25ap.add_argument("--exclude-tree", type=int, nargs="*", default=[])
26ap.add_argument("--out", required=True)
27a = ap.parse_args()
28TCK = os.sysconf("SC_CLK_TCK")
29CPUS = set()
30for part in a.cpus.split(","):
31 lo, _, hi = part.partition("-")
32 CPUS.update(range(int(lo), int(hi or lo) + 1))
33
34
35def cpustat():
36 out = {}
37 for line in open("/proc/stat"):
38 if line.startswith("cpu") and line[3].isdigit():
39 f = line.split()
40 c = int(f[0][3:])
41 if c in CPUS:
42 v = [int(x) for x in f[1:]]
43 out[c] = (sum(v), v[3] + v[4]) # total, idle + iowait
44 return out
45
46
47def threads():
48 """{(pid, tid): (comm, ppid, ticks, cpu)} for every thread on the host."""
49 out = {}
50 for d in os.listdir("/proc"):
51 if not d.isdigit():
52 continue
53 try:
54 tids = os.listdir("/proc/%s/task" % d)
55 except OSError:
56 continue
57 for t in tids:
58 try:
59 s = open("/proc/%s/task/%s/stat" % (d, t)).read()
60 except OSError:
61 continue
62 comm = s[s.index("(") + 1:s.rindex(")")]
63 f = s[s.rindex(")") + 2:].split()
64 out[(int(d), int(t))] = (comm, int(f[1]), int(f[11]) + int(f[12]), int(f[36]))
65 return out
66
67
68def tree(th, roots):
69 parent = {pid: v[1] for (pid, tid), v in th.items() if pid == tid}
70 keep, grew = set(roots), True
71 while grew:
72 grew = False
73 for pid, ppid in parent.items():
74 if ppid in keep and pid not in keep:
75 keep.add(pid)
76 grew = True
77 return keep
78
79
80stop = False
81
82
83def on_term(*_):
84 global stop
85 stop = True
86
87
88signal.signal(signal.SIGTERM, on_term)
89signal.signal(signal.SIGINT, on_term)
90roots = a.exclude_tree + [os.getpid()]
91names, total = {}, {} # (pid, cpu) -> ticks over the run
92c0, t0 = cpustat(), threads()
93start = c0
94with open(a.out, "a") as out:
95 while not stop:
96 time.sleep(1)
97 c1, t1 = cpustat(), threads()
98 mine = tree(t1, roots)
99 util = {str(c): round(100 * (1 - (c1[c][1] - c0[c][1]) / max(1, c1[c][0] - c0[c][0])), 1)
100 for c in sorted(CPUS)}
101 foreign = {}
102 for key, (comm, _, ticks, cpu) in t1.items():
103 pid = key[0]
104 if pid in mine or cpu not in CPUS or comm.startswith("nvidia-modeset") or key not in t0:
105 continue
106 d = ticks - t0[key][2]
107 if d <= 0:
108 continue
109 names[pid] = t1.get((pid, pid), (comm,))[0]
110 foreign[(pid, cpu)] = foreign.get((pid, cpu), 0) + d
111 total[(pid, cpu)] = total.get((pid, cpu), 0) + d
112 out.write(json.dumps({"t": round(time.time(), 3), "core_busy_pct": util,
113 "foreign": [{"pid": p, "comm": names[p], "cpu": c, "ticks": n}
114 for (p, c), n in sorted(foreign.items())]}) + "\n")
115 out.flush()
116 c0, t0 = c1, t1
117 end = cpustat()
118 # elapsed ticks of one core, from the kernel's own per-core counters
119 elapsed = max(end[c][0] - start[c][0] for c in CPUS)
120 off = [{"pid": p, "comm": names[p], "cpu": c, "ticks": n}
121 for (p, c), n in sorted(total.items()) if n * 5 > elapsed]
122 out.write(json.dumps({"summary": True, "elapsed_ticks": elapsed, "clk_tck": TCK,
123 "offenders": off}) + "\n")
124sys.exit(1 if off else 0)