From 97d548e2b8c1c9d9c7d8d2acf7782530a3d98ece Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 12 Nov 2026 16:43:46 +0100 Subject: [PATCH] Between-graphs host breakdown (4.30 ms per round, stage by stage): between_graphs_report.py and ledger Co-Authored-By: Claude Sonnet 5.5 --- docs/experiments/step-ledger.md | 2 + .../e2e/codex/speed/between_graphs_report.py | 489 ++++++++++++++++++ 2 files changed, 491 insertions(+) create mode 100644 scripts/e2e/codex/speed/between_graphs_report.py diff --git a/docs/experiments/step-ledger.md b/docs/experiments/step-ledger.md index 82695c88..aa552c5e 100644 --- a/docs/experiments/step-ledger.md +++ b/docs/experiments/step-ledger.md @@ -81,6 +81,8 @@ Round-level totals first (they are the sum of the steps below). **Critical path of the verify graph, first read (plan 6b, tool `scripts/e2e/codex/speed/critical_path_report.py`, evidence `/data/leleka-e2e/spd-gap/runs/critical-path-67k-existing-windows/`, 2026-11-12; existing 67k replay windows r29 of `verify-tail-head-chain-cupti-windows-rerun`, about 750 graphs each, no new GPU time).** Per graph of QP (twin QQ in brackets): round (graph start to the next graph start) 17.93 ms (18.25), graph 13.20 ms (13.53), between graphs 4.74 ms (4.72; host: draft, accept, answer); inside the graph the mixer phases (end of the FFN chain to the next doorbell: GDN step, attention, router) 5.75 ms (5.77) and the FFN phases (doorbell to the end of the combine) 6.85 ms (7.16); the host/tier wait inside the FFN phases (A, B, M waits above their floor) 3.81 ms (4.13), of which the first 16 layers 1.98 ms (2.14); only 31 % (32 %) of the layers are not host-bound (22 % (23 %) in layers 0-15), the first layers wait longest (layer 0: 100 % host-bound, M wait mean 104 us, B wait 156 us, M end 358 us after the doorbell). The twins agree within 0.3 ms, so the numbers are not noise. Reading: (1) a device saving in the FFN phase reaches the round in at most 31 % of the layers (the rest is absorbed by the wait); (2) a saving in the mixer phase (K7 GDN step +0.155 ms, K7a, the QSA prelude and attention) moves the doorbell earlier and the CPU leg starts at the doorbell, so it reaches the round in full by construction (5.75 ms of the 13.2 ms graph, 32 % of the round, are mixer phases); (3) the earlier statement that the section deltas 'do not reach the round' is NOT supported: the stage A/B (PB against PG, ms/round -0.09 ms, twin spread 0.74 ms) was too noisy to see 0.7 ms (3.5 % of the round), it did not show their absence; (4) the host leg is 4.74 ms between graphs plus 3.81 ms of waiting inside them (8.55 ms of 17.93, 48 %), which is what hex-finish's host/tier work shortens. The QT window (HEAD_CHAIN_BATCH on) shows round 15.48 ms and 47.5 % of layers not host-bound against 17.93 / 31 % for QP and QQ: different sessions have different tier states, so one window per arm cannot compare placement; this is the reason to take the candidate profile in the same way (3 windows, twin). Against the vanilla window of the same replay cell (`report-qp-vs-vanl.md`, separate session, so the tier state differs): round 16.23 ms against 17.93, graph 11.54 against 13.20, **between graphs 4.70 against 4.74 (equal)**, **mixer phases 5.89 against 5.75 (LEL is not behind)**, FFN phases 5.12 against 6.85 (+1.73 ms), host/tier wait inside the graph 0.80 against 3.81 ms, layers not host-bound 62 % against 31 %. So the whole gap to vanilla in this pair sits in the FFN phases and is the host/tier wait; the mixer phases (K7, K7a, prelude, attention) and the host leg between graphs are at parity, which is why K7 was dropped (see the K7 row). Not claimed: any end-to-end gain; the reach is an upper bound without the cascade into the next layer. Next: 256k windows of the default and the candidate profile (needs a CUPTI watcher in the q245 Codex job). +**Between graphs, 4.30 ms per round (2026-11-12, `scripts/e2e/codex/speed/between_graphs_report.py`, report `/data/leleka-e2e/spd-gap/runs/critical-path-67k-existing-windows/between-graphs.md`; the same QP/QQ/QT windows, no GPU).** The 4.74 ms of `critical_path_report.py` includes 6 gaps of 30-119 ms of skipped graphs; with every consecutive pair the mean is 4.30 ms (QP 4.299, QQ 4.306, p50 4.12, p90 6.19), twins agree within 0.03 ms per stage. Stages in ms per round, all serial (the next verify graph waits for each): host accept 0.045 (the accept decision itself is 4 us, no host-decision hole); commit and draft launch 0.186; MTP round graph 0.595 (GPU-bound); MTP step graphs 1.160 (2.45 steps of 0.473 ms, GPU-bound); chain turnaround (D2H of ids and probabilities, stop rule, step launch) 0.304 with the GPU idle 0.195; last draft to window build 0.087; tier-swap wait on copy stream 70 0.371 (0 in 75 % of the rounds, 1.48 ms in the 25 % that swap; 0.83 ms of swap copies per round); per-layer-embedding staging and launch prep 0.207; **verify graph `cuGraphLaunch` call to the first verify kernel 1.345 with the GPU idle**. GPU fully idle 1.95 ms of the 4.30 (verify launch 69 % of it). Removable in principle: early launch of the next verify graph up to about 1.3 ms, tier-swap wait up to 0.37 (policy change, not bitwise), PLE staging up to 0.15 (bitwise), on-device chaining about 0.08, scan/status into the graph about 0.04. Caveats: the launch cost is 0.69 us per kernel node and vanilla pays the same in this tracer (R5: 1.485 against 1.509 ms), and part of it may be tracer inflation (untraced `drv.launch` returns in 0.008 ms in `draft-round-5090.md`, but that is when the call returns, not when the first kernel starts); an untraced 'launch call to first kernel' measurement is the missing proof before any early-launch work. Equal to vanilla (4.70 against 4.74), so this part is not the gap to vanilla; it is the next absolute saving. + Structure first, then the layer steps in graph order: embed (R7), mixer half (V3 and the kernels in it), FFN half (V2/V4 and the kernels in it), tail (R8). | id | step | LEL | VANL | difference | source | owner | status | diff --git a/scripts/e2e/codex/speed/between_graphs_report.py b/scripts/e2e/codex/speed/between_graphs_report.py new file mode 100644 index 00000000..bc89cb43 --- /dev/null +++ b/scripts/e2e/codex/speed/between_graphs_report.py @@ -0,0 +1,489 @@ +"""What fills the part of the decode round that lies between two verify graphs (ledger: the 4.7 ms "between graphs"). + +Offline analysis of CUPTI windows (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, uses no GPU. + + python3 -B between_graphs_report.py TRACE_DIR[=LABEL]... [--lct DIR] (markdown on stdout) + +A gap is the interval from the end of verify graph i (>= 900 kernels per correlation id; first and last two graphs +dropped) to the start of verify graph i+1 (gaps whose start-to-start period exceeds 200 ms are dropped). Every record +that STARTS inside the gap is attributed, on every stream and on the host thread. The gap is cut into consecutive +stages by anchors found in the trace (the scan kernels, the status read-back, the cuGraphLaunch calls, the draft +graphs, the per-layer-embedding staging, the stream-70 wait of a tier swap); the stages add up to the gap. Per stage +the report gives the wall time, the GPU busy part (union of kernels and copies of all streams), the GPU idle part and +the host thread split into time blocked in synchronisation calls, time inside other driver calls and the rest (host +compute). The GPU idle intervals of the whole gap are also listed by the kind of work before and after them. Rounds +with a tier swap (a wait on stream 70) are also reported apart. +""" +import argparse +import bisect +import collections +import sys + +DEFAULT_LCT_DIR = "/data/leleka-e2e/decode/tools" +MIN_VERIFY_KERNELS = 900 +DROPPED_GRAPHS = 2 +MAX_PERIOD_MS = 200.0 +SWAP_STREAM = 70 +COPY_ENGINE_STREAM = 7 +WAIT_CALLS = ("cuStreamSynchronize", "cuCtxSynchronize", "cuEventSynchronize") +PLE_CALLS = ("cuMemcpyHtoD_v2", "cuCtxSynchronize", "cuMemcpyDtoH_v2") +STAGES = ( + ("tail_wake", "verify end -> scan kernels start (host wakes, launches the 2 scan kernels, syncs)"), + ("scan_status", "logits scan + 4-byte status D2H + context sync"), + ("accept_host", "context sync returns -> commit graph launch call (host accept / commit staging)"), + ("draft_launch", "commit launch + draft staging + MTP round graph launch -> first draft kernel"), + ("draft_round", "MTP round graph (first draft step with the catch-up of the accepted rows)"), + ("chain_turn", "draft chain turnaround, all steps (D2H of ids/probs, stop rule, step graph launch)"), + ("chain_steps", "MTP step graphs, all steps (draft tokens 2 and on)"), + ("post_draft", "last draft end -> PLE start (D2H of the last draft, stop rule, window build) or swap wait"), + ("swap_wait", "wait on the tier-swap copy stream (stream 70) after the last draft"), + ("ple_staging", "per-layer-embedding staging of the next window rows (syncs, H2D, scatter/decode, D2H)"), + ("launch_prep", "PLE end -> verify graph cuGraphLaunch call"), + ("verify_launch", "verify cuGraphLaunch call -> first verify kernel (GPU idle)"), +) +Launch = collections.namedtuple("Launch", "kind stream start end kernels busy") +Call = collections.namedtuple("Call", "name start end") +Activity = collections.namedtuple("Activity", "start end kind") +Gap = collections.namedtuple("Gap", "end next_start next_kernels inside launches activity copies syncs calls") + + +def load_lct(lct_dir): + sys.path.insert(0, lct_dir) + import lct # noqa: PLC0415 (directory given on the command line) + return lct + + +def quantile(values, part): + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(part * len(ordered)))] if ordered else float("nan") + + +def mean_of(values): + return sum(values) / len(values) if values else float("nan") + + +def verify_spans(trace): + """(start, end, kernels) of every verify graph in time order without the first and last two; all verify corrs.""" + by_launch = collections.defaultdict(list) + for kernel in trace.kernels: + by_launch[kernel.corr].append(kernel) + big = [group for group in by_launch.values() if len(group) >= MIN_VERIFY_KERNELS] + spans = sorted((min(k.start for k in g), max(k.end for k in g), len(g)) for g in big) + return spans[DROPPED_GRAPHS:-DROPPED_GRAPHS], {g[0].corr for g in big} + + +def classify(names): + """Kind of one launch from the kernel names in start order.""" + if any("draft_commit" in name for name in names): + return "commit" + if any(name in ("verify_clear_status", "verify_scan_logits") for name in names): + return "scan" + if any("leleka_kar_ple" in name for name in names): + return "ple" + return "draft" if names[0].startswith("mtp_") else "other" + + +def build_launches(trace, verify_corrs): + """Launches (one per correlation id) of the non-verify kernels sorted by start, and the kernel-level activity.""" + by_launch = collections.defaultdict(list) + for kernel in trace.kernels: + if kernel.corr not in verify_corrs: + by_launch[kernel.corr].append(kernel) + launches, activity = [], [] + for group in by_launch.values(): + group.sort(key=lambda k: k.start) + kind = classify([trace.names.get(k.name, "?") for k in group]) + launches.append(Launch(kind, group[0].stream, group[0].start, max(k.end for k in group), len(group), + sum(k.end - k.start for k in group))) + activity.extend(Activity(k.start, k.end, kind) for k in group) + for copy in trace.copies: + activity.append(Activity(copy.start, copy.end, "copy%d" % copy.stream)) + return sorted(launches, key=lambda item: item.start), activity + + +class StartIndex: + """Records sorted by start; `inside(low, high)` returns those with low <= start < high.""" + + def __init__(self, records): + self.records = sorted(records, key=lambda r: r.start) + self.keys = [r.start for r in self.records] + + def inside(self, low, high): + return self.records[bisect.bisect_left(self.keys, low):bisect.bisect_left(self.keys, high)] + + +def build_gaps(trace, spans, verify_corrs): + launch_list, activity_list = build_launches(trace, verify_corrs) + named_calls = [Call(trace.names.get(a.name, "?"), a.start, a.end) for a in trace.apis] + indexes = dict(launches=StartIndex(launch_list), activity=StartIndex(activity_list), + copies=StartIndex(trace.copies), syncs=StartIndex(trace.syncs), calls=StartIndex(named_calls)) + gaps = [] + for (start, end, _), (next_start, _, next_kernels) in zip(spans, spans[1:]): + if 0 < (next_start - start) / 1e6 < MAX_PERIOD_MS: + pick = {name: index.inside(end, next_start) for name, index in indexes.items()} + pick["calls"] = indexes["calls"].inside(end - 1000000, next_start) + gaps.append(Gap(end, next_start, next_kernels, indexes["activity"].inside(start, end), **pick)) + return gaps + + +def first_where(items, test): + return next((item for item in items if test(item)), None) + + +def status_read_end(gap, floor): + """End of the context sync that follows the 4-byte status D2H (the accept input), or `floor`.""" + status = first_where(gap.copies, lambda c: c.ckind == 2 and c.bytes == 4) + if status is None: + return floor + sync = first_where(gap.calls, lambda c: c.name == "cuCtxSynchronize" and c.start >= status.start) + return sync.end if sync else status.end + + +def swap_wait_window(gap, after, before): + """(start, end) of the wait on the tier-swap stream between `after` and `before`, or None.""" + wait = first_where(gap.syncs, lambda y: y.stream == SWAP_STREAM and y.type == 3 and after <= y.start < before) + return (wait.start, wait.end) if wait else None + + +def ple_window(gap, after, before): + """(start, end) of the per-layer-embedding staging calls between `after` and `before`; empty at `after`.""" + calls = [c for c in gap.calls if c.name in PLE_CALLS and after <= c.start < before] + first = first_where(calls, lambda c: c.name == "cuMemcpyHtoD_v2") or first_where(calls, lambda c: True) + if first is None: + return after, after + return first.start, max(c.end for c in calls if c.start >= first.start) + + +def graph_launches(gap): + return [c for c in gap.calls if c.name == "cuGraphLaunch" and c.start >= gap.end] + + +def moments(gap): + """Boundaries of the stages, ns, monotone from the verify end to the next verify start (None = no event).""" + draft = [item for item in gap.launches if item.kind == "draft"] + scan = first_where(gap.launches, lambda item: item.kind == "scan") + launches = graph_launches(gap) + verify_call = launches[-1].start if launches else gap.next_start + scan_start = scan.start if scan else gap.end + status_end = status_read_end(gap, scan_start) + commit_call = first_where(launches, lambda c: c.start >= status_end) + draft_start = draft[0].start if draft else (commit_call.start if commit_call else status_end) + draft_end = draft[-1].end if draft else draft_start + swap = swap_wait_window(gap, draft_end, verify_call) + ple = ple_window(gap, swap[1] if swap else draft_end, verify_call) + return dict(scan=scan_start, status=status_end, commit=commit_call.start if commit_call else status_end, + draft=draft_start, round_end=draft[0].end if draft else draft_start, draft_end=draft_end, + swap=swap or (ple[0], ple[0]), ple=ple, verify_call=verify_call), draft + + +def clamp_chain(values, floor, ceiling): + """Each value limited to [previous value, ceiling], so the cuts stay in order.""" + out, current = [], floor + for value in values: + current = min(max(value, current), ceiling) + out.append(current) + return out + + +def stage_intervals(gap): + """Stage name -> list of (start, end) ns; the intervals of all stages tile the gap.""" + cut, draft = moments(gap) + order = [cut["scan"], cut["status"], cut["commit"], cut["draft"], cut["round_end"], cut["draft_end"], + cut["swap"][0], cut["swap"][1], cut["ple"][0], cut["ple"][1], cut["verify_call"]] + mark = [gap.end] + clamp_chain(order, gap.end, gap.next_start) + [gap.next_start] + turns, steps = chain_intervals(draft, mark[5], mark[6]) + return {"tail_wake": [(mark[0], mark[1])], "scan_status": [(mark[1], mark[2])], + "accept_host": [(mark[2], mark[3])], "draft_launch": [(mark[3], mark[4])], + "draft_round": [(mark[4], mark[5])], "chain_turn": turns, "chain_steps": steps, + "post_draft": [(mark[6], mark[7]), (mark[8], mark[9])], "swap_wait": [(mark[7], mark[8])], + "ple_staging": [(mark[9], mark[10])], "launch_prep": [(mark[10], mark[11])], + "verify_launch": [(mark[11], mark[12])]} + + +def chain_intervals(draft, round_end, draft_end): + """(turnaround intervals, step intervals) of the chain steps that follow the round graph.""" + turns, steps, previous = [], [], round_end + for launch in draft[1:]: + start, end = max(launch.start, previous), min(launch.end, draft_end) + turns.append((previous, start)) + steps.append((start, max(start, end))) + previous = max(start, end) + return turns, steps + + +def sweep_activity(activity, low, high): + """Disjoint GPU-busy blocks inside [low, high] and the idle intervals (start, end, kind before, kind after).""" + merged, idle, reach, kind_before = [], [], low, "verify" + for item in activity: + start, end = max(item.start, low), min(item.end, high) + if end <= start: + continue + if start > reach: + idle.append((reach, start, kind_before, item.kind)) + if merged and start <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], end) + else: + merged.append([start, end]) + if end > reach: + reach, kind_before = end, item.kind + if reach < high: + idle.append((reach, high, kind_before, "verify")) + return merged, idle + + +def overlap_length(blocks, ends, low, high): + """Length of [low, high] covered by the disjoint sorted `blocks` (`ends` = their end points).""" + covered = 0 + for block in blocks[bisect.bisect_right(ends, low):]: + if block[0] >= high: + break + covered += min(block[1], high) - max(block[0], low) + return covered + + +class Coverage: + """GPU-busy blocks (disjoint, sorted) of one gap and the length of any intervals inside them.""" + + def __init__(self, blocks): + self.blocks = blocks + self.ends = [block[1] for block in blocks] + + def busy(self, intervals): + return sum(overlap_length(self.blocks, self.ends, low, high) for low, high in intervals) + + +def union_length(intervals): + total, reach = 0, None + for start, end in sorted(intervals): + if reach is None or start > reach: + total, reach = total + end - start, end + elif end > reach: + total, reach = total + end - reach, end + return total + + +def host_split(calls, intervals): + """(ns blocked in synchronisation calls, ns in other driver calls) inside the stage intervals.""" + waiting, working = 0, 0 + for low, high in intervals: + clipped = [(max(c.start, low), min(c.end, high), c.name) for c in calls if c.end > low and c.start < high] + blocked = union_length([(a, b) for a, b, name in clipped if name in WAIT_CALLS]) + waiting += blocked + working += union_length([(a, b) for a, b, _ in clipped]) - blocked + return waiting, working + + +def measure_stage(gap, intervals, covers): + """Wall time of a stage, GPU time with kernels, with copies only, idle, and the host thread's three parts (ms).""" + wall = sum(high - low for low, high in intervals) + anything, kernels = covers[0].busy(intervals), covers[1].busy(intervals) + waiting, working = host_split(gap.calls, intervals) + return dict(wall=wall / 1e6, kernels=kernels / 1e6, copies=(anything - kernels) / 1e6, + idle=(wall - anything) / 1e6, wait=waiting / 1e6, call=working / 1e6, + compute=max(0.0, wall - waiting - working) / 1e6) + + +def overlap_facts(gap, stages): + """Work that runs beside the critical path: commit graph, hidden host calls, swap copies, copies into the graph.""" + commit = first_where(gap.launches, lambda item: item.kind == "commit") + draft_end, next_start = stages["post_draft"][0][0], gap.next_start + swap = [c for c in gap.copies if c.stream == SWAP_STREAM] + round_wall = sum(high - low for low, high in stages["draft_round"]) + host_blocked = host_split(gap.calls, stages["draft_round"])[0] + return dict(commit_ms=(commit.end - commit.start) / 1e6 if commit else 0.0, + commit_slack_ms=(draft_end - commit.end) / 1e6 if commit else 0.0, + host_busy_under_draft_ms=(round_wall - host_blocked) / 1e6, swap_copies=len(swap), + swap_busy_ms=sum(c.end - c.start for c in swap) / 1e6, + swap_after_draft_ms=sum(max(0, c.end - max(c.start, draft_end)) for c in swap) / 1e6, + into_graph_ms=sum(max(0, c.end - next_start) for c in gap.copies) / 1e6) + + +def inside_graph(gap): + """Kind -> [count, ms] of the non-verify GPU work that starts while the preceding verify graph runs.""" + totals = collections.defaultdict(lambda: [0, 0.0]) + for item in gap.inside: + totals[item.kind][0] += 1 + totals[item.kind][1] += (item.end - item.start) / 1e6 + return totals + + +def measure_gap(gap): + stages = stage_intervals(gap) + blocks, idle = sweep_activity(gap.activity, gap.end, gap.next_start) + kernel_work = [item for item in gap.activity if not item.kind.startswith("copy")] + covers = (Coverage(blocks), Coverage(sweep_activity(kernel_work, gap.end, gap.next_start)[0])) + return dict(total=(gap.next_start - gap.end) / 1e6, swap=any(c.stream == SWAP_STREAM for c in gap.copies), + next_kernels=gap.next_kernels, inside=inside_graph(gap), idle=idle, + stages={name: measure_stage(gap, spans, covers) for name, spans in stages.items()}, + draft_steps=len(stages["chain_steps"]), overlap=overlap_facts(gap, stages)) + + +def load_window(trace_dir, lct): + trace = lct.Trace(trace_dir) + spans, verify_corrs = verify_spans(trace) + gaps = build_gaps(trace, spans, verify_corrs) + graph_ms = mean_of([(end - start) / 1e6 for start, end, _ in spans]) + return dict(rounds=[measure_gap(gap) for gap in gaps], graph_ms=graph_ms, graphs=len(spans)) + + +def cell_triplet(values): + return "%.3f / %.3f / %.3f" % (mean_of(values), quantile(values, 0.5), quantile(values, 0.9)) + + +def stage_values(rounds, name, field): + return [r["stages"][name][field] for r in rounds] + + +def main_table(windows): + labels = list(windows) + lines = ["| stage | " + " | ".join("%s mean / p50 / p90" % label for label in labels) + " | what |", + "| --- |" + " --- |" * (len(labels) + 1)] + for name, text in STAGES: + cells = [cell_triplet(stage_values(windows[label]["rounds"], name, "wall")) for label in labels] + lines.append("| %s | %s | %s |" % (name, " | ".join(cells), text)) + totals = [cell_triplet([r["total"] for r in windows[label]["rounds"]]) for label in labels] + lines.append("| **between graphs** | %s | verify end to next verify start |" % " | ".join(totals)) + return lines + + +def split_table(rounds): + lines = ["| stage | wall | GPU kernels running | GPU copies only | GPU idle | host blocked in sync " + "| host in other calls | host compute |", "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"] + fields = ("wall", "kernels", "copies", "idle", "wait", "call", "compute") + for name, _ in STAGES: + cells = ["%.3f" % mean_of(stage_values(rounds, name, field)) for field in fields] + lines.append("| %s | %s |" % (name, " | ".join(cells))) + sums = ["%.3f" % sum(mean_of(stage_values(rounds, n, f)) for n, _ in STAGES) for f in fields] + return lines + ["| **sum** | %s |" % " | ".join(sums)] + + +def swap_table(windows): + lines = ["| window | rounds | swap rounds | between graphs, plain rounds (mean / p50 / p90) | swap rounds mean |", + "| --- | ---: | ---: | --- | ---: |"] + for label, window in windows.items(): + plain = [r["total"] for r in window["rounds"] if not r["swap"]] + swap = [r["total"] for r in window["rounds"] if r["swap"]] + lines.append("| %s | %d | %d | %s | %.3f |" % (label, len(window["rounds"]), len(swap), cell_triplet(plain), + mean_of(swap))) + return lines + + +def plain_stage_table(windows): + labels = list(windows) + head = ["%s plain mean / p90" % label for label in labels] + ["%s swap mean" % label for label in labels] + lines = ["| stage | " + " | ".join(head) + " |", "| --- |" + " --- |" * len(head)] + for name, _ in STAGES: + plain, swap = [], [] + for label in labels: + rounds = windows[label]["rounds"] + values = [stage_values([r for r in rounds if r["swap"] == flag], name, "wall") for flag in (False, True)] + plain.append("%.3f / %.3f" % (mean_of(values[0]), quantile(values[0], 0.9))) + swap.append("%.3f" % mean_of(values[1])) + lines.append("| %s | %s | %s |" % (name, " | ".join(plain), " | ".join(swap))) + return lines + + +def idle_table(rounds): + totals = collections.defaultdict(lambda: [0, 0.0]) + for one in rounds: + for start, end, before, after in one["idle"]: + totals[(before, after)][0] += 1 + totals[(before, after)][1] += (end - start) / 1e6 + lines = ["| GPU idle interval (kind before -> after) | count per round | ms per round |", "| --- | ---: | ---: |"] + for (before, after), (count, total) in sorted(totals.items(), key=lambda item: -item[1][1])[:12]: + lines.append("| %s -> %s | %.2f | %.3f |" % (before, after, count / len(rounds), total / len(rounds))) + return lines + + +def launch_cost_table(windows): + """Verify launch call to first kernel against the kernel count of the graph (per-node cost of the launch).""" + lines = ["| window | kernels in graph | rounds | verify_launch mean / p90 ms | us per kernel |", + "| --- | ---: | ---: | --- | ---: |"] + for label, window in windows.items(): + groups = collections.defaultdict(list) + for one in window["rounds"]: + groups[one["next_kernels"] // 50 * 50].append(one["stages"]["verify_launch"]["wall"]) + for size, values in sorted(groups.items()): + if len(values) >= 20: + lines.append("| %s | %d-%d | %d | %.3f / %.3f | %.3f |" % ( + label, size, size + 49, len(values), mean_of(values), quantile(values, 0.9), + 1000 * mean_of(values) / (size + 25))) + return lines + + +def chain_length_table(windows): + """Rounds by the number of chain step graphs after the round graph: share and mean ms between graphs.""" + lines = ["| window | chain steps | share of rounds | between graphs mean ms | draft part (round + chain) ms |", + "| --- | ---: | ---: | ---: | ---: |"] + draft_names = ("draft_launch", "draft_round", "chain_turn", "chain_steps") + for label, window in windows.items(): + rounds = window["rounds"] + for steps in sorted({r["draft_steps"] for r in rounds}): + group = [r for r in rounds if r["draft_steps"] == steps] + if len(group) * 100 >= len(rounds): + draft = [sum(r["stages"][n]["wall"] for n in draft_names) for r in group] + lines.append("| %s | %d | %.1f %% | %.3f | %.3f |" % ( + label, steps, 100 * len(group) / len(rounds), mean_of([r["total"] for r in group]), mean_of(draft))) + return lines + + +def inside_table(windows): + """Non-verify GPU work that starts while a verify graph runs: per graph count and GPU ms by kind.""" + lines = ["| window | kind of work (starts inside the verify graph) | count per graph | ms per graph |", + "| --- | --- | ---: | ---: |"] + for label, window in windows.items(): + rounds = window["rounds"] + kinds = sorted({kind for r in rounds for kind in r["inside"]}) + for kind in kinds: + count = mean_of([r["inside"][kind][0] if kind in r["inside"] else 0 for r in rounds]) + busy = mean_of([r["inside"][kind][1] if kind in r["inside"] else 0.0 for r in rounds]) + lines.append("| %s | %s | %.2f | %.3f |" % (label, kind, count, busy)) + return lines + + +def overlap_table(windows): + keys = ("commit_ms", "commit_slack_ms", "host_busy_under_draft_ms", "swap_copies", "swap_busy_ms", + "swap_after_draft_ms", "into_graph_ms") + lines = ["| mean per round | " + " | ".join(windows) + " |", "| --- |" + " ---: |" * len(windows)] + for key in keys + ("draft_steps",): + cells = [] + for window in windows.values(): + values = [r["overlap"][key] if key in r["overlap"] else r[key] for r in window["rounds"]] + cells.append("%.3f" % mean_of(values)) + lines.append("| %s | %s |" % (key, " | ".join(cells))) + return lines + + +def report(windows): + lines = ["| window | graphs | rounds | graph ms | between graphs ms |", "| --- | ---: | ---: | ---: | ---: |"] + for label, window in windows.items(): + between = mean_of([r["total"] for r in window["rounds"]]) + lines.append("| %s | %d | %d | %.3f | %.3f |" % (label, window["graphs"], len(window["rounds"]), + window["graph_ms"], between)) + lines += ["", "### Stages, ms per round"] + main_table(windows) + ["", "### Plain rounds and swap rounds"] + lines += swap_table(windows) + [""] + plain_stage_table(windows) + for label, window in windows.items(): + lines += ["", "### %s: wall, GPU and host split per stage (mean ms per round)" % label] + lines += split_table(window["rounds"]) + [""] + idle_table(window["rounds"]) + lines += ["", "### Verify graph launch cost against graph size"] + launch_cost_table(windows) + lines += ["", "### Chain length"] + chain_length_table(windows) + lines += ["", "### Other work inside the verify graph"] + inside_table(windows) + lines += ["", "### Work beside the critical path"] + overlap_table(windows) + print("\n".join(lines)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("traces", nargs="+", help="TRACE_DIR or TRACE_DIR=LABEL") + parser.add_argument("--lct", default=DEFAULT_LCT_DIR) + args = parser.parse_args() + lct = load_lct(args.lct) + windows = {} + for item in args.traces: + path, _, label = item.partition("=") + windows[label or path.rstrip("/").split("/")[-2]] = load_window(path, lct) + report(windows) + + +if __name__ == "__main__": + main()