"""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": ("= 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 (