From c88e7a8b6ffffbcaf6d3bea999557a005205afe4 Mon Sep 17 00:00:00 2001 From: Wonhyuk Yang Date: Fri, 23 Oct 2026 14:12:49 +0900 Subject: [PATCH 1/2] [Tools] util_viewer reads the breakdown wallclock writes, by wallclock's own names The viewer looked for breakdown.json and read its compile records under "the compiler" (a leftover of a blanket rename); wallclock writes breakdown_.json and keys the records "torchsim-compile". So --breakdown over a dump path found nothing, and given the file by name timing_from_breakdowns returned {} and torchsim-compile sorted after spike. wallclock now writes the records under TORCHSIM_COMPILE and states its group order as GROUPS; util_viewer imports wallclock and reads PREFIX, TORCHSIM_COMPILE and GROUPS from it. tests/system/test_breakdown_viewer.py writes a breakdown through wallclock (span, ingest_compile, the exit hook) and reads it with the viewer. On the parent: find_breakdowns(dump) == [], timing_from_breakdowns(file) == {}, groups ['spike', 'torchsim-compile', 'elsewhere']. Added to the CI matrix. Refs #426 --- .github/workflows/pytorchsim_test.yml | 5 ++- pytorchsim/simulator/wallclock.py | 11 ++--- scripts/util_viewer.py | 23 +++++++---- tests/system/test_breakdown_viewer.py | 59 +++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 16 deletions(-) create mode 100644 tests/system/test_breakdown_viewer.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index f2a275de9..9564f3bf1 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -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. @@ -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 diff --git a/pytorchsim/simulator/wallclock.py b/pytorchsim/simulator/wallclock.py index 1565d9d48..98606aa8c 100644 --- a/pytorchsim/simulator/wallclock.py +++ b/pytorchsim/simulator/wallclock.py @@ -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(): @@ -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], } @@ -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")] @@ -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)}") @@ -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 = [] diff --git a/scripts/util_viewer.py b/scripts/util_viewer.py index 60476c50f..6e957c774 100644 --- a/scripts/util_viewer.py +++ b/scripts/util_viewer.py @@ -8,7 +8,7 @@ Compile wall clock comes from the the compiler `timing.json` each kernel workdir holds, joined to a run by the `triton_` 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_.json` (TORCHSIM_BREAKDOWN=1) adds Spike, gem5 and TOGSim on top. Usage: python scripts/util_viewer.py togsim_results -o util.html @@ -16,12 +16,16 @@ 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") @@ -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_.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) @@ -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] @@ -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: @@ -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") @@ -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_.json (TORCHSIM_BREAKDOWN=1), " "which adds Spike, gem5 and TOGSim wall clock") args = ap.parse_args(argv) diff --git a/tests/system/test_breakdown_viewer.py b/tests/system/test_breakdown_viewer.py new file mode 100644 index 000000000..630cbf609 --- /dev/null +++ b/tests/system/test_breakdown_viewer.py @@ -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_.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") From 56142ad47465c9851842d55d4ed8acd1232b8383 Mon Sep 17 00:00:00 2001 From: Wonhyuk Yang Date: Fri, 23 Oct 2026 14:12:49 +0900 Subject: [PATCH 2/2] [Frontend] Inductor's graph cache key names the machine NPUChoices.uuid() was "pytorchsim-npu-choices-3-" + record_digest(), and the digest is "none" for any machine with no recorded picks, so every such TORCHSIM_TARGET handed Inductor the same FX cache key and reused another machine's cached graphs, though tiling and reduction_split_factor read the machine. select.graph_digest() digests the target's name, target().as_dict() and num_cores together with record_digest(); uuid() is "pytorchsim-npu-choices-4-" + that digest. test_select.test_graph_cache_key_names_the_machine loads three machine files named m.yml (tpuv6e as is, num_cores 2, vpu_spad_size_kb_per_lane 512) with no record; on the parent all three uuids are 'pytorchsim-npu-choices-3-none'. Refs #426 --- pytorchsim/driver/select.py | 12 ++++++++++ pytorchsim/frontend/inductor_patches.py | 4 ++-- tests/system/test_select.py | 32 +++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/pytorchsim/driver/select.py b/pytorchsim/driver/select.py index dc025e5bb..d2e4d9091 100644 --- a/pytorchsim/driver/select.py +++ b/pytorchsim/driver/select.py @@ -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] diff --git a/pytorchsim/frontend/inductor_patches.py b/pytorchsim/frontend/inductor_patches.py index 9baa7b607..c0fff44be 100644 --- a/pytorchsim/frontend/inductor_patches.py +++ b/pytorchsim/frontend/inductor_patches.py @@ -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.""" diff --git a/tests/system/test_select.py b/tests/system/test_select.py index 4f4e1d725..54df84ff1 100644 --- a/tests/system/test_select.py +++ b/tests/system/test_select.py @@ -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 //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()