Reads the five independent windows CP/WD/WH/WW/WZ of request 29 (read-only on the server) per window rows T: D1 DOWN_SUB16 -0.21 ms per graph on F layers (resolved at every T), D2 HITS_IN_COMBINE -0.043 ms per graph (tail after the CPU rows, resolved), D3 WAIT_M_ROWS a resolved loss (kernel floor 1.4 us + 0.43 us per block). ffn_window_report.py extracts one trace per call (stdlib, lct.py) and prints the report with the noise estimates. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
756 lines
36 KiB
Python
756 lines
36 KiB
Python
"""FFN switches D1 (DOWN_SUB16), D2 (HITS_IN_COMBINE), D3 (WAIT_M_ROWS): section deltas from independent CUPTI windows.
|
|
|
|
Offline analysis of CUPTI trace directories (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, no GPU.
|
|
Built on the extract code of ffn_phase_timeline.py (layer records of the 48-doorbell verify graphs) and
|
|
window_increment_report.py (verify graph = >= 900 kernels per correlation id, first and last two dropped, window rows
|
|
T = grid of the CPU-row copy kernel / 10), generalised for the kernels the three switches rename or remove.
|
|
|
|
extract TRACE_DIR LABEL OUT.json.gz|- [--engine-log FILE] [--lct DIR] (python3 -B; reads one trace, no GPU)
|
|
per layer the kernels from the doorbell to the end of the combine (offsets in ns, kernel family, stream, grid),
|
|
per graph its span and window rows T, per T and kernel family the launch and per-graph-time summaries, the
|
|
switch line of the engine log. `--lct` defaults to /data/leleka-e2e/decode/tools (read only).
|
|
report CP WD WH WW WZ (the five extract files, CP first; markdown on stdout)
|
|
|
|
Roles of a layer's FFN half (kernel family -> role): DB doorbell, EQ expert-input quantize, WA wait A (plan copy),
|
|
V_GU / V_DN gate-up and down of the VRAM-tier pass (first launch of the layer), P_GU / P_DN the same of the PCIe-tier
|
|
pass (second launch), WB wait B (PCIe leg), WM wait M (CPU rows), CR copy rows, WC the D3 kernel (wait M + copy rows),
|
|
AH add_hits (gone with D2), CB combine (`mtp_full_combine`, or the D2 `..._hits` kernel). Everything else is the
|
|
shared-expert chain (SH, a side stream).
|
|
The FFN phase is measured from the doorbell start to the END OF THE COMBINE: the same end in every variant (D2 removes
|
|
`add_hits`, so the old end "add_hits end" does not exist there).
|
|
Layer classes (as ffn_phase_timeline.py; they keep sessions with a different expert-tier state comparable):
|
|
F no PCIe leg (wait B <= 3.5 us) and no CPU wait: the wait+copy region (wait M start to copy end; D3: the one
|
|
kernel) is within 4 us of the 5th percentile of that region in the same window at the same T (the same rule in
|
|
every variant, because D3 hides wait M inside its kernel)
|
|
C CPU rows late, no PCIe leg; X PCIe leg (wait B above 3.5 us), with or without a CPU wait
|
|
A verdict of "resolved" needs the p50 and the mean delta to agree in sign, |mean delta| above two standard errors
|
|
(over graphs), and both above the noise. Noise of the F-class phase = the larger of (i) the sum of the p50 differences
|
|
of the kernels no switch touches in the F-class chain (DB EQ WA V_GU WB) between CP and a variant and (ii) the
|
|
first-half/second-half drift of the F-class phase p50 inside one window; noise of one device kernel = the largest p50
|
|
drift of the untouched device kernels (hyper-connection, quantize). There is no repeat window of one configuration.
|
|
"""
|
|
import argparse
|
|
import collections
|
|
import gzip
|
|
import json
|
|
import re
|
|
import statistics as st
|
|
import sys
|
|
|
|
FIRST = {"chain_doorbell_publish": "DB", "doorbell_publish_res": "DB", "quantize_q8_1": "EQ",
|
|
"chain_wait_copy_i32": "WA", "copy_i32_from_mapped": "PC", "native_gu_swiglu": "GU",
|
|
"native_down_multi": "DN", "verify_wait_flag_ge": "WAIT", "wait_flag_ge": "WAIT", "fetch_blobs": "FB",
|
|
"rebase_ptrs": "FB", "chain_copy_rows_from_mapped": "CR", "copy_rows_from_mapped": "CR", "add_hits": "AH",
|
|
"mtp_full_combine": "CB", "leleka_verify_wait_copy_rows": "WC"}
|
|
WAIT_FLOOR_US = 4.0
|
|
B_LONG_US = 3.5
|
|
SWITCH_RE = re.compile(r"requested Sm120Switches \{ (.*?) \}")
|
|
|
|
|
|
def role_of(fam):
|
|
if fam in FIRST:
|
|
return FIRST[fam]
|
|
if fam.startswith("sm120_moe_gu_swiglu"):
|
|
return "GU"
|
|
if fam.startswith(("window_moe_down", "sm120_moe_down")):
|
|
return "DN"
|
|
if fam.startswith("leleka_verify_combine"):
|
|
return "CB"
|
|
return "SH"
|
|
|
|
|
|
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 [len(v), st.mean(v), st.pstdev(v) if len(v) > 1 else 0.0, at(.1), at(.5), at(.9)] # n mean sd p10 p50 p90
|
|
|
|
|
|
# ---------------------------------------------------------------- extract (needs lct.py)
|
|
def graphs_of(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 layer_record(lct, trace, fams, ks, bells, li):
|
|
name = lambda k: trace.names.get(k.name, "?") # noqa: E731
|
|
bell = ks[bells[li]]
|
|
lo = ks[bells[li - 1]].start if li else ks[0].start
|
|
nxt = ks[bells[li + 1]].start if li < len(bells) - 1 else bell.start + 600000
|
|
seg = [k for k in ks if lo <= k.start < nxt]
|
|
qsa = any("topk_cluster" in name(k) for k in seg if k.start < bell.start)
|
|
ffn = [k for k in seg if k.start >= bell.start]
|
|
comb = [k for k in ffn if "combine" in name(k)]
|
|
if not comb:
|
|
return None
|
|
rec = []
|
|
for k in [k for k in ffn if k.start <= comb[0].start]:
|
|
fam = fams.setdefault(lct.family(name(k)), len(fams))
|
|
rec.append([fam, k.stream, k.start - bell.start, k.end - k.start, k.gx, k.gy])
|
|
return [0, li, int(qsa), 0, rec, comb[0].end - bell.start, comb[0].start - bell.start]
|
|
|
|
|
|
def family_stats(lct, trace, graphs):
|
|
"""Per window rows T and kernel family: launches (n mean sd p10 p50 p90 us) and per-graph time sum (ms)."""
|
|
name = lambda k: trace.names.get(k.name, "?") # noqa: E731
|
|
dur, per_graph, count = collections.defaultdict(list), collections.defaultdict(list), collections.Counter()
|
|
for ks in graphs:
|
|
t = window_rows(ks, name)
|
|
count[t] += 1
|
|
sums = collections.defaultdict(float)
|
|
for k in ks:
|
|
fam = lct.family(name(k))
|
|
dur[(t, fam)].append((k.end - k.start) / 1e3)
|
|
sums[fam] += (k.end - k.start) / 1e3
|
|
for fam, s in sums.items():
|
|
per_graph[(t, fam)].append(s)
|
|
out = {}
|
|
for (t, fam), v in dur.items():
|
|
out.setdefault(str(t), {"graphs": count[t], "fam": {}})["fam"][fam] = {
|
|
"launch": summary(v), "graph_sum": summary(per_graph[(t, fam)]), "per_graph": len(v) / count[t]}
|
|
return out
|
|
|
|
|
|
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:
|
|
return dict((a.strip(), b.strip()) for a, b in (x.split(":", 1) for x in m.group(1).split(", ")
|
|
if ":" in x and "{" not in x and "}" not in x))
|
|
return None
|
|
|
|
|
|
def extract(path, label, out, 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 = graphs_of(trace)
|
|
fams, layers, gmeta = {}, [], []
|
|
for gi, ks in enumerate(graphs):
|
|
t = window_rows(ks, name)
|
|
gmeta.append([gi, t, max(k.end for k in ks) - ks[0].start, len(ks)])
|
|
bells = [i for i, k in enumerate(ks) if "doorbell_publish" in name(k)]
|
|
if len(bells) != 48:
|
|
continue
|
|
for li in range(48):
|
|
rec = layer_record(lct, trace, fams, ks, bells, li)
|
|
if rec:
|
|
rec[0], rec[3] = gi, t
|
|
layers.append(rec)
|
|
blob = json.dumps({"path": path, "label": label, "switches": switch_line(engine_log), "graphs": gmeta,
|
|
"fams": sorted(fams, key=fams.get), "layers": layers,
|
|
"stats": family_stats(lct, trace, graphs)}, separators=(",", ":")).encode()
|
|
sink = sys.stdout.buffer if out == "-" else open(out, "wb")
|
|
sink.write(gzip.compress(blob, 6))
|
|
sink.flush()
|
|
|
|
|
|
# ---------------------------------------------------------------- loading, roles, classes
|
|
MIN_GRAPHS = 25
|
|
MAIN_T = (1, 2, 3, 4, 5, 6)
|
|
CHAIN = ["DB", "EQ", "WA", "V_GU", "V_DN", "WB", "P_GU", "P_DN", "WM", "CR", "WC", "AH", "CB"]
|
|
UNTOUCHED = ("DB", "EQ", "WA", "V_GU", "WB") # no switch changes these kernels
|
|
TOUCHED = {"D1": ("V_DN", "P_DN", "P_GU"), "D2": ("AH", "CB"), "D3": ("WM", "CR", "WC")}
|
|
SWITCH_OF = {"WD": "D1", "WH": "D2", "WW": "D3"}
|
|
NAMES = {"D1": "DOWN_SUB16", "D2": "HITS_IN_COMBINE", "D3": "WAIT_M_ROWS"}
|
|
DEVICE_CONTROLS = ("chain_gr_split", "chain_gr_down_t2w8_nb4", "chain_gr_up8", "quantize_q8_1")
|
|
HOST_DEPENDENT = ("chain_doorbell_publish", "chain_wait_copy_i32") # wait on the host: shown, not used as a control
|
|
MIN_GRAPHS_DRIFT = 40
|
|
|
|
|
|
def pct(v, p):
|
|
v = sorted(v)
|
|
return v[min(len(v) - 1, int(p * len(v)))] if v else 0.0
|
|
|
|
|
|
def mean(v):
|
|
return st.mean(v) if v else 0.0
|
|
|
|
|
|
def mean_se(v):
|
|
return (mean(v), st.pstdev(v) / len(v) ** .5) if len(v) > 1 else (mean(v), 0.0)
|
|
|
|
|
|
def view(fams, layer):
|
|
"""role -> list of (start, end, stream, gx, gy) in ns from the doorbell start (first launch of a role first)."""
|
|
roles, counts = collections.defaultdict(list), collections.Counter()
|
|
body = sorted(layer[4], key=lambda k: k[2])
|
|
n_waits = sum(1 for k in body if role_of(fams[k[0]]) == "WAIT")
|
|
wait_names = ("WA", "WB", "WM") if n_waits == 3 else ("WB", "WM") if n_waits == 2 else ("WB",)
|
|
for fam, stream, start, dur, gx, gy in body:
|
|
role = role_of(fams[fam])
|
|
if role in ("GU", "DN"):
|
|
role = ("V_", "P_")[min(counts[role], 1)] + role
|
|
elif role == "WAIT":
|
|
role = wait_names[min(counts[role], len(wait_names) - 1)]
|
|
counts[role_of(fams[fam])] += 1
|
|
roles[role].append((start, start + dur, stream, gx, gy))
|
|
return roles
|
|
|
|
|
|
def seg_ns(roles):
|
|
"""Wait-for-CPU-rows region: wait M start to copy end (D3: the one wait+copy kernel)."""
|
|
if roles.get("WC"):
|
|
return roles["WC"][0][1] - roles["WC"][0][0]
|
|
if roles.get("WM") and roles.get("CR"):
|
|
return roles["CR"][0][1] - roles["WM"][0][0]
|
|
return None
|
|
|
|
|
|
def span_after(roles, c):
|
|
"""(wait start to combine end, copy end to combine end) in ns, the in-layer part after wait B."""
|
|
first = roles.get("WC") or roles.get("WM")
|
|
last = roles.get("WC") or roles.get("CR")
|
|
if not first or not last:
|
|
return None, None
|
|
return c["phase"] - first[0][0], c["phase"] - last[0][1]
|
|
|
|
|
|
def load(path):
|
|
d = json.load(gzip.open(path))
|
|
cells = []
|
|
for lay in d["layers"]:
|
|
roles = view(d["fams"], lay)
|
|
wait_b = roles["WB"][0][1] - roles["WB"][0][0] if roles.get("WB") else 0
|
|
cell = {"g": lay[0], "li": lay[1], "qsa": lay[2], "T": lay[3], "phase": lay[5], "cbs": lay[6], "R": roles,
|
|
"wb": wait_b, "seg": seg_ns(roles)}
|
|
cell["to_end"], cell["tail"] = span_after(roles, cell)
|
|
cells.append(cell)
|
|
for t in range(1, 9): # class threshold: the wait+copy floor of the window itself (5th percentile at this T)
|
|
quiet = [c["seg"] for c in cells if c["T"] == t and c["seg"] and c["wb"] <= B_LONG_US * 1e3]
|
|
floor = pct(quiet, .05) if len(quiet) >= 30 else None
|
|
for c in (c for c in cells if c["T"] == t):
|
|
c["cls"] = "X" if c["wb"] > B_LONG_US * 1e3 else (
|
|
"C" if floor is None or (c["seg"] or 0) > floor + WAIT_FLOOR_US * 1e3 else "F")
|
|
d["cells"] = cells
|
|
d["n_graphs"] = collections.Counter(g[1] for g in d["graphs"])
|
|
return d
|
|
|
|
|
|
def sel(w, t=None, cls=None, qsa=None):
|
|
return [c for c in w["cells"] if (t is None or c["T"] == t) and (cls is None or c["cls"] == cls)
|
|
and (qsa is None or c["qsa"] == qsa)]
|
|
|
|
|
|
def dur_us(c, role):
|
|
r = c["R"].get(role)
|
|
return (r[0][1] - r[0][0]) / 1e3 if r else None
|
|
|
|
|
|
def us_or_none(ns):
|
|
return ns / 1e3 if ns else None
|
|
|
|
|
|
def routed_span_us(c):
|
|
"""V_GU start to the end of the PCIe-pass down (the routed experts' chain incl. wait B and the gaps), us."""
|
|
r = c["R"]
|
|
return (r["P_DN"][0][1] - r["V_GU"][0][0]) / 1e3 if r.get("P_DN") and r.get("V_GU") else None
|
|
|
|
|
|
def graph_means(cells, key):
|
|
by = collections.defaultdict(list)
|
|
for c in cells:
|
|
v = key(c)
|
|
if v is not None:
|
|
by[c["g"]].append(v)
|
|
return [mean(x) for x in by.values()]
|
|
|
|
|
|
# ---------------------------------------------------------------- tables
|
|
def md(header, rows):
|
|
print("| " + " | ".join(header) + " |")
|
|
print("| --- |" + " ---: |" * (len(header) - 1))
|
|
for r in rows:
|
|
print("| " + " | ".join(str(x) for x in r) + " |")
|
|
print()
|
|
|
|
|
|
def usable(ws, t):
|
|
return all(w["n_graphs"].get(t, 0) >= MIN_GRAPHS for w in ws)
|
|
|
|
|
|
def evidence(ws):
|
|
print("### 1. What each window really ran\n")
|
|
print("Switch line of `engine.log` (`requested Sm120Switches`) and the kernels launched per verify graph.\n")
|
|
keys = ("down_sub16", "hits_in_combine", "wait_m_rows", "combine_vec4")
|
|
rows = [["engine log " + k] + [w["switches"].get(k, "n/a") if w["switches"] else "n/a" for w in ws] for k in keys]
|
|
total = lambda w: sum(w["n_graphs"].values()) # noqa: E731
|
|
fams = ("window_moe_down_20", "window_moe_down_42", "sm120_moe_down_20", "sm120_moe_down_42", "add_hits",
|
|
"mtp_full_combine", "leleka_verify_combine_k10_vec4_hits", "verify_wait_flag_ge",
|
|
"chain_copy_rows_from_mapped", "leleka_verify_wait_copy_rows")
|
|
for f in fams:
|
|
cells = []
|
|
for w in ws:
|
|
n = sum(s["fam"][f]["launch"][0] for s in w["stats"].values() if f in s["fam"])
|
|
cells.append("%.2f" % (n / total(w)))
|
|
rows.append(["`%s` per graph" % f] + cells)
|
|
rows.append(["verify graphs kept"] + [str(total(w)) for w in ws])
|
|
md(["window"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def graph_counts(ws):
|
|
print("### 2. Verify graphs per window rows T (kept graphs; a T with fewer than %d is not compared)\n" % MIN_GRAPHS)
|
|
md(["T"] + [w["label"] for w in ws], [[t] + [w["n_graphs"].get(t, 0) for w in ws] for t in MAIN_T])
|
|
|
|
|
|
# ---------------------------------------------------------------- noise
|
|
def untouched_offset(cp, w, t, cls="F"):
|
|
"""Sum over the kernels no switch touches (DB EQ WA V_GU WB) of the p50 difference in the F-class chain, us."""
|
|
tot = 0.0
|
|
for role in UNTOUCHED:
|
|
a = [dur_us(c, role) for c in sel(cp, t, cls) if dur_us(c, role) is not None]
|
|
b = [dur_us(c, role) for c in sel(w, t, cls) if dur_us(c, role) is not None]
|
|
tot += pct(b, .5) - pct(a, .5)
|
|
return tot
|
|
|
|
|
|
def noise_f(cp, variants, t):
|
|
"""The noise estimate used for the F-class verdicts at T, us: the larger of (i) the largest offset of the
|
|
untouched chain between CP and a variant and (ii) the largest first-half/second-half drift inside one window
|
|
(windows with at least MIN_GRAPHS_DRIFT graphs at this T)."""
|
|
offsets = [abs(untouched_offset(cp, w, t)) for w in variants]
|
|
drifts = [abs(h[0] - h[1]) for w in [cp] + list(variants) for h in [halves(w, t)]
|
|
if h and w["n_graphs"].get(t, 0) >= MIN_GRAPHS_DRIFT]
|
|
return max(offsets + drifts)
|
|
|
|
|
|
def noise_kernel(cp, variants, t):
|
|
"""Noise of a single tier-independent device kernel, us: the largest p50 drift of the untouched device kernels."""
|
|
out = [0.0]
|
|
for fam in DEVICE_CONTROLS:
|
|
base = cp["stats"].get(str(t), {"fam": {}})["fam"].get(fam)
|
|
for w in variants:
|
|
other = w["stats"].get(str(t), {"fam": {}})["fam"].get(fam)
|
|
if base and other:
|
|
out.append(abs(other["launch"][4] - base["launch"][4]))
|
|
return max(out)
|
|
|
|
|
|
def halves(w, t):
|
|
"""F-class phase p50 of the first and the second half of the window's graphs (drift inside one session), us."""
|
|
cells = sel(w, t, "F")
|
|
gs = sorted({c["g"] for c in cells})
|
|
if len(cells) < 2 * 100:
|
|
return None
|
|
mid = gs[len(gs) // 2]
|
|
a = [c["phase"] / 1e3 for c in cells if c["g"] < mid]
|
|
b = [c["phase"] / 1e3 for c in cells if c["g"] >= mid]
|
|
return pct(a, .5), pct(b, .5)
|
|
|
|
|
|
def noise_section(ws, ts):
|
|
cp, variants = ws[0], ws[1:]
|
|
print("### 3. Noise (no repeat window of one configuration exists)\n")
|
|
print("(a) Kernels no switch touches, per-launch p50 difference to CP (us; largest |difference| over the four "
|
|
"variants; CP's own p50 in brackets), from all launches of the verify graphs at that T. The first four are "
|
|
"device-only kernels (they give the noise of one device kernel); the doorbell and the plan wait depend on "
|
|
"the host and are shown for context only:\n")
|
|
rows = []
|
|
for fam in DEVICE_CONTROLS + HOST_DEPENDENT:
|
|
cells = []
|
|
for t in ts:
|
|
base = cp["stats"].get(str(t), {"fam": {}})["fam"].get(fam)
|
|
diffs = [w["stats"][str(t)]["fam"][fam]["launch"][4] - base["launch"][4] for w in variants
|
|
if base and fam in w["stats"].get(str(t), {"fam": {}})["fam"]]
|
|
cells.append("%.2f (%.2f)" % (max(abs(x) for x in diffs), base["launch"][4]) if diffs else "-")
|
|
rows.append(["`%s`%s" % (fam, " (host-dependent)" if fam in HOST_DEPENDENT else "")] + cells)
|
|
md(["kernel"] + ["T=%d" % t for t in ts], rows)
|
|
print("(a2) The untouched kernels of the F-class chain (DB, EQ, WA, V_GU, WB), sum of the p50 differences to CP "
|
|
"(us per layer); the noise used for the F-class verdicts is the largest of these and of the in-window "
|
|
"drift (d):\n")
|
|
rows = [[w["label"]] + ["%+.2f" % untouched_offset(cp, w, t) for t in ts] for w in variants]
|
|
rows.append(["**noise used: max of the rows above and of (d)**"] + ["%.2f" % noise_f(cp, variants, t)
|
|
for t in ts])
|
|
rows.append(["noise of one device kernel (a)"] + ["%.2f" % noise_kernel(cp, variants, t) for t in ts])
|
|
md(["window"] + ["T=%d" % t for t in ts], rows)
|
|
print("(d) Drift inside one session: F-class phase p50 of the first half of the graphs minus the second half "
|
|
"(us per layer; every window, same T; windows with at least %d graphs and 100 F layers per half enter the "
|
|
"noise):\n" % MIN_GRAPHS_DRIFT)
|
|
rows = []
|
|
for w in ws:
|
|
cells = []
|
|
for t in ts:
|
|
h = halves(w, t)
|
|
cells.append("%+.2f" % (h[0] - h[1]) if h else "-")
|
|
rows.append([w["label"]] + cells)
|
|
md(["window"] + ["T=%d" % t for t in ts], rows)
|
|
|
|
|
|
# ---------------------------------------------------------------- per-launch tables (D1, D2, D3)
|
|
def role_cell(w, t, role, cls=None):
|
|
xs = [dur_us(c, role) for c in sel(w, t, cls) if dur_us(c, role) is not None]
|
|
if not xs:
|
|
return "-"
|
|
graphs = len({c["g"] for c in sel(w, t)})
|
|
return "%.2f (%.1f)" % (pct(xs, .5), sum(len(c["R"][role]) for c in sel(w, t, cls) if role in c["R"]) / graphs)
|
|
|
|
|
|
def grid_cell(w, t, role):
|
|
cnt = collections.Counter((c["R"][role][0][3], c["R"][role][0][4]) for c in sel(w, t) if c["R"].get(role))
|
|
if not cnt:
|
|
return "-"
|
|
top = cnt.most_common(2)
|
|
return " + ".join("%dx%d" % g for g, _ in top)
|
|
|
|
|
|
def launch_tables(ws, ts, title, roles, cls):
|
|
print(title + "\n")
|
|
for t in ts:
|
|
print("T=%d (graphs %s)\n" % (t, " / ".join(str(w["n_graphs"].get(t, 0)) for w in ws)))
|
|
rows = [[r + (" [%s]" % cls if cls else "")] + [role_cell(w, t, r, cls) for w in ws] for r in roles]
|
|
md(["role: p50 us (launches per graph)"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def grids(ws, ts):
|
|
print("Grid (x by y blocks) of the launches, most common first (VRAM pass, PCIe pass, PCIe gate/up):\n")
|
|
rows = []
|
|
for t in ts:
|
|
for role in ("V_DN", "P_DN", "P_GU"):
|
|
rows.append(["T=%d %s" % (t, role)] + [grid_cell(w, t, role) for w in ws])
|
|
md(["launch"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def f_chain_table(ws, ts):
|
|
print("F-class chain of one layer: p50 per role (us), the routed span (V_GU start to PCIe-pass down end), the "
|
|
"wait-to-end span (wait M or D3 kernel start to combine end), the tail (copy or D3 end to combine end) and "
|
|
"the whole FFN phase (doorbell start to combine end). Layers: no PCIe leg, no CPU wait.\n")
|
|
for t in ts:
|
|
cells = [sel(w, t, "F") for w in ws]
|
|
rows = []
|
|
for r in CHAIN:
|
|
vals = [[dur_us(c, r) for c in cs if dur_us(c, r) is not None] for cs in cells]
|
|
rows.append([r] + ["%.2f" % pct(v, .5) if v else "-" for v in vals])
|
|
parts = (("routed span", routed_span_us), ("wait-to-end span", lambda c: us_or_none(c["to_end"])),
|
|
("tail after the copy", lambda c: us_or_none(c["tail"])),
|
|
("**FFN phase (combine end)**", lambda c: c["phase"] / 1e3))
|
|
for label, f in parts:
|
|
rows.append([label] + ["%.2f" % pct([x for x in map(f, cs) if x is not None], .5) for cs in cells])
|
|
rows.append(["F layers (graphs)"] + ["%d (%d)" % (len(cs), len({c["g"] for c in cs})) for cs in cells])
|
|
print("T=%d\n" % t)
|
|
md(["role / span"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def d3_floor(ws, ts):
|
|
print("D3 kernel floor: wait+copy region of F-class layers (CP/WD/WH: wait M start to copy end; WW/WZ: the "
|
|
"`leleka_verify_wait_copy_rows` duration), p50 us, against the blocks of the copy (T x 10):\n")
|
|
rows = []
|
|
for t in ts:
|
|
row = ["T=%d (%d blocks)" % (t, 10 * t)]
|
|
for w in ws:
|
|
v = [c["seg"] / 1e3 for c in sel(w, t, "F") if c["seg"]]
|
|
row.append("%.2f" % pct(v, .5) if v else "-")
|
|
rows.append(row)
|
|
md(["T"] + [w["label"] for w in ws], rows)
|
|
xs, ys = [], []
|
|
for w in (ws[3], ws[4]):
|
|
for t in range(1, 9):
|
|
v = [c["seg"] / 1e3 for c in w["cells"] if c["T"] == t and c["wb"] <= B_LONG_US * 1e3 and c["seg"]]
|
|
if len(v) >= 100:
|
|
xs.append(10.0 * t)
|
|
ys.append(pct(v, .05))
|
|
n, sx, sy = len(xs), sum(xs), sum(ys)
|
|
slope = (n * sum(a * b for a, b in zip(xs, ys)) - sx * sy) / (n * sum(a * a for a in xs) - sx * sx)
|
|
print("Least-squares line through the 5th percentile of the D3 kernel (WW and WZ, T 1..8, %d points): "
|
|
"%.2f us + %.3f us per block. The CP pair (wait M + copy) stays at %.2f us from T=1 to T=6.\n" % (
|
|
n, (sy - slope * sx) / n, slope, pct([c["seg"] / 1e3 for c in sel(ws[0], 3) if c["seg"]], .05)))
|
|
|
|
|
|
# ---------------------------------------------------------------- F-class phase, verdicts
|
|
def f_stats(w, t, cls="F"):
|
|
cells = sel(w, t, cls)
|
|
gm = graph_means(cells, lambda c: c["phase"] / 1e3)
|
|
m, se = mean_se(gm)
|
|
graphs = len({c["g"] for c in sel(w, t)})
|
|
return {"n": len(cells), "g": len(gm), "p50": pct([c["phase"] / 1e3 for c in cells], .5), "mean": m, "se": se,
|
|
"per_graph": len(cells) / graphs if graphs else 0.0}
|
|
|
|
|
|
def delta(a, b):
|
|
return {"p50": b["p50"] - a["p50"], "mean": b["mean"] - a["mean"], "se": (a["se"] ** 2 + b["se"] ** 2) ** .5}
|
|
|
|
|
|
def verdict(d, noise):
|
|
same_sign = (d["p50"] > 0) == (d["mean"] > 0)
|
|
if same_sign and abs(d["mean"]) > 2 * d["se"] and min(abs(d["p50"]), abs(d["mean"])) > noise:
|
|
return "resolved " + ("gain" if d["mean"] < 0 else "LOSS")
|
|
return "unresolved"
|
|
|
|
|
|
def f_phase_section(ws, ts):
|
|
cp, variants = ws[0], ws[1:]
|
|
print("### 5. FFN phase of the F-class layers (doorbell start to combine end), per T\n")
|
|
print("p50 over layers; mean and standard error (se) over graphs of the per-graph mean of the F layers of that "
|
|
"graph. Delta = window minus CP (negative = faster). Noise = the untouched-chain offset of section 3. "
|
|
"Per graph = mean delta x CP's F layers per graph at this T.\n")
|
|
rows = []
|
|
for t in ts:
|
|
a = f_stats(cp, t)
|
|
rows.append(["T=%d CP" % t, a["n"], a["g"], "%.2f" % a["p50"], "%.2f" % a["mean"], "%.2f" % a["se"]]
|
|
+ [""] * 6)
|
|
for w in variants:
|
|
b = f_stats(w, t)
|
|
d = delta(a, b)
|
|
nz = noise_f(cp, variants, t)
|
|
rows.append(["T=%d %s" % (t, w["label"]), b["n"], b["g"], "%.2f" % b["p50"], "%.2f" % b["mean"],
|
|
"%.2f" % b["se"], "%+.2f" % d["p50"], "%+.2f" % d["mean"], "%.2f" % d["se"], "%.2f" % nz,
|
|
"%+.3f" % (d["mean"] * a["per_graph"] / 1e3), verdict(d, nz)])
|
|
md(["window", "F layers", "graphs", "p50 us", "mean us", "se", "d p50", "d mean", "se of d", "noise",
|
|
"ms per graph", "verdict"], rows)
|
|
|
|
|
|
def summary_section(ws, ts):
|
|
cp = ws[0]
|
|
print("### 6. Per switch: F-class section delta, per T and weighted by CP's T mix\n")
|
|
for w in ws[1:]:
|
|
name = SWITCH_OF.get(w["label"], "D1+D2+D3")
|
|
rows, wsum = [], 0.0
|
|
tot = {"p": 0.0, "m": 0.0, "g": 0.0, "n": 0.0, "se": 0.0}
|
|
for t in ts:
|
|
a, b = f_stats(cp, t), f_stats(w, t)
|
|
d = delta(a, b)
|
|
nz = noise_f(cp, ws[1:], t)
|
|
wt = cp["n_graphs"][t]
|
|
fpg = a["per_graph"] / 1e3
|
|
wsum += wt
|
|
tot["p"] += wt * d["p50"]
|
|
tot["m"] += wt * d["mean"]
|
|
tot["g"] += wt * d["mean"] * fpg
|
|
tot["se"] += (wt * d["se"] * fpg) ** 2
|
|
tot["n"] += wt * nz * fpg
|
|
rows.append(["T=%d" % t, "%.1f" % a["per_graph"], "%+.2f" % d["p50"], "%+.2f" % d["mean"], "%.2f" % d["se"],
|
|
"%.2f" % nz, "%+.3f" % (d["mean"] * fpg), verdict(d, nz)])
|
|
rows.append(["**CP mix**", "", "%+.2f" % (tot["p"] / wsum), "%+.2f" % (tot["m"] / wsum), "", "",
|
|
"%+.3f (se %.3f, noise %.3f)" % (tot["g"] / wsum, tot["se"] ** .5 / wsum, tot["n"] / wsum), ""])
|
|
print("**%s %s (%s minus CP)**\n" % (name, NAMES.get(name, "all three"), w["label"]))
|
|
md(["T", "F layers per graph", "d p50 us", "d mean us", "se", "noise us", "ms per graph", "verdict"], rows)
|
|
|
|
|
|
def additivity(ws, ts):
|
|
cp = ws[0]
|
|
print("### 7. Additivity: WZ against the sum of the single-switch deltas (F-class phase, us per layer; "
|
|
"p50 / mean)\n")
|
|
rows = []
|
|
for t in ts:
|
|
a = f_stats(cp, t)
|
|
ds = [delta(a, f_stats(w, t)) for w in ws[1:]]
|
|
sp = sum(d["p50"] for d in ds[:3])
|
|
sm = sum(d["mean"] for d in ds[:3])
|
|
rows.append(["T=%d" % t] + ["%+.2f / %+.2f" % (d["p50"], d["mean"]) for d in ds[:3]] +
|
|
["%+.2f / %+.2f" % (sp, sm), "%+.2f / %+.2f" % (ds[3]["p50"], ds[3]["mean"]),
|
|
"%+.2f / %+.2f" % (ds[3]["p50"] - sp, ds[3]["mean"] - sm)])
|
|
md(["T", "WD (D1)", "WH (D2)", "WW (D3)", "sum", "WZ (all three)", "WZ - sum"], rows)
|
|
|
|
|
|
# ---------------------------------------------------------------- other classes and totals
|
|
def graph_totals(w, t):
|
|
"""Whole-FFN-phase time per graph (sum over the 48 layers, ms) of the graphs of T rows that have all 48."""
|
|
tot, cnt = collections.defaultdict(float), collections.Counter()
|
|
for c in sel(w, t):
|
|
tot[c["g"]] += c["phase"] / 1e6
|
|
cnt[c["g"]] += 1
|
|
return [v for g, v in tot.items() if cnt[g] == 48]
|
|
|
|
|
|
def shift_share(cp, w, t):
|
|
a, b = sel(cp, t), sel(w, t)
|
|
terms, mix = {}, 0.0
|
|
total = 48 * (mean([c["phase"] for c in b]) - mean([c["phase"] for c in a])) / 1e6
|
|
for cls in "FCX":
|
|
ac, bc = [c["phase"] for c in a if c["cls"] == cls], [c["phase"] for c in b if c["cls"] == cls]
|
|
w_a, w_b = len(ac) / len(a), len(bc) / len(b)
|
|
terms[cls] = 48 * w_a * (mean(bc) - mean(ac)) / 1e6
|
|
mix += 48 * (w_b - w_a) * mean(bc) / 1e6
|
|
ga, gb = graph_totals(cp, t), graph_totals(w, t)
|
|
se = (mean_se(ga)[1] ** 2 + mean_se(gb)[1] ** 2) ** .5
|
|
return ["%+.3f" % terms["F"], "%+.3f" % terms["C"], "%+.3f" % terms["X"], "%+.3f" % mix, "%+.3f" % total,
|
|
"%.3f" % se]
|
|
|
|
|
|
def class_section(ws, ts):
|
|
cp, variants = ws[0], ws[1:]
|
|
print("### 8. Classes C and X, class shares and the whole FFN phase (tier-state confounded)\n")
|
|
print("Class share of the layers and the phase of the waiting classes. The phase of C and X is dominated by "
|
|
"the arrival of the CPU rows / the PCIe leg, which differs between sessions; read it as context, not as a "
|
|
"section delta.\n")
|
|
rows = []
|
|
for t in ts:
|
|
for w in ws:
|
|
cs = sel(w, t)
|
|
share = {k: 100.0 * len(sel(w, t, k)) / len(cs) for k in "FCX"}
|
|
row = ["T=%d %s" % (t, w["label"]), "%.0f/%.0f/%.0f" % tuple(share[k] for k in "FCX")]
|
|
for cls in "CX":
|
|
x = [c["phase"] / 1e3 for c in sel(w, t, cls)]
|
|
row.append("%.1f / %.1f" % (pct(x, .5), mean(x)))
|
|
rows.append(row)
|
|
md(["window", "share F/C/X %", "C phase p50 / mean us", "X phase p50 / mean us"], rows)
|
|
print("Delta to CP of the C and X phase, p50 / mean (se over graphs), us per layer. The windows without D3 (WD, "
|
|
"WH) show how far these move for other reasons (tier state); the D3 windows (WW, WZ) are the ones to "
|
|
"compare with the F-class loss of D3:\n")
|
|
rows = []
|
|
for t in ts:
|
|
for cls in "CX":
|
|
a = f_stats(cp, t, cls)
|
|
row = ["T=%d %s" % (t, cls)]
|
|
for w in variants:
|
|
d = delta(a, f_stats(w, t, cls))
|
|
row.append("%+.1f / %+.1f (%.1f)" % (d["p50"], d["mean"], d["se"]))
|
|
rows.append(row)
|
|
md(["T class"] + [w["label"] for w in variants], rows)
|
|
print("Shift-share of the whole FFN phase against CP, ms per graph (48 layers, CP's class shares as weights; "
|
|
"the four terms add up to the total; se = standard error of the difference of the per-graph totals):\n")
|
|
rows = []
|
|
for t in ts:
|
|
for w in variants:
|
|
rows.append(["T=%d %s" % (t, w["label"])] + shift_share(cp, w, t))
|
|
md(["window", "within F", "within C", "within X", "class mix", "total", "total se"], rows)
|
|
|
|
|
|
def span_section(ws, ts):
|
|
print("### 9. Verify graph duration (first kernel start to last kernel end), p50 ms, difference to CP in brackets "
|
|
"(sanity total only)\n")
|
|
rows = []
|
|
for t in ts:
|
|
row, base = ["T=%d" % t], None
|
|
for w in ws:
|
|
p = pct([g[2] / 1e6 for g in w["graphs"] if g[1] == t], .5)
|
|
base = p if base is None else base
|
|
row.append("%.3f" % p if w is ws[0] else "%.3f (%+.3f)" % (p, p - base))
|
|
rows.append(row)
|
|
md(["T"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def by_kind_section(ws, ts):
|
|
print("F-class FFN phase p50 by layer kind (us; 36 GDN layers and 12 QSA layers per graph):\n")
|
|
rows = []
|
|
for t in ts:
|
|
for kind, kn in ((0, "gdn"), (1, "qsa")):
|
|
rows.append(["T=%d %s" % (t, kn)] + ["%.2f" % pct([c["phase"] / 1e3 for c in sel(w, t, "F", kind)], .5)
|
|
for w in ws])
|
|
md(["T kind"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def kernel_delta_section(ws, ts):
|
|
cp, variants = ws[0], ws[1:]
|
|
print("### 4b. Kernel-level deltas in the F-class chain, window minus CP (p50 us per layer)\n")
|
|
print("Columns: the VRAM-pass down, the PCIe-pass down, the PCIe-pass gate/up (D1); the wait+copy region (D3: wait "
|
|
"M start to copy end, or the one kernel); `add_hits` plus combine from the end of the copy region to the end "
|
|
"of the combine (D2: the tail); the routed span V_GU start to P_DN end. Noise of one device kernel from "
|
|
"section 3 (a) in the last column.\n")
|
|
rows = []
|
|
for t in ts:
|
|
a = {r: pct([dur_us(c, r) for c in sel(cp, t, "F") if dur_us(c, r) is not None], .5)
|
|
for r in ("V_DN", "P_DN", "P_GU")}
|
|
a["seg"] = pct([c["seg"] / 1e3 for c in sel(cp, t, "F") if c["seg"]], .5)
|
|
a["tail"] = pct([c["tail"] / 1e3 for c in sel(cp, t, "F") if c["tail"]], .5)
|
|
a["span"] = pct([routed_span_us(c) for c in sel(cp, t, "F") if routed_span_us(c)], .5)
|
|
for w in variants:
|
|
b = {r: pct([dur_us(c, r) for c in sel(w, t, "F") if dur_us(c, r) is not None], .5)
|
|
for r in ("V_DN", "P_DN", "P_GU")}
|
|
b["seg"] = pct([c["seg"] / 1e3 for c in sel(w, t, "F") if c["seg"]], .5)
|
|
b["tail"] = pct([c["tail"] / 1e3 for c in sel(w, t, "F") if c["tail"]], .5)
|
|
b["span"] = pct([routed_span_us(c) for c in sel(w, t, "F") if routed_span_us(c)], .5)
|
|
rows.append(["T=%d %s" % (t, w["label"])] + ["%+.2f" % (b[k] - a[k]) for k in
|
|
("V_DN", "P_DN", "P_GU", "seg", "tail", "span")]
|
|
+ ["%.2f" % noise_kernel(cp, variants, t)])
|
|
md(["window", "d V_DN", "d P_DN", "d P_GU", "d wait+copy", "d tail", "d routed span", "noise (kernel)"], rows)
|
|
|
|
|
|
def tail_section(ws, ts):
|
|
cp, variants = ws[0], ws[1:]
|
|
print("### 4c. The tail after the copy of the CPU rows (copy or D3 kernel end to combine end), all classes\n")
|
|
print("This part of a layer is after the last wait, so it is on the critical path in every layer, waiting or not, "
|
|
"and does not depend on the expert tier. p50 us per layer; the last columns are the mean delta x 48 layers "
|
|
"in ms per graph and its verdict against the single-kernel noise.\n")
|
|
rows = []
|
|
for t in ts:
|
|
for cls in ("F", "C", "X", None):
|
|
a = [c["tail"] / 1e3 for c in sel(cp, t, cls) if c["tail"]]
|
|
gm_a = graph_means(sel(cp, t, cls), lambda c: c["tail"] / 1e3 if c["tail"] else None)
|
|
row = ["T=%d %s" % (t, cls or "all"), "%.2f" % pct(a, .5)]
|
|
for w in variants:
|
|
b = [c["tail"] / 1e3 for c in sel(w, t, cls) if c["tail"]]
|
|
gm_b = graph_means(sel(w, t, cls), lambda c: c["tail"] / 1e3 if c["tail"] else None)
|
|
d = {"p50": pct(b, .5) - pct(a, .5), "mean": mean_se(gm_b)[0] - mean_se(gm_a)[0],
|
|
"se": (mean_se(gm_a)[1] ** 2 + mean_se(gm_b)[1] ** 2) ** .5}
|
|
row.append("%+.2f (%+.3f ms, %s)" % (d["p50"], 48 * d["mean"] / 1e3,
|
|
verdict(d, noise_kernel(cp, variants, t))))
|
|
rows.append(row)
|
|
md(["T class", "CP p50"] + ["%s d p50 (per graph)" % w["label"] for w in variants], rows)
|
|
|
|
|
|
def x_class_section(ws, ts):
|
|
print("### 4d. D1 in the layers with a PCIe leg (class X): gate/up and down of both passes, p50 / mean us\n")
|
|
rows = []
|
|
for t in ts:
|
|
for role in ("V_DN", "P_GU", "P_DN"):
|
|
row = ["T=%d %s [X]" % (t, role)]
|
|
for w in ws:
|
|
x = [dur_us(c, role) for c in sel(w, t, "X") if dur_us(c, role) is not None]
|
|
row.append("%.2f / %.2f" % (pct(x, .5), mean(x)) if x else "-")
|
|
rows.append(row)
|
|
md(["launch"] + [w["label"] for w in ws], rows)
|
|
|
|
|
|
def report(paths):
|
|
ws = [load(p) for p in paths]
|
|
ts = [t for t in MAIN_T if usable(ws, t)]
|
|
print("Windows: " + ", ".join("%s = %s" % (w["label"], w["path"]) for w in ws))
|
|
print("T compared (at least %d graphs in all five windows): %s\n" % (MIN_GRAPHS, ts))
|
|
evidence(ws)
|
|
graph_counts(ws)
|
|
noise_section(ws, ts)
|
|
print("### 4. Per-launch kernels of the three switches\n")
|
|
print("#### D1 DOWN_SUB16: routed experts' gate/up and down, VRAM pass (V) and PCIe pass (P)\n")
|
|
launch_tables(ws, ts, "All layers, p50 us (launches per graph):", ("V_GU", "V_DN", "P_GU", "P_DN"), None)
|
|
launch_tables(ws, ts, "F-class layers only:", ("V_DN", "P_DN", "P_GU"), "F")
|
|
grids(ws, ts)
|
|
print("#### D2 HITS_IN_COMBINE and D3 WAIT_M_ROWS\n")
|
|
launch_tables(ws, ts, "All layers, p50 us (launches per graph):", ("WM", "CR", "WC", "AH", "CB"), None)
|
|
launch_tables(ws, ts, "F-class layers only:", ("WM", "CR", "WC", "AH", "CB"), "F")
|
|
d3_floor(ws, ts)
|
|
x_class_section(ws, ts)
|
|
kernel_delta_section(ws, ts)
|
|
tail_section(ws, ts)
|
|
f_chain_table(ws, ts)
|
|
by_kind_section(ws, ts)
|
|
f_phase_section(ws, ts)
|
|
summary_section(ws, ts)
|
|
additivity(ws, ts)
|
|
class_section(ws, ts)
|
|
span_section(ws, 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("out")
|
|
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, metavar="CP WD WH WW WZ")
|
|
a = ap.parse_args()
|
|
if a.cmd == "extract":
|
|
extract(a.trace, a.label, a.out, a.lct, a.engine_log)
|
|
else:
|
|
report(a.files)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|