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
2 changes: 1 addition & 1 deletion .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<YYYYMMDD_HHMMSS_<hash>>.log` (stats) and `.trace` (instruction trace). The path is also printed at the end of every run.
- **Per-run results:** `togsim_results/<YYYYMMDD_HHMMSS_<hash>>.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 <dump path>` for the compile clock (`timing.json`, joined by `triton_<hash>`) and `--breakdown <dump path>` 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_<user>/<hash>/...py` — useful for inspecting generated kernel code.

Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/backend/codecache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/backend/template_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions pytorchsim/simulator/timing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
149 changes: 37 additions & 112 deletions pytorchsim/simulator/timing/togsim.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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.")

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -298,83 +278,28 @@ 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())

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__":
Expand Down
58 changes: 58 additions & 0 deletions tests/system/data/togsim_tpuv6e.json
Original file line number Diff line number Diff line change
@@ -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}
]
}
Loading