Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ on:
# test file, and is not identical to it: a file the allowlist runs as several entries (Gemma's
# --preset) runs here once without arguments, which runs the same presets in one process, and
# tests/system tests the allowlist leaves out run here too: test_compiler_failure,
# test_reduction_tiling and test_select, and test_patch_scope, test_togsim_exit and
# test_togsim_result, which emit no kernel and so are no route coverage.
# test_reduction_tiling and test_select, and test_breakdown_viewer, test_patch_scope,
# test_togsim_exit and test_togsim_result, which emit no kernel and so are no route coverage.
# Regenerate the allowlist with
# python scripts/ci/triton_route_sweep.py --all --update-allowlist
# and mirror its files here; a test absent from both is not gated anywhere.
Expand Down Expand Up @@ -79,6 +79,7 @@ jobs:
- tests/ops/misc/test_widen_dtype.py
- tests/ops/reduce/test_batchnorm.py
- tests/ops/view/test_view3D_2D.py
- tests/system/test_breakdown_viewer.py
- tests/system/test_bundle_reuse.py
- tests/system/test_compiler_failure.py
- tests/system/test_eager.py
Expand Down
12 changes: 12 additions & 0 deletions pytorchsim/driver/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,15 @@ def record_digest():
return hashlib.sha256(f.read()).hexdigest()[:16]
except (FileNotFoundError, compiler_bridge.NoTarget):
return "none"


def graph_digest():
"""A digest of what an npu graph is compiled against, for Inductor's cache key: the machine
(its name, the keys the compiler reads, num_cores) and its recorded picks."""
try:
t = compiler_bridge.target()
machine = {"name": t.name, "keys": t.as_dict(), "num_cores": config.CONFIG_NUM_CORES}
except compiler_bridge.NoTarget:
machine = None
said = json.dumps({"machine": machine, "record": record_digest()}, sort_keys=True)
return hashlib.sha256(said.encode()).hexdigest()[:16]
4 changes: 2 additions & 2 deletions pytorchsim/frontend/inductor_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,8 +458,8 @@ def _npu_choices_class():

class NPUChoices(LookupTableChoices):
def uuid(self):
"""This class's part of Inductor's cache key, with the recorded picks it hands out."""
return f"pytorchsim-npu-choices-3-{select.record_digest()}"
"""This class's part of Inductor's cache key: the machine and the picks it hands out."""
return f"pytorchsim-npu-choices-4-{select.graph_digest()}"

def _get_lookup_table(self):
"""This machine's recorded picks; Inductor's own looks only on CUDA."""
Expand Down
11 changes: 6 additions & 5 deletions pytorchsim/simulator/wallclock.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
TOGSIM_RUN = "togsim/run"

ORDER = [TORCHSIM_COMPILE, SPIKE, GEM5_SAMPLE, GEM5_BUILD, GEM5_RUN, TOGSIM_TABLES, TOGSIM_RUN]
GROUPS = tuple(dict.fromkeys(c.split("/")[0] for c in ORDER))


def enabled():
Expand Down Expand Up @@ -91,8 +92,8 @@ def as_dict(self):
"components": {c: {"calls": n, "seconds": dt}
for c, (n, dt) in self.totals.items()},
"kernels": self.kernels,
"torchsim-compile": [{"kernel": k, "kind": kind, "timing": r}
for k, kind, r in self.compiles],
TORCHSIM_COMPILE: [{"kernel": k, "kind": kind, "timing": r}
for k, kind, r in self.compiles],
}


Expand Down Expand Up @@ -208,7 +209,7 @@ def render(rec):
wall = rec.get("wall") or 0.0
comps = rec.get("components") or {}
kernels = rec.get("kernels") or {}
entries = rec.get("torchsim-compile") or []
entries = rec.get(TORCHSIM_COMPILE) or []
compiles = [e["timing"] for e in entries if e.get("kind", "compile") == "compile"]
launch = [e["timing"] for e in entries
if e.get("kind") in ("spike", "cycle")]
Expand All @@ -221,7 +222,7 @@ def render(rec):
groups.setdefault(c.split("/")[0], [0, 0.0])
groups[c.split("/")[0]][0] += e["calls"]
groups[c.split("/")[0]][1] += e["seconds"]
for g in [x for x in ("torchsim-compile", "spike", "gem5", "togsim") if x in groups]:
for g in [x for x in GROUPS if x in groups]:
calls, dt = groups[g]
pct = 100.0 * dt / wall if wall else 0.0
out.append(f" {g:<14} {dt:9.2f}s {pct:5.1f}% x{calls:<5} {_bar(pct / 100)}")
Expand Down Expand Up @@ -264,7 +265,7 @@ def render(rec):

