Files
leleka/scripts/e2e/codex/speed/window_increment_report.py
Pavlo RatushnyiandClaude Sonnet 5.5 6c0a5fc1f0 Windows of S11, S9, U5a: section deltas with the repeat as noise (reader script and note)
window_increment_report.py reads CUPTI windows offline (extract on the server, report on the laptop): switches that
really ran (kernel names, engine log), per-T per-launch durations, increment deltas against the CZ-CD repeat.
The note records that the windows of verify-s11-s9-u5a-cupti-windows are cumulative and the deltas per switch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 01:24:28 +01:00

357 lines
17 KiB
Python

"""Section deltas between CUPTI windows that differ by one verify switch (ledger rows S11, S9, U5a, K10).
Offline analysis of CUPTI trace directories (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, no GPU.
extract TRACE_DIR LABEL [--lct DIR] [--engine-log FILE] (python3 -B; reads the trace, writes JSON on stdout)
per window row count T (the CPU-row copy grid is T * 10 blocks) of every verify graph (>= 900 kernels per
correlation id, first and last two dropped): per-graph metrics and per-launch durations of the section kernels
(summaries n / mean / sd / p10 / p50 / p90), kernel names with launches per graph, the switch line of the
engine log. `--lct` defaults to /data/leleka-e2e/decode/tools (read only).
report CONTROL STEP1 STEP2 STEP3 REPEAT (five extract JSON files; markdown on stdout)
the switches each window ran (kernel-name evidence), per-T section tables, increments STEP1-CONTROL,
STEP2-STEP1, STEP3-STEP2 with their noise REPEAT-STEP3 (REPEAT is the same configuration as STEP3) and the verify
graph duration.
Sections (all per graph, kernel time = sum of kernel durations, span = first start to last end, gaps included):
combine `mtp_full_combine` (S11 off) or `leleka_verify_combine_k10_vec4` (S11 on): one launch per layer
head kernels after the last `mtp_full_native_write` up to the `head_quant` of the language-model head:
5 launches per token (S9 off) or the multi read (S9 on); span = from that write's end to that quantize
pair layer halves' hyper-connection split + down (`chain_gr_split` + `chain_gr_down*`) or the fused
`leleka_gr_down_fused*` (U5a); the head's instance is not counted here
read the same instance up to `chain_gr_up*` (the whole hyper-connection read of a layer half)
gr every hyper-connection kernel of the graph (layers and head)
A verdict of "resolved" needs the p50 and the mean delta to agree in sign, |delta of the mean| above two standard errors
of the difference, and both above the repeat window pair's own delta.
"""
import argparse
import collections
import json
import re
import statistics as st
import sys
COMBINE_NAMES = ("mtp_full_combine", "leleka_verify_combine_k10_vec4")
SPLIT, DOWN, FUSED, UP = "chain_gr_split", "chain_gr_down", "leleka_gr_down_fused", "chain_gr_up"
SWITCH_RE = re.compile(r"combine_vec4: (\w+), head_mix_multi: (\w+), gr_down_fused: (\w+)")
KEY_NAMES = ("mtp_full_combine", "leleka_verify_combine_k10_vec4", "mtp_full_gr_norm", "mtp_full_down_silu",
"mtp_full_pre_final", "mtp_full_native_write", "chain_gr_split", "chain_gr_down_t2w8_nb4",
"leleka_gr_down_fused_t2w8", "chain_gr_up8")
MIN_GRAPHS = 15
def summary(values):
v = sorted(values)
if not v:
return None
at = lambda p: v[min(len(v) - 1, int(p * len(v)))] # noqa: E731
return {"n": len(v), "mean": st.mean(v), "sd": st.pstdev(v) if len(v) > 1 else 0.0, "p10": at(.1), "p50": at(.5),
"p90": at(.9)}
# ---------------------------------------------------------------- extract
def verify_graphs(trace):
by = collections.defaultdict(list)
for k in trace.kernels:
by[k.corr].append(k)
ids = sorted((c for c, v in by.items() if len(v) >= 900), key=lambda c: min(k.start for k in by[c]))
return [sorted(by[c], key=lambda k: k.start) for c in ids[2:-2]]
def window_rows(ks, name):
rows = collections.Counter(k.gx // 10 for k in ks if "copy_rows" in name(k))
return rows.most_common(1)[0][0] if rows else -1
def hc_instances(ks, name, last_combine_start):
"""(first, down, up, is_head) per hyper-connection read: split or fused kernel, the down kernel after a split, the
up kernel; the instances after the last combine are the head's."""
streams = collections.defaultdict(list)
for k in ks:
streams[k.stream].append(k)
out = []
for seq in streams.values():
for i, k in enumerate(seq):
n = name(k)
if n != SPLIT and not n.startswith(FUSED):
continue
nxt = seq[i + 1:i + 4]
down = nxt[0] if n == SPLIT and nxt and name(nxt[0]).startswith(DOWN) else None
up = next((x for x in nxt if name(x).startswith(UP)), None)
if up is not None:
out.append((k, down, up, k.start > last_combine_start))
return out
def graph_record(ks, name):
"""One graph: its metrics (us) and the per-launch lists of the section kernels."""
us = lambda x: x / 1e3 # noqa: E731
dur = lambda k: us(k.end - k.start) # noqa: E731
combines = [k for k in ks if name(k) in COMBINE_NAMES]
writes = [k for k in ks if name(k) == "mtp_full_native_write"]
quant = [k for k in ks if name(k) == "head_quant"]
if not combines or not writes or not quant:
return None
last_write, last_quant = writes[-1], quant[-1]
head = [k for k in ks if last_write.end <= k.start < last_quant.start]
inst = hc_instances(ks, name, combines[-1].start)
layer = [i for i in inst if not i[3]]
gr_all = [k for i in inst for k in (i[0], i[1], i[2]) if k is not None]
pair_dur = [dur(a) + (dur(d) if d else 0.0) for a, d, u, _ in layer]
pair_span = [us((d or a).end - a.start) for a, d, u, _ in layer]
read_span = [us(u.end - a.start) for a, d, u, _ in layer]
return {
"metrics": {
"kernels": len(ks), "graph_span": us(max(k.end for k in ks) - ks[0].start),
"kernel_sum": sum(dur(k) for k in ks),
"combine_n": len(combines), "combine_sum": sum(dur(k) for k in combines),
"head_n": len(head), "head_sum": sum(dur(k) for k in head),
"head_span": us(last_quant.start - last_write.end),
"pair_n": len(layer), "pair_sum": sum(pair_dur), "pair_span_sum": sum(pair_span),
"read_span_sum": sum(read_span), "gr_n": len(gr_all), "gr_sum": sum(dur(k) for k in gr_all),
},
"launch": {
"combine": [dur(k) for k in combines],
"split": [dur(a) for a, d, u, h in layer if d], "down": [dur(d) for a, d, u, h in layer if d],
"fused": [dur(a) for a, d, u, h in layer if not d], "up": [dur(u) for a, d, u, h in layer],
"pair_dur": pair_dur, "pair_span": pair_span, "read_span": read_span,
},
}
def switch_line(engine_log):
if not engine_log:
return None
for line in open(engine_log, errors="replace"):
m = SWITCH_RE.search(line)
if m and "sm120 switches" in line:
return {"combine_vec4": m.group(1), "head_mix_multi": m.group(2), "gr_down_fused": m.group(3)}
return None
def extract(path, label, lct_dir, engine_log):
sys.path.insert(0, lct_dir)
sys.dont_write_bytecode = True
import lct
trace = lct.Trace(path)
name = lambda k: trace.names.get(k.name, "?") # noqa: E731
graphs = verify_graphs(trace)
by_t = collections.defaultdict(list)
names = collections.defaultdict(lambda: [0, 0.0])
for ks in graphs:
for k in ks:
e = names[name(k)]
e[0] += 1
e[1] += (k.end - k.start) / 1e3
rec = graph_record(ks, name)
if rec:
by_t[window_rows(ks, name)].append(rec)
out = {"label": label, "trace": path, "graphs": len(graphs), "switch_line": switch_line(engine_log), "byT": {},
"names": {n: {"per_graph": c / len(graphs), "mean_us": us / c} for n, (c, us) in names.items()}}
for t, recs in sorted(by_t.items()):
out["byT"][str(t)] = {
"graphs": len(recs),
"graph": {m: summary([r["metrics"][m] for r in recs]) for m in recs[0]["metrics"]},
"launch": {k: summary([x for r in recs for x in r["launch"][k]]) for k in recs[0]["launch"]},
}
json.dump(out, sys.stdout, separators=(",", ":"))
# ---------------------------------------------------------------- report
def per_launch(window, kind, t):
return window["byT"].get(str(t), {}).get("launch", {}).get(kind)
def get(window, t, metric):
return window["byT"].get(str(t), {}).get("graph", {}).get(metric)
def usable_ts(windows):
sets = [{int(t) for t, v in w["byT"].items() if v["graphs"] >= MIN_GRAPHS and int(t) > 0} for w in windows]
return sorted(set.intersection(*sets))
def inferred(w):
n = lambda k: w["names"].get(k, {"per_graph": 0})["per_graph"] # noqa: E731
on = []
if n("leleka_verify_combine_k10_vec4") > 0 and n("mtp_full_combine") == 0:
on.append("S11")
if n("mtp_full_gr_norm") == 0:
on.append("S9")
if n("leleka_gr_down_fused_t2w8") > 0 and n("chain_gr_split") <= 1: # the head's own read keeps split + down
on.append("U5a")
return "+".join(on) or "none"
def evidence(windows):
print("### 1. Switches each window ran\n")
print("Launches per verify graph of the switch kernels (all graphs of the window), and the switch line of the "
"engine log (`requested Sm120Switches`).\n")
print("| kernel | " + " | ".join(w["label"] for w in windows) + " |")
print("| --- |" + " ---: |" * len(windows))
for n in KEY_NAMES:
cells = ["%.2f" % w["names"].get(n, {"per_graph": 0})["per_graph"] for w in windows]
print("| `%s` | " % n + " | ".join(cells) + " |")
log = ["/".join(w["switch_line"][k] for k in ("combine_vec4", "head_mix_multi", "gr_down_fused"))
if w["switch_line"] else "n/a" for w in windows]
print("| engine log: combine_vec4 / head_mix_multi / gr_down_fused | " + " | ".join(log) + " |")
print("| **ran** (from the kernels) | " + " | ".join(inferred(w) for w in windows) + " |\n")
def fmt(s, key="p50"):
return "%.2f" % s[key] if s else "-"
LAUNCH_KINDS = ("combine", "split", "down", "fused", "up", "pair_dur", "pair_span", "read_span")
def launch_tables(windows, ts):
print("### 2. Per-launch p50 duration (us) and launches per graph, by window rows T\n")
print("Cell: p50 per-launch duration (launches per graph). `pair_dur` = split + down kernel time (U5a: the fused "
"kernel), `pair_span` = split start to down end, `read_span` = split/fused start to `chain_gr_up8` end, "
"all per layer half.\n")
for t in ts:
print("T=%d (graphs %s)\n" % (t, " / ".join(str(w["byT"][str(t)]["graphs"]) for w in windows)))
print("| kernel | " + " | ".join(w["label"] for w in windows) + " |")
print("| --- |" + " ---: |" * len(windows))
for kind in LAUNCH_KINDS:
cells = []
for w in windows:
s = per_launch(w, kind, t)
cells.append("%s (%.1f)" % (fmt(s), s["n"] / w["byT"][str(t)]["graphs"]) if s else "-")
print("| %s | " % kind + " | ".join(cells) + " |")
rows = (("head launches per graph (mean)", "head_n", "mean"),
("head kernel time, us per graph (p50)", "head_sum", "p50"),
("head span, us per graph (p50)", "head_span", "p50"),
("GR kernels per graph (mean)", "gr_n", "mean"),
("GR kernel time, us per graph (p50)", "gr_sum", "p50"))
for label, metric, key in rows:
print("| %s | " % label + " | ".join(fmt(get(w, t, metric), key) for w in windows) + " |")
print()
def diff(a, b):
"""b minus a for one metric at one T: (delta p50, delta mean, standard error of the delta of the means)."""
if not a or not b:
return None
se = (a["sd"] ** 2 / a["n"] + b["sd"] ** 2 / b["n"]) ** .5
return b["p50"] - a["p50"], b["mean"] - a["mean"], se
def verdict(d, noise):
if not d or not noise:
return "n/a"
p50, mean, se = d
if (p50 > 0) == (mean > 0) and abs(mean) > 2 * se and min(abs(p50), abs(mean)) > max(abs(noise[0]), abs(noise[1])):
return "resolved"
return "below noise"
INCREMENTS = (("S11 combine vec4 (CS - CP)", 0), ("S9 head mix multi (CH - CS)", 1), ("U5a fused HC down (CD - CH)", 2))
SECTIONS = {
0: (("combine kernel time per graph", "combine_sum"),),
1: (("head kernel time per graph", "head_sum"), ("head span per graph", "head_span")),
2: (("pair kernel time per graph (layers)", "pair_sum"), ("pair span per graph (layers)", "pair_span_sum"),
("read span per graph (layers)", "read_span_sum"), ("GR role kernel time per graph", "gr_sum")),
}
LAUNCH_ROWS = {0: (("combine launch", "combine"),), 1: (),
2: (("pair kernel time per layer half", "pair_dur"), ("pair span per layer half", "pair_span"),
("read span per layer half", "read_span"))}
def increments(w, ts):
print("### 3. Increments and noise\n")
print("Delta = later window minus earlier. Cell: p50 / mean of the per-graph value in ms per graph (negative = the "
"later window is faster), then the verdict against the repeat pair (CZ minus CD, the same configuration). "
"Noise rows give that repeat's own p50 / mean delta.\n")
for title, i in INCREMENTS:
a, b = w[i], w[i + 1]
print("**%s**\n" % title)
print("| section | " + " | ".join("T=%d" % t for t in ts) + " |\n| --- |" + " ---: |" * len(ts))
for label, metric in SECTIONS[i]:
ds = [diff(get(a, t, metric), get(b, t, metric)) for t in ts]
ns = [diff(get(w[3], t, metric), get(w[4], t, metric)) for t in ts]
print("| %s | " % label + " | ".join(
"%+.4f / %+.4f (%s)" % (d[0] / 1e3, d[1] / 1e3, verdict(d, n)) if d else "-"
for d, n in zip(ds, ns)) + " |")
print("| noise: %s | " % label + " | ".join(
"%+.4f / %+.4f" % (n[0] / 1e3, n[1] / 1e3) if n else "-" for n in ns) + " |")
print()
launch_increment(w, i, ts)
mix_summary(w, ts)
def launch_increment(w, i, ts):
if not LAUNCH_ROWS[i]:
return
a, b = w[i], w[i + 1]
print("Per launch (us, p50 / mean; the combine is one launch per layer, the pair one per layer half):\n")
print("| per launch | " + " | ".join("T=%d" % t for t in ts) + " |\n| --- |" + " ---: |" * len(ts))
for label, kind in LAUNCH_ROWS[i]:
ds = [diff(per_launch(a, kind, t), per_launch(b, kind, t)) for t in ts]
ns = [diff(per_launch(w[3], kind, t), per_launch(w[4], kind, t)) for t in ts]
print("| %s | " % label + " | ".join("%+.2f / %+.2f" % d[:2] if d else "-" for d in ds) + " |")
print("| noise: %s | " % label + " | ".join("%+.2f / %+.2f" % n[:2] if n else "-" for n in ns) + " |")
print()
def mix_summary(w, ts):
print("### 4. Section delta weighted by the earlier window's T mix (ms per graph, p50 deltas)\n")
print("| increment | section | delta | repeat delta | spread over T (min .. max) |")
print("| --- | --- | ---: | ---: | --- |")
for title, i in INCREMENTS:
a, b = w[i], w[i + 1]
weights = {t: a["byT"][str(t)]["graphs"] for t in ts}
total = sum(weights.values())
for label, metric in SECTIONS[i]:
ds = {t: diff(get(a, t, metric), get(b, t, metric)) for t in ts}
ns = {t: diff(get(w[3], t, metric), get(w[4], t, metric)) for t in ts}
mixed = sum(weights[t] * ds[t][0] for t in ts) / total / 1e3
repeat = sum(weights[t] * ns[t][0] for t in ts) / total / 1e3
lo, hi = min(d[0] for d in ds.values()) / 1e3, max(d[0] for d in ds.values()) / 1e3
print("| %s | %s | %+.4f | %+.4f | %+.4f .. %+.4f |" % (title.split(" (")[0], label, mixed, repeat, lo, hi))
print()
def graph_totals(windows, ts):
print("### 5. Verify graph duration (first kernel start to last kernel end), p50 us (kernels per graph, p50)\n")
print("Sanity total only: each window is its own session, so the expert-tier state differs between windows "
"(compare within one T and one window, not as a section delta).\n")
print("| T | " + " | ".join(w["label"] for w in windows) + " |")
print("| --- |" + " ---: |" * len(windows))
for t in ts:
cells = ["%s (%s)" % (fmt(get(w, t, "graph_span")), fmt(get(w, t, "kernels"))) for w in windows]
print("| %d | " % t + " | ".join(cells) + " |")
print()
def report(paths):
w = [json.load(open(p)) for p in paths]
ts = usable_ts(w)
print("Windows: " + ", ".join("%s = %s" % (x["label"], x["trace"]) for x in w))
print("T values with at least %d graphs in every window: %s\n" % (MIN_GRAPHS, ts))
evidence(w)
launch_tables(w, ts)
increments(w, ts)
graph_totals(w, ts)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
e = sub.add_parser("extract")
e.add_argument("trace")
e.add_argument("label")
e.add_argument("--lct", default="/data/leleka-e2e/decode/tools")
e.add_argument("--engine-log")
r = sub.add_parser("report")
r.add_argument("files", nargs=5)
a = ap.parse_args()
if a.cmd == "extract":
extract(a.trace, a.label, a.lct, a.engine_log)
else:
report(a.files)
if __name__ == "__main__":
main()