From 28cdd4830d61f314f8fecaea6ec62a92b9a66a63 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Sat, 24 Oct 2026 13:45:17 +0900 Subject: [PATCH] [Simulator] TOGSim's results are the file it writes with --result, and the compiler pin is PTB main 70221f4 get_result_from_file read TOGSim's end-of-run lines with five regular expressions, and a log it could not parse came back as infinite cycles with only a warning. TOGSim writes the same values as JSON with --result (PSAL-POSTECH/TOGSim#60, in TOGSim 5791272). Both launch paths hand it a path, and TOGSimProcess.read_result returns that object; template_timing takes total_cycles from it, and a run that wrote no file is a FileNotFoundError, which a timed candidate turns into a logged inf. The regexes, FINISH_STR and the unused TOGSIM_RESULT_PATH_KEY go. A session's TOGSim output was never kept: the process was started without a pipe, so shutdown's read of its stdout was always empty and no .log was written. Its stdout now goes to the session's .log directly (a pipe could fill and stall a long session), and a run's .log, .trace and .json share one stamp, _stamp(). The compiler pin moves from PTB 522042a to main 70221f4, whose TOGSim is 5791272: a TOGSim without --result refuses it. The kernel object stays format 8; the accelerator is named pytorchsim_tpuv6e there, which nothing in this tree names. test_togsim_result runs a stub Simulator that writes a result file TOGSim 5791272 wrote for a tpuv6e test_matmul.py run, and pins that both paths pass --result and read it back, that a session keeps the Simulator's output in its .log beside its .trace and .json, and that a run without a file is an error. Checked on PTB 70221f4 with TOGSim 5791272: test_matmul in timing mode 11/11, every kernel's total_cycles from its JSON equal to its log's Total execution cycles (14 runs); test_select in timing mode, test_add, test_eager, test_patch_scope, test_histc, test_topk, test_grouped_mm, test_togsim_exit pass; test_conv_decomposition's depthwise_grad fails as on 522042a (PTB #351). --- .claude/CLAUDE.md | 2 +- pytorchsim/backend/codecache.py | 2 +- pytorchsim/backend/template_timing.py | 2 +- pytorchsim/simulator/timing/__init__.py | 6 +- pytorchsim/simulator/timing/togsim.py | 149 +++++---------------- tests/system/data/togsim_tpuv6e.json | 58 ++++++++ tests/system/data/togsim_tpuv6e.log | 53 -------- tests/system/test_togsim_result.py | 96 +++++++++---- third_party/pytorchsim-triton-backend.json | 2 +- 9 files changed, 175 insertions(+), 195 deletions(-) create mode 100644 tests/system/data/togsim_tpuv6e.json delete mode 100644 tests/system/data/togsim_tpuv6e.log diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 542043cb9..b9eb54f2b 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -176,7 +176,7 @@ with torch.npu.TOGSimulator(config_path=...): - **TOGSim hardware model changes:** in the TOGSim repository, `src/{Core,Dram,Interconnect,L2Cache,Tile,TileGraph}.cc` + matching `include/*.h`. They reach this repository when the compiler pins that TOGSim commit and this repository pins that compiler commit. - **TOG generation:** the compiler emits the tile-operation-graph (TOG) as C++, compiles it to `tog.so` against TOGSim's `togsim_runtime.h` and records the compute type of each tile (`pytorchsim_triton_compiler/lowering/tog/`; `tog_cpp`, `tog_so` and `tile_types` in `kernel.json`); this repo measures the tiles under gem5 and writes `tog_cycles.tsv` and `tog_units.tsv` beside the TOG (`pytorchsim/simulator/timing/__init__.py`); TOGSim replays the TOG into a TileGraph (`tog_to_tilegraph`). - **Eager fallback registration:** `torch.npu.register_eager_to_compile([...])` — see `tests/system/test_eager.py`. -- **Per-run results:** `togsim_results/>.log` (stats) and `.trace` (instruction trace). The path is also printed at the end of every run. +- **Per-run results:** `togsim_results/>.json` (the results TOGSim writes with `--result`, which the frontend reads), `.log` (its output) and `.trace` (the commands it was sent). The path is also printed at the end of every run. - **Utilization of a run:** `python scripts/util_viewer.py togsim_results -o util.html` builds a self-contained page from the info-level logs already on disk (vector unit / DMA / DRAM over cycles, per kernel, one lane each so overlap is visible). Add `--timing ` for the compile clock (`timing.json`, joined by `triton_`) and `--breakdown ` for the whole-run split across compile / Spike / gem5 / TOGSim (`breakdown.json`, written by `TORCHSIM_BREAKDOWN=1`). For per-instruction Gantt detail instead, re-run with `TOGSIM_DEBUG_LEVEL=trace` and pipe through `scripts/trace_timeline.py` into Perfetto. - **Wrapper codegen path:** printed as `Wrapper Codegen Path = /tmp/torchinductor_//...py` — useful for inspecting generated kernel code. diff --git a/pytorchsim/backend/codecache.py b/pytorchsim/backend/codecache.py index d8027a513..8c85add34 100644 --- a/pytorchsim/backend/codecache.py +++ b/pytorchsim/backend/codecache.py @@ -251,7 +251,7 @@ def __call__(self, *args): "are reported when the simulator closes", self.kernel_name, result) else: - logger.info("[TOGSim] %s simulated -> %s", self.kernel_name, result) + logger.info("[TOGSim] %s simulated: %d cycles", self.kernel_name, result["total_cycles"]) return result diff --git a/pytorchsim/backend/template_timing.py b/pytorchsim/backend/template_timing.py index 4b1228abd..168bc76c5 100644 --- a/pytorchsim/backend/template_timing.py +++ b/pytorchsim/backend/template_timing.py @@ -50,7 +50,7 @@ def _time_tile(src_code, meta, kernel_name, workdir, cut=None): result = TOGSimProcess.run_standalone(os.path.join(mine, "tile_graph.onnx"), os.path.join(mine, "attribute"), autotune_mode=True, cut=cut) - return TOGSimProcess.get_result_from_file(result)[-1] + return TOGSimProcess.read_result(result)["total_cycles"] except (compiler_bridge.CompilerError, RuntimeError, FileNotFoundError) as exc: why = retile.too_big(exc) or (f"cut, {exc}" if isinstance(exc, Cut) else type(exc).__name__) logger.info("[select] %s %s: %s", kernel_name, workdir, why) diff --git a/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index ac7b5abf9..3178bb7db 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -47,8 +47,8 @@ def emitted(): def run_togsim(workdir, meta, args=()): - """Simulate the TOG, or hand it to an open TOGSimulator. Standalone returns the parsed result; - a queued launch returns its kernel id, as the stream's numbers are whole only when it closes.""" + """Simulate the TOG, or hand it to an open TOGSimulator. Standalone returns the result TOGSim wrote, + read; a queued launch returns its kernel id, as the stream's numbers are whole only when it closes.""" import torch from pytorchsim.simulator.timing.togsim import TOGSimProcess @@ -66,7 +66,7 @@ def run_togsim(workdir, meta, args=()): return torch.npu.launch_kernel(handle, _held_for_the_session(mine, attribute)) result_path = TOGSimProcess.run_standalone(handle, attribute) - return TOGSimProcess.get_result_from_file(result_path) + return TOGSimProcess.read_result(result_path) def attribute_dir(workdir): diff --git a/pytorchsim/simulator/timing/togsim.py b/pytorchsim/simulator/timing/togsim.py index c3e0de5c3..d7212b078 100644 --- a/pytorchsim/simulator/timing/togsim.py +++ b/pytorchsim/simulator/timing/togsim.py @@ -1,10 +1,9 @@ -"""TOGSim as a process: started once, fed kernels over a FIFO, read back from its log.""" +"""TOGSim as a process: started once, fed kernels over a FIFO, read back from the result file it writes.""" import datetime +import json import os -import re import shlex import subprocess -import sys import threading import time import uuid @@ -59,8 +58,6 @@ def __exit__(self, exc_type, exc_val, exc_tb): class TOGSimProcess(): - TOGSIM_RESULT_PATH_KEY = "TOGSIM_RESULT_PATH" - FINISH_STR = "Simulation finished" def __init__(self, config_path=None, togsim_path=None) -> None: if config_path is None: config_path = config.CONFIG_MACHINE_FILE @@ -72,6 +69,10 @@ def __init__(self, config_path=None, togsim_path=None) -> None: self.config_yaml = self.load_yaml(self.config_path) self.process = None self._next_kernel_id = 0 + os.makedirs(config.CONFIG_TORCHSIM_LOG_PATH, exist_ok=True) + stem = os.path.join(config.CONFIG_TORCHSIM_LOG_PATH, _stamp()) + self.log_path, self.trace_path, self.result_path = stem + ".log", stem + ".trace", stem + ".json" + self._log_handle = None self.fifo_dir = os.path.join("/tmp", f"togsim_fifo_{os.getpid()}") os.makedirs(self.fifo_dir, exist_ok=True) @@ -92,16 +93,15 @@ def __init__(self, config_path=None, togsim_path=None) -> None: raise RuntimeError(f"Failed to open trace file: {e}") def _start_process(self): - cmd = f"{self.get_togsim_command(self.config_path, self.base_dir)} --models_list {self.trace_file_path}" + cmd = (f"{self.get_togsim_command(self.config_path, self.base_dir)} --models_list {self.trace_file_path}" + f" --result {self.result_path}") if config.CONFIG_TOGSIM_DEBUG_LEVEL: cmd += f" --log_level {config.CONFIG_TOGSIM_DEBUG_LEVEL}" logger.debug(f"[TOGSim] cmd> {cmd}") if self.process is None: - self.process = subprocess.Popen( - shlex.split(cmd), - universal_newlines=True - ) + self._log_handle = open(self.log_path, "w") + self.process = subprocess.Popen(shlex.split(cmd), stdout=self._log_handle, universal_newlines=True) else: logger.warning("[TOGSim] Simulator is already running.") @@ -154,36 +154,15 @@ def shutdown(self): status = 0 if self.process: status = self.process.wait() - - stdout_output = "" - stderr_output = "" - if self.process.stdout: - stdout_output = self.process.stdout.read() - if self.process.stderr: - stderr_output = self.process.stderr.read() - - if stderr_output: - sys.stderr.write(stderr_output) - sys.stderr.flush() - - if stdout_output: - result_path = config.CONFIG_TORCHSIM_LOG_PATH - os.makedirs(result_path, exist_ok=True) - file_name = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + ".log" - result_path = os.path.join(result_path, file_name) - with open(result_path, "w") as f: - f.write(stdout_output) - logger.info(f'[TOGSim] Simulation log is stored to "{result_path}"') + self._log_handle.close() + logger.info(f'[TOGSim] Simulation log is stored to "{self.log_path}"') + if not status: + logger.info(f'[TOGSim] Simulation result is stored to "{self.result_path}"') self.process = None - if self.trace_log: - result_path = config.CONFIG_TORCHSIM_LOG_PATH - os.makedirs(result_path, exist_ok=True) - file_name = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + ".trace" - trace_path = os.path.join(result_path, file_name) - with open(trace_path, "w") as f: - f.write(self.trace_log) - logger.info(f'[TOGSim] Trace log is stored to "{trace_path}"') + with open(self.trace_path, "w") as f: + f.write(self.trace_log) + logger.info(f'[TOGSim] Trace log is stored to "{self.trace_path}"') self._cleanup_fifos() if status: @@ -234,9 +213,9 @@ def run_standalone( togsim_path=None, cut=None, ): - """Run one kernel in a TOGSim of its own and wait. Returns the path of its log. `cut`, polled - while it runs, kills it with a reason (raised as Cut); a Simulator that exits non-zero is a - RuntimeError carrying its status and its last line.""" + """Run one kernel in a TOGSim of its own and wait. Returns the path of the result file it wrote + (--result), beside its log. `cut`, polled while it runs, kills it with a reason (raised as Cut); a + Simulator that exits non-zero is a RuntimeError carrying its status and its last line.""" if config_path is None: config_path = config.CONFIG_MACHINE_FILE if togsim_path is None: @@ -248,9 +227,9 @@ def run_standalone( base_dir = Path(config.CONFIG_TORCHSIM_LOG_PATH) base_dir.mkdir(parents=True, exist_ok=True) - timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') - file_name = f"{timestamp}_{uuid.uuid4().hex[:8]}" - result_path = base_dir / f"{file_name}.log" + file_name = _stamp() + log_path = base_dir / f"{file_name}.log" + result_path = base_dir / f"{file_name}.json" trace_file_path = base_dir / f"{file_name}.trace" kernel_id, device_index, stream_index, timestamp = 0, 0, 0, 0 @@ -267,7 +246,8 @@ def run_standalone( raise FileNotFoundError(f"{tog_so} not found -- the kernel has no TOG to simulate") base_cmd = TOGSimProcess.get_togsim_command(config_path, togsim_path) unit_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_units.tsv") - cmd = f"{base_cmd} --tog_so {tog_so} --cycle_table {cycle_tsv} --unit_table {unit_tsv}" + cmd = (f"{base_cmd} --tog_so {tog_so} --cycle_table {cycle_tsv} --unit_table {unit_tsv}" + f" --result {result_path}") if attribute_path: cmd += f" --attribute_path {attribute_path}" if config.CONFIG_TOGSIM_DEBUG_LEVEL: @@ -298,7 +278,7 @@ def run_standalone( raise RuntimeError(f"TOGSim Simulator exited with status {e.returncode}: " f"{said[-1] if said else 'it printed nothing'}") from e - with open(result_path, "w") as f: + with open(log_path, "w") as f: f.write(result.decode()) f.flush() os.fsync(f.fileno()) @@ -306,75 +286,20 @@ def run_standalone( if not autotune_mode: import logging as _logging model_path_log = f' of "{model_path}" ' if logger.isEnabledFor(_logging.DEBUG) else " " - logger.info(f'[TOGSim] Simulation log{model_path_log}is stored to "{result_path}"') + logger.info(f'[TOGSim] Simulation log{model_path_log}is stored to "{log_path}"') return result_path - _UNIT_LINE = re.compile(r"\] (Core \[\d+\]|Total) : (.+?) utilization\(%\): (\d+\.?\d*), " - r"active_cycles: (\d+), idle_cycles: (\d+)") - _DRAM_CHANNEL = re.compile(r"\[DRAM\] channel (\d+) \| .*?(\d+\.?\d*)% of utilization") - _DRAM_COMBINED = re.compile(r"\[DRAM\] channels .* combined \| .*?(\d+\.?\d*)% of utilization") - @staticmethod - def get_result_from_file(result_path): - """(core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle) of a run's log. - core_metrics["units"] holds every 'Core [i]' and 'Total' unit row; the flat keys read the - machine's array unit (its systolic_array_unit) and Vpu off the Total row, else the one core.""" - core_metrics = {} - dram_channel_bw = {} - avg_dram_bw = 0.0 - simulation_time = float("inf") - total_cycle = float("inf") - - with open(result_path, "r") as f: - lines = f.readlines() - - for idx, line in enumerate(lines): - if TOGSimProcess.FINISH_STR in line: - break - else: - logger.warning(f"[TOGSim] Warning: Unable to parse the output file ({result_path}). The file may be improperly formatted.") - return core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle - - units = {} - combined = None - for line in lines[idx:]: - m = TOGSimProcess._UNIT_LINE.search(line) - if m: - units.setdefault(m.group(1), {})[m.group(2)] = { - "utilization": float(m.group(3)), "active_cycles": int(m.group(4)), - "idle_cycles": int(m.group(5))} - continue - m = TOGSimProcess._DRAM_CHANNEL.search(line) - if m: - dram_channel_bw[f"CH[{m.group(1)}]"] = float(m.group(2)) - continue - m = TOGSimProcess._DRAM_COMBINED.search(line) - if m: - combined = float(m.group(1)) - elif 'Total execution cycles' in line: - total_cycle = int(re.search(r'Total execution cycles: (\d+)', line).group(1)) - elif 'Wall-clock time for simulation' in line: - simulation_time = float(re.search(r'Wall-clock time for simulation: (\d+\.?\d*) seconds', line).group(1)) - - if combined is not None: - avg_dram_bw = combined - elif dram_channel_bw: - avg_dram_bw = sum(dram_channel_bw.values()) / len(dram_channel_bw) - - if units: - core_metrics["units"] = units - whole = units.get("Total") or next(iter(units.values())) - array = whole.get(config.CONFIG_MACHINE.togsim_unit) - vector = whole.get("Vpu") - if array: - core_metrics["Systolic_Array_Utilization"] = array["utilization"] - core_metrics["MatMul_active_cycle"] = array["active_cycles"] - if vector: - core_metrics["Vector_Unit_Utilization"] = vector["utilization"] - core_metrics["Vector_active_cycle"] = vector["active_cycles"] - if total_cycle != float("inf"): - core_metrics["Total_cycle"] = total_cycle - return core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle + def read_result(result_path): + """The results TOGSim wrote with --result: total_cycles, wall_clock_s, core_cycles, units, dma, dram + and kernels, each as its end-of-run line prints it (TOGSim's docs/output-lines.md).""" + with open(result_path) as f: + return json.load(f) + + +def _stamp(): + """The name a run's .log, .trace and .json share: when it started, and a random suffix.""" + return datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + f"_{uuid.uuid4().hex[:8]}" if __name__ == "__main__": diff --git a/tests/system/data/togsim_tpuv6e.json b/tests/system/data/togsim_tpuv6e.json new file mode 100644 index 000000000..1e1461380 --- /dev/null +++ b/tests/system/data/togsim_tpuv6e.json @@ -0,0 +1,58 @@ +{ + "version": "1.0.0", + "total_cycles": 2707, + "wall_clock_s": null, + "core_cycles": { + "0": 2707 + }, + "units": { + "Core [0]": { + "Issue": {"utilization_pct": 0.3417066863686738, "active_cycles": 9, "idle_cycles": 2698}, + "TPUV6E_MISC": {"utilization_pct": 0.07388252678241596, "active_cycles": 2, "idle_cycles": 2705}, + "TPUV6E_MXU": {"utilization_pct": 2.3642408570373106, "active_cycles": 64, "idle_cycles": 2643}, + "TPUV6E_SFU": {"utilization_pct": 0, "active_cycles": 0, "idle_cycles": 2707}, + "TPUV6E_XLU": {"utilization_pct": 0, "active_cycles": 0, "idle_cycles": 2707}, + "Vpu": {"utilization_pct": 0, "active_cycles": 0, "idle_cycles": 2707} + } + }, + "dma": { + "0": {"active_cycles": 256, "idle_cycles": 2451, "dram_bw_gbps": 169, "responses": 8192} + }, + "dram": {"channels": { + "0": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "1": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "2": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "3": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "4": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "5": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "6": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "7": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "8": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "9": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "10": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "11": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "12": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "13": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "14": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "15": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "16": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "17": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "18": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "19": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "20": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "21": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "22": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "23": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "24": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "25": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "26": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "27": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "28": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "29": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "30": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64}, + "31": {"bandwidth_gbps": 9.699061691909863, "utilization_pct": 18.94347958473161, "reads": 192, "writes": 64} + }, "combined": {"bandwidth_gbps": 310.3699741411156, "utilization_pct": 18.94347958473161, "reads": 6144, "writes": 2048}}, + "kernels": [ + {"scheduler": 0, "kernel_id": 0, "started": 1, "finished": 1934} + ] +} diff --git a/tests/system/data/togsim_tpuv6e.log b/tests/system/data/togsim_tpuv6e.log deleted file mode 100644 index 9868aa38c..000000000 --- a/tests/system/data/togsim_tpuv6e.log +++ /dev/null @@ -1,53 +0,0 @@ -[2026-10-14 09:54:02.100] [info] Simulation finished -[2026-10-14 09:54:02.100] [info] === DRAM statistics === -[2026-10-14 09:54:02.100] [info] [DRAM] Per-channel average bandwidth -[2026-10-14 09:54:02.100] [info] [DRAM] channel 0 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 1 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 2 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 3 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 4 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 5 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 6 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 7 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 8 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 9 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 10 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 11 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 12 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 13 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 14 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 15 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 16 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 17 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 18 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 19 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 20 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 21 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 22 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 23 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 24 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 25 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 26 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 27 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 28 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 29 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 30 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channel 31 | 1.43 GB/s avg., 2.79% of utilization | 8 reads, 4 writes -[2026-10-14 09:54:02.100] [info] [DRAM] channels 0..31 combined | 45.69 GB/s aggregate, 2.79% of utilization (avg. per channel) | 256 reads, 128 writes -[2026-10-14 09:54:02.100] [info] ===== Instructions count ===== -[2026-10-14 09:54:02.100] [info] Core [0] : MOVIN inst_count: 2 -[2026-10-14 09:54:02.100] [info] Core [0] : MOVOUT inst_count: 1 -[2026-10-14 09:54:02.100] [info] Core [0] : COMP inst_count: 2 (GEMM: 0, Vector: 2, XLU: 0) -[2026-10-14 09:54:02.100] [info] Core [0] : MEMORY_BAR inst_count: 0 -[2026-10-14 09:54:02.100] [info] ========= Core stat ========= -[2026-10-14 09:54:02.100] [info] Core [0] : Issue utilization(%): 1.16, active_cycles: 10, idle_cycles: 852 -[2026-10-14 09:54:02.100] [info] Core [0] : TPUV6E_MISC utilization(%): 0.06, active_cycles: 1, idle_cycles: 861 -[2026-10-14 09:54:02.100] [info] Core [0] : TPUV6E_MXU utilization(%): 1.86, active_cycles: 16, idle_cycles: 846 -[2026-10-14 09:54:02.100] [info] Core [0] : TPUV6E_SFU utilization(%): 0.00, active_cycles: 0, idle_cycles: 862 -[2026-10-14 09:54:02.100] [info] Core [0] : TPUV6E_XLU utilization(%): 0.00, active_cycles: 0, idle_cycles: 862 -[2026-10-14 09:54:02.100] [info] Core [0] : Vpu utilization(%): 0.81, active_cycles: 7, idle_cycles: 855 -[2026-10-14 09:54:02.100] [info] Core [0] : DMA active_cycles: 12, DMA idle_cycles: 850, DRAM BW: 24.000 GB/s (384 responses) -[2026-10-14 09:54:02.100] [info] Core [0] : NUMA local memory: 384 requests, remote memory: 0 requests -[2026-10-14 09:54:02.100] [info] Core [0] : Total_cycles: 862 -[2026-10-14 09:54:02.100] [info] Core [0] : computes held at least once by the core's compute in flight: 0 -[2026-10-14 09:54:02.100] [info] Total execution cycles: 862 diff --git a/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py index 04aeeb41a..e04c3a077 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -1,40 +1,90 @@ -"""get_result_from_file reads the statistics TOGSim prints with the unit table: one row per unit, the -array named by the machine's systolic_array_unit. The log is cut from a tpuv6e run of test_matmul.py.""" +"""TOGSim's results reach the frontend through the file it writes with --result, never its log, and a +session keeps the Simulator's output in its .log. The Simulator is a stub writing a tpuv6e test_matmul.py +run's result, so no TOGSim is needed.""" import os +import stat import sys import tempfile +from unittest import mock sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) from pytorchsim import config from pytorchsim.simulator.timing.togsim import TOGSimProcess -DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") +RESULT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "togsim_tpuv6e.json") +SAID = "[info] [TOGSim] the stub ran" +STUB = """#!/bin/sh +echo "{said}" +while [ $# -gt 0 ]; do + [ "$1" = --models_list ] && cat "$2" > /dev/null + [ "$1" = --result ] && {write} + shift +done +""" -def test_unit_table_rows(): - core, channels, avg_bw, wall, total = TOGSimProcess.get_result_from_file( - os.path.join(DATA, "togsim_tpuv6e.log")) - units = core["units"]["Core [0]"] - array = units[config.CONFIG_MACHINE.togsim_unit] - assert array == {"utilization": 1.86, "active_cycles": 16, "idle_cycles": 846} - assert core["Systolic_Array_Utilization"] == array["utilization"] - assert core["MatMul_active_cycle"] == array["active_cycles"] - assert core["Vector_Unit_Utilization"] == units["Vpu"]["utilization"] == 0.81 - assert core["Vector_active_cycle"] == 7 - assert core["Total_cycle"] == total == 862 - assert len(channels) == 32 and channels["CH[0]"] == 2.79 and avg_bw == 2.79 - assert wall == float("inf") +def _checkout(root, writes=True): + """A TOGSim checkout whose Simulator drains its command stream and, if `writes`, copies RESULT to + its --result path; the machine file and a kernel directory beside it.""" + os.makedirs(os.path.join(root, "build", "bin")) + simulator = config.togsim_simulator(root) + with open(simulator, "w") as f: + f.write(STUB.format(said=SAID, write=f'cp {RESULT} "$2"' if writes else "true")) + os.chmod(simulator, os.stat(simulator).st_mode | stat.S_IXUSR) + machine = os.path.join(root, "machine.yml") + with open(machine, "w") as f: + f.write("core_freq_mhz: 1\n") + kernel = os.path.join(root, "k") + os.makedirs(kernel) + for name in ("tog.so", "tog_cycles.tsv", "tog_units.tsv"): + open(os.path.join(kernel, name), "w").close() + return machine, os.path.join(kernel, "tile_graph.onnx"), os.path.join(kernel, "attribute") -def test_unfinished_log_has_the_same_shape(): - with tempfile.NamedTemporaryFile("w", suffix=".log") as log: - log.write("[info] Core [0] : Total_cycles: 3\n") - log.flush() - assert TOGSimProcess.get_result_from_file(log.name) == ({}, {}, 0.0, float("inf"), float("inf")) +def _logs_in(root): + return mock.patch.dict(os.environ, TORCHSIM_LOG_PATH=os.path.join(root, "logs")) + + +def test_standalone_reads_the_result_file(): + with tempfile.TemporaryDirectory() as root, _logs_in(root): + machine, handle, attribute = _checkout(root) + path = TOGSimProcess.run_standalone(handle, attribute, autotune_mode=True, config_path=machine, + togsim_path=root) + got = TOGSimProcess.read_result(path) + units = got["units"]["Core [0]"] + assert got["total_cycles"] == got["core_cycles"]["0"] > 0 + assert {config.CONFIG_MACHINE.togsim_unit, "Vpu"} <= set(units) + assert len(got["dram"]["channels"]) == 32 and got["dram"]["combined"]["reads"] > 0 + + +def test_session_writes_its_result_file(): + with tempfile.TemporaryDirectory() as root, _logs_in(root): + machine, handle, attribute = _checkout(root) + sim = TOGSimProcess(config_path=machine, togsim_path=root) + sim.launch_kernel(0, 0, handle, attribute) + sim.shutdown() + assert TOGSimProcess.read_result(sim.result_path)["total_cycles"] > 0 + with open(sim.log_path) as f: + assert SAID in f.read(), sim.log_path + stem = os.path.splitext(sim.result_path)[0] + assert sim.log_path == stem + ".log" and os.path.isfile(stem + ".trace") + + +def test_a_run_without_a_result_file_is_an_error(): + with tempfile.TemporaryDirectory() as root, _logs_in(root): + machine, handle, attribute = _checkout(root, writes=False) + path = TOGSimProcess.run_standalone(handle, attribute, autotune_mode=True, config_path=machine, + togsim_path=root) + try: + TOGSimProcess.read_result(path) + except FileNotFoundError: + return + raise AssertionError(f"{path} was read though the Simulator wrote no result") if __name__ == "__main__": - test_unit_table_rows() - test_unfinished_log_has_the_same_shape() + test_standalone_reads_the_result_file() + test_session_writes_its_result_file() + test_a_run_without_a_result_file_is_an_error() print("PASS") diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index 38d3adcb6..a7c158fa2 100644 --- a/third_party/pytorchsim-triton-backend.json +++ b/third_party/pytorchsim-triton-backend.json @@ -2,6 +2,6 @@ "description": "Pin for the compiler the codegen route lowers through: PyTorchSim-Triton-Backend, with its LLVM, Triton, the vcix-accelerator environment (RISC-V toolchain, pk, Spike, gem5), the accelerator model, and TOGSim, which the compiler carries as its third_party/TOGSim submodule: this pin is therefore also what pins the Simulator, the runtime header and the machine configs. CI builds its base image FROM ghcr.io/psal-postech/pytorchsim-triton-backend:, the image that repository publishes for every commit on its main and develop, so ref must be such a commit. scripts/build_from_source.sh checks the same ref out for a local toolchain. The repository is private; its package grants this repository read access.", "pytorchsim_triton_backend": { "repository": "PSAL-POSTECH/PyTorchSim-Triton-Backend", - "ref": "522042aebe93d71483f1bb2a6dcf1c95ac9a1f0f" + "ref": "70221f46c64a0b49d4bdbdf6ea4a3926f57a79ed" } }