Files
leleka/scripts/e2e/codex/speed/between_graphs_report.py

490 lines
24 KiB
Python

"""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()