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

194 lines
9.3 KiB
Python

"""Where the decode round waits for the host/tier, per layer index (plan 6b of the speed program; ledger rows K7, V5,
V7).
Offline analysis of CUPTI windows (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, uses no GPU.
extract TRACE_DIR LABEL [--lct DIR] [--tokens T] (python3 -B; reads one window, writes JSON on stdout)
every verify graph with 48 doorbells (>= 900 kernels per correlation id, first and last two dropped) is cut into
its 48 layers (doorbell to the next doorbell); each layer has three waits in stream order, A (plan published),
B (PCIe copies landed) and M (CPU rows written). A layer is host-bound when one of them lasts longer than its
floor (A, M above 4 us, B above 3 us): the device had finished its own work and stood still for the other side.
report FILE... [--first-layers N] (markdown on stdout)
per window: the round (verify graph start to the next verify graph start) split into graph time and the rest
(draft, accept, answer: the host leg between graphs), the host wait inside the graph (sum of the wait time above
the
floor) for the first N layers (default 16) and the others, the share of layers that are NOT host-bound, and the
table per layer index.
Reach of a device saving of `d` microseconds in every layer. The host leg starts at the doorbell, so a saving in the
mixer phase
(add_hits end to the next doorbell: GDN step, attention, router) moves the doorbell and the CPU rows earlier and
reaches the
round in full. A saving in the FFN phase (doorbell to add_hits end) reaches it only in the layers where the device is
not
waiting for the host (not host-bound); in a host-bound layer it is absorbed by the wait (slack).
"""
import argparse
import collections
import json
import statistics as stats
import sys
sys.path.insert(0, "/data/leleka-e2e/decode/tools")
import cupti_flag_waits as flag_waits # noqa: E402 (same directory; its own lct import)
LAYERS = 48
FLOOR_US = {"a": 4.0, "b": 3.0, "m": 4.0}
MAX_ROUND_MS = 200.0
def quantile(values, part):
ordered = sorted(values)
return ordered[min(len(ordered) - 1, int(part * len(ordered)))] if ordered else float("nan")
def excess_us(layer):
return sum(max(0.0, layer[key] - FLOOR_US[key]) for key in ("a", "b", "m"))
def add_phases(name_of, record, segment, bell, next_bell_start):
"""Mixer phase (end of the FFN chain to the next doorbell) and FFN phase (doorbell to the end of `add_hits` or, when
HITS_IN_COMBINE fused it, of the combine kernel) of one layer, us."""
hits = [k for k in segment if "add_hits" in name_of(k) or "combine" in name_of(k)]
record["ffn"] = (hits[-1].end - bell.start) / 1e3 if hits else 0.0
record["mixer"] = (next_bell_start - hits[-1].end) / 1e3 if hits and next_bell_start else 0.0
return record
def graph_layers(name_of, kernels, tokens, mode):
"""The 48 layer records of one verify graph, or None when it does not have 48 doorbells or T differs."""
bells = [k for k in kernels if "doorbell_publish" in name_of(k)]
if len(bells) != LAYERS:
return None
layers = []
for index, bell in enumerate(bells):
next_start = bells[index + 1].start if index + 1 < LAYERS else 0
segment = [k for k in kernels if bell.start <= k.start < (next_start or bell.start + 400000)]
record = flag_waits.layer_record(name_of, segment, bell, mode)
if record is None or (tokens is not None and record["tokens"] != tokens):
return None
layers.append(add_phases(name_of, record, segment, bell, next_start))
return layers
def host_bound(layer):
return any(layer[key] > FLOOR_US[key] for key in ("a", "b", "m"))
def round_periods(spans):
"""Start-to-start periods and the idle part of the round between consecutive verify graphs (ms)."""
periods, rests = [], []
for (start, end), (next_start, _) in zip(spans, spans[1:]):
period = (next_start - start) / 1e6
if 0 < period < MAX_ROUND_MS:
periods.append(period)
rests.append((next_start - end) / 1e6)
return periods, rests
def extract(trace_dir, label, tokens, mode):
trace, graphs = flag_waits.load(trace_dir)
name_of = lambda k: trace.names.get(k.name, "") # noqa: E731
spans, per_graph = [], []
for kernels in graphs:
layers = graph_layers(name_of, kernels, tokens, mode)
spans.append((min(k.start for k in kernels), max(k.end for k in kernels)))
if layers is not None:
per_graph.append((spans[-1], layers))
periods, rests = round_periods([span for span, _ in per_graph])
return dict(label=label, graphs=len(per_graph), graph_ms=[(e - s) / 1e6 for (s, e), _ in per_graph],
period_ms=periods, rest_ms=rests, layers=[[dict(l, host_bound=host_bound(l)) for l in ls]
for _, ls in per_graph])
def mean_of(values):
return stats.mean(values) if values else float("nan")
def summarise(data, first_layers):
layers = data["layers"]
wait_first = [sum(excess_us(l) for l in g[:first_layers]) / 1e3 for g in layers]
wait_rest = [sum(excess_us(l) for l in g[first_layers:]) / 1e3 for g in layers]
free = [sum(1 for l in g if not l["host_bound"]) / LAYERS for g in layers]
free_first = [sum(1 for l in g[:first_layers] if not l["host_bound"]) / first_layers for g in layers]
mixer = [sum(l["mixer"] for l in g) / 1e3 for g in layers]
ffn = [sum(l["ffn"] for l in g) / 1e3 for g in layers]
return dict(label=data["label"], graphs=data["graphs"], graph=mean_of(data["graph_ms"]),
period=mean_of(data["period_ms"]), rest=mean_of(data["rest_ms"]),
wait_first=mean_of(wait_first), wait_rest=mean_of(wait_rest),
free=mean_of(free), free_first=mean_of(free_first), mixer=mean_of(mixer), ffn=mean_of(ffn))
def summary_table(rows, first_layers):
head = ("| window | graphs | round ms | graph ms | between graphs ms | host wait first %d layers ms | "
"host wait other layers ms | layers not host-bound | not host-bound, first %d | mixer phases ms | "
"FFN phases ms |"
% (first_layers, first_layers))
lines = [head, "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"]
for r in rows:
lines.append("| %s | %d | %.2f | %.2f | %.2f | %.3f | %.3f | %.1f %% | %.1f %% | %.2f | %.2f |" % (
r["label"], r["graphs"], r["period"], r["graph"], r["rest"], r["wait_first"], r["wait_rest"],
100 * r["free"], 100 * r["free_first"], r["mixer"], r["ffn"]))
return lines
def layer_table(data):
by_index = collections.defaultdict(list)
for graph in data["layers"]:
for index, layer in enumerate(graph):
by_index[index].append(layer)
lines = ["| layer | host-bound | M wait mean us | M wait p90 us | B wait mean us | M end after doorbell p50 us |",
"| ---: | ---: | ---: | ---: | ---: | ---: |"]
for index in range(LAYERS):
rows = by_index[index]
lines.append("| %d | %.0f %% | %.1f | %.1f | %.1f | %.1f |" % (
index, 100 * mean_of([1.0 if r["host_bound"] else 0.0 for r in rows]),
mean_of([r["m"] for r in rows]), quantile([r["m"] for r in rows], 0.9),
mean_of([r["b"] for r in rows]), quantile([r["m_end"] for r in rows], 0.5)))
return lines
def reach_lines(rows):
out = ["", "Reach of a device saving of 1 us in every layer, in us a graph (upper bound, no cascade):",
"* mixer phase (GDN step, attention, router; before the doorbell): 48 us, because the host leg starts",
" at the doorbell and the whole saving moves it earlier;",
"* FFN phase (doorbell to the end of the FFN chain): 48 x share of layers not host-bound; in a host-bound",
" layer the device waits for the CPU rows and the saving is absorbed up to that wait."]
for r in rows:
out.append(" * %s: FFN phase %.1f us (%.0f %% of the layers are not host-bound)." % (
r["label"], 48 * r["free"], 100 * r["free"]))
return out
def report(paths, first_layers):
windows = [json.load(open(p)) for p in paths]
rows = [summarise(w, first_layers) for w in windows]
lines = summary_table(rows, first_layers) + reach_lines(rows)
for window in windows:
lines += ["", "### %s" % window["label"]] + layer_table(window)
print("\n".join(lines))
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="cmd", required=True)
one = sub.add_parser("extract")
one.add_argument("trace")
one.add_argument("label")
one.add_argument("--lct", default="/data/leleka-e2e/decode/tools")
one.add_argument("--tokens", type=int, default=None)
one.add_argument("--mode", choices=("LEL", "VANL"), default="LEL", help="engine of the trace")
many = sub.add_parser("report")
many.add_argument("files", nargs="+")
many.add_argument("--first-layers", type=int, default=16)
args = parser.parse_args()
if args.cmd == "extract":
sys.path.insert(0, args.lct)
json.dump(extract(args.trace, args.label, args.tokens, args.mode), sys.stdout)
else:
report(args.files, args.first_layers)
if __name__ == "__main__":
main()