if kernels:
out += ["", " per kernel (self time, seconds)"]
cols = [g for g in ("torchsim-compile", "spike", "gem5", "togsim") if g in groups]
cols = [g for g in GROUPS if g in groups]
head = "".join(f"{c:>10}" for c in cols)
out.append(f" {'kernel':<46}{head}{'total':>10}")
rows = []
Expand Down
23 changes: 14 additions & 9 deletions scripts/util_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@
Compile wall clock comes from the the compiler `timing.json` each kernel workdir holds,
joined to a run by the `triton_<hash>` beside its `--tog_so` (`--trace_so` in a log from before
TOGSim ABI 16). A PyTorchSim
`breakdown.json` (TORCHSIM_BREAKDOWN=1) adds Spike, gem5 and TOGSim on top.
`breakdown_<run>.json` (TORCHSIM_BREAKDOWN=1) adds Spike, gem5 and TOGSim on top.

Usage:
python scripts/util_viewer.py togsim_results -o util.html
python scripts/util_viewer.py togsim_results --timing outputs -o util.html
python scripts/util_viewer.py togsim_results --breakdown outputs -o util.html
"""
import argparse
import fnmatch
import glob
import json
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from pytorchsim.simulator import wallclock # noqa: E402

_CMDLINE = re.compile(r"--(?:tog_so|trace_so) (\S+)")
_CONFIG_INT = re.compile(r"^(\w+): (\d+)$")
_PEAK_BW = re.compile(r"Total bandwidth ([\d.]+) GB/s, (\d+) MHz, (\d+) channels, (\d+) bytes")
Expand Down Expand Up @@ -222,12 +226,13 @@ def read_breakdown(path):


def find_breakdowns(roots):
"""Collect every PyTorchSim breakdown.json under the given roots."""
"""Collect every PyTorchSim breakdown_<run>.json (or older breakdown.json) under the roots."""
name = f"{wallclock.PREFIX}*.json"
out = []
for root in roots:
if os.path.isdir(root):
files = glob.glob(os.path.join(root, "**", "breakdown.json"), recursive=True)
elif os.path.basename(root) == "breakdown.json":
files = glob.glob(os.path.join(root, "**", name), recursive=True)
elif fnmatch.fnmatch(os.path.basename(root), name):
files = [root]
else:
files = glob.glob(root)
Expand All @@ -239,7 +244,7 @@ def find_breakdowns(roots):


def breakdown_groups(rec):
"""Fold a breakdown's components into the compiler/spike/gem5/togsim plus elsewhere."""
"""Fold a breakdown's components into wallclock's groups, then any other, plus elsewhere."""
groups = {}
for comp, e in (rec.get("components") or {}).items():
g = comp.split("/")[0]
Expand All @@ -249,7 +254,7 @@ def breakdown_groups(rec):
cur["parts"].append({"name": comp, "calls": e["calls"], "seconds": e["seconds"]})
wall = rec.get("wall") or 0.0
elsewhere = wall - (rec.get("measured") or 0.0)
order = [g for g in ("the compiler", "spike", "gem5", "togsim") if g in groups]
order = [g for g in wallclock.GROUPS if g in groups]
order += [g for g in sorted(groups) if g not in order]
out = [dict(groups[g], name=g) for g in order]
if elsewhere > 0:
Expand All @@ -258,10 +263,10 @@ def breakdown_groups(rec):


def timing_from_breakdowns(breakdowns):
"""Pull the the compiler compile records a breakdown embeds, keyed by kernel label."""
"""Pull the torchsim-compile records a breakdown embeds, keyed by kernel label."""
out = {}
for bd in breakdowns:
for e in bd.get("the compiler") or []:
for e in bd.get(wallclock.TORCHSIM_COMPILE) or []:
if e.get("kind", "compile") != "compile":
continue
rec = e.get("timing")
Expand Down Expand Up @@ -1213,7 +1218,7 @@ def main(argv=None):
help="extra roots to scan for the compiler timing.json; the workdir beside "
"each log's tog_so is always checked")
ap.add_argument("--breakdown", nargs="*", default=None, metavar="ROOT",
help="roots to scan for PyTorchSim breakdown.json (TORCHSIM_BREAKDOWN=1), "
help="roots to scan for PyTorchSim breakdown_<run>.json (TORCHSIM_BREAKDOWN=1), "
"which adds Spike, gem5 and TOGSim wall clock")
args = ap.parse_args(argv)

