diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 843dee2c7..71f28514c 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -178,7 +178,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.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/driver/codecache.py b/pytorchsim/driver/codecache.py index 4c1cea51a..c4ee3f997 100644 --- a/pytorchsim/driver/codecache.py +++ b/pytorchsim/driver/codecache.py @@ -258,7 +258,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/driver/select.py b/pytorchsim/driver/select.py index d2e4d9091..815685d04 100644 --- a/pytorchsim/driver/select.py +++ b/pytorchsim/driver/select.py @@ -58,7 +58,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 = autotune.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.py b/pytorchsim/simulator/timing.py index 4f37e2941..c5c2a1bb5 100644 --- a/pytorchsim/simulator/timing.py +++ b/pytorchsim/simulator/timing.py @@ -176,7 +176,7 @@ def write_cycle_tables(workdir, meta): 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, + Standalone returns the result TOGSim wrote, read; a queued launch returns its kernel id, since the stream's numbers are only whole when the simulator closes. """ import torch @@ -196,7 +196,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/togsim.py b/pytorchsim/simulator/togsim.py index c5f9afd4f..17c21d63e 100644 --- a/pytorchsim/simulator/togsim.py +++ b/pytorchsim/simulator/togsim.py @@ -1,12 +1,12 @@ -"""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. Also the multi-tenant entry points built on it, and the Poisson arrivals that drive them. """ +import json import os import numpy as np import shlex import subprocess -import re import sys import yaml import time @@ -64,8 +64,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 @@ -77,6 +75,9 @@ 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 # Auto-incrementing kernel ID + os.makedirs(config.CONFIG_TORCHSIM_LOG_PATH, exist_ok=True) + self.result_path = os.path.join(config.CONFIG_TORCHSIM_LOG_PATH, datetime.datetime.now().strftime( + '%Y%m%d_%H%M%S') + f"_{uuid.uuid4().hex[:8]}.json") # Create FIFOs for command and event communication self.fifo_dir = os.path.join("/tmp", f"togsim_fifo_{os.getpid()}") @@ -101,7 +102,8 @@ 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}" @@ -205,6 +207,8 @@ def shutdown(self): with open(result_path, "w") as f: f.write(stdout_output) logger.info(f'[TOGSim] Simulation log is stored to "{result_path}"') + if not status: + logger.info(f'[TOGSim] Simulation result is stored to "{self.result_path}"') self.process = None # Save trace_log with same name but .trace extension @@ -304,7 +308,7 @@ def run_standalone( killed and the run raises Cut with it (autotune cuts a slow candidate) Returns: - Path to the simulation result log file + Path to the result file TOGSim wrote (--result), beside the log Raises: RuntimeError: the Simulator exited non-zero (a kernel it refuses), the message @@ -324,7 +328,8 @@ def run_standalone( 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" + 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" # Create trace file in result directory @@ -342,7 +347,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: @@ -374,7 +380,7 @@ def run_standalone( f"{said[-1] if said else 'it printed nothing'}") from e # Prevent race condition - with open(result_path, "w") as f: + with open(log_path, "w") as f: f.write(result.decode()) f.flush() os.fsync(f.fileno()) @@ -382,75 +388,15 @@ 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 poisson_request_generator(lambda_requests, max_msec_time=None): diff --git a/tests/system/data/togsim_tpuv6e.json b/tests/system/data/togsim_tpuv6e.json new file mode 100644 index 000000000..f9d956be5 --- /dev/null +++ b/tests/system/data/togsim_tpuv6e.json @@ -0,0 +1,58 @@ +{ + "version": "e0c820f+result", + "total_cycles": 2102, + "wall_clock_s": null, + "core_cycles": { + "0": 2102 + }, + "units": { + "Core [0]": { + "Issue": {"utilization_pct": 0.24579765302886145, "active_cycles": 5, "idle_cycles": 2097}, + "TPUV6E_MISC": {"utilization_pct": 0.023786869647954328, "active_cycles": 1, "idle_cycles": 2101}, + "TPUV6E_MXU": {"utilization_pct": 0.7611798287345385, "active_cycles": 16, "idle_cycles": 2086}, + "TPUV6E_SFU": {"utilization_pct": 0, "active_cycles": 0, "idle_cycles": 2102}, + "TPUV6E_XLU": {"utilization_pct": 0, "active_cycles": 0, "idle_cycles": 2102}, + "Vpu": {"utilization_pct": 0.7136060894386299, "active_cycles": 15, "idle_cycles": 2087} + } + }, + "dma": { + "0": {"active_cycles": 12, "idle_cycles": 2090, "dram_bw_gbps": 10, "responses": 384} + }, + "dram": {"channels": { + "0": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "1": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "2": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "3": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "4": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "5": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "6": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "7": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "8": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "9": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "10": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "11": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "12": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "13": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "14": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "15": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "16": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "17": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "18": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "19": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "20": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "21": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "22": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "23": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "24": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "25": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "26": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "27": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "28": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "29": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "30": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4}, + "31": {"bandwidth_gbps": 0.585499524262607, "utilization_pct": 1.1435537412851255, "reads": 8, "writes": 4} + }, "combined": {"bandwidth_gbps": 18.735984776403424, "utilization_pct": 1.1435537412851255, "reads": 256, "writes": 128}}, + "kernels": [ + {"scheduler": 0, "kernel_id": 0, "started": 1, "finished": 1329} + ] +} 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 02a55faeb..242dff90b 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -1,40 +1,83 @@ -"""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. The +Simulator here is a stub that writes the result of a tpuv6e run of test_matmul.py, 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.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") +STUB = """#!/bin/sh +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(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 + + +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")