Files

258 lines
10 KiB
Python

"""Loader and interval helpers for CUPTI trace directories written by tools/cupti-trace (libleleka_cupti_trace.so).
Pure Python (no numpy): `struct.iter_unpack` over the fixed-size record files. All times are CUPTI ns.
"""
import os
import re
import struct
from collections import namedtuple
K = namedtuple("K", "start end dev stream corr graph node name gx gy gz bx by bz sshm dshm regs launch pad")
C = namedtuple("C", "start end bytes dev stream corr graph node ckind skind dkind flags apicorr")
M = namedtuple("M", "start end bytes dev stream corr graph mkind pad")
Y = namedtuple("Y", "start end corr stream event type ctx ret")
A = namedtuple("A", "start end corr thread name ret domain pad")
G = namedtuple("G", "start end corr graph dev stream")
# struct formats mirror the C++ side's #pragma pack(1) records: 80, 56, 44, 40, 36, 32 bytes
FMT = {
"kernel.bin": ("<QQIIIIQIiiiiiiiiHBB", K),
"memcpy.bin": ("<QQQIIIIQBBBBI", C),
"memset.bin": ("<QQQIIIIHH", M),
"sync.bin": ("<QQIIIIII", Y),
"api.bin": ("<QQIIIIB3s", A),
"graph.bin": ("<QQIIII", G),
}
CKIND = {0: "?", 1: "H2D", 2: "D2H", 3: "H2A", 4: "A2H", 5: "A2A", 6: "A2D", 7: "D2A", 8: "D2D", 9: "H2H", 10: "P2P"}
MKIND = {0: "?", 1: "pageable", 2: "pinned", 3: "device", 4: "array", 5: "managed", 6: "dev-static", 7: "mgd-static"}
SYNCTYPE = {0: "?", 1: "event-sync", 2: "stream-wait-event", 3: "stream-sync", 4: "ctx-sync"}
class Trace:
def __init__(self, path, window_ms=None):
"""window_ms=(t0, t1): milliseconds from the trace window start; records outside are skipped while loading (big traces)."""
self.path = path
self._win = window_ms
self.meta = {}
text = open(os.path.join(path, "meta.txt"), errors="replace").read()
for line in text.split("\n"):
k, _, v = line.strip().partition(" ")
self.meta[k] = v
for key in ("window_start", "window_stop"): # tolerate a meta.txt damaged by a window cut at exit (old tracer)
m = re.search(key + r" (\d+)", text)
if m:
self.meta[key] = m.group(1)
self.names = {}
p = os.path.join(path, "strings.tsv")
if os.path.exists(p):
for line in open(p, encoding="utf-8", errors="replace"):
i, _, n = line.rstrip("\n").partition("\t")
if i.isdigit():
self.names[int(i)] = n
self._demangle()
self.threads = {}
p = os.path.join(path, "threads.tsv")
if os.path.exists(p):
for line in open(p):
t, _, n = line.rstrip("\n").partition("\t")
if t.isdigit():
self.threads[int(t)] = n
self._lo = self._hi = None
if window_ms is not None:
w0 = int(self.meta.get("window_start", 0))
self._lo = w0 + int(window_ms[0] * 1e6)
self._hi = w0 + int(window_ms[1] * 1e6)
self.kernels = self._load("kernel.bin")
self.copies = self._load("memcpy.bin")
self.memsets = self._load("memset.bin")
self.syncs = self._load("sync.bin")
self.apis = self._load("api.bin")
self.graphs = self._load("graph.bin")
self.t0 = int(self.meta.get("window_start", 0)) or (min([r.start for r in self.kernels] or [0]))
self.t1 = int(self.meta.get("window_stop", 0)) or (max([r.end for r in self.kernels] or [0]))
if self._lo is not None:
self.t0, self.t1 = self._lo, min(self._hi, self.t1)
self.real_off = int(self.meta.get("realtime_ns", 0)) - int(self.meta.get("cupti_ts_ns", 0))
def _demangle(self):
"""Replace mangled kernel names by c++filt output (cached next to the trace as strings.dem.tsv; needs c++filt, or WSL)."""
import subprocess
cache = os.path.join(self.path, "strings.dem.tsv")
if not os.path.exists(cache):
ids = [i for i, n in self.names.items() if n.startswith("_Z")]
if not ids:
return
text = "\n".join(self.names[i] for i in ids) + "\n"
out = None
for cmd in (["c++filt"], ["wsl", "-d", "Ubuntu", "-e", "c++filt"]):
try:
out = subprocess.run(cmd, input=text.encode(), capture_output=True, timeout=120).stdout.decode("utf-8", "replace").split("\n")
if len(out) >= len(ids):
break
except Exception:
out = None
if not out:
return
try:
with open(cache, "w", encoding="utf-8", newline="\n") as f:
for i, d in zip(ids, out):
f.write("%d\t%s\n" % (i, d.strip()))
except OSError:
for i, d in zip(ids, out):
self.names[i] = d.strip()
return
for line in open(cache, encoding="utf-8", errors="replace"):
i, _, n = line.rstrip("\n").partition("\t")
if i.isdigit() and n:
self.names[int(i)] = n
def _load(self, fn):
p = os.path.join(self.path, fn)
if not os.path.exists(p) or os.path.getsize(p) == 0:
return []
fmt, nt = FMT[fn]
sz = struct.calcsize(fmt)
with open(p, "rb") as f:
data = f.read()
data = data[: len(data) // sz * sz]
lo, hi = self._lo, self._hi
if lo is None:
return [nt(*t) for t in struct.iter_unpack(fmt, data)]
return [nt(*t) for t in struct.iter_unpack(fmt, data) if t[1] >= lo and t[0] <= hi]
def kname(self, r):
return self.names.get(r.name, "?")
def clip(self, lo, hi):
"""Keep only records overlapping [lo, hi] (CUPTI ns) and make that the window."""
for nm in ("kernels", "copies", "memsets", "syncs", "apis", "graphs"):
setattr(self, nm, [r for r in getattr(self, nm) if r.end >= lo and r.start <= hi])
self.t0, self.t1 = lo, hi
def union(intervals):
"""Merge [(a,b),...] into disjoint sorted [a,b] lists."""
out = []
for a, b in sorted(intervals):
if out and a <= out[-1][1]:
if b > out[-1][1]:
out[-1][1] = b
else:
out.append([a, b])
return out
def total(ivs):
return sum(b - a for a, b in ivs)
def intersect_total(u1, u2):
"""Total overlap of two disjoint sorted interval lists."""
i = j = 0
t = 0
while i < len(u1) and j < len(u2):
a = max(u1[i][0], u2[j][0])
b = min(u1[i][1], u2[j][1])
if b > a:
t += b - a
if u1[i][1] < u2[j][1]:
i += 1
else:
j += 1
return t
_fam_cache = {}
def _strip_templates(n):
out, depth = [], 0
args = []
cur = []
for ch in n:
if ch == "<":
depth += 1
if depth == 1:
cur = []
continue
elif ch == ">":
depth -= 1
if depth == 0:
args.append("".join(cur))
continue
if depth == 0:
out.append(ch)
elif depth >= 1:
cur.append(ch)
return "".join(out), args
def family(name):
"""Short kernel family label: namespaces, parameter lists, template arguments and a trailing _kernel are dropped; the first
template argument is kept for the kernels that are one template instantiated per format (mul_mat_q, dequant_kernel, cutlass)."""
f = _fam_cache.get(name)
if f is not None:
return f
n = name.replace("(anonymous namespace)::", "")
n = re.sub(r"^(void|std::enable_if<.*?>::type)\s+", "", n)
# parameter list: the last top-level '(' ... end
depth = 0
cut = len(n)
for k, ch in enumerate(n):
if ch == "<":
depth += 1
elif ch == ">":
depth -= 1
elif ch == "(" and depth == 0:
cut = k
break
n = n[:cut].strip()
base, args = _strip_templates(n)
base = base.strip()
if "::" in base:
base = base.split("::")[-1]
base = re.sub(r"_kernel$", "", base)
first = args[0].split(",")[0].strip() if args else ""
first = first.replace("(ggml_type)", "t")
if base in ("mul_mat_q", "dequant", "mul_mat_q_stream_k_fixup", "Kernel2") and first:
base = base + "<" + first[:60] + ">"
_fam_cache[name] = base or name
return _fam_cache[name]
def percentile(sorted_vals, p):
if not sorted_vals:
return 0.0
return sorted_vals[min(len(sorted_vals) - 1, int(p / 100.0 * len(sorted_vals)))]
def chunk_windows(full_log, trace_dir):
"""Chunk windows (ms from the trace window start) of the stamped PREFILL-PROFILE lines of a job log (<label>.full: lines
"<unix s.ms> PREFILL-PROFILE first=.. tokens=.. total_ms=.."). A chunk ends at its line's stamp and started total_ms earlier."""
import json
done = None
for cand in (trace_dir.rstrip("/\\").rsplit(".lct", 1)[0] + ".done", os.path.join(trace_dir, "done.json")):
if os.path.exists(cand):
done = json.load(open(cand))
break
if done is None: # a window that was cut at process exit (old tracer): recover the bounds from meta.txt
text = open(os.path.join(trace_dir, "meta.txt"), errors="replace").read()
m0 = re.search(r'"unix_ms_start":(\d+)', text)
m1 = re.search(r'"unix_ms_stop":(\d+)', text)
done = {"unix_ms_start": int(m0.group(1)) if m0 else 0, "unix_ms_stop": int(m1.group(1)) if m1 else 1 << 62}
t0 = done["unix_ms_start"] / 1000.0
t1 = done["unix_ms_stop"] / 1000.0
out = []
for line in open(full_log, errors="replace"):
m = re.match(r"^(\d+\.\d+) .*PREFILL-PROFILE (.*)$", line)
if not m:
continue
end = float(m.group(1))
kv = dict(x.split("=", 1) for x in m.group(2).split() if "=" in x)
tot = float(kv.get("total_ms", 0)) / 1000.0
if end < t0 or end - tot > t1:
continue
out.append({"first": kv.get("first"), "tokens": kv.get("tokens"), "total_ms": kv.get("total_ms"),
"t0_ms": (end - tot - t0) * 1000.0, "t1_ms": (end - t0) * 1000.0, "kv": kv})
return out