Expand Down
59 changes: 59 additions & 0 deletions tests/system/test_breakdown_viewer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""The perf viewer reads the breakdown wallclock writes: its file under the dump path, the compile
records under the key the writer uses, and torchsim-compile first among the groups. Nothing runs."""
import json
import os
import runpy
import sys
import tempfile
from unittest import mock

TORCHSIM_DIR = os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")
sys.path.insert(0, TORCHSIM_DIR)

from pytorchsim.simulator import wallclock # noqa: E402

VIEWER = runpy.run_path(os.path.join(TORCHSIM_DIR, "scripts", "util_viewer.py"))
KERNEL = "triton_poi_fused_add_0"
TIMING = {"label": KERNEL, "stages": [{"name": "transform", "seconds": 0.5},
{"name": "lower", "seconds": 0.25}]}


def _written_breakdown(root):
"""The dump path a run with TORCHSIM_BREAKDOWN=1 leaves: one compiled kernel, one Spike launch."""
workdir = os.path.join(root, KERNEL)
os.makedirs(workdir)
with open(os.path.join(workdir, "timing.json"), "w") as f:
json.dump(TIMING, f)
env = {"TORCHSIM_BREAKDOWN": "1", "TORCHSIM_DUMP_PATH": root}
with mock.patch.dict(os.environ, env), mock.patch.object(wallclock, "REC", wallclock.Record()):
with wallclock.span(wallclock.TORCHSIM_COMPILE, KERNEL):
wallclock.ingest_compile(workdir, KERNEL)
with wallclock.span(wallclock.SPIKE, KERNEL):
pass
wallclock._at_exit()


def test_viewer_finds_the_file_wallclock_writes():
"""wallclock names its file breakdown_<run>.json; a viewer scanning for breakdown.json finds none."""
with tempfile.TemporaryDirectory() as root:
_written_breakdown(root)
found = VIEWER["find_breakdowns"]([root])
assert len(found) == 1, f"the viewer found {found} under {os.listdir(root)}"


def test_viewer_reads_the_compile_records():
"""Given the file, the compile records are read under the key the writer uses, and the group
order is the writer's."""
with tempfile.TemporaryDirectory() as root:
_written_breakdown(root)
found = VIEWER["find_breakdowns"]([os.path.join(root, f) for f in os.listdir(root)
if f.endswith(".json")])
assert VIEWER["timing_from_breakdowns"](found) == {KERNEL: TIMING}
names = [g["name"] for g in VIEWER["breakdown_groups"](found[0])]
assert names[:2] == [wallclock.TORCHSIM_COMPILE, wallclock.SPIKE], names


if __name__ == "__main__":
test_viewer_finds_the_file_wallclock_writes()
test_viewer_reads_the_compile_records()
print("PASS")
32 changes: 32 additions & 0 deletions tests/system/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,39 @@ def tile(src, meta, name, wd, cut):
assert time.monotonic() - t0 < 0.2 * select.CUT_FACTOR + 1


def _machine(root, sub, **change):
"""tpuv6e's machine file with `change` applied, at <root>/<sub>/m.yml: one name, other content."""
import yaml
from pytorchsim import config
with open(os.path.join(config.CONFIG_TOGSIM_CONFIG_DIR, "tpuv6e.yml")) as f:
raw = yaml.safe_load(f)
raw.update(change)
os.makedirs(os.path.join(root, sub))
path = os.path.join(root, sub, "m.yml")
with open(path, "w") as f:
yaml.safe_dump(raw, f)
return path


def test_graph_cache_key_names_the_machine():
"""Inductor's FX cache key differs between machines with no recorded picks, so one machine's
cached graph is not handed to another: the core count and the lanes' scratchpad shape it."""
from pytorchsim.frontend.inductor_patches import _npu_choices_class
with tempfile.TemporaryDirectory() as root:
paths = [_machine(root, "base"), _machine(root, "cores", num_cores=2),
_machine(root, "spad", vpu_spad_size_kb_per_lane=512)]
keys = []
for path in paths:
with mock.patch.dict(os.environ, TORCHSIM_TARGET=path), \
mock.patch.object(select, "RECORD_DIR", os.path.join(root, "record")):
assert select.record_digest() == "none"
keys.append(_npu_choices_class()().uuid())
assert keys[-1] == _npu_choices_class()().uuid()
assert len(set(keys)) == len(keys), keys


if __name__ == "__main__":
test_graph_cache_key_names_the_machine()
test_a_config_running_past_the_cut_is_inf()
test_a_refused_config_is_inf_and_none_left_is_an_error()
test_select_record_and_rebuild()
Expand Down