File size: 6,671 Bytes
23d1b53 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Summary of a ``profile_ops.py`` device profile (``ops_perf_results_<ts>.csv`` of ``python -m tracy -r``).
python code/scripts/profile_summary.py $ROOT/generated/profiler/vla-jepa_baseline --json out.json --md out.md
Per stage section (``vision`` / ``prefix`` / ``expert`` signposts, one traced replay each): programs, device kernel
sum, op-to-op gap sum, span (first FW start -> last FW end at the CHIP_FREQ of the log, else 1350 MHz); per op code;
per (op code, input shapes) group (the "top costs"); the largest gaps. csv + json only (no ttnn).
"""
from __future__ import annotations
import argparse
import csv
import glob
import json
import os
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional
KERNEL = "DEVICE KERNEL DURATION [ns]"
FW = "DEVICE FW DURATION [ns]"
GAP = "OP TO OP LATENCY [ns]"
SECTIONS = ("vision", "prefix", "expert")
def find_csv(path: Path) -> Path:
if path.is_file():
return path
found = sorted(glob.glob(str(path / "**" / "ops_perf_results*.csv"), recursive=True), key=os.path.getmtime)
if not found:
raise FileNotFoundError(f"no ops_perf_results*.csv under {path}")
return Path(found[-1])
def num(r: Dict[str, str], k: str) -> float:
v = (r.get(k) or "").strip()
try:
return float(v) if v else 0.0
except ValueError:
return 0.0
def freq_of(csv_path: Path) -> float:
for cand in [csv_path.parent / "profile_log_device.csv", csv_path.parent.parent / "profile_log_device.csv",
csv_path.parent / ".logs" / "profile_log_device.csv"]:
try:
head = cand.read_text(errors="ignore").splitlines()[0]
except OSError:
continue
for part in head.split(","):
if "CHIP_FREQ" in part and ":" in part:
try:
return float(part.split(":")[1].strip())
except ValueError:
pass
return 1350.0
def shape(r: Dict[str, str], prefix: str) -> str:
dims = []
for d in "WZYX":
v = (r.get(f"{prefix}_{d}_PAD[LOGICAL]") or "").strip()
if not v:
return ""
dims.append(v.split("[")[1].rstrip("]") if "[" in v else v)
dt = (r.get(f"{prefix}_DATATYPE") or "").replace("BFLOAT", "bf").replace("FLOAT32", "fp32")
return "x".join(dims) + ("/" + dt if dt else "")
def key_of(r: Dict[str, str]) -> str:
ins = [shape(r, f"INPUT_{i}") for i in range(2)]
return f"{r.get('OP CODE', '?')} " + " , ".join(s for s in ins if s)
def section_rows(rows: List[Dict[str, str]], name: str) -> List[Dict[str, str]]:
out, on = [], False
for r in rows:
if (r.get("OP TYPE") or "") == "signpost":
code = r.get("OP CODE", "")
if on and code == f"{name}_end":
break
on = on or code == name
continue
if on:
out.append(r)
return out
def summarize(ops: List[Dict[str, str]], freq: float, top: int = 25) -> Dict[str, Any]:
kernel = [num(r, KERNEL) / 1e3 for r in ops]
gaps = [num(r, GAP) / 1e3 for r in ops]
starts = [num(r, "DEVICE FW START CYCLE") for r in ops]
ends = [num(r, "DEVICE FW END CYCLE") for r in ops]
valid = [s for s in starts if s > 0]
span = (max(ends) - min(valid)) / freq if valid and max(ends) > 0 else None
by_op: Dict[str, List[float]] = defaultdict(lambda: [0, 0.0])
by_key: Dict[str, List[float]] = defaultdict(lambda: [0, 0.0])
fid: Dict[str, int] = defaultdict(int)
for r, k in zip(ops, kernel):
by_op[r.get("OP CODE", "?")][0] += 1
by_op[r.get("OP CODE", "?")][1] += k
by_key[key_of(r)][0] += 1
by_key[key_of(r)][1] += k
f = (r.get("MATH FIDELITY") or "").strip()
if f:
fid[f] += 1
total = sum(kernel) or 1.0
order = sorted(range(1, len(ops)), key=lambda i: -gaps[i])[:10]
return {
"ops": len(ops), "kernel_sum_us": sum(kernel), "op2op_sum_us": sum(gaps[1:]),
"span_us": span, "freq_mhz": freq, "fidelity": dict(fid),
"by_op": [{"op": o, "count": int(c), "kernel_us": t, "share": t / total}
for o, (c, t) in sorted(by_op.items(), key=lambda kv: -kv[1][1])],
"top": [{"key": o, "count": int(c), "kernel_us": t, "share": t / total, "us_per_call": t / max(c, 1)}
for o, (c, t) in sorted(by_key.items(), key=lambda kv: -kv[1][1])[:top]],
"gaps": [{"i": i, "op": ops[i].get("OP CODE"), "after": ops[i - 1].get("OP CODE"), "gap_us": gaps[i]}
for i in order],
}
def to_md(res: Dict[str, Any]) -> str:
lines = [f"source: `{res['csv']}`", ""]
lines.append("| stage | programs | kernel sum (us) | op-to-op gaps (us) | span (us) |")
lines.append("|---|---|---|---|---|")
for s in SECTIONS:
if s not in res["sections"]:
continue
d = res["sections"][s]
span = "n/a" if d["span_us"] is None else f"{d['span_us']:.0f}"
lines.append(f"| {s} | {d['ops']} | {d['kernel_sum_us']:.0f} | {d['op2op_sum_us']:.0f} | {span} |")
for s in SECTIONS:
if s not in res["sections"]:
continue
d = res["sections"][s]
lines += ["", f"### {s}: per op code", "", "| op | count | kernel us | share |", "|---|---|---|---|"]
for r in d["by_op"][:14]:
lines.append(f"| {r['op']} | {r['count']} | {r['kernel_us']:.0f} | {r['share']:.1%} |")
lines += ["", f"### {s}: top (op, input shapes)", "", "| op and inputs | count | kernel us | us/call | share |",
"|---|---|---|---|---|"]
for r in d["top"][:16]:
lines.append(f"| `{r['key']}` | {r['count']} | {r['kernel_us']:.0f} | {r['us_per_call']:.1f} | "
f"{r['share']:.1%} |")
return "\n".join(lines) + "\n"
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("path")
ap.add_argument("--json", default="")
ap.add_argument("--md", default="")
a = ap.parse_args()
p = find_csv(Path(a.path))
with open(p, newline="") as f:
rows = list(csv.DictReader(f))
freq = freq_of(p)
res: Dict[str, Any] = {"csv": str(p), "sections": {}}
for s in SECTIONS:
ops = section_rows(rows, s)
if ops:
res["sections"][s] = summarize(ops, freq)
md = to_md(res)
print(md)
if a.json:
with open(a.json, "w") as f:
json.dump(res, f, indent=1)
if a.md:
with open(a.md, "w") as f:
f.write(md)
if __name__ == "__main__":
main()
|