Download code/scripts/profile_summary.py from changh95/vla-jepa-base-p150: direct link, hf CLI and curl.
- Browser
- Download file 6.67 kB
-
https://huggingface.co/changh95/vla-jepa-base-p150/resolve/main/code/scripts/profile_summary.py
- Command line
-
hf download hf://changh95/vla-jepa-base-p150/code/scripts/profile_summary.py
-
curl -L -o profile_summary.py https://huggingface.co/changh95/vla-jepa-base-p150/resolve/main/code/scripts/profile_summary.py
6.67 kB
| #!/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() | |