From 0841f7cc0f9cdbc89395d0a9a6b0bc68a7d58159 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 01:11:40 +0200 Subject: [PATCH 1/8] tools/cupti-trace: CUPTI Activity tracer (injectable, trigger-file windows) + scripts/profile loader and single-trace report Co-Authored-By: Claude Sonnet 5.5 --- scripts/profile/lct.py | 155 +++++++ scripts/profile/lct_report.py | 196 ++++++++ tools/cupti-trace/.gitignore | 2 + tools/cupti-trace/build.sh | 12 + tools/cupti-trace/cupti_trace.cpp | 720 +++++++++++++++++++++++++++++ tools/cupti-trace/test/test_app.cu | 42 ++ 6 files changed, 1127 insertions(+) create mode 100644 scripts/profile/lct.py create mode 100644 scripts/profile/lct_report.py create mode 100644 tools/cupti-trace/.gitignore create mode 100644 tools/cupti-trace/build.sh create mode 100644 tools/cupti-trace/cupti_trace.cpp create mode 100644 tools/cupti-trace/test/test_app.cu diff --git a/scripts/profile/lct.py b/scripts/profile/lct.py new file mode 100644 index 00000000..a306b1b5 --- /dev/null +++ b/scripts/profile/lct.py @@ -0,0 +1,155 @@ +"""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": ("= 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 family(name): + """Short kernel family label: strip parameter lists, template arguments and namespaces.""" + f = _fam_cache.get(name) + if f is not None: + return f + n = name + depth = 0 + cut = len(n) + for i, ch in enumerate(n): + if ch == "<": + depth += 1 + elif ch == ">": + depth -= 1 + elif ch == "(" and depth == 0: + cut = i + break + n = n[:cut] + out, depth = [], 0 + for ch in n: + if ch == "<": + depth += 1 + elif ch == ">": + depth -= 1 + elif depth == 0: + out.append(ch) + n = "".join(out).strip() + n = re.sub(r"^void\s+", "", n) + if "::" in n: + n = n.split("::")[-1] + n = re.sub(r"\s+", " ", n) + _fam_cache[name] = n 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)))] diff --git a/scripts/profile/lct_report.py b/scripts/profile/lct_report.py new file mode 100644 index 00000000..9ab8ca55 --- /dev/null +++ b/scripts/profile/lct_report.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Single-trace report of a CUPTI window (tools/cupti-trace output directory). + + python3 scripts/profile/lct_report.py [--top N] [--gap-us 50] [--t0 MS --t1 MS] (MS relative to the window start) + +Sections: window summary; per-kernel-family time; copies (kind, memory kinds, sizes, achieved GB/s); compute-stream idle gaps +with the host-side reason (blocking sync call, copy in flight, launch-bound); copy/compute overlap; API time by call. +""" +import argparse +import bisect +import os +import sys +from collections import defaultdict + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lct as L + + +def fmtb(n): + for u, d in (("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)): + if n >= d: + return "%.1f%s" % (n / d, u) + return "%dB" % n + + +def bucket(b): + for u, d in (("1M+", 1 << 20), ("64K-1M", 1 << 16), ("4K-64K", 1 << 12)): + if b >= d: + return u + return "<4K" + + +def pick_compute_stream(tr): + t = defaultdict(int) + for k in tr.kernels: + t[(k.dev, k.stream)] += k.end - k.start + return max(t.items(), key=lambda kv: kv[1])[0] if t else None + + +def gaps_with_reasons(tr, stream, min_gap_ns): + """Idle gaps of one stream between consecutive kernels, each with the host-side reason.""" + ks = sorted((k for k in tr.kernels if (k.dev, k.stream) == stream), key=lambda k: k.start) + apis = sorted(tr.apis, key=lambda a: a.start) + starts = [a.start for a in apis] + copies_u = L.union([(c.start, c.end) for c in tr.copies if (c.dev, c.stream) != stream]) + res = [] + for prev, nxt in zip(ks, ks[1:]): + a, b = prev.end, nxt.start + if b - a < min_gap_ns: + continue + best, best_ov, launch_cover = None, 0, 0 + i = max(0, bisect.bisect_left(starts, a - 50_000_000)) + while i < len(apis) and apis[i].start < b: + x = apis[i] + i += 1 + ov = min(b, x.end) - max(a, x.start) + if ov <= 0: + continue + nm = tr.names.get(x.name, "?") + if "Launch" in nm or "Graph" in nm: + launch_cover += ov + if any(s in nm for s in ("Synchronize", "Wait", "MemcpyDtoH", "MemcpyHtoD_v2", "cudaMemcpy_")) and ov > best_ov: + best, best_ov = (nm, x.thread), ov + cov = L.intersect_total([[a, b]], copies_u) + if best and best_ov > 0.5 * (b - a): + why = "host-sync %s (thr %s)" % (best[0], tr.threads.get(best[1], best[1])) + elif cov > 0.5 * (b - a): + why = "copy-in-flight (other stream)" + elif launch_cover > 0.3 * (b - a): + why = "launch-bound (cpu issuing)" + elif best: + why = "host-sync(partial) %s" % best[0] + else: + why = "unattributed (cpu between calls / no api record)" + res.append((a, b, why, prev, nxt)) + return res + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("dir") + ap.add_argument("--top", type=int, default=25) + ap.add_argument("--gap-us", type=float, default=50) + ap.add_argument("--t0", type=float, default=None) + ap.add_argument("--t1", type=float, default=None) + ap.add_argument("--stream", type=int, default=None, help="compute stream id (default: busiest)") + a = ap.parse_args() + tr = L.Trace(a.dir) + if a.t0 is not None or a.t1 is not None: + lo = tr.t0 + int((a.t0 or 0) * 1e6) + hi = tr.t0 + int(a.t1 * 1e6) if a.t1 is not None else tr.t1 + tr.clip(lo, hi) + W = (tr.t1 - tr.t0) / 1e6 + print("== window %s: %.1f ms, label=%r reason=%s" % (a.dir, W, tr.meta.get("label"), tr.meta.get("stop_reason"))) + print(" kernels %d, copies %d, memsets %d, syncs %d, api %d, graphs %d; unix start %.3f" % ( + len(tr.kernels), len(tr.copies), len(tr.memsets), len(tr.syncs), len(tr.apis), len(tr.graphs), (tr.t0 + tr.real_off) / 1e9)) + ku = L.union([(k.start, k.end) for k in tr.kernels]) + print(" GPU kernel-busy (any stream): %.1f ms = %.1f%% of window" % (L.total(ku) / 1e6, 100 * L.total(ku) / max(1, tr.t1 - tr.t0))) + streams = defaultdict(lambda: [0, 0]) + for k in tr.kernels: + s = streams[(k.dev, k.stream)] + s[0] += 1 + s[1] += k.end - k.start + for key, (n, t) in sorted(streams.items(), key=lambda kv: -kv[1][1])[:8]: + print(" stream dev%d/%d: %d kernels, %.1f ms of kernel time" % (key[0], key[1], n, t / 1e6)) + + print("\n== kernel families (sum of kernel durations; concurrent kernels overlap)") + fam = defaultdict(lambda: [0, 0]) + for k in tr.kernels: + f = fam[L.family(tr.kname(k))] + f[0] += 1 + f[1] += k.end - k.start + tot = sum(v[1] for v in fam.values()) or 1 + print(" %-52s %8s %10s %9s %6s" % ("family", "count", "total ms", "mean us", "share")) + for n, (c, t) in sorted(fam.items(), key=lambda kv: -kv[1][1])[: a.top]: + print(" %-52s %8d %10.2f %9.1f %5.1f%%" % (n[:52], c, t / 1e6, t / 1e3 / c, 100 * t / tot)) + + print("\n== copies") + grp = defaultdict(lambda: [0, 0, 0]) + for c in tr.copies: + g = grp[(L.CKIND.get(c.ckind, c.ckind), L.MKIND.get(c.skind, c.skind), L.MKIND.get(c.dkind, c.dkind), c.dev, c.stream)] + g[0] += 1 + g[1] += c.bytes + g[2] += c.end - c.start + print(" %-38s %7s %10s %9s %9s" % ("kind src->dst dev/stream", "count", "MB", "busy ms", "GB/s")) + for key, (n, b, t) in sorted(grp.items(), key=lambda kv: -kv[1][1])[:12]: + print(" %-38s %7d %10.1f %9.2f %9.1f" % ("%s %s->%s d%d/s%d" % key, n, b / 1e6, t / 1e6, b / max(1, t))) + h2d = [c for c in tr.copies if c.ckind == 1] + if h2d: + sizes = sorted(c.bytes for c in h2d) + gbs = sorted(c.bytes / max(1, c.end - c.start) for c in h2d if c.bytes >= 65536) + print(" H2D: %d copies, %.1f MB; size p10/p50/p90/max = %s / %s / %s / %s" % ( + len(h2d), sum(sizes) / 1e6, fmtb(L.percentile(sizes, 10)), fmtb(L.percentile(sizes, 50)), fmtb(L.percentile(sizes, 90)), fmtb(sizes[-1]))) + if gbs: + print(" H2D copies >= 64 KiB: GB/s p10/p50/p90 = %.1f / %.1f / %.1f (per copy, own start..end)" % ( + L.percentile(gbs, 10), L.percentile(gbs, 50), L.percentile(gbs, 90))) + hu = L.union([(c.start, c.end) for c in h2d]) + print(" H2D union busy %.1f ms (%.1f%% of window), aggregate %.1f GB/s over the union" % ( + L.total(hu) / 1e6, 100 * L.total(hu) / max(1, tr.t1 - tr.t0), sum(c.bytes for c in h2d) / max(1, L.total(hu)))) + buckets = defaultdict(lambda: [0, 0]) + for c in h2d: + b = buckets[bucket(c.bytes)] + b[0] += 1 + b[1] += c.bytes + print(" H2D size histogram (count): " + ", ".join("%s:%d" % (k, v[0]) for k, v in sorted(buckets.items(), key=lambda kv: -kv[1][1]))) + + cs = None + if a.stream is not None: + cs = next((s for s in streams if s[1] == a.stream), None) + cs = cs or pick_compute_stream(tr) + if cs: + print("\n== compute stream dev%d/%d idle gaps >= %.0f us" % (cs[0], cs[1], a.gap_us)) + ks = [k for k in tr.kernels if (k.dev, k.stream) == cs] + span = max(k.end for k in ks) - min(k.start for k in ks) + busy = L.total(L.union([(k.start, k.end) for k in ks])) + print(" span %.1f ms, busy %.1f ms, idle %.1f ms (%.1f%%)" % (span / 1e6, busy / 1e6, (span - busy) / 1e6, 100 * (span - busy) / max(1, span))) + gp = gaps_with_reasons(tr, cs, a.gap_us * 1e3) + why = defaultdict(lambda: [0, 0]) + for g in gp: + w = why[g[2].split("(thr")[0].strip()] + w[0] += 1 + w[1] += g[1] - g[0] + print(" gaps >= %.0f us: %d, total %.1f ms" % (a.gap_us, len(gp), sum(g[1] - g[0] for g in gp) / 1e6)) + for r, (n, t) in sorted(why.items(), key=lambda kv: -kv[1][1])[:10]: + print(" %-60s %6d gaps %9.2f ms" % (r[:60], n, t / 1e6)) + print(" 10 longest gaps (ms from window start: length, reason, prev kernel -> next kernel):") + for g in sorted(gp, key=lambda g: g[0] - g[1])[:10]: + print(" @%9.2f %7.2f ms %s | %s -> %s" % ((g[0] - tr.t0) / 1e6, (g[1] - g[0]) / 1e6, g[2][:60], L.family(tr.kname(g[3]))[:28], L.family(tr.kname(g[4]))[:28])) + cu = L.union([(c.start, c.end) for c in tr.copies if c.ckind in (1, 2)]) + cku = L.union([(k.start, k.end) for k in ks]) + if cu: + ov = L.intersect_total(cu, cku) + print(" copy/compute overlap: %.1f%% of H2D+D2H copy-busy time runs while the compute stream executes a kernel (%.1f of %.1f ms)" % ( + 100 * ov / max(1, L.total(cu)), ov / 1e6, L.total(cu) / 1e6)) + print(" copy-only time (compute stream idle): %.1f ms" % ((L.total(cu) - ov) / 1e6)) + + print("\n== API/sync (CPU) time by call (sum of call durations)") + ap_ = defaultdict(lambda: [0, 0, 0]) + for x in tr.apis: + g = ap_[tr.names.get(x.name, "?")] + g[0] += 1 + g[1] += x.end - x.start + g[2] = max(g[2], x.end - x.start) + for n, (c, t, mx) in sorted(ap_.items(), key=lambda kv: -kv[1][1])[:15]: + print(" %-44s %8d calls %10.2f ms mean %8.1f us max %8.1f us" % (n[:44], c, t / 1e6, t / 1e3 / c, mx / 1e3)) + sy = defaultdict(lambda: [0, 0]) + for y in tr.syncs: + g = sy[L.SYNCTYPE.get(y.type, y.type)] + g[0] += 1 + g[1] += y.end - y.start + for n, (c, t) in sy.items(): + print(" sync activity %-22s %6d %9.2f ms" % (n, c, t / 1e6)) + + +if __name__ == "__main__": + main() diff --git a/tools/cupti-trace/.gitignore b/tools/cupti-trace/.gitignore new file mode 100644 index 00000000..79bb6bcc --- /dev/null +++ b/tools/cupti-trace/.gitignore @@ -0,0 +1,2 @@ +libleleka_cupti_trace.so +test/test_app diff --git a/tools/cupti-trace/build.sh b/tools/cupti-trace/build.sh new file mode 100644 index 00000000..cf01481a --- /dev/null +++ b/tools/cupti-trace/build.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Build the CUPTI tracer. Needs the CUDA toolkit headers (cuda.h not required) and the CUPTI redist (include/, lib/). +# CUPTI=~/cupti ./build.sh -> libleleka_cupti_trace.so (RUNPATH: the build's CUPTI lib dir, ../cupti/lib, ~/work/cupti/lib) +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +CUPTI=${CUPTI:-$HOME/cupti} +CUDA=${CUDA:-$HOME/cuda-toolkits/13.2.2} +out=${1:-$here/libleleka_cupti_trace.so} +g++ -O2 -std=c++17 -fPIC -shared -Wall -Wextra -Wno-unused-parameter -I"$CUPTI/include" -I"$CUDA/include" \ + "$here/cupti_trace.cpp" -o "$out" -L"$CUPTI/lib" -lcupti -lpthread \ + -Wl,-rpath,"$CUPTI/lib" -Wl,-rpath,'$ORIGIN/../cupti/lib' -Wl,-rpath,'/home/para/work/cupti/lib' -Wl,--enable-new-dtags +echo "built $out" diff --git a/tools/cupti-trace/cupti_trace.cpp b/tools/cupti-trace/cupti_trace.cpp new file mode 100644 index 00000000..e85fe183 --- /dev/null +++ b/tools/cupti-trace/cupti_trace.cpp @@ -0,0 +1,720 @@ +// cupti_trace.cpp - thin CUPTI Activity tracer, loadable into ANY CUDA process without modifying it. +// +// CUDA_INJECTION64_PATH=/path/libleleka_cupti_trace.so (the driver loads it at cuInit and calls InitializeInjection) +// LD_PRELOAD=/path/libleleka_cupti_trace.so (the constructor does the same) +// libcupti.so.13 is found through the library's RUNPATH (see build.sh) or LD_LIBRARY_PATH. Tracing is OFF until a window +// is triggered; armed-but-idle cost is one thread that stat()s the trigger path every 50 ms. +// +// Windows (any number per process, one at a time; each writes its own output directory): +// 1. Trigger file (long-lived daemons). LELEKA_CUPTI_TRIGGER= (alias LCT_TRIGGER). Write one JSON line atomically +// (tmp + rename): {"seconds": 8, "out": "/abs/prefix", "label": "free text"} +// The library renames it to .active, records until `seconds` (hard cap LCT_MAX_SECONDS, default 120) or until +// .stop exists, writes .lct/ (the data) and .done (JSON: bytes, counts, unix-ms start/stop), and renames +// .active to .done. A trigger that arrives during a window is left in place and taken after it ends. +// A failure to initialise CUPTI never affects the process: .error gets the reason. +// 2. Environment (one window): LCT_START_AFTER_S=, LCT_START_FILE=, +// LCT_START_API=: (Nth call), LCT_START_SYM=:, +// LCT_DURATION_S, LCT_STOP_FILE, LCT_STOP_API=: (counted after the start). With none of the start triggers and +// no LELEKA_CUPTI_TRIGGER, recording starts at once. Output: $LCT_OUT/lct./. +// 3. LCT_SIGNALS=1: SIGUSR1 starts and SIGUSR2 stops the environment window. +// Other: LCT_API=0 (no API records) | 1 (selected: launch/copy/sync/event/graph/alloc, default) | 2 (all); +// LCT_BUF_MB (activity buffer, default 32); LCT_MAX_MB (cap per window, default 3072); LCT_VERBOSE=1. +// +// Window directory (fixed-size little-endian records, one file per kind, multi-MB stdio buffers, no per-record syscalls): +// kernel.bin CONCURRENT_KERNEL incl. graph-launched (graphId/graphNodeId) KRec memcpy.bin MEMCPY + MEMCPY2 CRec +// memset.bin MEMSET MRec sync.bin SYNCHRONIZATION (stream/event/context sync, stream wait) YRec +// api.bin DRIVER/RUNTIME API ARec graph.bin GRAPH_TRACE GRec strings.tsv idname threads.tsv tidcomm +// meta.txt clocks (CUPTI ns <-> CLOCK_REALTIME), label, window marks. +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma pack(push, 1) +struct KRec { // 80 bytes + uint64_t start, end; + uint32_t dev, stream, corr, graphId; + uint64_t graphNodeId; + uint32_t nameId; + int32_t gx, gy, gz, bx, by, bz; + int32_t sshm, dshm; + uint16_t regs; + uint8_t launchType, pad; +}; +struct CRec { // 56 bytes + uint64_t start, end, bytes; + uint32_t dev, stream, corr, graphId; + uint64_t graphNodeId; + uint8_t copyKind, srcKind, dstKind, flags; + uint32_t apiCorr; +}; +struct MRec { // 48 bytes + uint64_t start, end, bytes; + uint32_t dev, stream, corr, graphId; + uint16_t memKind, pad; +}; +struct YRec { // 40 bytes + uint64_t start, end; + uint32_t corr, stream, eventId, type, ctx, ret; +}; +struct ARec { // 40 bytes + uint64_t start, end; + uint32_t corr, thread, nameId, ret; + uint8_t domain, pad[3]; +}; +struct GRec { // 40 bytes + uint64_t start, end; + uint32_t corr, graphId, dev, stream; +}; +#pragma pack(pop) + +namespace { + +struct Out { + FILE* f = nullptr; + std::vector buf; + void open(const std::string& path, size_t bytes) { + f = fopen(path.c_str(), "wb"); + if (f) { + buf.assign(bytes, 0); + setvbuf(f, buf.data(), _IOFBF, bytes); + } + } + void put(const void* p, size_t n) { + if (f) fwrite(p, 1, n, f); + } + void flush() { + if (f) fflush(f); + } + void close() { + if (f) fclose(f); + f = nullptr; + std::vector().swap(buf); + } +}; + +struct Window { + std::string out; // directory + std::string prefix; // for .done ("" for env windows) + std::string label, trigger; + double seconds = -1; + bool fromTrigger = false; +}; + +struct State { + std::mutex mu; // protects the writers, string table and counters + Out kern, copy, mset, sync, api, graph, strs, meta; + std::unordered_map strId; + std::unordered_map apiName[2]; + bool winOpen = false; + uint64_t bytesOut = 0, maxBytes = 0; + uint64_t counts[6] = {0, 0, 0, 0, 0, 0}; + std::atomic inited{false}, recording{false}, finished{false}, cuptiOk{false}; + std::atomic reqStart{false}, reqStop{false}; + std::atomic startCnt{0}, stopCnt{0}, startTarget{0}, stopTarget{0}, symCnt{0}, symTarget{0}; + std::string symSubstr; + std::vector startIds, stopIds; + CUpti_SubscriberHandle sub = nullptr; + uint64_t winStart = 0; + uint64_t offReal = 0; // CLOCK_REALTIME ns - CUPTI ns + int apiLevel = 1; + bool verbose = false; + size_t bufBytes = 32u << 20; + int winSeq = 0; + std::string trigger, errPath; +}; +State S; + +const char* envs(const char* k) { + const char* v = getenv(k); + return (v && *v) ? v : nullptr; +} + +#define CK(call) \ + do { \ + CUptiResult _r = (call); \ + if (_r != CUPTI_SUCCESS) { \ + const char* _m = nullptr; \ + cuptiGetResultString(_r, &_m); \ + fprintf(stderr, "[lct] %s failed: %s (%d)\n", #call, _m ? _m : "?", (int)_r); \ + } \ + } while (0) + +void writeFile(const std::string& path, const std::string& body) { + FILE* f = fopen(path.c_str(), "w"); + if (!f) return; + fwrite(body.data(), 1, body.size(), f); + fclose(f); +} + +void mkdirs(const std::string& p) { + for (size_t i = 1; i <= p.size(); ++i) + if (i == p.size() || p[i] == '/') mkdir(p.substr(0, i).c_str(), 0755); +} + +uint32_t intern(const std::string& s) { // caller holds S.mu + auto it = S.strId.find(s); + if (it != S.strId.end()) return it->second; + uint32_t id = (uint32_t)S.strId.size() + 1; + S.strId.emplace(s, id); + std::string line = std::to_string(id) + "\t" + s + "\n"; + S.strs.put(line.data(), line.size()); + return id; +} + +uint32_t apiNameId(int domain, uint32_t cbid) { // caller holds S.mu + auto& m = S.apiName[domain]; + auto it = m.find(cbid); + if (it != m.end()) return it->second; + const char* name = nullptr; + cuptiGetCallbackName(domain == 0 ? CUPTI_CB_DOMAIN_DRIVER_API : CUPTI_CB_DOMAIN_RUNTIME_API, cbid, &name); + uint32_t id = intern(name ? name : ("cbid" + std::to_string(cbid))); + m[cbid] = id; + return id; +} + +void note(const char* fmt, ...) __attribute__((format(printf, 1, 2))); +void note(const char* fmt, ...) { // caller holds S.mu or is single-threaded + char b[768]; + va_list ap; + va_start(ap, fmt); + vsnprintf(b, sizeof b, fmt, ap); + va_end(ap); + S.meta.put(b, strlen(b)); + if (S.verbose) fputs(b, stderr); +} + +void handleRecord(CUpti_Activity* rec) { // caller holds S.mu, S.winOpen + switch (rec->kind) { + case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL: + case CUPTI_ACTIVITY_KIND_KERNEL: { + auto* k = (CUpti_ActivityKernel11*)rec; + KRec r{}; + r.start = k->start; r.end = k->end; r.dev = k->deviceId; r.stream = k->streamId; r.corr = k->correlationId; + r.graphId = k->graphId; r.graphNodeId = k->graphNodeId; + r.nameId = intern(k->name ? k->name : "?"); + r.gx = k->gridX; r.gy = k->gridY; r.gz = k->gridZ; r.bx = k->blockX; r.by = k->blockY; r.bz = k->blockZ; + r.sshm = k->staticSharedMemory; r.dshm = k->dynamicSharedMemory; r.regs = k->registersPerThread; + r.launchType = k->launchType; + S.kern.put(&r, sizeof r); S.counts[0]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_MEMCPY: { + auto* m = (CUpti_ActivityMemcpy6*)rec; + CRec r{}; + r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId; + r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId; + r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = m->flags; + r.apiCorr = m->runtimeCorrelationId; + S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_MEMCPY2: { + auto* m = (CUpti_ActivityMemcpyPtoP4*)rec; + CRec r{}; + r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId; + r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId; + r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = 0x80; + r.apiCorr = 0; + S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_MEMSET: { + auto* m = (CUpti_ActivityMemset4*)rec; + MRec r{}; + r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId; + r.corr = m->correlationId; r.graphId = m->graphId; r.memKind = m->memoryKind; + S.mset.put(&r, sizeof r); S.counts[2]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_SYNCHRONIZATION: { + auto* m = (CUpti_ActivitySynchronization2*)rec; + YRec r{}; + r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.stream = m->streamId; r.eventId = m->cudaEventId; + r.type = (uint32_t)m->type; r.ctx = m->contextId; r.ret = m->returnValue; + S.sync.put(&r, sizeof r); S.counts[3]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_DRIVER: + case CUPTI_ACTIVITY_KIND_RUNTIME: { + auto* m = (CUpti_ActivityAPI*)rec; + ARec r{}; + r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.thread = m->threadId; + r.domain = rec->kind == CUPTI_ACTIVITY_KIND_DRIVER ? 0 : 1; + r.nameId = apiNameId(r.domain, m->cbid); + r.ret = m->returnValue; + S.api.put(&r, sizeof r); S.counts[4]++; S.bytesOut += sizeof r; + break; + } + case CUPTI_ACTIVITY_KIND_GRAPH_TRACE: { + auto* m = (CUpti_ActivityGraphTrace2*)rec; + GRec r{}; + r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.graphId = m->graphId; r.dev = m->deviceId; + r.stream = m->streamId; + S.graph.put(&r, sizeof r); S.counts[5]++; S.bytesOut += sizeof r; + break; + } + default: + break; + } +} + +void CUPTIAPI bufferRequested(uint8_t** buffer, size_t* size, size_t* maxNumRecords) { + *size = S.bufBytes; + *maxNumRecords = 0; + void* p = nullptr; + if (posix_memalign(&p, 8, *size) != 0) p = nullptr; + *buffer = (uint8_t*)p; +} + +void CUPTIAPI bufferCompleted(CUcontext, uint32_t, uint8_t* buffer, size_t, size_t validSize) { + if (validSize > 0) { + std::lock_guard g(S.mu); + if (S.winOpen) { + CUpti_Activity* rec = nullptr; + while (cuptiActivityGetNextRecord(buffer, validSize, &rec) == CUPTI_SUCCESS) + if (S.bytesOut < S.maxBytes) handleRecord(rec); + size_t dropped = 0; + cuptiActivityGetNumDroppedRecords(nullptr, 0, &dropped); + if (dropped) note("dropped_records %zu\n", dropped); + } + } + free(buffer); +} + +bool selectedApi(const char* n) { + static const char* const want[] = {"Launch", "Memcpy", "Memset", "Synchronize", "Event", "StreamWait", "Graph", "MemAlloc", + "MemFree", "MemHost", "StreamCreate", "StreamDestroy", "StreamBeginCapture", + "StreamEndCapture", "StreamWriteValue", "StreamWaitValue", "MemMap", "Malloc", "Free"}; + for (const char* w : want) + if (strstr(n, w)) return !strstr(n, "Query"); // polling loops would drown everything + return false; +} + +void enableKinds(bool on) { + const CUpti_ActivityKind kinds[] = {CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL, CUPTI_ACTIVITY_KIND_MEMCPY, + CUPTI_ACTIVITY_KIND_MEMCPY2, CUPTI_ACTIVITY_KIND_MEMSET, + CUPTI_ACTIVITY_KIND_SYNCHRONIZATION}; + // GRAPH_TRACE records a graph launch as ONE item and hides its nodes (CUPTI docs): opt-in only (LCT_GRAPH_TRACE=1). + if (envs("LCT_GRAPH_TRACE")) { + CUptiResult r = on ? cuptiActivityEnable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE) : cuptiActivityDisable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE); + (void)r; + } + for (auto k : kinds) { + CUptiResult r = on ? cuptiActivityEnable(k) : cuptiActivityDisable(k); + if (on && r != CUPTI_SUCCESS) fprintf(stderr, "[lct] cuptiActivityEnable(%d) = %d\n", (int)k, (int)r); + } + if (S.apiLevel >= 1) { + if (on) { + cuptiActivityEnable(CUPTI_ACTIVITY_KIND_DRIVER); + cuptiActivityEnable(CUPTI_ACTIVITY_KIND_RUNTIME); + if (S.apiLevel == 1) { // all on, then switch the uninteresting entry points (queries, getters, pushes) off + int nd = 0, nr = 0; + for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) { + const char* n = nullptr; + if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) { + cuptiActivityEnableDriverApi(cb, 0); + nd++; + } + } + for (uint32_t cb = 1; cb < CUPTI_RUNTIME_TRACE_CBID_SIZE; ++cb) { + const char* n = nullptr; + if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_RUNTIME_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) { + cuptiActivityEnableRuntimeApi(cb, 0); + nr++; + } + } + if (S.verbose) fprintf(stderr, "[lct] api filter: %d driver + %d runtime cbids off\n", nd, nr); + } + } else { + cuptiActivityDisable(CUPTI_ACTIVITY_KIND_DRIVER); + cuptiActivityDisable(CUPTI_ACTIVITY_KIND_RUNTIME); + } + } +} + +uint64_t cuptiNow() { + uint64_t t = 0; + cuptiGetTimestamp(&t); + return t; +} + +void startWindow(const Window& w, const char* why) { + mkdirs(w.out); + { + std::lock_guard g(S.mu); + const size_t B = 8u << 20; + S.strId.clear(); S.apiName[0].clear(); S.apiName[1].clear(); + S.bytesOut = 0; + for (auto& c : S.counts) c = 0; + S.kern.open(w.out + "/kernel.bin", B); + S.copy.open(w.out + "/memcpy.bin", B); + S.mset.open(w.out + "/memset.bin", 1u << 20); + S.sync.open(w.out + "/sync.bin", B); + S.api.open(w.out + "/api.bin", B); + S.graph.open(w.out + "/graph.bin", 1u << 20); + S.strs.open(w.out + "/strings.tsv", 1u << 20); + S.meta.open(w.out + "/meta.txt", 1u << 12); + timespec rt{}, mono{}; + uint64_t ts = cuptiNow(); + clock_gettime(CLOCK_REALTIME, &rt); + clock_gettime(CLOCK_MONOTONIC, &mono); + S.offReal = (uint64_t)rt.tv_sec * 1000000000ull + rt.tv_nsec - ts; + char exe[512] = {0}; + ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1); + if (n > 0) exe[n] = 0; + note("format 1\npid %d\nexe %s\nlabel %s\ncupti_ts_ns %llu\nrealtime_ns %llu\nmonotonic_ns %lld\n", (int)getpid(), exe, + w.label.c_str(), (unsigned long long)ts, (unsigned long long)(ts + S.offReal), + (long long)mono.tv_sec * 1000000000LL + mono.tv_nsec); + note("structs KRec=%zu CRec=%zu MRec=%zu YRec=%zu ARec=%zu GRec=%zu\napi_level %d\nreason %s\n", sizeof(KRec), + sizeof(CRec), sizeof(MRec), sizeof(YRec), sizeof(ARec), sizeof(GRec), S.apiLevel, why); + S.winStart = ts; + S.winOpen = true; + } + enableKinds(true); + S.recording.store(true); + fprintf(stderr, "[lct] pid %d window '%s' started (%s) -> %s\n", (int)getpid(), w.label.c_str(), why, w.out.c_str()); +} + +std::string threadTable() { + std::string s; + DIR* d = opendir("/proc/self/task"); + if (!d) return s; + while (dirent* e = readdir(d)) { + if (e->d_name[0] == '.') continue; + std::string p = std::string("/proc/self/task/") + e->d_name + "/comm"; + FILE* f = fopen(p.c_str(), "r"); + if (!f) continue; + char c[64] = {0}; + if (fgets(c, sizeof c, f)) { + c[strcspn(c, "\n")] = 0; + s += std::string(e->d_name) + "\t" + c + "\n"; + } + fclose(f); + } + closedir(d); + return s; +} + +std::string stopWindow(const Window& w, const char* why) { + S.recording.store(false); + enableKinds(false); + CK(cuptiActivityFlushAll(CUPTI_ACTIVITY_FLAG_FLUSH_FORCED)); + uint64_t t = cuptiNow(); + std::string done; + { + std::lock_guard g(S.mu); + char b[640]; + snprintf(b, sizeof b, + "{\"label\":\"%s\",\"reason\":\"%s\",\"dir\":\"%s\",\"pid\":%d,\"cupti_start_ns\":%llu,\"cupti_stop_ns\":%llu," + "\"unix_ms_start\":%llu,\"unix_ms_stop\":%llu,\"bytes\":%llu,\"kernels\":%llu,\"copies\":%llu,\"memsets\":%llu," + "\"syncs\":%llu,\"api\":%llu,\"graphs\":%llu}\n", + w.label.c_str(), why, w.out.c_str(), (int)getpid(), (unsigned long long)S.winStart, (unsigned long long)t, + (unsigned long long)((S.winStart + S.offReal) / 1000000ull), (unsigned long long)((t + S.offReal) / 1000000ull), + (unsigned long long)S.bytesOut, (unsigned long long)S.counts[0], (unsigned long long)S.counts[1], + (unsigned long long)S.counts[2], (unsigned long long)S.counts[3], (unsigned long long)S.counts[4], + (unsigned long long)S.counts[5]); + done = b; + note("window_start %llu\nwindow_stop %llu\nstop_reason %s\n", (unsigned long long)S.winStart, (unsigned long long)t, why); + S.winOpen = false; + std::string th = threadTable(); + FILE* f = fopen((w.out + "/threads.tsv").c_str(), "w"); + if (f) { + fwrite(th.data(), 1, th.size(), f); + fclose(f); + } + S.kern.close(); S.copy.close(); S.mset.close(); S.sync.close(); S.api.close(); S.graph.close(); S.strs.close(); S.meta.close(); + } + fprintf(stderr, "[lct] pid %d window '%s' stopped (%s): %s", (int)getpid(), w.label.c_str(), why, done.c_str()); + if (!w.prefix.empty()) writeFile(w.prefix + ".done", done); + else writeFile(w.out + "/done.json", done); + return done; +} + +void CUPTIAPI apiCallback(void*, CUpti_CallbackDomain domain, CUpti_CallbackId cbid, const CUpti_CallbackData* d) { + if (domain != CUPTI_CB_DOMAIN_DRIVER_API || d->callbackSite != CUPTI_API_ENTER) return; + if (!S.recording.load(std::memory_order_relaxed)) { + if (S.startTarget.load() && !S.reqStart.load()) + for (auto id : S.startIds) + if (id == cbid) { + if (S.startCnt.fetch_add(1) + 1 == S.startTarget.load()) S.reqStart.store(true); + break; + } + if (S.symTarget.load() && !S.reqStart.load() && d->symbolName && strstr(d->symbolName, S.symSubstr.c_str())) + if (S.symCnt.fetch_add(1) + 1 == S.symTarget.load()) S.reqStart.store(true); + } else if (S.stopTarget.load()) { + for (auto id : S.stopIds) + if (id == cbid) { + if (S.stopCnt.fetch_add(1) + 1 == S.stopTarget.load()) S.reqStop.store(true); + break; + } + } +} + +std::vector findDriverIds(const std::string& name) { + std::vector ids; + for (int pass = 0; pass < 2 && ids.empty(); ++pass) + for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) { + const char* n = nullptr; + if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) != CUPTI_SUCCESS || !n) continue; + if (pass == 0 ? name == n : strncmp(n, name.c_str(), name.size()) == 0) ids.push_back(cb); + } + return ids; +} + +bool parseNameN(const char* spec, std::string& name, uint64_t& n) { + std::string s = spec; + size_t c = s.rfind(':'); + if (c == std::string::npos) return false; + name = s.substr(0, c); + n = strtoull(s.c_str() + c + 1, nullptr, 10); + return n > 0; +} + +// Minimal JSON field extraction for {"seconds": N, "out": "...", "label": "..."} (flat, no nested objects). +std::string jsonStr(const std::string& j, const char* key) { + std::string k = std::string("\"") + key + "\""; + size_t p = j.find(k); + if (p == std::string::npos) return ""; + p = j.find(':', p); + if (p == std::string::npos) return ""; + p = j.find_first_not_of(" \t\r\n", p + 1); + if (p == std::string::npos) return ""; + if (j[p] == '"') { + std::string r; + for (++p; p < j.size() && j[p] != '"'; ++p) { + if (j[p] == '\\' && p + 1 < j.size()) ++p; + r += j[p]; + } + return r; + } + size_t e = j.find_first_of(",} \t\r\n", p); + return j.substr(p, e == std::string::npos ? std::string::npos : e - p); +} + +bool takeTrigger(Window& w) { + struct stat st; + if (S.trigger.empty() || stat(S.trigger.c_str(), &st) != 0) return false; + FILE* f = fopen(S.trigger.c_str(), "r"); + if (!f) return false; + std::string j; + char b[1024]; + size_t n; + while ((n = fread(b, 1, sizeof b, f)) > 0 && j.size() < 65536) j.append(b, n); + fclose(f); + const double cap = envs("LCT_MAX_SECONDS") ? atof(envs("LCT_MAX_SECONDS")) : 120.0; + std::string sec = jsonStr(j, "seconds"), out = jsonStr(j, "out"); + w = Window(); + w.fromTrigger = true; + w.trigger = S.trigger; + w.seconds = sec.empty() ? 10.0 : atof(sec.c_str()); + if (w.seconds > cap || w.seconds <= 0) w.seconds = cap; + w.label = jsonStr(j, "label"); + for (auto& c : w.label) + if (c == '"' || c == '\\' || c == '\n' || c == '\r') c = '_'; + if (out.empty()) out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string("/tmp")) + "/lct-win-" + std::to_string(++S.winSeq); + w.prefix = out; + w.out = out + ".lct"; + if (rename(S.trigger.c_str(), (S.trigger + ".active").c_str()) != 0) { + writeFile(S.errPath, std::string("cannot rename trigger: ") + strerror(errno) + "\n"); + return false; + } + return true; +} + +void onSignal(int sig) { + if (sig == SIGUSR1) S.reqStart.store(true); + if (sig == SIGUSR2) S.reqStop.store(true); +} + +void watcher() { + const double startAfter = envs("LCT_START_AFTER_S") ? atof(envs("LCT_START_AFTER_S")) : -1; + const double envDur = envs("LCT_DURATION_S") ? atof(envs("LCT_DURATION_S")) : -1; + const char* startFile = envs("LCT_START_FILE"); + const char* stopFile = envs("LCT_STOP_FILE"); + const bool hasEnvTrigger = startAfter >= 0 || startFile || S.startTarget.load() || S.symTarget.load() || envs("LCT_SIGNALS"); + bool immediate = S.trigger.empty() && !hasEnvTrigger && !envs("LCT_WAIT"); + bool envWindowPending = hasEnvTrigger || immediate; + const auto t0 = std::chrono::steady_clock::now(); + auto secs = [&] { return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); }; + struct stat st; + Window cur; + double winT0 = 0; + bool active = false; + int tick = 0; + while (!S.finished.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + if (!S.cuptiOk.load()) continue; + if (!active) { + const char* why = nullptr; + if (takeTrigger(cur)) why = "trigger"; + else if (envWindowPending) { + if (immediate) why = "immediate"; + else if (S.reqStart.load()) why = "signal/api"; + else if (startAfter >= 0 && secs() >= startAfter) why = "after_s"; + else if (startFile && stat(startFile, &st) == 0) why = "start_file"; + if (why) { + cur = Window(); + cur.seconds = envDur; + cur.out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string(".")) + "/lct." + std::to_string((int)getpid()); + cur.label = "env"; + envWindowPending = false; + immediate = false; + } + } + if (why) { + startWindow(cur, why); + winT0 = secs(); + active = true; + S.reqStart.store(false); + S.reqStop.store(false); + S.startTarget.store(0); + S.symTarget.store(0); + tick = 0; + } + } else { + const char* why = nullptr; + if (S.reqStop.load()) why = "signal/api"; + else if (cur.seconds > 0 && secs() - winT0 >= cur.seconds) why = "duration"; + else if (stopFile && !cur.fromTrigger && stat(stopFile, &st) == 0) why = "stop_file"; + else if (cur.fromTrigger && stat((S.trigger + ".stop").c_str(), &st) == 0) why = "stop_file"; + else if (S.bytesOut >= S.maxBytes) why = "max_mb"; + if (why) { + stopWindow(cur, why); + if (cur.fromTrigger) { + rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str()); + unlink((S.trigger + ".stop").c_str()); + } + active = false; + S.stopTarget.store(0); + } else if (++tick % 20 == 0) { // ~ every second: complete buffers reach the file even if the process is killed + cuptiActivityFlushAll(0); + std::lock_guard g(S.mu); + S.kern.flush(); S.copy.flush(); S.mset.flush(); S.sync.flush(); S.api.flush(); S.graph.flush(); S.strs.flush(); + } + } + } + if (active) { + stopWindow(cur, "exit"); + if (cur.fromTrigger) rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str()); + } +} + +void atExit() { + if (!S.inited.load()) return; + S.finished.store(true); + // The watcher is detached and may still be inside a window: give it a moment to close the files. + if (S.recording.load()) { + for (int i = 0; i < 100 && S.recording.load(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } +} + +void init() { + bool exp = false; + if (!S.inited.compare_exchange_strong(exp, true)) return; + S.verbose = envs("LCT_VERBOSE") != nullptr; + S.apiLevel = envs("LCT_API") ? atoi(envs("LCT_API")) : 1; + if (envs("LCT_BUF_MB")) S.bufBytes = (size_t)atoi(envs("LCT_BUF_MB")) << 20; + S.maxBytes = (uint64_t)((envs("LCT_MAX_MB") ? atof(envs("LCT_MAX_MB")) : 3072.0) * 1048576.0); + const char* trig = envs("LELEKA_CUPTI_TRIGGER") ? envs("LELEKA_CUPTI_TRIGGER") : envs("LCT_TRIGGER"); + if (trig) { + S.trigger = trig; + S.errPath = S.trigger + ".error"; + } + + // CUPTI setup; a failure only disables tracing. + bool ok = true; + auto chk = [&](CUptiResult r, const char* what) { + if (r != CUPTI_SUCCESS) { + const char* m = nullptr; + cuptiGetResultString(r, &m); + std::string e = std::string(what) + " failed: " + (m ? m : "?") + "\n"; + fputs(("[lct] " + e).c_str(), stderr); + if (!S.errPath.empty()) writeFile(S.errPath, e); + ok = false; + } + }; + chk(cuptiActivityRegisterCallbacks(bufferRequested, bufferCompleted), "cuptiActivityRegisterCallbacks"); + if (ok) { + size_t sz = S.bufBytes, vs = sizeof sz; + cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE, &vs, &sz); + size_t lim = 32; + vs = sizeof lim; + cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_POOL_LIMIT, &vs, &lim); + cuptiActivityFlushPeriod(1000); + } + + std::string nm; + uint64_t cnt = 0; + bool needSub = false; + std::vector all; + if (ok && envs("LCT_START_API") && parseNameN(envs("LCT_START_API"), nm, cnt)) { + S.startIds = findDriverIds(nm); + S.startTarget.store(cnt); + needSub = true; + all.insert(all.end(), S.startIds.begin(), S.startIds.end()); + } + if (ok && envs("LCT_START_SYM") && parseNameN(envs("LCT_START_SYM"), nm, cnt)) { + S.symSubstr = nm; + S.symTarget.store(cnt); + needSub = true; + for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) { + const char* n = nullptr; + if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && strncmp(n, "cuLaunchKernel", 14) == 0) + all.push_back(cb); + } + } + if (ok && envs("LCT_STOP_API") && parseNameN(envs("LCT_STOP_API"), nm, cnt)) { + S.stopIds = findDriverIds(nm); + S.stopTarget.store(cnt); + needSub = true; + all.insert(all.end(), S.stopIds.begin(), S.stopIds.end()); + } + if (needSub) { + chk(cuptiSubscribe(&S.sub, (CUpti_CallbackFunc)apiCallback, nullptr), "cuptiSubscribe"); + for (auto id : all) cuptiEnableCallback(1, S.sub, CUPTI_CB_DOMAIN_DRIVER_API, id); + } + if (envs("LCT_SIGNALS")) { + signal(SIGUSR1, onSignal); + signal(SIGUSR2, onSignal); + } + S.cuptiOk.store(ok); + atexit(atExit); + std::thread(watcher).detach(); + fprintf(stderr, "[lct] pid %d tracer %s (trigger %s)\n", (int)getpid(), ok ? "armed" : "DISABLED (CUPTI init failed)", + S.trigger.empty() ? "env/immediate" : S.trigger.c_str()); +} + +} // namespace + +extern "C" { +__attribute__((visibility("default"))) int InitializeInjection(void) { + init(); + return 1; +} +__attribute__((constructor)) static void lctCtor() { + // Under LD_PRELOAD the constructor runs before main. Under CUDA_INJECTION64_PATH the driver calls InitializeInjection. + if (!envs("LCT_NO_CTOR") && !envs("CUDA_INJECTION64_PATH")) init(); +} +} diff --git a/tools/cupti-trace/test/test_app.cu b/tools/cupti-trace/test/test_app.cu new file mode 100644 index 00000000..a815abf6 --- /dev/null +++ b/tools/cupti-trace/test/test_app.cu @@ -0,0 +1,42 @@ +// Tiny CUDA workload for the tracer self-test: kernels, graph launch, pinned/pageable H2D, memset, syncs. Runs ~SECONDS s. +#include +#include +#include +#include +__global__ void saxpy(float* y, const float* x, float a, int n) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = a * x[i] + y[i]; +} +int main(int argc, char** argv) { + double secs = argc > 1 ? atof(argv[1]) : 6.0; + const int n = 1 << 22; + float *dx, *dy, *hp, *hq; + cudaMalloc(&dx, n * 4); cudaMalloc(&dy, n * 4); + cudaMallocHost(&hp, n * 4); + hq = (float*)malloc(n * 4); + for (int i = 0; i < n; i++) hp[i] = hq[i] = 1.0f; + cudaStream_t s1, s2; cudaStreamCreate(&s1); cudaStreamCreate(&s2); + cudaGraph_t g; cudaGraphExec_t ge; + cudaStreamBeginCapture(s1, cudaStreamCaptureModeGlobal); + for (int k = 0; k < 8; k++) saxpy<<>>(dy, dx, 2.0f, n); + cudaStreamEndCapture(s1, &g); + cudaGraphInstantiate(&ge, g, 0); + cudaMemset(dy, 0, n * 4); + double t0 = 0; timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); t0 = ts.tv_sec + ts.tv_nsec * 1e-9; + long it = 0; + for (;;) { + cudaMemcpyAsync(dx, hp, n * 4, cudaMemcpyHostToDevice, s2); // pinned + cudaMemcpyAsync(dx, hq, n * 4 / 4, cudaMemcpyHostToDevice, s2); // pageable + cudaStreamSynchronize(s2); + cudaGraphLaunch(ge, s1); + saxpy<<>>(dy, dx, 1.0f, n); + cudaStreamSynchronize(s1); + cudaDeviceSynchronize(); + usleep(2000); + it++; + clock_gettime(CLOCK_MONOTONIC, &ts); + if (ts.tv_sec + ts.tv_nsec * 1e-9 - t0 > secs) break; + } + printf("done iterations=%ld\n", it); + return 0; +} From aef32a0795f5aa813f57ad7c4abfb96d2ba69696 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 02:39:25 +0200 Subject: [PATCH 2/8] scripts/profile: ledger tools (report, port-vs-original ledger, h2d source probe, holder job scripts) Co-Authored-By: Claude Sonnet 5.5 --- scripts/profile/build_rt.sh | 23 ++ scripts/profile/h2d_src_probe.cu | 113 ++++++++ scripts/profile/jobs/9001-ledger-h2d-probe.sh | 10 + .../jobs/901-ledger-port-prefill16k.sh | 9 + .../jobs/902-ledger-orig-prefill16k.sh | 9 + .../jobs/9021-ledger-orig-prefill16k-off.sh | 6 + scripts/profile/jobs/903-ledger-port-180k.sh | 6 + scripts/profile/jobs/904-ledger-orig-180k.sh | 7 + .../profile/jobs/905-ledger-port-decode.sh | 7 + .../profile/jobs/906-ledger-orig-decode.sh | 6 + scripts/profile/jobs/ledger-common.sh | 112 ++++++++ scripts/profile/lct.py | 118 ++++++-- scripts/profile/lct_ledger.py | 254 ++++++++++++++++++ scripts/profile/lct_report.py | 67 +++-- scripts/profile/steps.map | 30 +++ 15 files changed, 736 insertions(+), 41 deletions(-) create mode 100644 scripts/profile/build_rt.sh create mode 100644 scripts/profile/h2d_src_probe.cu create mode 100644 scripts/profile/jobs/9001-ledger-h2d-probe.sh create mode 100644 scripts/profile/jobs/901-ledger-port-prefill16k.sh create mode 100644 scripts/profile/jobs/902-ledger-orig-prefill16k.sh create mode 100644 scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh create mode 100644 scripts/profile/jobs/903-ledger-port-180k.sh create mode 100644 scripts/profile/jobs/904-ledger-orig-180k.sh create mode 100644 scripts/profile/jobs/905-ledger-port-decode.sh create mode 100644 scripts/profile/jobs/906-ledger-orig-decode.sh create mode 100644 scripts/profile/jobs/ledger-common.sh create mode 100644 scripts/profile/lct_ledger.py create mode 100644 scripts/profile/steps.map diff --git a/scripts/profile/build_rt.sh b/scripts/profile/build_rt.sh new file mode 100644 index 00000000..2d64d875 --- /dev/null +++ b/scripts/profile/build_rt.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Build the leleka-runtime test binary of THIS worktree in WSL (never on the server) and print its path. +# scripts/profile/build_rt.sh TAG (run from Windows Git Bash in the worktree; needs WSL distro "Ubuntu") +# Result: WSL ~/ledger-bin/rt-TAG. Copy to the server with: scp (see docs/ledger.md). +set -euo pipefail +tag=${1:?tag} +root=$(git rev-parse --show-toplevel) +tmp=$(mktemp -d) +git -C "$root" -c core.autocrlf=false ls-files -z | tar -C "$root" --null -T - -cf "$tmp/wt.tar" +win=$(cygpath -w "$tmp/wt.tar" | sed 's#\\#/#g; s#^\([A-Za-z]\):#/mnt/\L\1#') +wsl -d Ubuntu -e bash -lc " +set -e +source ~/.cargo/env +export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin +rm -rf ~/ledger-src && mkdir -p ~/ledger-src ~/ledger-bin && tar -xf '$win' -C ~/ledger-src +cd ~/ledger-src +export CARGO_TARGET_DIR=\$HOME/ledger-target +nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib 2>&1 | tee ~/ledger-build-$tag.log | grep -E 'Executable|^error|warning: unused' | tail -5 +exe=\$(grep -o 'target/release/deps/leleka_runtime-[0-9a-f]*' ~/ledger-build-$tag.log | tail -1) +cp \$CARGO_TARGET_DIR/\${exe#target/} ~/ledger-bin/rt-$tag +ls -la ~/ledger-bin/rt-$tag +" +rm -rf "$tmp" diff --git a/scripts/profile/h2d_src_probe.cu b/scripts/profile/h2d_src_probe.cu new file mode 100644 index 00000000..e78696e3 --- /dev/null +++ b/scripts/profile/h2d_src_probe.cu @@ -0,0 +1,113 @@ +// Model-free probe (claude/ledger): sustained host-to-device DMA rate of the expert stream by SOURCE MEMORY KIND and COPY SHAPE. +// The ledger found the port's ring at ~37 GB/s (3 copies of 0.5-0.9 MB from the registered bank) while the Original's ring runs at +// ~50 GB/s (1 copy of ~2.1 MB from its arena). This isolates which property matters. +// nvcc -O2 -arch=sm_120 h2d_src_probe.cu -o h2d_src_probe ; ./h2d_src_probe [shard.gguf] +// Source kinds: hostalloc | anon4k+register(0) | anon4k+register(PORTABLE) | anon4k+register(DEVICEMAP, the port's bank) | +// anon+MADV_HUGEPAGE+register(DEVICEMAP) | file mapping (MAP_SHARED, PROT_READ) + register(READ_ONLY). +// Shapes (per "expert" of ENTRY bytes): 3 x ENTRY/3 from three role-major regions (the port) | 1 x ENTRY contiguous (the Original) | +// 1 x 2 MiB 4K-aligned | 1 x 8 MiB. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0) +using Clock = std::chrono::steady_clock; + + +static uint8_t* anon(size_t bytes, bool thp) { + void* p = mmap(nullptr, bytes + (2 << 20), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) { perror("mmap"); exit(1); } + uint8_t* a = (uint8_t*)(((size_t)p + (2 << 20) - 1) & ~((size_t)(2 << 20) - 1)); + if (thp) madvise(a, bytes, MADV_HUGEPAGE); + memset(a, 0x5a, bytes); + return a; +} + +// run: copy `n` entries, each `pieces` copies of ENTRY/pieces bytes, cycling over `regions` role-major regions (pieces==3) or one region +static double run(uint8_t* base, size_t region_bytes, size_t entry, int pieces, bool role_major, size_t stride, uint8_t* ring, int slots, + cudaStream_t s, int n, int depth) { + std::vector ev(depth + 1); + for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming)); + cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b)); + size_t piece = entry / pieces; + size_t unit = role_major ? stride : stride * pieces; // distance between consecutive experts inside one region + size_t per_region = region_bytes / (role_major ? pieces : 1) / unit; + CK(cudaEventRecord(a, s)); + for (int k = 0; k < n; ++k) { + int slot = k % slots; + if (k >= depth) CK(cudaStreamWaitEvent(s, ev[(k - depth) % (depth + 1)], 0)); + for (int p = 0; p < pieces; ++p) { + const uint8_t* src; + if (role_major) src = base + (size_t)p * (region_bytes / pieces) + (size_t)(k % per_region) * stride; + else src = base + (size_t)(k % per_region) * unit + (size_t)p * stride; + CK(cudaMemcpyAsync(ring + (size_t)slot * entry + p * piece, src, piece, cudaMemcpyHostToDevice, s)); + } + CK(cudaEventRecord(ev[k % (depth + 1)], s)); + if (k >= depth + 2) CK(cudaEventSynchronize(ev[(k - depth - 2) % (depth + 1)])); + } + CK(cudaEventRecord(b, s)); CK(cudaEventSynchronize(b)); + float ms; CK(cudaEventElapsedTime(&ms, a, b)); + for (auto& e : ev) cudaEventDestroy(e); + cudaEventDestroy(a); cudaEventDestroy(b); + return (double)n * entry / (ms * 1e6); +} + +int main(int argc, char** argv) { + const size_t ENTRY = 2046000; + const size_t REGION = 3ull << 30; // 3 GiB per source kind + CK(cudaSetDevice(0)); + cudaStream_t s; CK(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking)); + const int SLOTS = 64; + uint8_t* ring; CK(cudaMalloc((void**)&ring, (9ull << 20) * SLOTS)); + struct Shape { const char* name; size_t entry; int pieces; bool role_major; size_t stride; }; + std::vector shapes = {{"3 x 682000 role-major (port)", ENTRY, 3, true, ENTRY / 3}, + {"3 x 682000 role-major, 4K-aligned stride", ENTRY, 3, true, 684032}, + {"1 x 2046000 contiguous (Original)", ENTRY, 1, false, ENTRY}, + {"1 x 2046000, 4K-aligned stride", ENTRY, 1, false, 2048000 + 4096 - 2048000 % 4096}, + {"1 x 2 MiB aligned", 2u << 20, 1, false, 2u << 20}, {"1 x 8 MiB", 8u << 20, 1, false, 8u << 20}}; + struct Kind { const char* name; int id; }; + std::vector kinds = {{"cudaHostAlloc", 0}, {"anon 4K + register(0)", 1}, {"anon 4K + register(PORTABLE)", 2}, + {"anon 4K + register(DEVICEMAP) (port bank)", 3}, {"anon THP + register(DEVICEMAP)", 4}, {"file map RO + register(READ_ONLY)", 5}}; + for (auto& kd : kinds) { + uint8_t* base = nullptr; size_t bytes = REGION; void* map = nullptr; size_t map_bytes = 0; int fd = -1; + if (kd.id == 0) { CK(cudaHostAlloc((void**)&base, bytes, cudaHostAllocDefault)); memset(base, 0x5a, bytes); } + else if (kd.id >= 1 && kd.id <= 4) { + base = anon(bytes, kd.id == 4); + unsigned flags = kd.id == 1 ? 0 : kd.id == 2 ? cudaHostRegisterPortable : cudaHostRegisterMapped; + CK(cudaHostRegister(base, bytes, flags)); + } else { + if (argc < 2) { printf("%-44s skipped (no shard path)\n", kd.name); continue; } + fd = open(argv[1], O_RDONLY); + struct stat st; fstat(fd, &st); + map_bytes = (size_t)st.st_size < bytes ? st.st_size : bytes; + map = mmap(nullptr, map_bytes, PROT_READ, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) { printf("%-44s mmap failed\n", kd.name); continue; } + base = (uint8_t*)map; bytes = map_bytes; + volatile uint8_t sink = 0; + for (size_t i = 0; i < bytes; i += 4096) sink += base[i]; // fault the pages in + cudaError_t e = cudaHostRegister(base, bytes, cudaHostRegisterReadOnly); + if (e != cudaSuccess) { printf("%-44s register failed: %s\n", kd.name, cudaGetErrorString(e)); munmap(map, map_bytes); continue; } + } + for (auto& sh : shapes) { + double best = 0, sum = 0; + for (int rep = 0; rep < 3; ++rep) { + double r = run(base, bytes, sh.entry, sh.pieces, sh.role_major, sh.stride, ring, SLOTS, s, 2400, 16); + if (r > best) best = r; + sum += r; + } + printf("%-44s %-36s %6.1f GB/s (best %6.1f)\n", kd.name, sh.name, sum / 3, best); + fflush(stdout); + } + if (kd.id == 0) cudaFreeHost(base); + else if (kd.id <= 4) { cudaHostUnregister(base); } + else { cudaHostUnregister(base); munmap(map, map_bytes); close(fd); } + } + return 0; +} diff --git a/scripts/profile/jobs/9001-ledger-h2d-probe.sh b/scripts/profile/jobs/9001-ledger-h2d-probe.sh new file mode 100644 index 00000000..28d49660 --- /dev/null +++ b/scripts/profile/jobs/9001-ledger-h2d-probe.sh @@ -0,0 +1,10 @@ +# claude/ledger: model-free probe, H2D DMA rate by source memory kind and copy shape (the port's 3 x 0.68 MB role-major pieces from the registered bank +# vs the Original's single ~2 MB blob from its arena). GPU otherwise idle (holder job). +source ~/work/ledger/ledger-common.sh +header 2>/dev/null | head -3 +nvidia-smi --query-gpu=pcie.link.gen.current,pcie.link.width.current,clocks.sm,clocks.mem --format=csv,noheader +timeout 600 $LD/bin/h2d_src_probe $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf 2>&1 +echo "rc=$?"; date -u +%FT%TZ +# the same probe question inside the port: the bank's anonymous Vecs with transparent huge pages (LELEKA_BANK_THP=on), traced like port-16k-off +mem_ok 30 && port_long port-16k-thp 16000 2 PREFILL-PROFILE 2 9 LELEKA_BANK_THP=on +date -u +%FT%TZ diff --git a/scripts/profile/jobs/901-ledger-port-prefill16k.sh b/scripts/profile/jobs/901-ledger-port-prefill16k.sh new file mode 100644 index 00000000..e7d6b08b --- /dev/null +++ b/scripts/profile/jobs/901-ledger-port-prefill16k.sh @@ -0,0 +1,9 @@ +# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill (chunks 8192 + 7807) of the PORT (rt-base = head 7330ddb), second pass of +# each process (pass 0 pays the one-time finite admission). A: tier off, B: expert tier on, C: tier off WITHOUT the tracer (overhead A/B). +source ~/work/ledger/ledger-common.sh +mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; } +header +port_long port-16k-off 16000 2 PREFILL-PROFILE 2 9 +port_long port-16k-on 16000 2 PREFILL-PROFILE 2 9 $PORT_TIER +port_long port-16k-off-plain 16000 2 PREFILL-PROFILE 0 9 +date -u +%FT%TZ diff --git a/scripts/profile/jobs/902-ledger-orig-prefill16k.sh b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh new file mode 100644 index 00000000..e17f9f55 --- /dev/null +++ b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh @@ -0,0 +1,9 @@ +# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill of the unmodified ORIGINAL (--serve, prompt ids of job 0708), second request +# traced (the first is the warm-up of the same process). One profiling pass per scenario, not a throughput A/B. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +header +R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R +orig_serve orig-16k-off 2 9 "--prefill 8192 --max-context 65536 --kv-resident 20480" $R +orig_serve orig-16k-on 2 9 "--prefill auto --max-context 65536 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh new file mode 100644 index 00000000..2fcede75 --- /dev/null +++ b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh @@ -0,0 +1,6 @@ +# claude/ledger: the ORIGINAL without the expert tier (job 902's off arm was refused: a native pack needs --spec T >= 2), traced, 16000 tokens, second request. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R +orig_serve orig-16k-off 2 9 "--prefill 8192 --spec 4 --max-context 65536 --kv-resident 20480" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/903-ledger-port-180k.sh b/scripts/profile/jobs/903-ledger-port-180k.sh new file mode 100644 index 00000000..0810d90d --- /dev/null +++ b/scripts/profile/jobs/903-ledger-port-180k.sh @@ -0,0 +1,6 @@ +# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the PORT (22 chunks), tier on (the job 915 configuration), trace from the start of the request. +source ~/work/ledger/ledger-common.sh +mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; } +header +port_long port-180k 180000 1 "long-smoke prompt tokens" 1 150 $PORT_TIER +date -u +%FT%TZ diff --git a/scripts/profile/jobs/904-ledger-orig-180k.sh b/scripts/profile/jobs/904-ledger-orig-180k.sh new file mode 100644 index 00000000..d8ae891c --- /dev/null +++ b/scripts/profile/jobs/904-ledger-orig-180k.sh @@ -0,0 +1,7 @@ +# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the unmodified ORIGINAL (job 916 configuration, --serve), trace from the start of the request. +source ~/work/ledger/ledger-common.sh +mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; } +header +R=$LD/req180k.txt; { echo "GEN 16 $(cat $G/long-180k/prompt180000.ids)"; echo QUIT; } > $R +orig_serve orig-180k 1 150 "--prefill auto --max-context 262144 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R +date -u +%FT%TZ diff --git a/scripts/profile/jobs/905-ledger-port-decode.sh b/scripts/profile/jobs/905-ledger-port-decode.sh new file mode 100644 index 00000000..1f9ca4ad --- /dev/null +++ b/scripts/profile/jobs/905-ledger-port-decode.sh @@ -0,0 +1,7 @@ +# claude/ledger: CUPTI timeline of the decode rounds of the PORT: 6-prompt corpus x 2 passes x 128 tokens, spec 4 + suffix 3, min_p 0.5, 2048 slots/layer, static residency. +# Window of 10 s after the 2nd finished request (the first prompt, twice), i.e. over the 2nd prompt's two requests. +source ~/work/ledger/ledger-common.sh +mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; } +header +port_corpus port-corpus 2 10 +date -u +%FT%TZ diff --git a/scripts/profile/jobs/906-ledger-orig-decode.sh b/scripts/profile/jobs/906-ledger-orig-decode.sh new file mode 100644 index 00000000..5de0bc37 --- /dev/null +++ b/scripts/profile/jobs/906-ledger-orig-decode.sh @@ -0,0 +1,6 @@ +# claude/ledger: the same corpus on the unmodified ORIGINAL (--serve, round-profile/original-requests.txt), static residency, trace window before request 3. +source ~/work/ledger/ledger-common.sh +mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; } +header +orig_serve orig-corpus 3 10 "--prefill 2048 --max-context 4096 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55 --adapt-every 0" $G/round-profile/original-requests.txt +date -u +%FT%TZ diff --git a/scripts/profile/jobs/ledger-common.sh b/scripts/profile/jobs/ledger-common.sh new file mode 100644 index 00000000..b8d00d23 --- /dev/null +++ b/scripts/profile/jobs/ledger-common.sh @@ -0,0 +1,112 @@ +# Sourced by the 90x-ledger-*.sh holder jobs (copied next to them on the server, ~/work/ledger/). +# Runs the PORT (test binary) or the unmodified ORIGINAL (strata) with the CUPTI tracer injected and a trigger-file window. +set -uo pipefail +export PATH=$HOME/cuda-toolkits/13.2.2/bin:$PATH RUST_BACKTRACE=1 +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +A=$HOME/leleka-gates/assets +G=$HOME/work/gpu-runs +LD=$HOME/work/ledger +OUT=$LD/traces; mkdir -p $OUT +CUPTI_LIB=$HOME/work/cupti-trace/libleleka_cupti_trace.so +TRIG=$LD/cupti.trigger +ORIG=${ORIG:-$HOME/work/numerics-orig/build/strata} +PROFILE=$G/baseline/profile.bin +T_LONG=backend::original_serve_smoke::original_serve_long_context_streamed_kv_smoke +T_CORPUS=original_serve_smoke_prompt_decode +mkdir -p $G/mtp-staging-own; chmod 700 $G/mtp-staging-own +export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json +export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf +export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own +export LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 LELEKA_BRINGUP_TRACE=1 LELEKA_SERVE_PROFILE=1 +PORT_TIER="LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$PROFILE LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55" +BIN=${BIN:-$LD/bin/rt-base} + +mem_ok() { local avail; avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"; [ "${avail:-0}" -ge "$1" ]; } + +# trig LABEL SECONDS OUTNAME: ask the injected tracer for one window (same protocol as the daemon's trigger file) +trig() { + rm -f $TRIG.active $TRIG.done $TRIG.stop + printf '{"seconds": %s, "out": "%s/%s", "label": "%s"}\n' "$2" "$OUT" "$3" "$1" > $TRIG.tmp && mv $TRIG.tmp $TRIG + for _ in $(seq 100); do [ -e $TRIG.active ] && return 0; sleep 0.05; done + echo "TRIGGER-NOT-TAKEN $1" +} +trig_stop() { touch $TRIG.stop; } +stamp() { perl -MTime::HiRes=time -ne 'BEGIN{$|=1} printf "%.3f %s", time, $_'; } +header() { date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,clocks.max.sm --format=csv,noheader; sha256sum $BIN $CUPTI_LIB; } + +# port_long LABEL TOKENS REPEAT TRIG_LINE_REGEX TRIG_AFTER_N WINDOW_S [ENV=V ...] +# one model process of the port's long-context smoke (chunk 8192, INT8 KV streamed, 16 new tokens); the tracer window starts +# when the TRIG_AFTER_N-th line matching TRIG_LINE_REGEX has been printed. TRIG_AFTER_N=0: no window (tracer not injected). +port_long() { + local label=$1 toks=$2 rep=$3 re=$4 after=$5 win=$6; shift 6 + local inj=() + [ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== port $label tokens=$toks repeat=$rep trigger=$re#$after win=${win}s: $*"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + mkdir -p $G/ledger-ids + local n=0 + env "${inj[@]}" LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes LELEKA_ORIGINAL_SERVE_LONG_TOKENS=$toks LELEKA_ORIGINAL_SERVE_LONG_REPEAT=$rep \ + LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=16 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192 \ + LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 "$@" \ + $BIN --ignored --exact --test-threads=1 --nocapture $T_LONG 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do + case "$line" in *"$re"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac + case "$line" in *PREFILL-PROFILE*|*long-smoke*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac + done + echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ +} + +# port_corpus LABEL TRIG_AFTER_N WINDOW_S [ENV=V ...]: the 6 prompts of prompts.txt, each served twice, 128 new tokens, static residency; +# the window starts after the N-th "DBG profile request" line (a finished request). +port_corpus() { + local label=$1 after=$2 win=$3; shift 3 + local inj=() + [ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== port $label corpus trigger=after request #$after win=${win}s: $*"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + local n=0 + env "${inj[@]}" LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$G/prompts.txt LELEKA_SMOKE_MAX_NEW=128 LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=2 \ + LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=4096 LELEKA_ORIGINAL_SERVE_CAPACITY=2048 LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_GRAPH_EXEC_REUSE=off \ + LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 $PORT_TIER "$@" \ + $BIN --ignored --test-threads=1 --nocapture $T_CORPUS 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do + case "$line" in *"DBG profile request"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac + case "$line" in *"DBG profile request"*|*"DBG timing"*|*"DBG tier request"*|*"smoke:"*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac + done + echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ +} + +# orig_serve LABEL STRATA_FLAGS... -- REQUEST_FILE_LINES... : the unmodified Original in --serve mode; requests are fed through a FIFO +# one at a time; before request number TRIG_BEFORE a tracer window of WINDOW_S seconds is requested (TRIG_BEFORE=0: none). +# usage: orig_serve LABEL TRIG_BEFORE WINDOW_S "flags" reqfile +orig_serve() { + local label=$1 before=$2 win=$3 flags=$4 req=$5 + local inj=() + [ "$before" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400) + echo "=== original $label trigger before request #$before win=${win}s: $flags"; date -u +%FT%TZ + rm -f $TRIG $TRIG.active $TRIG.done + local d=$OUT/$label.orig; mkdir -p $d; rm -f $d/fifo; mkfifo $d/fifo + local kar=${KAR_PATH:-/proc/self/fd/${LELEKA_STRA169_KAR_FD:-0}} + env "${inj[@]}" STRATA_DECODE_TIMING=1 $ORIG --pack $A/data/iq3_s --native $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf \ + --ple-gguf $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf --ple-kar $kar --ple-kar-level 2 \ + --serve --mtp $A/data/mtp-rt --kv int8 $flags \ + < $d/fifo > $d/out.txt 2> $d/err.txt & + local pid=$! + exec 7>$d/fifo + for _ in $(seq 1200); do grep -q "^READY" $d/out.txt 2>/dev/null && break; kill -0 $pid 2>/dev/null || break; sleep 0.5; done + grep -q "^READY" $d/out.txt || { echo "original did not become ready"; tail -3 $d/err.txt | cut -c1-300; exec 7>&-; kill $pid 2>/dev/null; return 1; } + local i=0 line + while IFS= read -r line; do + i=$((i+1)) + [ "$line" = QUIT ] && break + [ "$before" -gt 0 ] && [ $i -eq "$before" ] && trig "$label" "$win" "$label" + echo "$(date +%s.%N) request $i sent" + printf '%s\n' "$line" >&7 + for _ in $(seq 6000); do [ "$(grep -c '^DONE' $d/out.txt)" -ge $i ] && break; kill -0 $pid 2>/dev/null || break; sleep 0.2; done + echo "$(date +%s.%N) request $i done: $(grep '^DONE' $d/out.txt | sed -n ${i}p | cut -c1-120)" + done < $req + echo QUIT >&7; exec 7>&- + wait $pid; echo "rc=$? original=$label"; date -u +%FT%TZ + grep -E "prefill [0-9]+ tokens|PCIe probe" $d/err.txt | cut -c1-300 + grep -E "strata decode|strata serve: (prompt|decode)" $d/err.txt | cut -c1-600 | head -40 + grep "^DONE" $d/out.txt | awk '{printf "ORIG-DONE produced %s prompt_ms %s decode_ms %s -> %.2f tok/s\n", $2, $4, $5, $2*1000/$5}' +} diff --git a/scripts/profile/lct.py b/scripts/profile/lct.py index a306b1b5..4d67b1df 100644 --- a/scripts/profile/lct.py +++ b/scripts/profile/lct.py @@ -42,6 +42,7 @@ class Trace: 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): @@ -59,6 +60,38 @@ class Trace: self.t1 = int(self.meta.get("window_stop", 0)) or (max([r.end for r in self.kernels] or [0])) 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: @@ -115,37 +148,58 @@ def intersect_total(u1, u2): _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: strip parameter lists, template arguments and namespaces.""" + """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 + 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 i, ch in enumerate(n): + for k, ch in enumerate(n): if ch == "<": depth += 1 elif ch == ">": depth -= 1 elif ch == "(" and depth == 0: - cut = i + cut = k break - n = n[:cut] - out, depth = [], 0 - for ch in n: - if ch == "<": - depth += 1 - elif ch == ">": - depth -= 1 - elif depth == 0: - out.append(ch) - n = "".join(out).strip() - n = re.sub(r"^void\s+", "", n) - if "::" in n: - n = n.split("::")[-1] - n = re.sub(r"\s+", " ", n) - _fam_cache[name] = n or name + 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] @@ -153,3 +207,29 @@ 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 (