From 9ac527463265469dffaab7af9018d4da19edcbba Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 13:50:12 +0900 Subject: [PATCH 1/4] [Simulator] gem5 records a per-tile coprocessor timeline when TORCHSIM_GEM5_TRACE=1 With TORCHSIM_GEM5_TRACE=1 the cycle-table run passes --coprocessor-trace-file=coprocessor_trace.pftrace to gem5, which writes the sampled tiles' coprocessor trace as a Perfetto binary trace in schema coprocessor-trace/2 (1 cycle = 1 ns). write_cycle_tables reads it with the decoder in pytorchsim/simulator/perfetto_trace.py and splits it into tog_tile_timeline.pftrace beside tog_tile_cycles.tsv: one process per cycle-table row, named by row, tile, call and cycles, with the instruction lanes ("insn", "insn 2", ...) as threads and one counter track per .. Each dump closes the window the latest reset opened; slices are clipped to the window, a counter's held value is carried in at the window start and everything is rebased to it. A schema other than coprocessor-trace/2, a window count or a window length that disagrees with the cycle table is refused instead of tabled. The file carries a tog-tile-timeline/2 schema instant and ts in cycles at 1 ns each. Off by default; nothing changes for a run without the variable. perfetto_trace.py is the codec, a hand-written protobuf wire encoder and decoder with no dependency: encode_trace and decode_trace between a Chrome-style event dict and the binary Trace, and decode_tracks for a trace with inline names such as gem5's. It lands here because gem5.py needs it at compile time; its unit tests are in test_perfetto_trace.py. Depends on gem5 (PSAL-POSTECH/gem5, branch coprocessor-trace: coprocessorTraceFile on the Coprocessor unit) and on the Coprocessor repository's script_systolic.py --coprocessor-trace-file option (branch coprocessor-trace). The new test needs neither: it splits a two-window prefix and the whole of a real sample checked into tests/system/data/viewer, and a hand-encoded trace for clipping and carried counters. --- .github/workflows/pytorchsim_test.yml | 4 +- pytorchsim/config.py | 2 + pytorchsim/simulator/perfetto_trace.py | 446 ++++++++++++++++++ pytorchsim/simulator/timing/__init__.py | 5 + pytorchsim/simulator/timing/gem5.py | 130 ++++- .../viewer/coprocessor_trace_sample.pftrace | Bin 0 -> 8807 bytes .../coprocessor_trace_two_tiles.pftrace | Bin 0 -> 4694 bytes tests/system/test_gem5_trace_split.py | 143 ++++++ tests/system/test_perfetto_trace.py | 103 ++++ 9 files changed, 830 insertions(+), 3 deletions(-) create mode 100644 pytorchsim/simulator/perfetto_trace.py create mode 100644 tests/system/data/viewer/coprocessor_trace_sample.pftrace create mode 100644 tests/system/data/viewer/coprocessor_trace_two_tiles.pftrace create mode 100644 tests/system/test_gem5_trace_split.py create mode 100644 tests/system/test_perfetto_trace.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 58dce160..cf428e5b 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -19,7 +19,7 @@ on: # test_reduction_tiling and test_select, and test_autotune_tables, test_breakdown_viewer, # test_device_interface, test_launch_dir, test_module_form, test_npuwattch_json, test_one_layer_kv_write, # test_one_layer_mask, test_one_layer_softcap_mask, test_patch_scope, test_route_allowlist, test_togsim_exit, -# test_togsim_result and test_verify_golden, which emit no kernel and so are no route coverage. +# test_togsim_result, test_gem5_trace_split, test_perfetto_trace and test_verify_golden, 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. @@ -94,6 +94,7 @@ jobs: - tests/system/test_compiler_failure.py - tests/system/test_device_interface.py - tests/system/test_eager.py + - tests/system/test_gem5_trace_split.py - tests/system/test_launch_dir.py - tests/system/test_launch_record.py - tests/system/test_module_form.py @@ -102,6 +103,7 @@ jobs: - tests/system/test_one_layer_mask.py - tests/system/test_one_layer_softcap_mask.py - tests/system/test_patch_scope.py + - tests/system/test_perfetto_trace.py - tests/system/test_reduction_tiling.py - tests/system/test_route_allowlist.py - tests/system/test_select.py diff --git a/pytorchsim/config.py b/pytorchsim/config.py index 6097daa6..31669cf0 100644 --- a/pytorchsim/config.py +++ b/pytorchsim/config.py @@ -18,6 +18,8 @@ CONFIG_KVCACHE_LAYOUT = os.environ.get("TORCHSIM_KVCACHE_LAYOUT", "headwise").strip() or "headwise" if CONFIG_KVCACHE_LAYOUT not in ("headwise", "tokenwise"): raise ValueError(f"TORCHSIM_KVCACHE_LAYOUT={CONFIG_KVCACHE_LAYOUT!r}: headwise or tokenwise") +#: Set to 1 to have gem5 trace the coprocessor and write tog_tile_timeline.pftrace beside the cycle table. +CONFIG_GEM5_TRACE = os.environ.get("TORCHSIM_GEM5_TRACE", "0") == "1" #: The compiler checkout (stages 1-5, ttir to the RISC-V ELF), a separate repository, not vendored. CONFIG_TORCHSIM_COMPILE_DIR = os.environ.get( "TORCHSIM_COMPILE_DIR", default=os.path.join(CONFIG_TORCHSIM_DIR, "pytorchsim-triton-compiler")) diff --git a/pytorchsim/simulator/perfetto_trace.py b/pytorchsim/simulator/perfetto_trace.py new file mode 100644 index 00000000..6bccce85 --- /dev/null +++ b/pytorchsim/simulator/perfetto_trace.py @@ -0,0 +1,446 @@ +"""Chrome-style event dicts <-> Perfetto binary traces over a hand-written protobuf codec (no dependency). +Fields: Trace.packet=1; TracePacket ts=8 seq=10 track_event=11 interned=12 flags=13 track_descriptor=60; +TrackEvent categories=3 annotations=4 type=9 name_iid=10 track_uuid=11 double_counter=44 (more: commit).""" +import json +import math +import struct + +SLICE_BEGIN, SLICE_END, INSTANT, COUNTER = 1, 2, 3, 4 +SEQ_INCREMENTAL_STATE_CLEARED, SEQ_NEEDS_INCREMENTAL_STATE = 1, 2 +CHILD_ORDERING_EXPLICIT = 3 +SEQUENCE_ID = 1 +GLOBAL_TRACK_NAME = "global" +METADATA_TRACK_NAME = "trace metadata" +METADATA_EVENT = "otherData" +TILE_TIMELINE_SCHEMA = "tog-tile-timeline/2" +_VARINT, _FIXED64, _LEN, _FIXED32 = 0, 1, 2, 5 +_MASK = (1 << 64) - 1 + + +def _varint(n): + n &= _MASK + out = bytearray() + while n > 0x7F: + out.append((n & 0x7F) | 0x80) + n >>= 7 + out.append(n) + return bytes(out) + + +def _vi(field, n): + return _varint(field << 3 | _VARINT) + _varint(n) + + +def _bytes(field, payload): + return _varint(field << 3 | _LEN) + _varint(len(payload)) + payload + + +def _str(field, text): + return _bytes(field, text.encode("utf-8")) + + +def _f64(field, x): + return _varint(field << 3 | _FIXED64) + struct.pack("> 3, key & 7 + if wire == _VARINT: + val, i = _read_varint(buf, i) + elif wire == _LEN: + size, i = _read_varint(buf, i) + val, i = buf[i:i + size], i + size + if len(val) != size: + raise ValueError("truncated length-delimited field") + elif wire in (_FIXED64, _FIXED32): + size = 8 if wire == _FIXED64 else 4 + val, i = buf[i:i + size], i + size + if len(val) != size: + raise ValueError("truncated fixed field") + else: + raise ValueError(f"unsupported wire type {wire}") + out.append((field, wire, val)) + return out + + +def _read_varint(buf, i): + shift = val = 0 + while True: + if i >= len(buf): + raise ValueError("truncated varint") + b = buf[i] + i += 1 + val |= (b & 0x7F) << shift + if not b & 0x80: + return val, i + shift += 7 + + +class _Interner: + """String -> iid, ids from 1, in first-use order.""" + + def __init__(self): + self.ids = {} + + def get(self, text): + return self.ids.setdefault(text, len(self.ids) + 1) + + def entries(self, field): + return b"".join(_bytes(field, _vi(1, i) + _str(2, t)) for t, i in self.ids.items()) + + +def _encode_annotation(names, name, value): + """A DebugAnnotation (name iid, then the value's field); empty containers go as JSON strings.""" + head = b"" if name is None else _vi(1, names.get(name)) + if value is None: + return head + if isinstance(value, bool): + return head + _vi(2, int(value)) + if isinstance(value, int): + return head + _vi(4, value) + if isinstance(value, float): + return head + _f64(5, value) + if isinstance(value, str): + return head + _str(6, value) + if not value: + return head + _str(9, json.dumps(value)) + if isinstance(value, dict): + return head + b"".join(_bytes(11, _encode_annotation(names, k, v)) for k, v in value.items()) + return head + b"".join(_bytes(12, _encode_annotation(names, None, v)) for v in value) + + +class _Packets: + """The TracePackets of one trace: descriptors first, then the events by time.""" + + def __init__(self, trace): + self.trace, self.cats, self.names, self.keys = trace, _Interner(), _Interner(), _Interner() + self.next_uuid, self.pname, self.psort, self.tname, self.tsort = 0, {}, {}, {}, {} + self.proc, self.thread, self.counter, self.global_uuid = {}, {}, {}, None + self.descriptors, self.events = [], [] + + def uuid(self): + self.next_uuid += 1 + return self.next_uuid + + def build(self): + tables = {"process_name": (self.pname, False), "process_sort_index": (self.psort, False), + "thread_name": (self.tname, True), "thread_sort_index": (self.tsort, True)} + for e in self.trace["traceEvents"]: + if e["ph"] == "M": + table, per_thread = tables[e["name"]] + table[(e["pid"], e["tid"]) if per_thread else e["pid"]] = next(iter(e["args"].values())) + self._add_global_tracks() + for pid in sorted({*self.pname, *self.psort}): + self._get_process(pid) + for pid, tid in sorted({*self.tname, *self.tsort}): + self._get_thread(pid, tid) + order = 0 + for e in self.trace["traceEvents"]: + ph = e["ph"] + if ph == "X": + order = self._add_slice(e, order) + elif ph == "i": + self._add_event(INSTANT, self._get_instant_track(e), e["ts"], e.get("name"), e, order) + order += 1 + elif ph == "C": + order = self._add_counter(e, order) + return self._finish() + + def _add_global_tracks(self): + self.global_uuid, meta_uuid = self.uuid(), self.uuid() + other = self.trace.get("otherData") or {} + self.descriptors.append(_vi(1, self.global_uuid) + _str(2, GLOBAL_TRACK_NAME)) + desc = _vi(1, meta_uuid) + _str(2, METADATA_TRACK_NAME) + if other.get("time_axis"): + desc += _str(14, other["time_axis"]) + self.descriptors.append(desc) + body = self._track_event(INSTANT, meta_uuid, METADATA_EVENT, None, other) + self.events.append(((0, 1, 0, -1), body, 0)) + + def _get_process(self, pid): + if pid not in self.proc: + uid = self.proc[pid] = self.uuid() + body = _vi(1, pid) + if pid in self.pname: + body += _str(6, self.pname[pid]) + if pid in self.psort: + body += _vi(3, self.psort[pid]) + self.descriptors.append(_vi(1, uid) + _bytes(3, body) + _vi(11, CHILD_ORDERING_EXPLICIT)) + return self.proc[pid] + + def _get_thread(self, pid, tid): + if (pid, tid) not in self.thread: + self._get_process(pid) + uid = self.thread[(pid, tid)] = self.uuid() + body = _vi(1, pid) + _vi(2, tid) + if (pid, tid) in self.tname: + body += _str(5, self.tname[(pid, tid)]) + rank = b"" + if (pid, tid) in self.tsort: + body += _vi(3, self.tsort[(pid, tid)]) + rank = _vi(12, self.tsort[(pid, tid)] + 1) + self.descriptors.append(_vi(1, uid) + _bytes(4, body) + rank) + return self.thread[(pid, tid)] + + def _get_counter(self, pid, name, key, multi): + if (pid, name, key) not in self.counter: + parent = self._get_process(pid) + uid = self.counter[(pid, name, key)] = self.uuid() + self.descriptors.append(_vi(1, uid) + _str(2, f"{name} {key}" if multi else name) + _vi(5, parent) + + _bytes(8, _str(6, key)) + _str(14, name)) + return self.counter[(pid, name, key)] + + def _get_instant_track(self, e): + scope = e.get("s", "t") + if scope == "g": + return self.global_uuid + if scope == "p": + return self._get_process(e["pid"]) + return self._get_thread(e["pid"], e["tid"]) + + def _track_event(self, kind, track, name, cat, args, counter=None): + body = _vi(9, kind) + _vi(11, track) + if cat: + body += _vi(3, self.cats.get(cat)) + if name is not None: + body += _vi(10, self.names.get(name)) + for k, v in (args or {}).items(): + body += _bytes(4, _encode_annotation(self.keys, k, v)) + if counter is not None: + body += _f64(44, float(counter)) + return body + + def _add_event(self, kind, track, ts, name, e, order, counter=None, key=None): + key = key or (self._ns(ts), 1, 0, order) + self.events.append((key, self._track_event(kind, track, name, e.get("cat"), e.get("args"), counter), + self._ns(ts))) + + @staticmethod + def _ns(us): + return round(us * 1000) + + def _add_slice(self, e, order): + track = self._get_thread(e["pid"], e["tid"]) + start = self._ns(e["ts"]) + dur = self._ns(e["dur"]) + begin = self._track_event(SLICE_BEGIN, track, e["name"], e.get("cat"), e.get("args")) + self.events.append(((start, 1, -dur, order), begin, start)) + end_key = (start, 1, 0, order + 0.5) if dur == 0 else (start + dur, 0, -order, 0) + self.events.append((end_key, _vi(9, SLICE_END) + _vi(11, track), start + dur)) + return order + 1 + + def _add_counter(self, e, order): + args = e["args"] + for key, value in args.items(): + track = self._get_counter(e["pid"], e["name"], key, len(args) > 1) + self._add_event(COUNTER, track, e["ts"], None, {}, order, counter=value) + order += 1 + return order + + def _finish(self): + interned = (self.cats.entries(1) + self.names.entries(2) + self.keys.entries(3)) + first = _vi(10, SEQUENCE_ID) + _bytes(12, interned) + _vi(13, SEQ_INCREMENTAL_STATE_CLEARED) + out = [_bytes(1, first)] + for desc in self.descriptors: + out.append(_bytes(1, _vi(10, SEQUENCE_ID) + _bytes(60, desc))) + for key, body, ts in sorted(self.events, key=lambda x: x[0]): + out.append(_bytes(1, _vi(8, ts) + _vi(10, SEQUENCE_ID) + _bytes(11, body) + + _vi(13, SEQ_NEEDS_INCREMENTAL_STATE))) + return b"".join(out) + + +def encode_trace(trace): + """The binary Perfetto trace of a Chrome-style event dict {"traceEvents": [...], "otherData": {...}}. + X becomes a slice begin and end on its thread track, i an instant, C one counter track per arg key and + M the process and thread names and order; ts and dur are microseconds, stored as integer ns. otherData + rides on an instant of the "trace metadata" track. Slices that overlap without nesting are not + representable.""" + return _Packets(trace).build() + + +def write_trace(path, trace): + """`trace` encoded and written to `path`; returns the byte count.""" + data = encode_trace(trace) + with open(path, "wb") as fh: + fh.write(data) + return len(data) + + +def _decode_annotation(names, buf): + """(name, value) of one DebugAnnotation message.""" + name, value, entries, items, seen = None, None, [], [], None + for field, _, val in parse_message(buf): + if field == 1: + name = names[val] + elif field == 10: + name = val.decode("utf-8") + elif field in (2, 3, 4): + value = bool(val) if field == 2 else (val - (1 << 64) if field == 4 and val >> 63 else val) + elif field == 5: + value = struct.unpack("> 63 else e.get(30, [None])[0] + events.append({"ts": f.get(8, [0])[0], "kind": e[9][0], "track": e[11][0], + "name": e[23][0].decode("utf-8") if 23 in e else None, + "args": dict(_decode_annotation({}, a) for a in e.get(4, [])), "value": value}) + return tracks, events diff --git a/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index 49c90bd1..a2de4489 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -21,6 +21,8 @@ TENSORS_TXT = "tog_tensor_bytes.txt" TENSOR_SHAPES_TXT = "tog_tensor_shapes.txt" +TIMELINE_PFTRACE = "tog_tile_timeline.pftrace" + LOCK_NAME = ".timing.lock" LOCK_TIMEOUT = 1800 @@ -179,6 +181,9 @@ def write_cycle_tables(workdir, meta): with open(os.path.join(workdir, UNITS_TSV), "w") as f: f.write("".join("\t".join(str(v) for v in r) + "\n" for r in rows)) gem5.dump_cycle_table_tsv(table, os.path.join(workdir, CYCLE_TSV)) + if config.CONFIG_GEM5_TRACE: + gem5.write_tile_timeline(m5out, table, gem5.read_tile_labels(m5out, n_tiles), + os.path.join(workdir, TIMELINE_PFTRACE)) logger.info("[Gem5] tile cycles: %s", table) return n_tiles diff --git a/pytorchsim/simulator/timing/gem5.py b/pytorchsim/simulator/timing/gem5.py index 1e1137b6..3eafbd4b 100644 --- a/pytorchsim/simulator/timing/gem5.py +++ b/pytorchsim/simulator/timing/gem5.py @@ -1,5 +1,6 @@ """gem5 over the compiler's cycle binary, one sampled tile per dump, and the tables TOGSim reads -beside the TOG from those dumps: tog_tile_cycles.tsv (cycle, overlapping) and tog_unit_table.tsv.""" +beside the TOG from those dumps: tog_tile_cycles.tsv (cycle, overlapping) and tog_unit_table.tsv; with +TORCHSIM_GEM5_TRACE=1 also tog_tile_timeline.pftrace, the coprocessor trace split by cycle-table row.""" import os import re @@ -7,10 +8,14 @@ from pytorchsim import config, contract from pytorchsim.backend import compiler_bridge -from pytorchsim.simulator import wallclock +from pytorchsim.simulator import perfetto_trace, wallclock logger = config.setup_logger() +TRACE_FILE = "coprocessor_trace.pftrace" +TRACE_SCHEMA = "coprocessor-trace/2" +TS_UNIT = "cycle (1 ns per cycle)" + def run_cycle_binary(workdir, meta): """The m5out of the compiler's cycle ELF run under gem5, or None when gem5 could not run it.""" @@ -39,6 +44,8 @@ def _simulate(target_binary, obj_dir, manifest, silent_mode=False): "--model", run["model"], "--machine-config", run["machine_config"], "--vlane", str(machine.vector_lanes), "--vlen", str(machine.vlen_bits)] + if config.CONFIG_GEM5_TRACE: + gem5_cmd.append(f"--coprocessor-trace-file={TRACE_FILE}") if not silent_mode: logger.debug(f"[Gem5] cmd> {' '.join(gem5_cmd)}") @@ -82,6 +89,125 @@ def tile_tables(m5out, overlap_offsets): return cycle_table(overlap_offsets, dumps), unit_rows(dumps) +def write_tile_timeline(m5out, table, labels, path): + """tog_tile_timeline.pftrace from the coprocessor trace gem5 left in `m5out`: one process per cycle-table + row (`labels` are its (tile, call)), ts in cycles from the tile's reset; None when tracing was off.""" + trace = os.path.join(m5out, TRACE_FILE) + if not os.path.isfile(trace): + return None + with open(trace, "rb") as fh: + data = fh.read() + rows = split_trace_by_tile(data, [c for c, _ in table]) + perfetto_trace.write_trace(path, build_timeline_trace(rows, labels)) + return path + + +def split_trace_by_tile(data, cycles): + """[{row, cycles, insns, counters}] from a coprocessor-trace/2 file: each dump closes the window opened + by the latest reset; slices are clipped to it, counters carry their held value in and all are rebased to + the window start. Another schema, a window count or a window length that is not `cycles` raises.""" + tracks, events = perfetto_trace.decode_tracks(data) + stats = [e for e in events if tracks[e["track"]]["name"] == "stats"] + schema = next((e["args"].get("schema") for e in stats if e["name"] == "schema"), None) + if schema != TRACE_SCHEMA: + raise ValueError(f"coprocessor trace schema {schema!r}, expected {TRACE_SCHEMA}") + windows, start = [], None + for e in sorted((e for e in stats if e["name"] in ("reset", "dump")), key=lambda e: e["ts"]): + if e["name"] == "reset": + start = e["ts"] + elif start is not None: + windows.append((start, e["ts"])) + start = None + if len(windows) != len(cycles): + raise ValueError(f"coprocessor trace has {len(windows)} tile windows, " + f"the cycle table {len(cycles)} rows") + slices, counters = _pair_slices(tracks, events), _get_counter_events(tracks, events) + rows = [] + for row, ((lo, hi), want) in enumerate(zip(windows, cycles)): + if hi - lo != int(want): + raise ValueError(f"coprocessor trace window {row} is {hi - lo} cycles, " + f"the cycle table says {want}") + rows.append({"row": row, "cycles": hi - lo, "insns": _clip_slices(slices, lo, hi), + "counters": _clip_counters(counters, lo, hi)}) + return rows + + +def _pair_slices(tracks, events): + """[(lane, name, begin, end, args)] of the begin/end pairs on the instruction lanes, in file order.""" + open_, out = {}, [] + for e in events: + t = tracks[e["track"]] + if t["counter"] or t["name"] == "stats" or t["process"]: + continue + if e["kind"] == perfetto_trace.SLICE_BEGIN: + open_[e["track"]] = e + elif e["kind"] == perfetto_trace.SLICE_END: + b = open_.pop(e["track"]) + out.append((t["name"], b["name"], b["ts"], e["ts"], b["args"])) + return out + + +def _get_counter_events(tracks, events): + """{counter name: [(ts, value)]} sorted by ts, from the counter tracks.""" + out = {} + for e in events: + if e["kind"] == perfetto_trace.COUNTER: + out.setdefault(tracks[e["track"]]["name"], []).append((e["ts"], e["value"])) + return {k: sorted(v, key=lambda x: x[0]) for k, v in out.items()} + + +def _clip_slices(slices, lo, hi): + """The slices overlapping [lo, hi) clipped to it, as (lane, name, ts - lo, dur, args), by start.""" + out = [] + for lane, name, a, b, args in slices: + a, b = max(a, lo), min(b, hi) + if b > a: + out.append((lane, name, a - lo, b - a, args)) + return sorted(out, key=lambda s: s[2]) + + +def _clip_counters(counters, lo, hi): + """[(name, ts - lo, value)]: each counter's value at `lo` carried in at 0, then its changes inside.""" + out = [] + for name, points in counters.items(): + held = [v for ts, v in points if ts <= lo] + if held: + out.append((name, 0, held[-1])) + out += [(name, ts - lo, v) for ts, v in points if lo < ts < hi] + return sorted(out, key=lambda c: c[1]) + + +def build_timeline_trace(rows, labels): + """The event dict of a tile timeline: a process per row named by its row, tile, call and cycles, a thread + per instruction lane, a counter track per counter; ts in us, 1 cycle = 1 ns.""" + events = [] + for r in rows: + pid = r["row"] + 1 + tile, call = labels[r["row"]] + events += [{"ph": "M", "name": "process_name", "pid": pid, "tid": 0, "args": { + "name": f"tile row {r['row']}: tile {tile} call {call} ({r['cycles']} cycles)"}}, + {"ph": "M", "name": "process_sort_index", "pid": pid, "tid": 0, + "args": {"sort_index": r["row"]}}] + lanes = {} + for lane, name, ts, dur, args in r["insns"]: + if lane not in lanes: + lanes[lane] = len(lanes) + 1 + events.append({"ph": "M", "name": "thread_name", "pid": pid, "tid": lanes[lane], + "args": {"name": lane}}) + events.append({"ph": "X", "cat": "insn", "name": name, "pid": pid, "tid": lanes[lane], + "ts": ts / 1000, "dur": dur / 1000, "args": args}) + events += [{"ph": "C", "cat": "unit", "name": name, "pid": pid, "ts": ts / 1000, + "args": {"delta": value}} for name, ts, value in r["counters"]] + return {"traceEvents": events, "otherData": { + "schema": perfetto_trace.TILE_TIMELINE_SCHEMA, "ts_unit": TS_UNIT, "rows": len(rows)}} + + +def read_tile_labels(m5out, n_tiles): + """[(tile, call)] per cycle-table row, from the dumps the compiler's gem5_samples reads.""" + dumps = compiler_bridge.compiler_contract("gem5_samples").read(m5out, n_tiles) + return [(d["tile"], d["call"]) for d in dumps] + + def cycle_table(overlap_offsets, dumps): """[(cycle, overlapping_cycle), ...], one per gem5 dump in row order. The compiler states each tile's overlap offset (None where nothing of it overlaps), and each dump names its tile.""" diff --git a/tests/system/data/viewer/coprocessor_trace_sample.pftrace b/tests/system/data/viewer/coprocessor_trace_sample.pftrace new file mode 100644 index 0000000000000000000000000000000000000000..3bba869a4282a643f14c3e190daf4a29dbb433a9 GIT binary patch literal 8807 zcmbW*X>e3k76)*;e*2waZFP6j4^|ks+&2(U3$Zr-WQ_ZR5Sf6eF z(pGg$pt*U4Y8GFJoRQr*oh*6FdxkhHohD?E05IFSr@S>0jh`4p$6lhc84Xjjl2_K$O?)=&OR(|LcLTGN(D zrn-AtQf-|HyF-6G#`)pcbf7Y{J7^AOdb99a$HMJ$0{@LDkL2D}e^NMs}cxYeH9D>#xrq*C>rL!f&Gy^Qu$r92FldE648!y=6n9%mD-{_~SKOAEZe0}CNioua z($G+|$j(?ohOS;Mt!z9e?rRvj$`_i^(VXh)wz?uEb^f;LVPC|oE1K4pO2$f~7sZ-u zqZ6W&rr8#3Z%$c>mWyM-p2WWrofjq|gX%)bfA=&eTP^#)ocs?~%PJd-;{JxA&SN<9 zn5S?0AL43xW#d`7JK{gmj!4rh+)Y;~`>|Z7rD%FjM_2Exgw@Ktee*jJ%hG{CA;T=m zmDQV61c4I_?CJC zPmb2+o2}Ag30&qp#?_|0IUeWS&<{hgFS(# z)y4{>LIUd?pRMf2GxfR_%q*}SJ?*j}9P5c2ix!IewmTDsdZ)566fbJn7d+_GOK6t% z_oV|adRPBr=2w1axD53kDIoMdsYvJpQnAn$Qi;%3Qc!3cDI~O=G(czvsZ?kuX`s-D zq(MR-kp>H;NyiF(Od2Be2}$o$hWeDGXNI9ZBk3_U)aN8U;|;Zobex3WO*&p^52;*e zFKL+2KGJZZ{iG2>2S_7@z95|-bdWSk=u6UQp|40M3Vltg5c-A`7W$S{DfAsFB6NsU zC3KinE%ZIKD?f@~dA-zY)45;(S(_uj4eKnWS+- zmy&9PE+d^TbU7(1bOmX=(3PZ^&{d=fLRXU}3SC2*By=rlve0#;DMGVIwL;gEek(Ma z^gE$Bq%(x(l725VkMswj`J^+27Ld*oT1Zkti!^0cIVob*+^Xyd;UDLb5Pm)homfCZ zR~M4-LW@Xv?Hfo)&SDZ$xP*j6-$=r6EG1#kmXR>D{~=)l+(g1OxtWB?bPEYn?p6{e z=4~WQ-`h!;%By3>Mk+97@Pr_#S0ts8@izIBUt4Y{?Um{_XUPHoGzLtay|78-& zf>%f=9$qD(#CVN_LgaN4%9V8_6gBHfD1F`_p+MR|^2=hik%W@$O%m2Gp-f4p>Cc%O z@eI30w5!^p8C{(?fDdsOh|$_;bi%~k2XLqP!D>^LbL7@Tl?`fFwC+tZHwPcv39$^zCSG3FcJ0E?w%?Y~4)uu*7rYah_)S zIfdoC+mUAUM9VglJv#Aij`uXv&$+k1X7tpHtA*9x0cA7g-ewBk5-f73DX#3tJQo7P zJc0X3lgyMQIRj_&&mIr=1nws>-oQHJakW_YIGb?}>ZwObsJb2_p*DM*gbHpY33c8RBvgY>l29`~MM7oyGzs_<0hl=NCw*v0o&i5?@V1z5WsjRs9+gYX7w)oDg0n;T-V_38#%$NjQ_dM#9PE zbrQ}u>qs~Stta8E^acqhstqKZyEc+=I(w5e-dXGowTToH+DyWE@V_LS8s8$}Z22|` zC(w6DIH$f#!fEzB63)EulW;QrfQ0k&77|X`TS+*JZzJKvzMX_~{SK0nOzhO;z7W`Q zQlATftt5osMnWgHlhD;2B)rg05?=d55|Z-~2`NmIkm!#|7>-X!7_?7G7~0QBm;j%X zFim!mFqw9fFy;1;FfsR%Fn#xtFv<6m@F^T1;e+{tgwN_A2_N5=Bz&S@k?jU;{gH>YgnI=obRn=z2h~%eLfMbG JPs2`H{s-?7B;No4 literal 0 HcmV?d00001 diff --git a/tests/system/data/viewer/coprocessor_trace_two_tiles.pftrace b/tests/system/data/viewer/coprocessor_trace_two_tiles.pftrace new file mode 100644 index 0000000000000000000000000000000000000000..e5165a111b920aa913038da49d62f58921761ada GIT binary patch literal 4694 zcmbW)X>b!|7zc2YO}pFB(q^mW5Nwhv6qORTrLCf{;~8gUh6%RQ>6aSP)n;synB5fk z=6xTW9^ico-iimF2worv<9%zqxW)TEHoMQ0f3~Dl_}2Z++vk1X=XtMqr)Gr)$tBCN zWGbDEX}X?F`;AnlzgZhoBe|3!KFihP^2%9Zxa5{gbR%l$^)A!g-X3*W=NVz4!@b&7 zs>gb?zG!eh3p$u&q@yuyvJ$L}l=LOLwO*yv?lKsNh=$&kNyH7MCN@9TtNH7v z_!GK6rKSDW_e86w30c7}Z58E_r_X9@Z$7DO_Q`Dx@q})qGchBcOqc^Yewfv;J}U&I zZK6Di8qPd*_6fyX)@6mU(sog{K-~X#Ak_8B!mevo^RvcIi>Eu& zml~KAzq)GBvAL~?)mfoj^2w#Sy!jQ%oP{!BV?Ld02Bb5i_fR?o$1GYxP5YJ3b%k?k zSJ&Fz`1Y=v$I;FHR*kyxS@X_!BXc*HO^KtMmevEBjcj!jR@VfjP(K1ahmQNRBHUf#6a4`iPxL2f0?}WfdZNEU_S4a){sTIK zTKx+;lIYx^wXJfy<0zu@K$D2h2Q?5~0Gdp6At*$25oik0#UO>~5>O-2rJyFF%Rp0! zE(bLeT>)w#x)Rh%bQS1mqN_p25M2YBMzjEQEYU*HaYTzi(}@;?W)Lj_sYFX{%AIob zh*cNVu3S`a7aIuNJudJrf21`wBH8HkIv9K@x) z5yT7NCJ--^n?byoZUOO^EMDK-`hdF$nOC0R=5+y8|E$$Z>zgOy!q|{@fN)o z#2fiO5O4PtAU+gUg81mTAH)aD10X(z9t81W^$>`Uw1+`_@I3ues+zd>Os~;w$q- z5MQioKz#ka1ma72Er_r3bs)a*Uk35B;1v)*9$p3U6XP`yKSW*!@pEN8h#xf@K>YN1 z1H=!cjUYE2R+~WlBzqIY=ND1#NoLcDxi{i8^Nnb}YCZj_B>w=fEPNn_T0^16rs6-q rt?nz-&2`pKZo5?ZpyrFVFlg0)pvn+Ix7b1LB~h!IpT&PnTNC~dt(xMG literal 0 HcmV?d00001 diff --git a/tests/system/test_gem5_trace_split.py b/tests/system/test_gem5_trace_split.py new file mode 100644 index 00000000..4810b85d --- /dev/null +++ b/tests/system/test_gem5_trace_split.py @@ -0,0 +1,143 @@ +"""gem5's coprocessor-trace/2 Perfetto file is split into one process per cycle-table row: a dump closes the +window the latest reset opened, slices are clipped, counters carry their held value in, ts is rebased to the +window, and a trace that disagrees with the table is refused. coprocessor_trace_two_tiles.pftrace is the +first two windows of the real sample (the file prefix up to its second dump); the sample is whole.""" +import os +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.environ.get("TORCHSIM_DIR") or os.path.dirname(os.path.dirname(HERE))) + +from pytorchsim.simulator import perfetto_trace # noqa: E402 +from pytorchsim.simulator.perfetto_trace import _bytes, _str, _vi # noqa: E402 +from pytorchsim.simulator.timing import gem5 # noqa: E402 + +DATA = os.path.join(HERE, "data", "viewer") +SAMPLE_CYCLES = [16, 284, 14, 282] +MXU = "TPUV6E_MXU.rows_in_flight" + + +def _read(name): + with open(os.path.join(DATA, name), "rb") as fh: + return fh.read() + + +def _refusal(data, cycles): + try: + gem5.split_trace_by_tile(data, cycles) + except ValueError as e: + return str(e) + return "no refusal" + + +def _descriptor(uuid, name, parent=None, process=False, counter=False): + body = _vi(1, uuid) + _str(2, name) + body += _bytes(3, _vi(1, 1)) if process else b"" + body += _vi(5, parent) if parent else b"" + body += _bytes(8, b"") if counter else b"" + return _bytes(1, _vi(10, 1) + _bytes(60, body)) + + +def _event(ts, kind, track, name=None, value=None, **args): + body = _vi(9, kind) + _vi(11, track) + (_str(23, name) if name else b"") + for k, v in args.items(): + body += _bytes(4, _str(10, k) + (_str(6, v) if isinstance(v, str) else _vi(4, v))) + body += _vi(30, value) if value is not None else b"" + return _bytes(1, _vi(8, ts) + _vi(10, 1) + _bytes(11, body)) + + +def _gem5_file(slices, counters, windows, schema="coprocessor-trace/2"): + """A coprocessor trace as gem5 writes it: slices (begin, end, name), counter points (ts, value) and + reset/dump windows, hand-encoded with the codec's wire helpers.""" + out = [_descriptor(1, "coprocessor m", process=True), _descriptor(2, "stats", 1), + _event(0, 3, 2, "schema", schema=schema), _descriptor(16, "insn", 1), + _descriptor(1000, "G.c", 1, counter=True)] + for lo, hi in windows: + out += [_event(lo, 3, 2, "reset", index=0), _event(hi, 3, 2, "dump", index=0)] + for a, b, name in slices: + out += [_event(a, 1, 16, name, id=1), _event(b, 2, 16)] + out += [_event(ts, 4, 1000, value=v) for ts, v in counters] + return b"".join(out) + + +def _integral(points, end): + """sum of value * cycles held over [first point, end) for [(ts, value)].""" + edges = points + [(end, 0)] + return sum(v * (edges[i + 1][0] - t) for i, (t, v) in enumerate(points)) + + +def test_each_window_becomes_the_row_of_its_tile(): + rows = gem5.split_trace_by_tile(_read("coprocessor_trace_two_tiles.pftrace"), [16, 284]) + assert [(r["row"], r["cycles"], len(r["insns"])) for r in rows] == [(0, 16, 1), (1, 284, 14)] + for r in rows: + assert all(0 <= ts and ts + dur <= r["cycles"] for _, _, ts, dur, _ in r["insns"]), r["row"] + assert all(0 <= ts <= r["cycles"] for _, ts, _ in r["counters"]), r["row"] + + +def test_a_window_the_cycle_table_does_not_have_is_refused(): + data = _read("coprocessor_trace_two_tiles.pftrace") + assert "2 tile windows, the cycle table 3 rows" in _refusal(data, [16, 284, 14]) + assert "window 1 is 284 cycles, the cycle table says 280" in _refusal(data, [16, 280]) + + +def test_another_schema_is_refused(): + data = _read("coprocessor_trace_two_tiles.pftrace") + assert b"coprocessor-trace/2" in data + assert "coprocessor-trace/1" in _refusal(data.replace(b"coprocessor-trace/2", b"coprocessor-trace/1"), + [16, 284]) + no_schema = _descriptor(1, "coprocessor m", process=True) + _descriptor(2, "stats", 1) + assert "schema None" in _refusal(no_schema, [10]) + + +def test_slices_are_clipped_and_counters_carry_their_held_value_into_each_window(): + data = _gem5_file(slices=[(5, 15, "a"), (18, 25, "b"), (40, 60, "c")], + counters=[(3, 2), (12, 5), (22, 0), (41, 7)], windows=[(10, 20), (30, 50)]) + r0, r1 = gem5.split_trace_by_tile(data, [10, 20]) + assert r0["insns"] == [("insn", "a", 0, 5, {"id": 1}), ("insn", "b", 8, 2, {"id": 1})] + assert r1["insns"] == [("insn", "c", 10, 10, {"id": 1})] + assert r0["counters"] == [("G.c", 0, 2), ("G.c", 2, 5)] + assert r1["counters"] == [("G.c", 0, 0), ("G.c", 11, 7)] + assert _integral([(t, v) for _, t, v in r0["counters"]], 10) == 2 * 2 + 5 * 8 + + +def test_no_trace_file_writes_no_timeline_and_a_trace_writes_one(): + labels = list(zip(range(4), [0, 0, 1, 1])) + table = [(c, 0) for c in SAMPLE_CYCLES] + with tempfile.TemporaryDirectory() as m5out: + path = os.path.join(m5out, "tog_tile_timeline.pftrace") + assert gem5.write_tile_timeline(m5out, table, labels, path) is None + assert not os.path.exists(path) + with open(os.path.join(m5out, gem5.TRACE_FILE), "wb") as fh: + fh.write(_read("coprocessor_trace_sample.pftrace")) + assert gem5.write_tile_timeline(m5out, table, labels, path) == path + trace = perfetto_trace.read_trace(path) + assert trace["otherData"]["schema"] == perfetto_trace.TILE_TIMELINE_SCHEMA + names = [e["args"]["name"] for e in trace["traceEvents"] if e["name"] == "process_name"] + assert names == ["tile row 0: tile 0 call 0 (16 cycles)", "tile row 1: tile 1 call 0 (284 cycles)", + "tile row 2: tile 2 call 1 (14 cycles)", + "tile row 3: tile 3 call 1 (282 cycles)"], names + slices = [e["pid"] for e in trace["traceEvents"] if e["ph"] == "X"] + assert [slices.count(p) for p in (1, 2, 3, 4)] == [1, 14, 1, 14] + + +def test_the_real_sample_has_four_windows_and_tile_1_issues_11968_mxu_row_cycles(): + rows = gem5.split_trace_by_tile(_read("coprocessor_trace_sample.pftrace"), SAMPLE_CYCLES) + assert [r["cycles"] for r in rows] == SAMPLE_CYCLES + mxu = [(ts, v) for n, ts, v in rows[1]["counters"] if n == MXU] + assert _integral(mxu, 284) == 11968 + labels = [(i, 0) for i in range(4)] + trace = perfetto_trace.decode_trace(perfetto_trace.encode_trace(gem5.build_timeline_trace(rows, labels))) + pts = sorted((round(e["ts"] * 1000), e["args"]["delta"]) for e in trace["traceEvents"] + if e["ph"] == "C" and e["name"] == MXU and e["pid"] == 2) + assert _integral(pts, 284) == 11968 + + +if __name__ == "__main__": + test_each_window_becomes_the_row_of_its_tile() + test_a_window_the_cycle_table_does_not_have_is_refused() + test_another_schema_is_refused() + test_slices_are_clipped_and_counters_carry_their_held_value_into_each_window() + test_no_trace_file_writes_no_timeline_and_a_trace_writes_one() + test_the_real_sample_has_four_windows_and_tile_1_issues_11968_mxu_row_cycles() + print("PASS") diff --git a/tests/system/test_perfetto_trace.py b/tests/system/test_perfetto_trace.py new file mode 100644 index 00000000..0be0b215 --- /dev/null +++ b/tests/system/test_perfetto_trace.py @@ -0,0 +1,103 @@ +"""The Perfetto codec: wire framing, the packets encode_trace writes, the event dict decode_trace returns, +and decode_tracks over a trace with inline names.""" +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.environ.get("TORCHSIM_DIR") or os.path.dirname(os.path.dirname(HERE))) + +from pytorchsim.simulator import perfetto_trace # noqa: E402 + + +def _canon(trace): + """Events of a trace as sorted tuples with ts and dur rounded to ns and None args dropped.""" + out = [] + for e in trace["traceEvents"]: + e = {k: v for k, v in e.items() if k != "cname"} + for key in ("ts", "dur"): + if key in e: + e[key] = round(e[key] * 1000) + out.append(json.dumps(e, sort_keys=True, default=str)) + return sorted(out) + + +def test_wire_codec_frames_varints_and_length_delimited_fields(): + """Varints are 7 bits a byte (300 -> ac 02, -1 -> ten bytes), a string is key, length, bytes, and a + truncated message raises.""" + assert perfetto_trace._varint(300) == b"\xac\x02" and len(perfetto_trace._varint(-1)) == 10 + msg = perfetto_trace._vi(1, 150) + perfetto_trace._str(2, "hé") + perfetto_trace._f64(3, 0.5) + assert msg[:3] == b"\x08\x96\x01" + assert perfetto_trace.parse_message(msg) == [(1, 0, 150), (2, 2, "hé".encode()), + (3, 1, b"\x00\x00\x00\x00\x00\x00\xe0?")] + for cut in (msg[:-3], msg[:6], b"\x08"): + try: + perfetto_trace.parse_message(cut) + except ValueError: + continue + raise AssertionError(f"accepted {cut!r}") + + +def test_encoded_trace_is_packets_with_descriptors_and_track_events(): + """Trace.packet=1 repeated: the first packet clears incremental state and interns names, then track + descriptors (process, thread, counter) and one TrackEvent packet per begin, end, instant and counter.""" + trace = {"traceEvents": [ + {"ph": "M", "name": "process_name", "pid": 1, "tid": 0, "args": {"name": "core"}}, + {"ph": "M", "name": "thread_name", "pid": 1, "tid": 7, "args": {"name": "Kernels"}}, + {"ph": "X", "name": "k", "cat": "kernel", "pid": 1, "tid": 7, "ts": 2.0, "dur": 3.0, + "args": {"n": 4}}, + {"ph": "C", "name": "util", "pid": 1, "ts": 2.0, "args": {"%": 9.5}}], "otherData": {"a": "b"}} + packets = [dict((f, v) for f, _, v in perfetto_trace.parse_message(v)) + for f, _, v in perfetto_trace.parse_message(perfetto_trace.encode_trace(trace)) if f == 1] + assert packets[0][13] == 1 and 12 in packets[0] and all(p[10] == 1 for p in packets) + kinds = [perfetto_trace.parse_message(p[60]) for p in packets if 60 in p] + names = [dict((f, v) for f, _, v in k) for k in kinds] + assert any(3 in n for n in names) and any(4 in n for n in names) and any(8 in n for n in names) + events = [(p[8], dict((f, v) for f, _, v in perfetto_trace.parse_message(p[11]))) + for p in packets if 11 in p] + assert [(ts, e[9]) for ts, e in events if ts] == [(2000, 1), (2000, 4), (5000, 2)], events + assert all(p[13] == 2 for p in packets if 11 in p) + + +def test_decode_returns_the_events_that_were_encoded(): + """Slices, instants (global, process and thread scope), counters (also two keys), names, sort indexes, + args of every type and otherData survive the encode and decode round trip, ts to the ns.""" + trace = {"traceEvents": [ + {"ph": "M", "name": "process_name", "pid": 3, "tid": 0, "args": {"name": "P"}}, + {"ph": "M", "name": "process_sort_index", "pid": 3, "tid": 0, "args": {"sort_index": 2}}, + {"ph": "M", "name": "thread_name", "pid": 3, "tid": 1, "args": {"name": "T"}}, + {"ph": "M", "name": "thread_sort_index", "pid": 3, "tid": 1, "args": {"sort_index": 0}}, + {"ph": "X", "name": "outer", "cat": "c", "pid": 3, "tid": 1, "ts": 1.5, "dur": 10.0, + "args": {"i": -5, "f": 0.25, "s": "ü", "b": True, "n": None, "d": {"x": [1, "y"]}, "e": [], + "o": {}}}, + {"ph": "X", "name": "inner", "pid": 3, "tid": 1, "ts": 1.5, "dur": 4.0, "args": {}}, + {"ph": "X", "name": "zero", "pid": 3, "tid": 1, "ts": 8.0, "dur": 0.0, "args": {}}, + {"ph": "i", "s": "g", "name": "run", "pid": 0, "tid": 0, "ts": 0.0, "args": {"log": "a"}}, + {"ph": "i", "s": "p", "name": "pi", "pid": 3, "tid": 0, "ts": 2.0, "args": {}}, + {"ph": "i", "s": "t", "name": "ti", "pid": 3, "tid": 1, "ts": 3.0, "args": {"k": 1}}, + {"ph": "C", "name": "gb", "pid": 3, "ts": 1.0, "args": {"GB/s": 2.5}}, + {"ph": "C", "name": "mxu", "pid": 3, "ts": 1.0, "args": {"rows": 4, "active": 8}}], + "otherData": {"time_axis": "1 us = 5 cycles", "runs": ["a", "b"], "core_mhz": 1751}} + back = perfetto_trace.decode_trace(perfetto_trace.encode_trace(trace)) + assert back["otherData"] == trace["otherData"] + got, want = _canon(back), _canon(trace) + assert [json.loads(g) for g in got] == [json.loads(w) for w in want], (got, want) + + +def test_decode_tracks_reads_inline_names_parents_and_counter_values(): + """gem5's form: a descriptor with a name and a parent, events with the name inline (field 23), string + and int annotations named inline (field 10) and an integer counter_value (field 30).""" + v, f, b = perfetto_trace._vi, perfetto_trace._str, perfetto_trace._bytes + desc = [v(1, 1) + f(2, "proc") + b(3, v(1, 1)), v(1, 9) + f(2, "insn") + v(5, 1), + v(1, 7) + f(2, "g.c") + v(5, 1) + b(8, b"")] + ann = b(4, f(10, "id") + v(4, 3)) + b(4, f(10, "bits") + f(6, "0x1")) + events = [(5, v(9, 1) + v(11, 9) + f(23, "add") + ann), (8, v(9, 2) + v(11, 9)), + (6, v(9, 4) + v(11, 7) + v(30, 4))] + data = b"".join(b(1, v(10, 1) + b(60, d)) for d in desc) + data += b"".join(b(1, v(8, ts) + v(10, 1) + b(11, e)) for ts, e in events) + tracks, got = perfetto_trace.decode_tracks(data) + assert tracks[1]["process"] + assert tracks[9] == {"name": "insn", "parent": 1, "process": False, "counter": False} + assert tracks[7]["counter"] + assert [(e["ts"], e["kind"], e["track"], e["name"], e["args"], e["value"]) for e in got] == [ + (5, 1, 9, "add", {"id": 3, "bits": "0x1"}, None), (8, 2, 9, None, {}, None), (6, 4, 7, None, {}, 4)] From 0bd142b668068164e787ada72a804d6342ec7ae8 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 13:50:32 +0900 Subject: [PATCH 2/4] [Tools] dump_profile writes a Perfetto trace of the simulated run and one tile trace per kernel scripts/dump_profile.py reads TOGSim logs and writes /trace.pftrace, a Perfetto binary trace on the simulated time axis: runs laid end to end in log order, ts and dur in microseconds (cycles / core MHz) and the raw cycles (start_cycle, cycles) in the args of every kernel, copy, DMA, compute and tile slice or instant. Per NPU core it has a Kernels thread (one slice per launch, with cycles including and excluding its copy_node runs, workdir, the model lines and ATen ops from TORCH_TRACE or Inductor's debug dir, and the relative paths tile_trace, source and dump_dir to go to next), a copy thread, one utilization counter per unit from the Core stat windows, and, for a trace-level log, DMA read/write, compute lanes and tile markers. A DRAM process has GB/s, utilization and request counters (per-channel ones with --dram-channels). Runs that scheduled nothing are listed in the metadata and left off. The axis (machine, core MHz, "simulated runs concatenated in log order; 1 us = N cycles") and the verdict rule ride on the trace's metadata instant. Each kernel slice also has a utilization-based speed of light (scripts/profile_sol.py, no FLOP counts): the utilization of Issue, MXU, Vpu, XLU, SFU and MISC (util_), the compute peak and its unit (sol_compute_pct, sol_compute_unit), DRAM GB/s and % of the peak in the log's "Total bandwidth" line, DMA busy % and a verdict: compute-bound (), memory-bound (DRAM), DMA-latency-bound or latency/dependency-bound. They are the cycle-weighted mean of the Core stat and DRAM windows overlapping the kernel's span (its copy_node runs included, as in cycles_incl_copy), or of the whole-run table when no window does (sol_source says which). BOUND = 60 and LOW = 20 are named constants: compute or DRAM at BOUND is bound, DMA at BOUND under LOW DRAM is DMA-latency-bound, anything else latency/dependency-bound. The binary writer is the codec in pytorchsim/simulator/perfetto_trace.py (previous commit). The binary form can only nest slices, so check_trace refuses overlapping non-nested slices of a thread. cname colors are not carried. Fields used are listed in the codec's docstring and the schema is Perfetto's trace protos. With the kernel's tog_tile_timeline.pftrace (TORCHSIM_GEM5_TRACE=1, or --tile-timeline KERNEL=PATH) it also writes tiles/.pftrace: the timeline with the kernel's name added to its metadata, one process per cycle-table row; a timeline of another schema is refused and kernels without one are skipped. Checked against Perfetto's trace processor in a throwaway container: for the 4-run demo trace, slices per (thread, name), global instants, counter tracks and samples (795) equal the encoded event model, ts and dur within 1 ns and the kernel slice's scalar args equal; the tile trace likewise. Needs pip and network, so it is not a test. The tests cover the tile trace, speed of light, args and metadata without Slurm, gem5 or a browser. Depends on the preceding commit for the codec and the tile timeline file; scripts/trace_timeline.py and scripts/util_viewer.py are not modified. --- .github/workflows/pytorchsim_test.yml | 3 +- scripts/dump_profile.py | 66 ++ scripts/profile_sol.py | 143 ++++ scripts/profile_trace.py | 625 ++++++++++++++++++ .../data/profile/tog_tile_timeline.pftrace | Bin 0 -> 790 bytes .../data/profile/togsim_two_kernels.log | 69 ++ tests/system/test_profile_dump.py | 396 +++++++++++ 7 files changed, 1301 insertions(+), 1 deletion(-) create mode 100644 scripts/dump_profile.py create mode 100644 scripts/profile_sol.py create mode 100644 scripts/profile_trace.py create mode 100644 tests/system/data/profile/tog_tile_timeline.pftrace create mode 100644 tests/system/data/profile/togsim_two_kernels.log create mode 100644 tests/system/test_profile_dump.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index cf428e5b..32ad5b33 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -19,7 +19,7 @@ on: # test_reduction_tiling and test_select, and test_autotune_tables, test_breakdown_viewer, # test_device_interface, test_launch_dir, test_module_form, test_npuwattch_json, test_one_layer_kv_write, # test_one_layer_mask, test_one_layer_softcap_mask, test_patch_scope, test_route_allowlist, test_togsim_exit, -# test_togsim_result, test_gem5_trace_split, test_perfetto_trace and test_verify_golden, which emit no kernel and so are no route coverage. +# test_togsim_result, test_gem5_trace_split, test_perfetto_trace, test_profile_dump and test_verify_golden, 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. @@ -104,6 +104,7 @@ jobs: - tests/system/test_one_layer_softcap_mask.py - tests/system/test_patch_scope.py - tests/system/test_perfetto_trace.py + - tests/system/test_profile_dump.py - tests/system/test_reduction_tiling.py - tests/system/test_route_allowlist.py - tests/system/test_select.py diff --git a/scripts/dump_profile.py b/scripts/dump_profile.py new file mode 100644 index 00000000..318731c9 --- /dev/null +++ b/scripts/dump_profile.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Write /trace.pftrace (Perfetto binary) and /tiles/.pftrace from TOGSim logs; open them in +ui.perfetto.dev. Inputs and flags: --help. Instruction slices need --log_level trace logs.""" +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pytorchsim.simulator import perfetto_trace # noqa: E402 +import profile_trace # noqa: E402 + + +TRACE_FILE = "trace.pftrace" + + +def write_profile(runs, out, origins=None, dram_channels=False, tile_files=None): + """trace.pftrace and tiles/.pftrace under `out` for parsed `runs`; returns (trace event dict, + kernels per run, live runs, tile paths relative to `out`).""" + live, _ = profile_trace.split_empty(runs) + docs = profile_trace.collect_tile_docs(live, tile_files) + tiles = {name: os.path.join("tiles", name + ".pftrace").replace(os.sep, "/") for name in docs} + trace, kernel_runs = profile_trace.build_trace(runs, origins, dram_channels, out, tiles) + profile_trace.check_trace(trace) + os.makedirs(os.path.join(out, "tiles") if docs else out, exist_ok=True) + perfetto_trace.write_trace(os.path.join(out, TRACE_FILE), trace) + for name, doc in docs.items(): + tile = profile_trace.build_tile_trace(doc, name) + profile_trace.check_trace(tile) + perfetto_trace.write_trace(os.path.join(out, tiles[name]), tile) + return trace, kernel_runs, live, tiles + + +def main(argv=None): + """Parse the given logs and write the dump.""" + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("paths", nargs="*", default=["togsim_results"], help="log files, globs or directories") + ap.add_argument("-o", "--out", default="profile", help="output directory") + ap.add_argument("--timing", nargs="*", default=None, metavar="ROOT", + help="roots to scan for the compiler's timing.json") + ap.add_argument("--torch-trace", nargs="*", default=None, metavar="DIR", + help="TORCH_TRACE log dirs or files; adds each kernel's model lines and ATen ops") + ap.add_argument("--inductor-debug", nargs="*", default=None, metavar="DIR", + help="TORCH_COMPILE_DEBUG dirs; the origin when TORCH_TRACE has none") + ap.add_argument("--map-path", action="append", default=[], metavar="CONTAINER=HOST", + help="read a logged path that does not exist here (a container's) from this prefix") + ap.add_argument("--tile-timeline", action="append", default=[], metavar="KERNEL=PATH", + help="use PATH as KERNEL's tog_tile_timeline.pftrace instead of the one in its dump dir") + ap.add_argument("--dram-channels", action="store_true", help="also one DRAM counter per channel") + args = ap.parse_args(argv) + path_map = [tuple(a.split("=", 1)) for a in args.map_path] + runs = profile_trace.collect_runs(args.paths, path_map) + if not runs: + print("no TOGSim logs found", file=sys.stderr) + return 1 + origins = profile_trace.read_inductor_origins(args.inductor_debug or []) + origins.update(profile_trace.map_torch_origins(profile_trace.read_torch_trace(args.torch_trace or []))) + tile_files = dict(a.split("=", 1) for a in args.tile_timeline) + trace, _, live, tiles = write_profile(runs, args.out, origins, args.dram_channels, tile_files) + print(f"{len(live)} run(s), {len(runs) - len(live)} empty, {len(trace['traceEvents'])} events, " + f"{len(tiles)} tile file(s) -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/profile_sol.py b/scripts/profile_sol.py new file mode 100644 index 00000000..09e22744 --- /dev/null +++ b/scripts/profile_sol.py @@ -0,0 +1,143 @@ +"""Utilization-based speed of light of a kernel's cycle span: each unit's, the DMA's and the DRAM's busy share +and a verdict. Not a FLOP roofline (no FLOP counts); numbers are cycle-weighted over the Core stat windows +that overlap the span, or the whole-run table when no window does.""" + +BOUND = 60.0 +LOW = 20.0 +VERDICT_COMPUTE = "compute-bound" +VERDICT_MEMORY = "memory-bound (DRAM)" +VERDICT_DMA = "DMA-latency-bound" +VERDICT_LATENCY = "latency/dependency-bound" +VERDICT_UNKNOWN = "unknown" +VERDICT_CLASSES = {VERDICT_MEMORY: "memory", VERDICT_DMA: "dma", VERDICT_LATENCY: "latency", + VERDICT_UNKNOWN: "unknown"} + + +def get_note(): + """One sentence stating how the verdict is decided, with the thresholds.""" + return (f"Utilization-based, not a FLOP roofline: compute-bound when a unit is at least {BOUND:.0f}% " + f"busy, " + f"memory-bound when DRAM bandwidth is at least {BOUND:.0f}% of peak, DMA-latency-bound when the " + f"DMA is at least {BOUND:.0f}% busy while DRAM is under {LOW:.0f}%, otherwise " + f"latency/dependency-bound.") + + +def get_verdict_class(verdict): + """The CSS class suffix of a verdict string.""" + return "compute" if verdict.startswith(VERDICT_COMPUTE) else VERDICT_CLASSES.get(verdict, "unknown") + + +def get_verdict(compute_pct, compute_unit, dram_pct, dma_pct): + """Verdict string from the compute peak, DRAM % of peak and DMA busy %; the larger of compute and DRAM + wins when both reach BOUND. None inputs count as 0; all None is unknown.""" + if compute_pct is None and dram_pct is None and dma_pct is None: + return VERDICT_UNKNOWN + comp, dram, dma = compute_pct or 0.0, dram_pct or 0.0, dma_pct or 0.0 + if comp >= BOUND and comp >= dram: + return f"{VERDICT_COMPUTE} ({compute_unit})" + if dram >= BOUND: + return VERDICT_MEMORY + if dma >= BOUND and dram < LOW: + return VERDICT_DMA + return VERDICT_LATENCY + + +def _overlap(a0, a1, b0, b1): + return max(0.0, min(a1, b1) - max(a0, b0)) + + +def _mean(values): + return sum(values) / len(values) if values else None + + +def _add(acc, key, weight, value): + cell = acc.setdefault(key, [0.0, 0.0]) + cell[0] += weight + cell[1] += weight * value + + +def _finish(acc): + return {k: v[1] / v[0] for k, v in acc.items() if v[0] > 0} + + +def _get_window_stats(run, start, end): + """(unit -> %, DMA busy %, GB/s) averaged over the stat windows overlapping [start, end); a missing + kind is None or empty.""" + cfg, units, dma, dram = run["config"], {}, {}, {} + interval = cfg.get("core_stats_print_period_cycles", 0) + for i, win in enumerate(run["wins"] if interval else []): + w = _overlap(i * interval, min((i + 1) * interval, run["cycles"]), start, end) + if not w: + continue + for name, per_core in win.items(): + _add(units, name, w, _mean(list(per_core.values()))) + busy = [a / (a + b) * 100.0 for a, b in run["dma_wins"][i].values() if a + b] \ + if i < len(run["dma_wins"]) else [] + if busy: + _add(dma, "dma", w, _mean(busy)) + wl = run["dram_window_cycles"] + for j, win in enumerate(run["dram_win"]): + w = _overlap(j * wl, min((j + 1) * wl, run["cycles"]), start, end) + if w: + _add(dram, "dram", w, win["gbps"]) + return _finish(units), _finish(dma).get("dma"), _finish(dram).get("dram") + + +def _get_total_stats(run): + """(unit -> %, DMA busy %, GB/s) of the whole-run table printed at the end of the log.""" + tot = run["total"] + units = {n: _mean(list(c.values())) for n, c in tot["units"].items()} + busy = [a / (a + b) * 100.0 for a, b in tot["dma"].values() if a + b] + return units, _mean(busy), tot["dram_gbps"] + + +def get_sol(run, start, end, labels): + """Speed of light of cycles [start, end) of a parsed run: per-unit util under display names, the compute + peak and its unit, DRAM GB/s and % of peak, DMA busy %, source ('windows' or 'run-total') and verdict.""" + units, dma, gbps = _get_window_stats(run, start, end) + source = "windows" + if not units and run["total"]["units"]: + units, source = _get_total_stats(run)[0], "run-total" + if dma is None: + dma = _get_total_stats(run)[1] + if gbps is None: + gbps = run["total"]["dram_gbps"] + util = {labels[n]: v for n, v in units.items()} + peak = max(util.items(), key=lambda kv: kv[1]) if util else (None, None) + peak_bw = run["config"].get("peak_gbps") + dram_pct = gbps / peak_bw * 100.0 if gbps is not None and peak_bw else None + return {"span": max(end - start, 0), "source": source if util else None, "util": util, + "compute_unit": peak[0], "compute_pct": peak[1], "dram_gbps": gbps, "dram_pct": dram_pct, + "dma_pct": dma, "verdict": get_verdict(peak[1], peak[0], dram_pct, dma)} + + +def merge_sols(weighted): + """One sol from [(weight, sol)] (weights are cycle spans): each number is the weighted mean over those + that have it, and the verdict is decided again from the means.""" + acc, util = {}, {} + for w, s in weighted: + if not w: + continue + for key in ("dram_gbps", "dram_pct", "dma_pct"): + if s[key] is not None: + _add(acc, key, w, s[key]) + for unit, v in s["util"].items(): + _add(util, unit, w, v) + mean, util = _finish(acc), _finish(util) + peak = max(util.items(), key=lambda kv: kv[1]) if util else (None, None) + return {"span": sum(w for w, _ in weighted), "source": None, "util": util, "compute_unit": peak[0], + "compute_pct": peak[1], "dram_gbps": mean.get("dram_gbps"), "dram_pct": mean.get("dram_pct"), + "dma_pct": mean.get("dma_pct"), + "verdict": get_verdict(peak[1], peak[0], mean.get("dram_pct"), mean.get("dma_pct"))} + + +def get_trace_args(sol): + """The slice args of a sol: sol_compute_pct, sol_compute_unit, sol_dram_pct, sol_dram_gbps, dma_busy_pct, + verdict, sol_source, sol_span_cycles and util_; numbers rounded to two places, None left out.""" + out = {"sol_span_cycles": sol["span"], "sol_source": sol["source"], "verdict": sol["verdict"], + "sol_compute_unit": sol["compute_unit"]} + for key, name in (("compute_pct", "sol_compute_pct"), ("dram_pct", "sol_dram_pct"), + ("dram_gbps", "sol_dram_gbps"), ("dma_pct", "dma_busy_pct")): + out[name] = None if sol[key] is None else round(sol[key], 2) + out.update({f"util_{u}": round(v, 2) for u, v in sol["util"].items()}) + return {k: v for k, v in out.items() if v is not None} diff --git a/scripts/profile_trace.py b/scripts/profile_trace.py new file mode 100644 index 00000000..5a28e6a6 --- /dev/null +++ b/scripts/profile_trace.py @@ -0,0 +1,625 @@ +"""TOGSim logs to a Chrome/Perfetto trace on the simulated time axis, and gem5 tile timelines to one each. +Runs are laid end to end in log order; ts and dur are microseconds (cycles / core MHz) and each slice's +args carry the raw cycles. Instruction slices need a --log_level trace log (trace_timeline.py).""" +import glob +import json +import math +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pytorchsim import contract # noqa: E402 +from pytorchsim.simulator import perfetto_trace # noqa: E402 +import profile_sol # noqa: E402 +import trace_timeline # noqa: E402 + +_CMDLINE = re.compile(r"--(?:tog_so|trace_so) (\S+)") +_ENQUEUED = re.compile(r"\[Scheduler (\d+)\] Enqueued kernel_id: (\d+), tog_path: (\S+?),") +_CONFIG_LOADED = re.compile(r'Loaded configuration file "([^"]+)"') +_CONFIG_INT = re.compile(r"^(\w+): (\d+)$") +_PEAK_BW = re.compile(r"Total bandwidth ([\d.]+) GB/s, (\d+) MHz, (\d+) channels, (\d+) bytes") +_UNIT = re.compile(r"Core \[(\d+)\] : (\S+?) utilization\(%\): ([\d.]+), " + r"active_cycles: (\d+), idle_cycles: (\d+)") +_DMA = re.compile(r"Core \[(\d+)\] : DMA active_cycles: (\d+), DMA idle_cycles: (\d+)") +_DRAM_FINAL_CH = re.compile(r"\[DRAM\] channel \d+ \| ([\d.]+) GB/s avg\., [\d.]+% of utilization " + r"\| \d+ reads, \d+ writes$") +_DRAM_WCH = re.compile(r"\[DRAM\] channel (\d+) \| ([\d.]+) GB/s avg\., ([\d.]+)% of utilization " + r"\| (\d+) reads, (\d+) writes \(interval") +_DRAM_WINDOW = re.compile(r"\[DRAM\] all \d+ channels combined \| ([\d.]+) GB/s " + r"aggregate, ([\d.]+)% of utilization[^|]*\| (\d+) reads, (\d+) writes" + r"(?: \(interval (\d+) cycles\))?") +_KERNEL_DONE = re.compile(r"\[Scheduler (\d+)\] Kernel (\d+) .* finished at cycle (\d+)") +_TOTAL_EXEC = re.compile(r"Total execution cycles: (\d+)") +_STAMP = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\]") +_TILE_SCHED = re.compile(r"\[(\d+)\]\[Core (\d+)\]\[TILE_SCHEDULED") +_FINAL_MARKERS = ("=== DRAM statistics ===", "[DRAM] Per-channel average bandwidth", + "===== Instructions count =====") + +_TT_HEAD = re.compile(r"^\S+ \S+ \d+ \S+\] (\{.*\})\s*$") +_TT_KERNEL = re.compile(r"kernel_name='(\w+)'") +_TT_CALL = re.compile(r"# Topologically Sorted Source Nodes: \[(.*?)\], Original ATen: \[(.*?)\]") +_TT_CALLEE = re.compile(r"^\s*(\w+)(?:\.run)?\(") +_TT_FILE = re.compile(r"^\s*# File: (.*)$") +_TT_NODE = re.compile(r"^\s*(\w+)(?:: [^=]*)? = ") +_TT_GRAPHS = (("dynamo_output_graph", "Dynamo FX graph"), + ("inductor_post_grad_graph", "Inductor post-grad graph"), + ("inductor_output_code", "Inductor output code")) + +PID_DRAM = 1000 +TID_KERNELS, TID_COPY, TID_DMA_READ, TID_DMA_WRITE, TID_TILES, TID_COMPUTE = 1, 2, 3, 4, 5, 10 + + +def _read_text(path): + """The whole file decoded as UTF-8, undecodable bytes replaced.""" + with open(path, encoding="utf-8", errors="replace") as fh: + return fh.read() + + +def get_host_path(path, path_map): + """`path` as this host sees it: a path that does not exist is mapped through the (from, to) prefixes.""" + if os.path.exists(path): + return path + for src, dst in path_map: + if path.startswith(src): + return dst + path[len(src):] + return path + + +def parse_log(path, path_map=()): + """One TOGSim log as a run dict, or None when it has no final stats. A run is one simulation from + cycle 0 and may schedule several kernels back to back.""" + text = _read_text(path) + if "Total execution cycles" not in text: + return None + cut = min((text.index(m) for m in _FINAL_MARKERS if m in text), default=len(text)) + head, tail = text[:cut], text[cut:] + stamp = _STAMP.match(text) + loaded = _CONFIG_LOADED.search(head) + run = {"log": os.path.basename(path), "stamp": stamp.group(1) if stamp else "", "config": {}, + "machine": os.path.basename(loaded.group(1)) if loaded else "", "wins": [], + "dram_win": [], "dma_wins": [], "kernels": [], "tiles": [], "events": None} + for line in head.splitlines(): + cm = _CONFIG_INT.match(line.strip()) + if cm and cm.group(1) in ("core_freq_mhz", "core_stats_print_period_cycles", "num_cores", + "num_systolic_array_per_core"): + run["config"].setdefault(cm.group(1), int(cm.group(2))) + bw = _PEAK_BW.search(head) + if bw: + run["config"]["dram_mhz"] = int(bw.group(2)) + run["config"]["peak_gbps"] = float(bw.group(1)) + cur, chans, enq, done = None, [], {}, {} + for line in head.splitlines(): + if "========= Core stat =========" in line: + cur = {} + run["wins"].append(cur) + run["dma_wins"].append({}) + elif "[DRAM]" in line: + m = _DRAM_WCH.search(line) + if m: + chans.append(float(m.group(2))) + continue + m = _DRAM_WINDOW.search(line) + if m: + run["dram_win"].append({"gbps": float(m.group(1)), "util": float(m.group(2)), + "reqs": int(m.group(3)) + int(m.group(4)), + "span": int(m.group(5) or 0), "ch": chans}) + chans = [] + elif "Scheduler" in line: + m = _ENQUEUED.search(line) + if m: + enq[int(m.group(2))] = m.group(3) + m = _KERNEL_DONE.search(line) + if m: + done[int(m.group(2))] = int(m.group(3)) + elif "[TILE_SCHEDULED" in line: + m = _TILE_SCHED.search(line) + if m: + run["tiles"].append((int(m.group(2)), int(m.group(1)))) + elif cur is not None: + m = _UNIT.search(line) + if m: + cur.setdefault(m.group(2), {})[int(m.group(1))] = float(m.group(3)) + continue + m = _DMA.search(line) + if m: + run["dma_wins"][-1][int(m.group(1))] = (int(m.group(2)), int(m.group(3))) + for kid in sorted(enq): + run["kernels"].append({"id": kid, "tog": get_host_path(enq[kid], path_map), "end": done.get(kid)}) + if not run["kernels"]: + m = _CMDLINE.search(head) + if m: + run["kernels"].append({"id": 0, "tog": get_host_path(m.group(1), path_map), "end": None}) + total = _TOTAL_EXEC.search(tail) + run["cycles"] = int(total.group(1)) if total else 0 + run["cores"] = max([c for w in run["wins"] for u in w.values() for c in u] or [0]) + 1 + run["total"] = _parse_final_stats(tail) + run["dram_window_cycles"] = get_dram_window_cycles(run) + if "[INST_ID=" in text: + num_sa = run["config"].get("num_systolic_array_per_core", 1) + insts = trace_timeline.parse(text.splitlines()) + run["events"] = trace_timeline.to_chrome(insts, num_sa)["traceEvents"] + return run + + +def _parse_final_stats(tail): + """The whole-run Core stat table and DRAM channel averages printed after the last window: units, DMA + (active, idle) per core and the summed DRAM GB/s (None without them).""" + units, dma, gbps = {}, {}, [] + lines = tail.splitlines() + start = max((i for i, ln in enumerate(lines) if "========= Core stat =========" in ln), default=None) + for ln in lines[start:] if start is not None else []: + m = _UNIT.search(ln) + if m: + units.setdefault(m.group(2), {})[int(m.group(1))] = float(m.group(3)) + continue + m = _DMA.search(ln) + if m: + dma[int(m.group(1))] = (int(m.group(2)), int(m.group(3))) + for ln in lines: + m = _DRAM_FINAL_CH.search(ln) + if m: + gbps.append(float(m.group(1))) + return {"units": units, "dma": dma, "dram_gbps": sum(gbps) if gbps else None} + + +def collect_runs(paths, path_map=()): + """Parsed runs of every log in `paths` (files, globs or directories), in timestamp order; a log that + cannot be parsed is reported and skipped.""" + files = [] + for p in paths: + files += sorted(glob.glob(os.path.join(p, "*.log"))) if os.path.isdir(p) else sorted(glob.glob(p)) + runs = [] + for f in sorted(set(files)): + try: + run = parse_log(f, path_map) + except (OSError, ValueError) as exc: + print(f"skip {f}: {exc}", file=sys.stderr) + continue + if run: + runs.append(run) + return sorted(runs, key=lambda r: (r["stamp"], r["log"])) + + +def split_empty(runs): + """(runs that scheduled a kernel and ran, the rest): a run with no kernel or one cycle is empty.""" + live = [r for r in runs if r["kernels"] and r["cycles"] > 1] + return live, [r for r in runs if r not in live] + + +def get_kernel_name(tog_so): + """The `triton_` directory name of a tog.so path, else the name of its directory.""" + parts = [p for p in tog_so.split(os.sep) if p] + return next((p for p in reversed(parts) if p.startswith("triton_")), + parts[-2] if len(parts) > 1 else tog_so) + + +def get_short_name(torch_kernel, fallback): + """Inductor's kernel name without the backend prefix and the hash suffix.""" + if not torch_kernel: + return fallback + name = re.sub(r"^pytorchsim_triton_compiler_", "", torch_kernel) + return re.sub(r"_[a-z0-9]{8}$", "", name) or fallback + + +def get_sidecar(tog_so, name): + """Path of `name` in the directory holding `tog_so` (its launch-* component dropped), if it exists.""" + parts = [p for p in tog_so.split(os.sep) if not p.startswith(f"{contract.LAUNCH_DIR_PREFIX}-")] + path = os.sep + os.path.join(*parts[:-1], name) + return path if os.path.exists(path) else None + + +def get_kernel_meta(workdir): + """(Inductor kernel name from meta.json, path of its Triton source) of the nearest dir at or above + `workdir` that holds meta.json.""" + for _ in range(4): + if os.path.exists(os.path.join(workdir, "meta.json")) or os.path.dirname(workdir) == workdir: + break + workdir = os.path.dirname(workdir) + try: + name = json.loads(_read_text(os.path.join(workdir, "meta.json"))).get("kernel_name") + except (OSError, ValueError): + name = None + return name, next(iter(sorted(glob.glob(os.path.join(workdir, "*_triton.py")))), None) + + +def read_torch_trace(paths): + """Each compile in PyTorch's TORCH_TRACE logs: the text of the graphs in _TT_GRAPHS.""" + files = [] + for p in paths: + files += sorted(glob.glob(os.path.join(p, "*.log"))) if os.path.isdir(p) else sorted(glob.glob(p)) + compiles = [] + for f in files: + by_id = {} + for head, payload in _read_torch_trace_events(f): + if "frame_id" not in head: + continue + name = next((k for k, _ in _TT_GRAPHS if k in head), None) + name = name or (head.get("artifact") or {}).get("name") + if name not in dict(_TT_GRAPHS): + continue + cid = f"{head['frame_id']}/{head['frame_compile_id']}" + c = by_id.get(cid) + if c is None: + c = by_id[cid] = {"graphs": {}} + compiles.append(c) + c["graphs"][dict(_TT_GRAPHS)[name]] = payload + return compiles + + +def _read_torch_trace_events(path): + """(header dict, payload text) for each record of one TORCH_TRACE log; payload lines start with a tab.""" + head, payload = None, [] + with open(path, encoding="utf-8", errors="replace") as fh: + for line in fh: + if line.startswith("\t"): + payload.append(line[1:].rstrip("\n")) + continue + if head is not None: + yield head, "\n".join(payload) + m = _TT_HEAD.match(line) + head, payload = (json.loads(m.group(1)) if m else None), [] + if head is not None: + yield head, "\n".join(payload) + + +def get_node_lines(graph): + """Node name -> the `# File:` comment FX wrote above it (the model line it was traced from).""" + lines, cur = {}, None + for ln in graph.splitlines(): + m = _TT_FILE.match(ln) + if m: + cur = m.group(1) + continue + m = _TT_NODE.match(ln) + if m and cur: + lines.setdefault(m.group(1), cur) + elif not ln.strip(): + cur = None + return lines + + +def get_call_sites(code, lines): + """Kernel name -> {nodes, aten, lines} from the `# Topologically Sorted Source Nodes` comment above + each call of a kernel `code` defines; `lines` maps a node to its model line.""" + names = set(_TT_KERNEL.findall(code)) + out = {k: {"nodes": [], "aten": [], "lines": []} for k in names} + call = None + for ln in code.splitlines(): + m = _TT_CALL.search(ln) + if m: + call = m + continue + if ln.lstrip().startswith("#"): + continue + k = _TT_CALLEE.match(ln) + if call and k and k.group(1) in names: + rec = out[k.group(1)] + for n in filter(None, (x.strip() for x in call.group(1).split(","))): + if n not in rec["nodes"]: + rec["nodes"].append(n) + if lines.get(n) and lines[n] not in rec["lines"]: + rec["lines"].append(lines[n]) + for a in filter(None, (x.strip() for x in call.group(2).split(","))): + if a not in rec["aten"]: + rec["aten"].append(a) + call = None + return out + + +def map_torch_origins(compiles): + """Inductor kernel name -> {aten, lines, nodes, from} out of TORCH_TRACE's output code and graphs.""" + out = {} + for c in compiles: + code = c["graphs"].get("Inductor output code", "") + lines = {**get_node_lines(c["graphs"].get("Inductor post-grad graph", "")), + **get_node_lines(c["graphs"].get("Dynamo FX graph", ""))} + for k, found in get_call_sites(code, lines).items(): + out.setdefault(k, dict(found, **{"from": "TORCH_TRACE"})) + return out + + +def read_inductor_origins(paths): + """Inductor kernel name -> {aten, lines, nodes, from} from each TORCH_COMPILE_DEBUG dir under `paths`.""" + dirs = [] + for root in paths: + dirs += sorted({os.path.dirname(f) for f in + glob.glob(os.path.join(root, "**", "output_code.py"), recursive=True)}) + out = {} + for d in dirs: + code = _read_text(os.path.join(d, "output_code.py")) + lines = {} + for fname in ("fx_graph_readable.py", "fx_graph_transformed.py"): + try: + lines = {**get_node_lines(_read_text(os.path.join(d, fname))), **lines} + except OSError: + continue + for k, found in get_call_sites(code, lines).items(): + out.setdefault(k, dict(found, **{"from": "Inductor debug " + os.path.basename(d)})) + return out + + +def build_kernels(run, origins): + """The run's kernels laid end to end from cycle 0, each with its cycles, short name, workdir and origin; + copy_node kernels are counted into the next real kernel's cycles_incl_copy, and its `span` is the + cycle range from the first of them to its own end (a trailing copy extends the last real kernel).""" + out, prev, pending = [], 0, [] + for k in run["kernels"]: + end = max(k["end"] if k["end"] is not None else run["cycles"], prev) + copy = "copy_node" in k["tog"] + workdir = contract.workdir_of(k["tog"]) + name = get_kernel_name(k["tog"]) + torch_kernel, source = (None, None) if copy else get_kernel_meta(workdir) + rec = {"id": k["id"], "tog": k["tog"], "dir": name, "copy": copy, "start": prev, "end": end, + "workdir": workdir, "torch_kernel": torch_kernel, "triton_source": source, + "short": "copy" if copy else get_short_name(torch_kernel, name), + "origin": origins.get(torch_kernel) if torch_kernel else None, "copy_cycles": 0, + "copies": []} + if copy: + pending.append(rec) + else: + rec["copies"], pending = pending, [] + out.append(rec) + prev = end + real = [r for r in out if not r["copy"]] + if pending and real: + real[-1]["copies"] += pending + for rec in out: + group = [rec] + rec["copies"] + rec["copy_cycles"] = sum(c["end"] - c["start"] for c in rec["copies"]) + rec["span"] = (min(c["start"] for c in group), max(c["end"] for c in group)) + return out + + +def label_units(names): + """raw unit name -> display name: the common prefix of the prefixed names dropped, then the part before + the first '.'; names that collide keep their raw spelling.""" + pref = [n for n in names if "_" in n] + common = os.path.commonprefix(pref) if pref else "" + common = common[:common.rfind("_") + 1] if "_" in common else "" + disp = {n: (n[len(common):] if common and n.startswith(common) else n).split(".")[0] for n in names} + count = {} + for d in disp.values(): + count[d] = count.get(d, 0) + 1 + return {n: (d if count[d] == 1 else n) for n, d in disp.items()} + + +def get_dram_window_cycles(run): + """Length in core cycles of one DRAM stats window: its period in DRAM clocks scaled by the clock ratio.""" + cfg, wins = run["config"], run["dram_win"] + span = next((w["span"] for w in wins if w["span"]), 0) or 200 + core_mhz, dram_mhz = cfg.get("core_freq_mhz"), cfg.get("dram_mhz") + if core_mhz and dram_mhz: + return span * core_mhz / dram_mhz + return float(cfg.get("core_stats_print_period_cycles") or span) + + +class _Events: + """Trace events with their process and thread names, so Perfetto shows clean names in a fixed order.""" + + def __init__(self): + self.events, self.procs, self.threads = [], {}, {} + + def proc(self, pid, name, sort): + self.procs[pid] = (name, sort) + + def thread(self, pid, tid, name, sort): + self.threads[(pid, tid)] = (name, sort) + + def add(self, **kw): + self.events.append(kw) + + def finish(self): + meta = [] + for pid, (name, sort) in sorted(self.procs.items()): + meta.append({"ph": "M", "name": "process_name", "pid": pid, "tid": 0, "args": {"name": name}}) + meta.append({"ph": "M", "name": "process_sort_index", "pid": pid, "tid": 0, + "args": {"sort_index": sort}}) + for (pid, tid), (name, sort) in sorted(self.threads.items()): + meta.append({"ph": "M", "name": "thread_name", "pid": pid, "tid": tid, "args": {"name": name}}) + meta.append({"ph": "M", "name": "thread_sort_index", "pid": pid, "tid": tid, + "args": {"sort_index": sort}}) + return meta + self.events + + +def get_rel_path(path, out): + """`path` relative to the directory `out` with '/' separators, or None when it does not exist.""" + if not path or not out or not os.path.exists(path): + return None + return os.path.relpath(path, out).replace(os.sep, "/") + + +def _get_kernel_links(k, out, tiles): + """tile_trace, source and dump_dir of a kernel as paths relative to `out` (those that exist).""" + links = {"tile_trace": (tiles or {}).get(k["dir"]), "source": get_rel_path(k["triton_source"], out), + "dump_dir": get_rel_path(k["workdir"], out)} + return {key: v for key, v in links.items() if v} + + +def build_trace(runs, origins=None, dram_channels=False, out=None, tiles=None): + """The Chrome trace of `runs` (parsed, in order), kernels via build_kernels; returns (trace dict, + per-run kernel records) so the index page reads the same numbers. With the dump directory `out`, kernel + slices carry their source and dump_dir paths relative to it, and tile_trace from `tiles` (kernel -> + path).""" + live, empty = split_empty(runs) + origins = origins or {} + ev, kernel_runs, offset_us = _Events(), [], 0.0 + names = (u for r in live for u in [*(u for w in r["wins"] for u in w), *r["total"]["units"]]) + labels = label_units(list(dict.fromkeys(names))) + for r in live: + mhz = r["config"].get("core_freq_mhz") or 1000 + kernels = build_kernels(r, origins) + kernel_runs.append(kernels) + for k in kernels: + k["sol"] = profile_sol.get_sol(r, k["span"][0], k["span"][1], labels) + + def us(cycles): + return offset_us + cycles / mhz + + ev.add(ph="i", s="g", name=f"run {r['log']}", pid=0, tid=0, ts=us(0), + args={"log": r["log"], "cycles": r["cycles"], "start_cycle": 0, "core_mhz": mhz}) + for c in range(r["cores"]): + pid = c + 1 + ev.proc(pid, f"NPU core {c}", c) + ev.thread(pid, TID_KERNELS, "Kernels", 0) + ev.thread(pid, TID_COPY, "copy", 1) + for k in kernels: + dur = k["end"] - k["start"] + span = k["copy_cycles"] + args = {"triton_kernel": k["dir"], "inductor_kernel": k["torch_kernel"], + "start_cycle": k["start"], "cycle_end": k["end"], "cycles": dur, + "cycles_excl_copy": dur, "cycles_incl_copy": dur + span, "workdir": k["workdir"], + "log": r["log"], **profile_sol.get_trace_args(k["sol"]), + **_get_kernel_links(k, out, tiles)} + if k["origin"]: + args["origin"] = k["origin"] + tid = TID_COPY if k["copy"] else TID_KERNELS + ev.add(ph="X", name=k["short"], cat="kernel", pid=pid, tid=tid, ts=us(k["start"]), + dur=dur / mhz, args=args) + _add_unit_counters(ev, r, labels, us) + _add_dram_counters(ev, r, us, dram_channels) + _add_instruction_slices(ev, r, us) + offset_us += r["cycles"] / mhz + ev.proc(PID_DRAM, "DRAM", 1000) + mhz = next((r["config"]["core_freq_mhz"] for r in live if r["config"].get("core_freq_mhz")), 1000) + machine = next((r["machine"] for r in live if r["machine"]), "unknown") + trace = {"traceEvents": ev.finish(), "displayTimeUnit": "ns", + "otherData": {"time_unit": "us = cycles / core_freq_mhz", "machine": machine, "core_mhz": mhz, + "time_axis": f"simulated runs concatenated in log order; 1 us = {mhz} cycles", + "verdict_note": profile_sol.get_note(), + "runs": [r["log"] for r in live], "empty_runs": [r["log"] for r in empty]}} + return trace, kernel_runs + + +def _add_unit_counters(ev, run, labels, us): + """One counter track per core and unit: the utilization % each Core stat window printed.""" + interval = run["config"].get("core_stats_print_period_cycles", 0) + for i, win in enumerate(run["wins"]): + if not interval or i * interval >= run["cycles"]: + break + for name, per_core in win.items(): + for core, util in per_core.items(): + ev.add(ph="C", name=f"{labels[name]} util %", pid=core + 1, ts=us(i * interval), + args={"util %": util}) + + +def _add_dram_counters(ev, run, us, dram_channels): + """DRAM counters per stats window: total GB/s, utilization %, requests, and with `dram_channels` + each channel's GB/s.""" + wl = get_dram_window_cycles(run) + for j, w in enumerate(run["dram_win"]): + if j * wl >= run["cycles"]: + break + ts = us(j * wl) + ev.add(ph="C", name="DRAM GB/s", pid=PID_DRAM, ts=ts, args={"GB/s": w["gbps"]}) + ev.add(ph="C", name="DRAM utilization %", pid=PID_DRAM, ts=ts, args={"util %": w["util"]}) + ev.add(ph="C", name="DRAM requests", pid=PID_DRAM, ts=ts, args={"requests": w["reqs"]}) + if dram_channels: + for ch, gbps in enumerate(w["ch"]): + ev.add(ph="C", name=f"DRAM channel {ch} GB/s", pid=PID_DRAM, ts=ts, args={"GB/s": gbps}) + + +def _add_instruction_slices(ev, run, us): + """DMA read/write slices, compute-lane slices and tile markers from a trace-level log.""" + if not run["events"]: + return + mhz = run["config"].get("core_freq_mhz") or 1000 + lanes = {} + for e in run["events"]: + if e.get("ph") != "X": + continue + pid, lane = e["pid"] + 1, e["tid"] + if lane == "dram-rd": + tid, tname = TID_DMA_READ, "DMA read" + elif lane == "dram-wr": + tid, tname = TID_DMA_WRITE, "DMA write" + else: + tid = lanes.setdefault((pid, lane), TID_COMPUTE + len(lanes)) + tname = f"compute {lane}" + ev.thread(pid, tid, tname, tid) + args = dict(e.get("args") or {}, start_cycle=e["ts"], cycles=e["dur"]) + ev.add(ph="X", name=e["name"], cat="insn", pid=pid, tid=tid, ts=us(e["ts"]), dur=e["dur"] / mhz, + args=args, **({"cname": e["cname"]} if "cname" in e else {})) + for core, cycle in run["tiles"]: + ev.thread(core + 1, TID_TILES, "tiles", 9) + ev.add(ph="i", s="t", name="tile scheduled", pid=core + 1, tid=TID_TILES, ts=us(cycle), + args={"start_cycle": cycle, "cycles": 0}) + + +def check_trace(trace): + """Raise ValueError unless every X has ts >= 0 and dur >= 0, every counter has numeric args and no + number is NaN or infinite.""" + for e in trace["traceEvents"]: + for key in ("ts", "dur"): + if key in e and (not isinstance(e[key], (int, float)) or not math.isfinite(e[key]) or e[key] < 0): + raise ValueError(f"bad {key} in {e}") + if e["ph"] == "X" and ("ts" not in e or "dur" not in e): + raise ValueError(f"slice without ts/dur: {e}") + if e["ph"] == "C": + vals = e.get("args") or {} + if not vals or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in vals.values()): + raise ValueError(f"counter without numeric args: {e}") + _check_args(e.get("args"), e) + check_nesting(trace) + + +def check_nesting(trace): + """Raise ValueError when two X slices of one thread overlap without one containing the other, or a + slice's pid or tid is not an int: the binary format can only nest.""" + by_thread = {} + for e in trace["traceEvents"]: + if e["ph"] == "X": + if not isinstance(e["pid"], int) or not isinstance(e["tid"], int): + raise ValueError(f"pid and tid must be ints: {e}") + by_thread.setdefault((e["pid"], e["tid"]), []).append(e) + for key, slices in by_thread.items(): + stack = [] + for e in sorted(slices, key=lambda e: (e["ts"], -e["dur"])): + while stack and stack[-1] <= e["ts"] + 1e-9: + stack.pop() + end = e["ts"] + e["dur"] + if stack and end > stack[-1] + 1e-9: + raise ValueError(f"slice {e['name']!r} overlaps its neighbour on thread {key}") + stack.append(end) + + +def _check_args(value, event): + """Raise ValueError for a NaN or infinite number anywhere in an event's args.""" + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(f"non-finite number in {event}") + for v in value.values() if isinstance(value, dict) else value if isinstance(value, list) else (): + _check_args(v, event) + + +def read_tile_timeline(tog_so, override=None): + """The event dict of the tog_tile_timeline.pftrace beside `tog_so` (or the file `override` names), or + None; a trace of another schema is refused.""" + path = override or get_sidecar(tog_so, "tog_tile_timeline.pftrace") + if not path: + return None + trace = perfetto_trace.read_trace(path) + schema = trace["otherData"].get("schema") + if schema != perfetto_trace.TILE_TIMELINE_SCHEMA: + raise ValueError(f"tile timeline {path}: unknown schema {schema!r}") + return trace + + +def collect_tile_docs(live, tile_files=None): + """Kernel dir name -> its tile timeline trace for every non-copy kernel of the runs that has one; + `tile_files` maps a kernel name to a file to use instead of the one beside its tog.so.""" + docs = {} + for r in live: + for k in r["kernels"]: + name = get_kernel_name(k["tog"]) + if name in docs or "copy_node" in k["tog"]: + continue + doc = read_tile_timeline(k["tog"], (tile_files or {}).get(name)) + if doc: + docs[name] = doc + return docs + + +def build_tile_trace(timeline, kernel): + """`timeline` (a tile timeline's event dict) with the kernel's name in its metadata.""" + return {**timeline, "otherData": {**timeline["otherData"], "kernel": kernel}} diff --git a/tests/system/data/profile/tog_tile_timeline.pftrace b/tests/system/data/profile/tog_tile_timeline.pftrace new file mode 100644 index 0000000000000000000000000000000000000000..25c27895c6b21f0372c666edd52e7c70a6c3dc75 GIT binary patch literal 790 zcmaiyUvHZ*6vbm>!13C&a-}xo$wHdcuG&gS7fpLg_fPC$5)bQy_7XY73uwed;I`|> z-9E`KB#qKa(Re`ix%YRjIhd6(n&ymB#7VAe&G%u|ElsAXkJ3oKM=__j3u%^>T6zqM zPMv0IA-!i%aZNqB(Yf&`wK%EDyV`Ro;W(dxVskRhO%06>cMEBhPVY0s4r27zYK`Va zIh6%FX#@^#JyXe4iG?z92D90yDGaFPol_LPFnOT_j1a*)(XIoL%Ayc~I30{cdY=}m zKI?Z9>wzP{SzBDV=E4;>0Pb?bVc?FMc|B_TaJobEvd!Z`bU?H=;$_o$L0x|EEx!If z`ZW2PT)%EU|CGFULwlwQBde!17B$odO8N6A)FjuFpG7{;%r?Kfi+ygKu4tF{x13~Z z@>?}oC9!R^vx$8fcVhJ8DzXwBBmV?qJ~HL}RTD3~7OKd#x(I!b;_$fjh0KJm#ZpzP zVQ2UsH2k@J literal 0 HcmV?d00001 diff --git a/tests/system/data/profile/togsim_two_kernels.log b/tests/system/data/profile/togsim_two_kernels.log new file mode 100644 index 00000000..65f157cf --- /dev/null +++ b/tests/system/data/profile/togsim_two_kernels.log @@ -0,0 +1,69 @@ +[2026-11-13 19:44:24.417] [info] [TOGSim] Command line: /opt/togsim/build/bin/Simulator --config /opt/togsim/configs/tpuv6e.yml --models_list /tmp/fifo +[2026-11-13 19:44:24.418] [info] [LoadConfig] Loaded configuration file "/opt/togsim/configs/tpuv6e.yml" +[2026-11-13 19:44:24.418] [info] PyTorchSim config: +num_cores: 1 +core_freq_mhz: 1751 +core_stats_print_period_cycles: 200 +num_systolic_array_per_core: 2 +systolic_array_split: round_robin +systolic_array_unit: TPUV6E_MXU +dma_load_latency_cycles: 27 +dma_load_ready_cycles: 842 +dma_store_latency_cycles: 24 +dma_store_ready_cycles: 784 +vpu_num_lanes: 128 +vpu_spad_size_kb_per_lane: 1024 +isa: [m, a, f, d, c, v, zvfh, zvfbfmin, zvl256b, pytorchsim_tpuv6e, spad-vector-memory] +vcix: {tpu_mxu_queue_entries: 512, tpu_mxu_delay_cycles: 187, tpu_mxu_registers: 2, tpu_mxu_issue_slots: 2, tpu_mxu_word_a_cycle: 1, tpu_xlu_queue_entries: 256, tpu_xlu_latency_cycles: 137, tpu_xlu_move_latency_cycles: 123, tpu_xlu_elements_per_cycle: 16, tpu_xlu_issue_per_cycle: 2, tpu_sfu_latency_cycles: 10, tpu_sfu_queue_registers: 16} +address_map: {spad_vaddr: 0x40000000, dram_base: 0x80000000, dram_size: 107374182400} +dram_type: ramulator2 +dram_channels: 32 +dram_stats_print_period_cycles: 200 +[2026-11-13 19:44:24.420] [info] [Config/DRAM] Total bandwidth 1638.40 GB/s, 3205 MHz, 32 channels, 32 bytes per request +[2026-11-13 19:44:29.451] [info] [Scheduler 0] Enqueued kernel_id: 0, tog_path: /data/dump/triton_fixture/launch-1-1-abcd/copy_node_1/tog.so, operation: kernel, request_time_cycles: 0 +[2026-11-13 19:44:29.451] [info] [Scheduler 0] Enqueued kernel_id: 1, tog_path: /data/dump/triton_fixture/launch-1-1-abcd/tog.so, operation: kernel, request_time_cycles: 0 +[2026-11-13 19:44:29.452] [trace] [1][Core 0][TILE_SCHEDULED ] spad=4 max_dispatch=2 +[2026-11-13 19:44:29.452] [trace] [2][Core 0][INST_ISSUED ][INST_ID=0] MOVIN (addr_name=tag0 dram=0x0000000000000200 rank=1 size=[128] stride=[1] elem_bits=32 async=true indirect=false tag_id=[0x0,0x0]) +[2026-11-13 19:44:29.452] [trace] [2][Core 0][DMA_LATENCY ][INST_ID=0] MOVIN (cycles=27 addr_name=tag0 tile=0) +[2026-11-13 19:44:29.452] [trace] [30][Core 0][ASYNC_DMA_ISSUE][INST_ID=0] MOVIN (ASYNC subgraph_id=0 addr_name=tag0 tag_id=[0x0,0x0] tag_idx=[0] tag_stride=[1] tile=0) +[2026-11-13 19:44:29.452] [trace] [114][Core 0][DRAM_RESP_FIRST][INST_ID=0] MOVIN (ASYNC subgraph_id=0 addr_name=tag0 tag_id=[0x0,0x0] tag_idx=[0] tag_stride=[1] tile=0) +[2026-11-13 19:44:29.452] [trace] [971][Core 0][DRAM_RESP_DONE ][INST_ID=0] MOVIN (ASYNC subgraph_id=0 addr_name=tag0 tag_id=[0x0,0x0] tag_idx=[0] tag_stride=[1] tile=0) +[2026-11-13 19:44:29.452] [trace] [972][Core 0][INST_ISSUED ][INST_ID=2] COMP (compute_type=0 compute_cycle=12 overlapping_cycle=0 sa=-1 tile=0) +[2026-11-13 19:44:29.452] [trace] [984][Core 0][INST_FINISHED ][INST_ID=2] COMP (compute_type=0 compute_cycle=12 overlapping_cycle=0 sa=-1 tile=0) +[2026-11-13 19:44:29.452] [trace] [985][Core 0][INST_ISSUED ][INST_ID=3] MOVOUT (addr_name=tag1 dram=0x0000000000004000 rank=1 elem_bits=32 async=false indirect=false tag=0x0 stride=[1] size=[128] tag_idx=[0] tile=0) +[2026-11-13 19:44:29.452] [trace] [1010][Core 0][INST_FINISHED ][INST_ID=3] MOVOUT (addr_name=tag1 tile=0) +[2026-11-13 19:44:29.457] [info] ========= Core stat ========= +[2026-11-13 19:44:29.457] [info] Core [0] : Issue utilization(%): 0.00, active_cycles: 0, idle_cycles: 200 +[2026-11-13 19:44:29.457] [info] Core [0] : TPUV6E_MISC.instructions utilization(%): 0.00, active_cycles: 0, idle_cycles: 200 +[2026-11-13 19:44:29.457] [info] Core [0] : TPUV6E_MXU.rows utilization(%): 0.00, active_cycles: 0, idle_cycles: 200 +[2026-11-13 19:44:29.457] [info] Core [0] : TPUV6E_SFU.instructions utilization(%): 0.00, active_cycles: 0, idle_cycles: 200 +[2026-11-13 19:44:29.457] [info] Core [0] : TPUV6E_XLU.elements utilization(%): 0.00, active_cycles: 0, idle_cycles: 200 +[2026-11-13 19:44:29.457] [info] Core [0] : Vpu utilization(%): 37.50, active_cycles: 75, idle_cycles: 125 +[2026-11-13 19:44:29.457] [info] Core [0] : DMA active_cycles: 2, DMA idle_cycles: 198, DRAM BW: 8.000 GB/s (32 responses) +[2026-11-13 19:44:29.457] [info] Core [0] : Total_cycles: 200 +[2026-11-13 19:44:29.457] [trace] [DRAM] channel 0 | 0.51 GB/s avg., 1.00% of utilization | 1 reads, 0 writes (interval 200 cycles) +[2026-11-13 19:44:29.457] [info] [DRAM] all 32 channels combined | 16.41 GB/s aggregate, 1.00% of utilization (avg. per channel) | 32 reads, 0 writes (interval 200 cycles) +[2026-11-13 19:44:29.479] [info] [Scheduler 0] Kernel 0 has completed - TOG path: x finished at cycle 400 +[2026-11-13 19:44:29.479] [info] [Scheduler 0] Kernel 1 has completed - TOG path: x finished at cycle 1049 +[2026-11-13 19:44:29.499] [info] === DRAM statistics === +[2026-11-13 19:44:29.500] [info] [DRAM] Per-channel average bandwidth +[2026-11-13 19:44:29.500] [info] [DRAM] channel 0 | 0.11 GB/s avg., 0.22% of utilization | 1 reads, 1 writes +[2026-11-13 19:44:29.500] [info] [DRAM] channel 1 | 0.11 GB/s avg., 0.22% of utilization | 1 reads, 1 writes +[2026-11-13 19:44:29.500] [info] ===== Instructions count ===== +[2026-11-13 19:44:29.500] [info] Core [0] : MOVIN inst_count: 2 +[2026-11-13 19:44:29.500] [info] Core [0] : MOVOUT inst_count: 2 +[2026-11-13 19:44:29.500] [info] Core [0] : COMP inst_count: 2 (GEMM: 0, Vector: 2, XLU: 0) +[2026-11-13 19:44:29.500] [info] Core [0] : MEMORY_BAR inst_count: 2 +[2026-11-13 19:44:29.500] [info] ========= Core stat ========= +[2026-11-13 19:44:29.500] [info] Core [0] : Issue utilization(%): 0.08, active_cycles: 2, idle_cycles: 1820 +[2026-11-13 19:44:29.500] [info] Core [0] : TPUV6E_MISC.instructions utilization(%): 0.00, active_cycles: 0, idle_cycles: 1822 +[2026-11-13 19:44:29.500] [info] Core [0] : TPUV6E_MXU.rows utilization(%): 0.00, active_cycles: 0, idle_cycles: 1822 +[2026-11-13 19:44:29.500] [info] Core [0] : TPUV6E_SFU.instructions utilization(%): 0.00, active_cycles: 0, idle_cycles: 1822 +[2026-11-13 19:44:29.500] [info] Core [0] : TPUV6E_XLU.elements utilization(%): 0.00, active_cycles: 0, idle_cycles: 1822 +[2026-11-13 19:44:29.500] [info] Core [0] : Vpu utilization(%): 0.11, active_cycles: 2, idle_cycles: 1820 +[2026-11-13 19:44:29.500] [info] Core [0] : DMA active_cycles: 4, DMA idle_cycles: 1818, DRAM BW: 1.000 GB/s (64 responses) +[2026-11-13 19:44:29.500] [info] Core [0] : NUMA local memory: 64 requests, remote memory: 0 requests +[2026-11-13 19:44:29.500] [info] Core [0] : Total_cycles: 1822 +[2026-11-13 19:44:29.500] [info] Core [0] : computes held at least once by the core's compute in flight: 0 +[2026-11-13 19:44:29.500] [info] Total execution cycles: 1822 +[2026-11-13 19:44:29.500] [info] Wall-clock time for simulation: 5.083092 seconds diff --git a/tests/system/test_profile_dump.py b/tests/system/test_profile_dump.py new file mode 100644 index 00000000..68a1ef1d --- /dev/null +++ b/tests/system/test_profile_dump.py @@ -0,0 +1,396 @@ +"""dump_profile turns TOGSim logs into a Perfetto trace on the simulated time axis (kernels, copy, unit and +DRAM counters, instruction slices) and one tile trace per kernel; empty runs stay off the axis.""" +import json +import os +import re +import shutil +import sys +import tempfile +from contextlib import redirect_stderr, redirect_stdout +from io import StringIO + +HERE = os.path.dirname(os.path.abspath(__file__)) +TORCHSIM_DIR = os.environ.get("TORCHSIM_DIR") or os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, TORCHSIM_DIR) +sys.path.insert(0, os.path.join(TORCHSIM_DIR, "scripts")) + +from pytorchsim.simulator import perfetto_trace # noqa: E402 +import dump_profile # noqa: E402 +import profile_sol # noqa: E402 +import profile_trace # noqa: E402 + +DATA = os.path.join(HERE, "data", "profile") +LOG = os.path.join(DATA, "togsim_two_kernels.log") +MHZ = 1751 +KERNEL = "pytorchsim_triton_compiler_fused_add_abcd1234" + + +def _workdir(root, tiles=True): + """A kernel workdir under `root` with the meta.json of KERNEL and, optionally, a tile timeline.""" + wd = os.path.join(root, "dump", "triton_fixture") + os.makedirs(os.path.join(wd, "launch-1-1-abcd", "copy_node_1"), exist_ok=True) + with open(os.path.join(wd, "meta.json"), "w") as fh: + json.dump({"kernel_name": KERNEL}, fh) + if tiles: + shutil.copy(os.path.join(DATA, "tog_tile_timeline.pftrace"), wd) + return wd + + +def _log(root, name="run.log", **kw): + """The fixture log with its container paths pointing into a fresh workdir under `root`.""" + wd = _workdir(root, **kw) + with open(LOG) as fh: + text = fh.read().replace("/data/dump/triton_fixture", wd) + path = os.path.join(root, name) + with open(path, "w") as fh: + fh.write(text) + return path, wd + + +def _trace(runs, **kw): + trace, _ = profile_trace.build_trace(runs, **kw) + return trace + + +def _by(trace, **want): + return [e for e in trace["traceEvents"] if all(e.get(k) == v for k, v in want.items())] + + +def test_kernel_and_copy_slices_carry_cycles_on_the_simulated_axis(): + """Each launch is an X slice named by its short name; its copy_node runs sit on the copy thread right + before it and are counted into cycles_incl_copy only.""" + with tempfile.TemporaryDirectory() as root: + path, wd = _log(root) + trace = _trace(profile_trace.collect_runs([path])) + kernel, = _by(trace, ph="X", tid=profile_trace.TID_KERNELS) + copy, = _by(trace, ph="X", tid=profile_trace.TID_COPY) + assert kernel["name"] == "fused_add" and copy["name"] == "copy", (kernel["name"], copy["name"]) + got = (copy["args"]["cycles"], kernel["args"]["cycles_excl_copy"], kernel["args"]["cycles_incl_copy"]) + assert got == (400, 649, 1049), got + assert kernel["args"]["workdir"] == wd and kernel["args"]["inductor_kernel"] == KERNEL + assert abs(copy["ts"] + copy["dur"] - kernel["ts"]) < 1e-9 and abs(kernel["dur"] - 649 / MHZ) < 1e-9 + + +def test_unit_counters_hold_the_logged_utilization_per_core(): + """A unit counter is named by the unit's short label and holds the % the Core stat window printed.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + trace = _trace(profile_trace.collect_runs([path])) + names = {e["name"] for e in trace["traceEvents"] if e["ph"] == "C" and e["pid"] == 1} + want = {"Issue util %", "MISC util %", "MXU util %", "SFU util %", "XLU util %", "Vpu util %"} + assert names == want, names + vpu, = _by(trace, ph="C", name="Vpu util %") + assert vpu["args"] == {"util %": 37.5} and vpu["ts"] == 0 + + +def test_dram_counters_total_by_default_channels_on_request(): + """DRAM has GB/s, utilization % and requests per window; per-channel tracks only with dram_channels.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + runs = profile_trace.collect_runs([path]) + plain, wide = _trace(runs), _trace(runs, dram_channels=True) + gbps, = _by(plain, ph="C", name="DRAM GB/s") + assert gbps["args"] == {"GB/s": 16.41} and gbps["pid"] == profile_trace.PID_DRAM + assert _by(plain, ph="C", name="DRAM requests")[0]["args"] == {"requests": 32} + assert not _by(plain, ph="C", name="DRAM channel 0 GB/s") + assert _by(wide, ph="C", name="DRAM channel 0 GB/s")[0]["args"] == {"GB/s": 0.51} + + +def test_trace_level_log_adds_dma_compute_and_tile_tracks(): + """MOVIN and MOVOUT land on DMA read/write, COMP on a compute lane, TILE_SCHEDULED is a marker.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + trace = _trace(profile_trace.collect_runs([path])) + read, = _by(trace, ph="X", tid=profile_trace.TID_DMA_READ) + write, = _by(trace, ph="X", tid=profile_trace.TID_DMA_WRITE) + assert read["args"]["cycles"] > 0 and write["name"].endswith("MVOUT)"), (read, write) + lanes = [e for e in trace["traceEvents"] if e.get("cat") == "insn" and e["tid"] >= 10] + assert [e["args"]["cycles"] for e in lanes] == [12] + assert _by(trace, ph="i", tid=profile_trace.TID_TILES)[0]["args"] == {"start_cycle": 1, "cycles": 0} + + +def test_empty_runs_stay_off_the_axis_and_runs_are_marked(): + """A log that scheduled nothing is listed as empty and adds no event; a live run gets a global marker.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + with open(path) as fh: + idle = re.sub(r"^.*Scheduler.*\n", "", fh.read(), flags=re.M) + with open(os.path.join(root, "idle.log"), "w") as fh: + fh.write(idle) + with open(path) as fh: + one_cycle = fh.read().replace("Total execution cycles: 1822", "Total execution cycles: 1") + with open(os.path.join(root, "one_cycle.log"), "w") as fh: + fh.write(one_cycle) + trace = _trace(profile_trace.collect_runs([root])) + other = trace["otherData"] + assert other["empty_runs"] == ["idle.log", "one_cycle.log"] and other["runs"] == ["run.log"] + marks = _by(trace, ph="i", s="g") + assert [m["args"]["log"] for m in marks] == ["run.log"] + + +def test_runs_are_concatenated_in_execution_order(): + """The second run starts where the first ended: ts offsets add up in microseconds.""" + with tempfile.TemporaryDirectory() as root: + first, _ = _log(root, "20261113_000000_a.log") + second, _ = _log(root, "20261113_000001_b.log") + trace = _trace(profile_trace.collect_runs([root])) + marks = _by(trace, ph="i", s="g") + assert [m["args"]["log"] for m in marks] == ["20261113_000000_a.log", "20261113_000001_b.log"] + assert abs(marks[1]["ts"] - 1822 / MHZ) < 1e-9, marks[1]["ts"] + + +def test_trace_is_perfetto_clean_and_check_rejects_bad_events(): + """Names come as metadata events; a negative duration, a NaN or a non-numeric counter is refused.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + trace = _trace(profile_trace.collect_runs([path])) + profile_trace.check_trace(trace) + meta = {(e["name"], e["pid"]): e["args"] for e in trace["traceEvents"] if e["ph"] == "M"} + assert meta[("process_name", 1)]["name"] == "NPU core 0" + assert meta[("process_name", 1000)]["name"] == "DRAM" + threads = {e["args"]["name"] for e in trace["traceEvents"] + if e["ph"] == "M" and e["name"] == "thread_name"} + assert {"Kernels", "copy", "DMA read", "DMA write", "tiles"} <= threads, threads + for bad in ({"ph": "X", "ts": 0, "dur": -1}, {"ph": "X", "ts": float("nan"), "dur": 1}, + {"ph": "C", "ts": 0, "args": {"v": "x"}}, {"ph": "C", "ts": 0, "args": {}}): + try: + profile_trace.check_trace({"traceEvents": [bad]}) + except ValueError: + continue + raise AssertionError(f"accepted {bad}") + + +def test_tile_trace_has_a_process_per_row_and_is_skipped_without_a_file(): + """tiles/.pftrace holds the sidecar's rows as processes; a kernel without one writes + nothing.""" + with tempfile.TemporaryDirectory() as root: + path, wd = _log(root) + out = os.path.join(root, "out") + runs = profile_trace.collect_runs([path]) + dump_profile.write_profile(runs, out) + tiles = perfetto_trace.read_trace(os.path.join(out, "tiles", "triton_fixture.pftrace")) + os.remove(os.path.join(wd, "tog_tile_timeline.pftrace")) + bare = os.path.join(root, "bare") + dump_profile.write_profile(runs, bare) + bare_files = sorted(os.listdir(bare)) + names = [e["args"]["name"] for e in tiles["traceEvents"] if e["name"] == "process_name"] + assert names == ["tile row 0: tile 0 call 0 (16 cycles)", "tile row 2: tile 2 call 1 (14 cycles)"], names + assert {e["pid"] for e in tiles["traceEvents"] if e["ph"] != "M"} == {1, 3} + assert bare_files == ["trace.pftrace"], bare_files + + +def test_tile_timeline_of_another_schema_is_refused(): + with tempfile.TemporaryDirectory() as root: + _, wd = _log(root) + perfetto_trace.write_trace(os.path.join(wd, "tog_tile_timeline.pftrace"), + {"traceEvents": [], "otherData": {"schema": "other/1"}}) + try: + profile_trace.read_tile_timeline(os.path.join(wd, "launch-1-1-abcd", "tog.so")) + except ValueError as e: + assert "other/1" in str(e) + return + raise AssertionError("accepted a foreign schema") + + +def test_origin_from_inductor_debug_is_utf8_and_map_path_finds_the_workdir(): + """A model line with non-ASCII text reaches the kernel's args intact; --map-path reads a container + path from the host prefix.""" + with tempfile.TemporaryDirectory() as root: + path, wd = _log(root) + dbg = os.path.join(root, "dbg") + os.makedirs(dbg) + with open(os.path.join(dbg, "output_code.py"), "w", encoding="utf-8") as fh: + fh.write(f"async_compile.triton('k', '''x''', kernel_name='{KERNEL}')\n" + f"# Topologically Sorted Source Nodes: [y], Original ATen: [aten.add]\n" + f"{KERNEL}.run(a, b)\n") + with open(os.path.join(dbg, "fx_graph_readable.py"), "w", encoding="utf-8") as fh: + fh.write("# File: /m/modèle.py:3 in forward\ny = torch.add(x, 1)\n") + with open(path) as fh: + mapped = fh.read().replace(wd, "/container/dump/triton_fixture") + with open(path, "w") as fh: + fh.write(mapped) + out = os.path.join(root, "out") + with redirect_stdout(StringIO()): + rc = dump_profile.main([path, "--inductor-debug", dbg, "--map-path", + f"/container/dump/triton_fixture={wd}", "-o", out]) + decoded = perfetto_trace.read_trace(os.path.join(out, "trace.pftrace")) + text = json.dumps(decoded, ensure_ascii=False) + assert rc == 0 + kernel, = _by(decoded, ph="X", tid=profile_trace.TID_KERNELS) + assert kernel["args"]["origin"]["lines"] == ["/m/modèle.py:3 in forward"], kernel["args"] + assert kernel["args"]["origin"]["aten"] == ["aten.add"] and "Ã" not in text + + +def _window_log(root, vpu2=77.5, gbps2=32.82, copy_end=300): + """The fixture log with a second Core stat and DRAM window (Vpu `vpu2`, `gbps2` GB/s) and the copy kernel + ending at `copy_end`.""" + path, wd = _log(root) + with open(path) as fh: + text = fh.read() + lines = text.splitlines(keepends=True) + first = next(i for i, ln in enumerate(lines) if "Core stat" in ln) + last = next(i for i, ln in enumerate(lines) if "Kernel 0 has completed" in ln) + block = "".join(lines[first:last]).replace("37.50", f"{vpu2:.2f}").replace("16.41", f"{gbps2:.2f}") + text = "".join(lines[:last]) + block + "".join(lines[last:]) + with open(path, "w") as fh: + fh.write(text.replace("finished at cycle 400", f"finished at cycle {copy_end}")) + return path + + +def _kernels(path): + """(copy record, kernel record) of the fixture log's only run.""" + trace, kernel_runs = profile_trace.build_trace(profile_trace.collect_runs([path])) + copy, kernel = kernel_runs[0] + return copy, kernel, trace + + +def test_sol_of_a_kernel_is_the_cycle_weighted_mean_of_the_windows_it_overlaps(): + """Windows 0-200 (Vpu 37.5, DMA 1%, 16.41 GB/s) and 200-400 (Vpu 77.5, 32.82 GB/s): a copy ending at 300 + overlaps them 200:100 cycles (Vpu 50.83); the kernel's incl-copy span 0-1049 overlaps 200:200 (57.5).""" + with tempfile.TemporaryDirectory() as root: + copy, kernel, _ = _kernels(_window_log(root)) + assert copy["span"] == (0, 300) and kernel["span"] == (0, 1049) + assert abs(copy["sol"]["util"]["Vpu"] - (37.5 * 200 + 77.5 * 100) / 300) < 1e-9 + assert abs(kernel["sol"]["compute_pct"] - 57.5) < 1e-9 and kernel["sol"]["compute_unit"] == "Vpu" + assert kernel["sol"]["util"]["MXU"] == 0.0 and kernel["sol"]["source"] == "windows" + assert abs(kernel["sol"]["dma_pct"] - 1.0) < 1e-9 + window = 200 * 1751 / 3205 + want = (16.41 * window + 32.82 * window) / (2 * window) + assert abs(kernel["sol"]["dram_gbps"] - want) < 1e-9 + assert abs(kernel["sol"]["dram_pct"] - want / 1638.4 * 100) < 1e-9 + assert kernel["sol"]["verdict"] == "latency/dependency-bound" + + +def test_sol_falls_back_to_the_whole_run_table_when_no_window_overlaps(): + """Without any window the Core table printed at the end and the per-channel DRAM averages answer: Vpu + 0.11 %, DMA 4/1822 cycles, 0.22 GB/s.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + with open(path) as fh: + lines = fh.read().splitlines(keepends=True) + first = next(i for i, ln in enumerate(lines) if "Core stat" in ln) + last = next(i for i, ln in enumerate(lines) if "Kernel 0 has completed" in ln) + with open(path, "w") as fh: + fh.write("".join(lines[:first] + lines[last:])) + _, kernel, _ = _kernels(path) + sol = kernel["sol"] + assert sol["source"] == "run-total" and sol["compute_unit"] == "Vpu" + assert abs(sol["compute_pct"] - 0.11) < 1e-9 + assert abs(sol["dma_pct"] - 4 / 1822 * 100) < 1e-9 and abs(sol["dram_gbps"] - 0.22) < 1e-9 + + +def test_verdict_follows_the_thresholds_and_the_logged_numbers(): + """BOUND and LOW decide: a unit at 85 % is compute-bound (named), 1200 GB/s of 1638.4 is memory-bound, a + DMA 75 % busy under 1 % DRAM is DMA-latency-bound; the fixture's low numbers are latency/dependency.""" + assert (profile_sol.BOUND, profile_sol.LOW) == (60.0, 20.0) + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + with open(path) as fh: + text = fh.read() + got = {} + for name, old, new in (("compute", "Vpu utilization(%): 37.50", "Vpu utilization(%): 85.00"), + ("memory", "16.41 GB/s aggregate", "1200.00 GB/s aggregate"), + ("dma", "DMA active_cycles: 2, DMA idle_cycles: 198", + "DMA active_cycles: 150, DMA idle_cycles: 50")): + with open(path, "w") as fh: + fh.write(text.replace(old, new)) + got[name] = _kernels(path)[1]["sol"]["verdict"] + assert got == {"compute": "compute-bound (Vpu)", "memory": "memory-bound (DRAM)", + "dma": "DMA-latency-bound"}, got + assert profile_sol.get_verdict(70, "MXU", 65, 10) == "compute-bound (MXU)" + assert profile_sol.get_verdict(50, "MXU", 65, 10) == "memory-bound (DRAM)" + assert profile_sol.get_verdict(10, "MXU", 30, 90) == "latency/dependency-bound" + assert profile_sol.get_verdict(None, None, None, None) == "unknown" + + +def test_kernel_slices_carry_sol_args_and_where_to_go_next(): + """The kernel slice has the speed-of-light numbers and relative tile_trace, source and dump_dir paths; + start_cycle and cycles sit on kernel, copy, DMA, compute and tile events.""" + with tempfile.TemporaryDirectory() as root: + path, wd = _log(root) + with open(os.path.join(wd, f"{KERNEL}_triton.py"), "w") as fh: + fh.write("@triton.jit\n") + out = os.path.join(root, "profile") + trace, _, _, _ = dump_profile.write_profile(profile_trace.collect_runs([path]), out) + tiles = perfetto_trace.read_trace(os.path.join(out, "tiles", "triton_fixture.pftrace")) + kernel, = _by(trace, ph="X", tid=profile_trace.TID_KERNELS) + args = kernel["args"] + assert args["sol_compute_pct"] == 37.5 and args["sol_compute_unit"] == "Vpu" and args["util_Vpu"] == 37.5 + assert args["sol_dram_pct"] == 1.0 and args["dma_busy_pct"] == 1.0 and args["util_MXU"] == 0.0 + assert args["verdict"] == "latency/dependency-bound" and args["sol_span_cycles"] == 1049 + assert args["tile_trace"] == "tiles/triton_fixture.pftrace" + assert args["source"] == f"../dump/triton_fixture/{KERNEL}_triton.py" + assert args["dump_dir"] == "../dump/triton_fixture" + slices = [e for e in trace["traceEvents"] if e["ph"] in ("X", "i") and e["pid"] != 0] + assert slices and all({"start_cycle", "cycles"} <= set(e["args"]) for e in slices), slices + copy, = _by(trace, ph="X", tid=profile_trace.TID_COPY) + assert (kernel["args"]["start_cycle"], copy["args"]["start_cycle"]) == (400, 0) + rows = [e for e in tiles["traceEvents"] if e["ph"] == "X"] + assert sorted((round(e["ts"] * 1000), round(e["dur"] * 1000)) for e in rows) == [(13, 1), (15, 1)] + + +def test_trace_metadata_names_the_machine_and_the_time_axis(): + """otherData says which machine, the core MHz and what one microsecond is, and states the verdict rule.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + trace = _trace(profile_trace.collect_runs([path])) + other = trace["otherData"] + assert other["machine"] == "tpuv6e.yml" and other["core_mhz"] == MHZ + assert other["time_axis"] == "simulated runs concatenated in log order; 1 us = 1751 cycles" + assert "utilization-based" in other["verdict_note"].lower() and "60%" in other["verdict_note"] + + +def _canon(trace): + """Events of a trace as sorted tuples with ts and dur rounded to ns and None args dropped.""" + out = [] + for e in trace["traceEvents"]: + e = {k: v for k, v in e.items() if k != "cname"} + for key in ("ts", "dur"): + if key in e: + e[key] = round(e[key] * 1000) + out.append(json.dumps(e, sort_keys=True, default=str)) + return sorted(out) + + +def test_trace_that_cannot_nest_is_refused_before_encoding(): + """Two slices on one thread that overlap without containing each other have no binary form; the check + names them, and a thread of sequential or nested slices passes.""" + def slice_(ts, dur): + return {"ph": "X", "name": f"s{ts}", "pid": 1, "tid": 1, "ts": ts, "dur": dur, "args": {}} + profile_trace.check_trace({"traceEvents": [slice_(0, 10), slice_(2, 3), slice_(10, 5)]}) + try: + profile_trace.check_trace({"traceEvents": [slice_(0, 10), slice_(5, 10)]}) + except ValueError as exc: + assert "overlaps" in str(exc) + return + raise AssertionError("accepted overlapping slices") + + +def test_written_trace_is_the_encoded_event_model_and_names_the_axis(): + """trace.pftrace decodes to the very events build_trace made (ts to the ns) with the axis sentence in + otherData, and no trace.json is written.""" + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + out = os.path.join(root, "out") + trace, _, _, _ = dump_profile.write_profile(profile_trace.collect_runs([path]), out) + back = perfetto_trace.read_trace(os.path.join(out, "trace.pftrace")) + files = sorted(os.listdir(out)) + assert files == ["tiles", "trace.pftrace"], files + assert back["otherData"] == trace["otherData"] + assert back["otherData"]["time_axis"] == "simulated runs concatenated in log order; 1 us = 1751 cycles" + assert [json.loads(e) for e in _canon(back)] == [json.loads(e) for e in _canon(trace)] + + +def test_tile_trace_names_its_kernel_and_keeps_the_timeline(): + """build_tile_trace adds the kernel to the tile timeline's metadata and nothing else; the result is + non-overlapping per thread, so it encodes.""" + timeline = profile_trace.read_tile_timeline(None, os.path.join(DATA, "tog_tile_timeline.pftrace")) + trace = profile_trace.build_tile_trace(timeline, "k") + profile_trace.check_trace(trace) + assert trace["otherData"] == {**timeline["otherData"], "kernel": "k"} + assert trace["traceEvents"] == timeline["traceEvents"] + + +def test_cli_without_logs_fails(): + with tempfile.TemporaryDirectory() as root, redirect_stderr(StringIO()): + assert dump_profile.main([os.path.join(root, "none"), "-o", os.path.join(root, "o")]) == 1 From 3a958ef97e2ade4240c0edb40e2001e85c9c2040 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 13:07:34 +0900 Subject: [PATCH 3/4] [Tools] profile/index.html lists the dump's files, and TORCHSIM_PROFILE_DUMP=1 writes the dump at exit dump_profile.py now also writes index.html beside trace.pftrace: a summary (total cycles, kernel launches, machine), a cycle-weighted run verdict with the share of cycles per verdict, a kernel table and links to the trace, TORCH_TRACE and tlparse (--tlparse). Under the trace link one sentence names the time axis (runs laid end to end, 1 us = N cycles). Under Kernels a note states that the speed of light is utilization-based, not a FLOP roofline, with the BOUND and LOW thresholds of scripts/profile_sol.py. The kernel table has launches, cycles including copy_node runs, share, compute % with its unit, DRAM % of peak, DMA % and a verdict (a colored badge by CSS only; numbers merged over the kernel's launches by cycle span, the verdict decided again from the merged numbers). Each row's links start with tile detail (tiles/.pftrace, with its own "tile in Perfetto" button), source (the generated Triton source) and the earliest stage MLIR, then the dump directory, the other stage files and timing.json. The page's only script is the Open in Perfetto button: it fetches the named .pftrace, opens ui.perfetto.dev and posts the binary buffer (from file:// it offers a file picker instead). Plain HTML and CSS, light and dark, usable at phone width, links relative to the dump and only to files that exist, written as UTF-8. TORCHSIM_PROFILE_DUMP=1 (pytorchsim/config.py) makes every TOGSim log this process starts (TOGSimProcess and run_standalone outside autotune) be recorded, and an atexit hook writes /profile/ from them (pytorchsim/simulator/profile_dump.py); a failure there is printed to stderr and does not change the exit status. TORCH_TRACE is linked and used for origins when set. Builds on the preceding dump_profile commit. The new test_profile_dump cases run without Slurm, gem5 or a browser; the two TOGSim hook sites need a real TOGSim and are not exercised by them. --- pytorchsim/config.py | 2 + pytorchsim/simulator/profile_dump.py | 37 ++++ pytorchsim/simulator/timing/togsim.py | 4 + scripts/dump_profile.py | 43 +++-- scripts/profile_index.py | 233 ++++++++++++++++++++++++++ tests/system/test_profile_dump.py | 132 +++++++++++++++ 6 files changed, 441 insertions(+), 10 deletions(-) create mode 100644 pytorchsim/simulator/profile_dump.py create mode 100644 scripts/profile_index.py diff --git a/pytorchsim/config.py b/pytorchsim/config.py index 31669cf0..5d252b4b 100644 --- a/pytorchsim/config.py +++ b/pytorchsim/config.py @@ -20,6 +20,8 @@ raise ValueError(f"TORCHSIM_KVCACHE_LAYOUT={CONFIG_KVCACHE_LAYOUT!r}: headwise or tokenwise") #: Set to 1 to have gem5 trace the coprocessor and write tog_tile_timeline.pftrace beside the cycle table. CONFIG_GEM5_TRACE = os.environ.get("TORCHSIM_GEM5_TRACE", "0") == "1" +#: Set to 1 to write /profile/ (Perfetto trace.json, tile traces, a thin index.html) at process exit. +CONFIG_PROFILE_DUMP = os.environ.get("TORCHSIM_PROFILE_DUMP", "0") == "1" #: The compiler checkout (stages 1-5, ttir to the RISC-V ELF), a separate repository, not vendored. CONFIG_TORCHSIM_COMPILE_DIR = os.environ.get( "TORCHSIM_COMPILE_DIR", default=os.path.join(CONFIG_TORCHSIM_DIR, "pytorchsim-triton-compiler")) diff --git a/pytorchsim/simulator/profile_dump.py b/pytorchsim/simulator/profile_dump.py new file mode 100644 index 00000000..7880bfe9 --- /dev/null +++ b/pytorchsim/simulator/profile_dump.py @@ -0,0 +1,37 @@ +"""TORCHSIM_PROFILE_DUMP=1: at exit, write /profile/ (trace.pftrace, tiles/, index.html) from the +TOGSim logs this process started. scripts/dump_profile.py does the same from the command line.""" +import atexit +import os +import sys + +from pytorchsim import config + +_LOGS = [] +_INSTALLED = [False] +_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +_SCRIPTS = os.path.join(_ROOT, "scripts") + + +def record_log(log_path): + """Remember a TOGSim log of this process for the exit dump; installs the exit hook on the first one.""" + if not config.CONFIG_PROFILE_DUMP: + return + _LOGS.append(log_path) + if not _INSTALLED[0]: + _INSTALLED[0] = True + atexit.register(_write_profile) + + +def _write_profile(): + """The dump of the recorded logs; a failure is reported on stderr and never changes the exit status.""" + sys.path.insert(0, _SCRIPTS) + try: + import dump_profile + out = os.path.join(config.get_dump_path(), "profile") + trace_dir = os.environ.get("TORCH_TRACE") + result = dump_profile.dump(_LOGS, out, torch_trace=[trace_dir] if trace_dir else []) + except Exception as exc: + print(f"[profile] dump failed: {exc}", file=sys.stderr) + return + if result: + print(f"[profile] wrote {out}/index.html", file=sys.stderr) diff --git a/pytorchsim/simulator/timing/togsim.py b/pytorchsim/simulator/timing/togsim.py index eac0a7dc..00fe5566 100644 --- a/pytorchsim/simulator/timing/togsim.py +++ b/pytorchsim/simulator/timing/togsim.py @@ -13,6 +13,7 @@ from tqdm import tqdm from pytorchsim import config +from pytorchsim.simulator import profile_dump logger = config.setup_logger() @@ -78,6 +79,7 @@ def __init__(self, config_path=None, togsim_path=None) -> None: 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" + profile_dump.record_log(self.log_path) self._log_handle = None self.fifo_dir = os.path.join("/tmp", f"togsim_fifo_{os.getpid()}") @@ -227,6 +229,8 @@ def run_standalone( base_dir.mkdir(parents=True, exist_ok=True) file_name = _stamp() log_path = base_dir / f"{file_name}.log" + if not autotune_mode: + profile_dump.record_log(str(log_path)) result_path = base_dir / f"{file_name}.json" trace_file_path = base_dir / f"{file_name}.trace" diff --git a/scripts/dump_profile.py b/scripts/dump_profile.py index 318731c9..7a669a73 100644 --- a/scripts/dump_profile.py +++ b/scripts/dump_profile.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -"""Write /trace.pftrace (Perfetto binary) and /tiles/.pftrace from TOGSim logs; open them in -ui.perfetto.dev. Inputs and flags: --help. Instruction slices need --log_level trace logs.""" +"""Write /trace.pftrace (Perfetto binary), /tiles/.pftrace and a thin /index.html of +links from TOGSim logs. Inputs and flags: --help. Instruction slices need --log_level trace logs.""" import argparse import os import sys @@ -8,6 +8,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from pytorchsim.simulator import perfetto_trace # noqa: E402 +import profile_index # noqa: E402 import profile_trace # noqa: E402 @@ -31,6 +32,29 @@ def write_profile(runs, out, origins=None, dram_channels=False, tile_files=None) return trace, kernel_runs, live, tiles +def dump(paths, out, timing_roots=(), torch_trace=(), inductor_debug=(), path_map=(), tile_files=None, + dram_channels=False, tlparse=None): + """Write trace.pftrace, tiles/ and index.html under `out` for the logs in `paths`; None when no log, + else (trace dict, live runs, tile files).""" + runs = profile_trace.collect_runs(paths, path_map) + if not runs: + return None + origins = profile_trace.read_inductor_origins(inductor_debug) + origins.update(profile_trace.map_torch_origins(profile_trace.read_torch_trace(torch_trace))) + trace, kernel_runs, live, tiles = write_profile(runs, out, origins, dram_channels, tile_files) + empty = [r for r in runs if r not in live] + rows = profile_index.summarize_kernels(live, kernel_runs, tiles, profile_index.find_timing(timing_roots)) + links = [(f"TORCH_TRACE: {d}", profile_index.get_link(d, out)) for d in torch_trace] + if tlparse: + page = os.path.join(tlparse, "index.html") + target = page if os.path.exists(page) else tlparse + links.append((f"tlparse: {tlparse}", profile_index.get_link(target, out))) + links = [(label, href) for label, href in links if href] + with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as fh: + fh.write(profile_index.render_index(out, live, empty, rows, links, TRACE_FILE)) + return trace, live, tiles + + def main(argv=None): """Parse the given logs and write the dump.""" ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) @@ -46,19 +70,18 @@ def main(argv=None): help="read a logged path that does not exist here (a container's) from this prefix") ap.add_argument("--tile-timeline", action="append", default=[], metavar="KERNEL=PATH", help="use PATH as KERNEL's tog_tile_timeline.pftrace instead of the one in its dump dir") + ap.add_argument("--tlparse", default=None, metavar="DIR", help="tlparse output dir to link") ap.add_argument("--dram-channels", action="store_true", help="also one DRAM counter per channel") args = ap.parse_args(argv) path_map = [tuple(a.split("=", 1)) for a in args.map_path] - runs = profile_trace.collect_runs(args.paths, path_map) - if not runs: + tile_files = dict(a.split("=", 1) for a in args.tile_timeline) + result = dump(args.paths, args.out, args.timing or [], args.torch_trace or [], args.inductor_debug or [], + path_map, tile_files, args.dram_channels, args.tlparse) + if result is None: print("no TOGSim logs found", file=sys.stderr) return 1 - origins = profile_trace.read_inductor_origins(args.inductor_debug or []) - origins.update(profile_trace.map_torch_origins(profile_trace.read_torch_trace(args.torch_trace or []))) - tile_files = dict(a.split("=", 1) for a in args.tile_timeline) - trace, _, live, tiles = write_profile(runs, args.out, origins, args.dram_channels, tile_files) - print(f"{len(live)} run(s), {len(runs) - len(live)} empty, {len(trace['traceEvents'])} events, " - f"{len(tiles)} tile file(s) -> {args.out}") + trace, live, tiles = result + print(f"{len(live)} run(s), {len(trace['traceEvents'])} events, {len(tiles)} tile file(s) -> {args.out}") return 0 diff --git a/scripts/profile_index.py b/scripts/profile_index.py new file mode 100644 index 00000000..f00e0e88 --- /dev/null +++ b/scripts/profile_index.py @@ -0,0 +1,233 @@ +"""The thin index.html of a profile dump: a run summary and verdict, a kernel table (cycles, speed of light, +verdict, links to tile detail, source and dump files), and links to trace.pftrace (Open in Perfetto), +TORCH_TRACE and tlparse. No charts: the analysis happens in Perfetto, the MLIR files and tlparse.""" +import glob +import html +import os +import sys +from urllib.parse import quote + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import profile_sol # noqa: E402 +import profile_trace # noqa: E402 + +_STAGE_SUFFIXES = (".mlir", ".s") + +_STYLE = """ +:root { --bg: #f9f9f7; --card: #fcfcfb; --ink: #0b0b0b; --muted: #6b6a66; --line: #e1e0d9; --link: #2a78d6; } +@media (prefers-color-scheme: dark) { + :root { --bg: #0d0d0d; --card: #1a1a19; --ink: #f2f2f0; --muted: #a3a29c; + --line: #2c2c2a; --link: #6aa5ee; } +} +* { box-sizing: border-box; } +body { margin: 0; padding: 24px 16px 48px; background: var(--bg); color: var(--ink); + font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; } +main { max-width: 1100px; margin: 0 auto; } +h1 { font-size: 20px; margin: 0 0 4px; } +h2 { font-size: 13px; margin: 24px 0 8px; color: var(--muted); text-transform: uppercase; + letter-spacing: .04em; } +p { margin: 0 0 8px; } +a { color: var(--link); text-decoration: none; } +a:hover { text-decoration: underline; } +.muted { color: var(--muted); } +.scroll { overflow-x: auto; background: var(--card); border: 1px solid var(--line); border-radius: 8px; } +table { border-collapse: collapse; width: 100%; font-size: 13px; } +th, td { padding: 6px 10px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; } +th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; } +td.n, th.n { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +td.links a { margin-right: 10px; white-space: nowrap; display: inline-block; } +button { font: inherit; padding: 4px 12px; border: 1px solid var(--line); border-radius: 6px; + background: var(--card); color: var(--ink); cursor: pointer; } +button:hover { border-color: var(--link); color: var(--link); } +ul { margin: 0; padding-left: 18px; } +.badge { display: inline-block; padding: 1px 8px; border-radius: 10px; font-size: 12px; white-space: nowrap; + border: 1px solid var(--line); } +.v-compute { background: #dcebfb; color: #174a85; border-color: #a9c9ee; } +.v-memory { background: #fbe3d0; color: #8a3d0a; border-color: #f0bc98; } +.v-dma { background: #f5e0f3; color: #7a2a73; border-color: #e2b4dd; } +.v-latency { background: #e7e7e3; color: #4b4a46; } +.v-unknown { color: var(--muted); } +@media (prefers-color-scheme: dark) { + .v-compute { background: #12304f; color: #a9cdf5; border-color: #24517f; } + .v-memory { background: #4a2a12; color: #f3c9a3; border-color: #7a4a24; } + .v-dma { background: #432040; color: #eec3ea; border-color: #6e3a69; } + .v-latency { background: #2e2e2c; color: #c4c3bd; } +} +""" + +_SCRIPT = """ +const PERFETTO = 'https://ui.perfetto.dev'; +const cache = {}; +let pending = null; +const note = (t) => { document.getElementById('note').textContent = t; }; +function post(file, buffer) { + const win = window.open(PERFETTO); + if (!win) { note('The browser blocked the new tab.'); return; } + const ping = setInterval(() => win.postMessage('PING', PERFETTO), 50); + window.addEventListener('message', function onPong(e) { + if (e.source !== win || e.data !== 'PONG') return; + clearInterval(ping); + window.removeEventListener('message', onPong); + win.postMessage({perfetto: {buffer: buffer, title: file}}, PERFETTO); + }); +} +async function openInPerfetto(file) { + if (!cache[file]) { + try { cache[file] = await (await fetch(file)).arrayBuffer(); } + catch (e) { + pending = file; + document.getElementById('pick').hidden = false; + note('Cannot read ' + file + ' from here: choose it below.'); + return; + } + } + post(file, cache[file]); +} +document.querySelectorAll('.open').forEach((b) => + b.addEventListener('click', () => openInPerfetto(b.dataset.file))); +document.getElementById('pick').addEventListener('change', async (e) => { + cache[pending] = await e.target.files[0].arrayBuffer(); + note('Loaded; press the button again.'); +}); +""" + + +def get_link(path, out): + """`path` as a URL relative to the directory `out`, or None when it does not exist.""" + rel = profile_trace.get_rel_path(path, out) + return quote(rel, safe="/") if rel else None + + +def find_timing(roots): + """workdir -> its timing.json for every timing.json under the roots (dirs or files).""" + out = {} + for root in roots: + if os.path.isdir(root): + files = glob.glob(os.path.join(root, "**", "timing.json"), recursive=True) + else: + files = [root] if os.path.basename(root) == "timing.json" else [] + out.update({os.path.dirname(os.path.abspath(f)): f for f in files}) + return out + + +def get_stage_files(workdir): + """The numbered stage outputs (01-ttir.mlir ... 11-kernel.s) in `workdir`, earliest first.""" + names = sorted(n for n in os.listdir(workdir) if n[:2].isdigit() and n[2:3] == "-" + and n.endswith(_STAGE_SUFFIXES)) if os.path.isdir(workdir) else [] + return [os.path.join(workdir, n) for n in names] + + +def get_source_file(workdir): + """The generated Triton source in `workdir`, or None.""" + files = sorted(glob.glob(os.path.join(workdir, "*_triton.py"))) + return files[0] if files else None + + +def summarize_kernels(live, kernel_runs, tiles, timing): + """One row per distinct kernel workdir, biggest first: launches, cycles including copy_node runs, the + share of all run cycles, the speed of light merged over its launches and the files worth linking.""" + total = sum(r["cycles"] for r in live) or 1 + rows = {} + for kernels in kernel_runs: + for k in kernels: + if k["copy"]: + continue + row = rows.setdefault(k["workdir"], {"short": k["short"], "dir": k["dir"], + "workdir": k["workdir"], "launches": 0, "cycles": 0, + "sols": []}) + row["launches"] += 1 + row["cycles"] += k["end"] - k["start"] + k["copy_cycles"] + row["sols"].append((k["span"][1] - k["span"][0], k["sol"])) + out = sorted(rows.values(), key=lambda r: -r["cycles"]) + for row in out: + row["share"] = 100.0 * row["cycles"] / total + row["tile"] = tiles.get(row["dir"]) + own = os.path.join(row["workdir"], "timing.json") + row["timing"] = timing.get(row["workdir"]) or (own if os.path.exists(own) else None) + row["stages"] = get_stage_files(row["workdir"]) + row["source"] = get_source_file(row["workdir"]) + row["sol"] = profile_sol.merge_sols(row.pop("sols")) + return out + + +def _render_sol_cells(sol): + """The compute % (unit), DRAM %, DMA % and verdict table cells of a speed-of-light dict.""" + def pct(v): + return "-" if v is None else f"{v:.1f}%" + unit = f" {html.escape(sol['compute_unit'])}" if sol["compute_unit"] else "" + verdict = html.escape(sol["verdict"]) + badge = f'{verdict}' + return (f'{pct(sol["compute_pct"])}{unit}{pct(sol["dram_pct"])}' + f'{pct(sol["dma_pct"])}{badge}') + + +def _render_run_verdict(rows): + """One line: the cycle-weighted verdict of all kernels and the share of cycles per verdict.""" + sol = profile_sol.merge_sols([(r["cycles"], r["sol"]) for r in rows]) + by = {} + for r in rows: + by[r["sol"]["verdict"]] = by.get(r["sol"]["verdict"], 0) + r["cycles"] + total = sum(by.values()) or 1 + ranked = sorted(by.items(), key=lambda x: -x[1]) + split = ", ".join(f"{100.0 * c / total:.0f}% {html.escape(v)}" for v, c in ranked) + nums = "; ".join(x for x in ( + f"compute {sol['compute_pct']:.1f}% {sol['compute_unit']}" if sol["compute_pct"] is not None else "", + f"DRAM {sol['dram_pct']:.1f}% of peak" if sol["dram_pct"] is not None else "", + f"DMA {sol['dma_pct']:.1f}% busy" if sol["dma_pct"] is not None else "") if x) + return (f"Run verdict: {html.escape(sol['verdict'])} ({nums}; cycle-weighted over kernels). " + f"By cycles: {split}.") + + +def _render_links(row, out): + """The row's links, tile detail (with its Perfetto button), source and the earliest stage first.""" + first = [("tile detail", row["tile"] and quote(row["tile"], safe="/")), + ("source", get_link(row["source"], out))] + first += [(os.path.basename(f), get_link(f, out)) for f in row["stages"][:1]] + rest = [("dump", get_link(row["workdir"], out))] + rest += [(os.path.basename(f), get_link(f, out)) for f in row["stages"][1:]] + rest += [("timing.json", get_link(row["timing"], out))] + cells = "".join(f'{html.escape(label)}' for label, href in first + rest if href) + if row["tile"]: + cells = (f' ' + + cells) + return cells + + +def render_index(out, live, empty, rows, extra_links, trace_name="trace.pftrace"): + """The index.html text: summary line, run verdict, kernel table and links; paths are relative to `out`.""" + total = sum(r["cycles"] for r in live) + machine = next((r["machine"] for r in live if r["machine"]), "unknown") + mhz = next((r["config"]["core_freq_mhz"] for r in live if r["config"].get("core_freq_mhz")), 1000) + launches = sum(r["launches"] for r in rows) + body = ["

NPU profile

", + f'

{total:,} cycles · {launches} kernel launches ({len(rows)} distinct) ' + f"· {len(live)} runs, {len(empty)} empty · machine {html.escape(machine)}

", + f"

{_render_run_verdict(rows)}

" if rows else "", + "

Trace

", + f'

{trace_name} · ' + f' ' + '

', + '

Time axis: the simulated runs laid end to end in log order; ' + f"1 µs = {mhz} cycles (the core clock); every slice also carries its raw cycles.

"] + if extra_links: + body.append("") + body += ["

Kernels

", f'

{html.escape(profile_sol.get_note())}

', + '
' + '' + '' + ""] + for row in rows: + body.append(f'' + f'{_render_sol_cells(row["sol"])}' + f'') + body.append("
kernellaunchescycles (incl. copy)sharecompute (unit)DRAMDMAverdictfiles
{html.escape(row["short"])}
{html.escape(row["dir"])}' + f'
{row["launches"]}{row["cycles"]:,}{row["share"]:.1f}%
") + if empty: + body.append('

Empty runs (no kernel scheduled): ' + + html.escape(", ".join(r["log"] for r in empty)) + "

") + return ('\n\n\n' + '\n' + 'NPU profile\n' + f"
\n" + "\n".join(body) + + f"\n
\n") diff --git a/tests/system/test_profile_dump.py b/tests/system/test_profile_dump.py index 68a1ef1d..a0ba307c 100644 --- a/tests/system/test_profile_dump.py +++ b/tests/system/test_profile_dump.py @@ -394,3 +394,135 @@ def test_tile_trace_names_its_kernel_and_keeps_the_timeline(): def test_cli_without_logs_fails(): with tempfile.TemporaryDirectory() as root, redirect_stderr(StringIO()): assert dump_profile.main([os.path.join(root, "none"), "-o", os.path.join(root, "o")]) == 1 + + +def _dump(root, **kw): + """Run dump_profile.dump on the fixture log in `root`; returns (out dir, index text).""" + path, wd = _log(root) + with open(os.path.join(wd, "timing.json"), "w") as fh: + json.dump({"stages": []}, fh) + with open(os.path.join(wd, "01-ttir.mlir"), "w") as fh: + fh.write("module {}\n") + with open(os.path.join(wd, f"{KERNEL}_triton.py"), "w") as fh: + fh.write("@triton.jit\n") + out = os.path.join(root, "profile") + dump_profile.dump([path], out, **kw) + with open(os.path.join(out, "index.html"), encoding="utf-8") as fh: + return out, fh.read() + + +def _hrefs(text): + return re.findall(r'href="([^"]+)"', text) + + +def test_index_lists_kernels_with_relative_links_that_resolve(): + """One row per kernel with its cycles including copy and its share; every link is relative and + points at a file that exists next to the dump.""" + with tempfile.TemporaryDirectory() as root: + out, text = _dump(root) + hrefs = _hrefs(text) + missing = [h for h in hrefs if not os.path.exists(os.path.normpath(os.path.join(out, h)))] + assert not [h for h in hrefs if h.startswith(("/", "http", "file:"))], hrefs + assert not missing, missing + for name in ("trace.pftrace", "tiles/triton_fixture.pftrace", "../dump/triton_fixture/timing.json", + "../dump/triton_fixture/01-ttir.mlir", "../dump/triton_fixture"): + assert name in hrefs, (name, hrefs) + assert f"{KERNEL}_triton.py" in " ".join(hrefs) + assert "fused_add" in text and "1,049" in text and "100.0%" not in text + assert "1,822 cycles" in text and "1 kernel launches (1 distinct)" in text and "tpuv6e.yml" in text + + +def test_index_has_speed_of_light_columns_verdict_and_the_axis_sentence(): + """The kernel row shows compute % with its unit, DRAM %, DMA % and a verdict badge; the summary has a + cycle-weighted run verdict; the note states the thresholds and that it is utilization-based.""" + with tempfile.TemporaryDirectory() as root: + _, text = _dump(root) + for head in ("compute (unit)", 'DRAM', 'DMA', "verdict"): + assert head in text, head + assert '37.5% Vpu1.0%1.0%' in text + assert 'latency/dependency-bound' in text + assert "Run verdict: latency/dependency-bound" in text and "100% latency/dependency-bound" in text + assert "Utilization-based, not a FLOP roofline" in text and "at least 60%" in text and "under 20%" in text + assert "1 µs = 1751 cycles" in text and "Time axis" in text + + +def test_index_row_links_start_with_tile_detail_source_and_the_earliest_stage(): + """Per kernel the first links are tile detail, source and 01-ttir.mlir, then the dump and the rest; the + tile also has an Open in Perfetto button for its own file.""" + with tempfile.TemporaryDirectory() as root: + _, text = _dump(root) + cell = re.search(r'(.*?)', text, re.S).group(1) + labels = re.findall(r">([^<]+)", cell) + assert labels[:3] == ["tile detail", "source", "01-ttir.mlir"], labels + assert labels[3:] == ["dump", "timing.json"], labels + assert 'class="open" data-file="tiles/triton_fixture.pftrace"' in cell + assert 'id="open" class="open" data-file="trace.pftrace"' in text and "trace.json" not in text + + +def test_index_has_one_script_that_hands_the_trace_to_perfetto(): + with tempfile.TemporaryDirectory() as root: + _, text = _dump(root) + assert text.count("' in text + assert "width=device-width" in text and "prefers-color-scheme: dark" in text + + +def test_index_links_torch_trace_and_tlparse_and_is_utf8(): + """TORCH_TRACE and tlparse dirs are linked when given (tlparse by its index.html); a non-ASCII path + survives in a UTF-8 file.""" + with tempfile.TemporaryDirectory() as root: + tp = os.path.join(root, "tlparse_é") + tt = os.path.join(root, "torch_trace") + os.makedirs(tp) + os.makedirs(tt) + with open(os.path.join(tp, "index.html"), "w") as fh: + fh.write("") + _, text = _dump(root, torch_trace=[tt], tlparse=tp) + raw = open(os.path.join(root, "profile", "index.html"), "rb").read() + assert "../tlparse_%C3%A9/index.html" in _hrefs(text) and "../torch_trace" in _hrefs(text) + assert "tlparse_é" in raw.decode("utf-8") and b"\xc3\x83" not in raw + + +def test_index_omits_links_to_files_that_are_not_there(): + """A kernel whose workdir is not on this host still gets a row, without dump, stage or tile links.""" + with tempfile.TemporaryDirectory() as root: + path, wd = _log(root, tiles=False) + with open(path) as fh: + gone = fh.read().replace(wd, "/nowhere/dump/triton_fixture") + with open(path, "w") as fh: + fh.write(gone) + out = os.path.join(root, "profile") + dump_profile.dump([path], out) + with open(os.path.join(out, "index.html"), encoding="utf-8") as fh: + text = fh.read() + assert "triton_fixture" in text and _hrefs(text) == ["trace.pftrace"] + + +def test_exit_hook_writes_the_dump_only_with_the_flag(): + """TORCHSIM_PROFILE_DUMP=1 makes a process that recorded a TOGSim log write its profile/ at exit.""" + import subprocess + code = ("from pytorchsim.simulator import profile_dump; import sys; profile_dump.record_log(sys.argv[1])") + with tempfile.TemporaryDirectory() as root: + path, _ = _log(root) + found = {} + for flag in ("1", "0"): + dump_path = os.path.join(root, f"dump_{flag}") + env = dict(os.environ, TORCHSIM_PROFILE_DUMP=flag, TORCHSIM_DUMP_PATH=dump_path, + TORCHSIM_DIR=TORCHSIM_DIR) + subprocess.run([sys.executable, "-c", code, path], cwd=TORCHSIM_DIR, env=env, check=True, + capture_output=True) + found[flag] = sorted(os.listdir(os.path.join(dump_path, "profile"))) \ + if os.path.isdir(os.path.join(dump_path, "profile")) else None + assert found == {"1": ["index.html", "tiles", "trace.pftrace"], "0": None}, found + + +def test_timing_roots_map_each_workdir_to_its_timing_json(): + with tempfile.TemporaryDirectory() as root: + wd = os.path.join(root, "a", "triton_x") + os.makedirs(wd) + with open(os.path.join(wd, "timing.json"), "w") as fh: + fh.write("{}") + import profile_index + assert profile_index.find_timing([root]) == {wd: os.path.join(wd, "timing.json")} + file = os.path.join(wd, "timing.json") + assert profile_index.find_timing([file]) == {wd: file} From b4f28d90b000ab4b6c9dd48e3597ac0d7d9cfffb Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 13:07:45 +0900 Subject: [PATCH 4/4] [Tools] Remove util_viewer.py: dump_profile.py and the profile/ dump replace it scripts/dump_profile.py and the profile/ directory it writes (trace.pftrace for Perfetto, tiles/.pftrace, a thin index.html; also written at exit with TORCHSIM_PROFILE_DUMP=1) replace the self-contained util_viewer.py page. Deleted with it: tests/system/test_breakdown_viewer.py, which only exercised that script, and its entries in the CI test list. scripts/trace_timeline.py stays because dump_profile's trace exporter parses trace-level logs with it. No Python code imports util_viewer; prose mentions remain in .claude/CLAUDE.md (left as they are). --- .github/workflows/pytorchsim_test.yml | 3 +- scripts/util_viewer.py | 1258 ------------------------- tests/system/test_breakdown_viewer.py | 85 -- 3 files changed, 1 insertion(+), 1345 deletions(-) delete mode 100644 scripts/util_viewer.py delete mode 100644 tests/system/test_breakdown_viewer.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 32ad5b33..a988a10d 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -16,7 +16,7 @@ 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_autotune_tables, test_breakdown_viewer, +# test_reduction_tiling and test_select, and test_autotune_tables, # test_device_interface, test_launch_dir, test_module_form, test_npuwattch_json, test_one_layer_kv_write, # test_one_layer_mask, test_one_layer_softcap_mask, test_patch_scope, test_route_allowlist, test_togsim_exit, # test_togsim_result, test_gem5_trace_split, test_perfetto_trace, test_profile_dump and test_verify_golden, which emit no kernel and so are no route coverage. @@ -88,7 +88,6 @@ jobs: - tests/ops/view/test_view3D_2D.py - tests/system/test_attribute_sources.py - tests/system/test_autotune_tables.py - - tests/system/test_breakdown_viewer.py - tests/system/test_bundle_reuse.py - tests/system/test_bundle_where.py - tests/system/test_compiler_failure.py diff --git a/scripts/util_viewer.py b/scripts/util_viewer.py deleted file mode 100644 index 13829817..00000000 --- a/scripts/util_viewer.py +++ /dev/null @@ -1,1258 +0,0 @@ -#!/usr/bin/env python3 -"""Turn TOGSim's default info-level logs into a self-contained NPU utilization page. - -Reads `togsim_results/*.log` -- no re-run and no `--log_level trace` needed, since -the periodic `Core stat` blocks every `core_stats_print_period_cycles` already carry -the whole time series. For per-instruction Gantt detail use `trace_timeline.py`. - -Compile wall clock comes from the the compiler `timing.json` each kernel workdir holds, -joined to a run by the workdir its `--tog_so` is in (`--trace_so` in a log from before -TOGSim ABI 16), above the launch directory TOGSim is handed. A PyTorchSim -`breakdown_.json` (TORCHSIM_BREAKDOWN=1) adds Spike, gem5 and TOGSim on top. - -Usage: - python scripts/util_viewer.py togsim_results -o util.html - python scripts/util_viewer.py togsim_results --timing outputs -o util.html - python scripts/util_viewer.py togsim_results --breakdown outputs -o util.html -""" -import argparse -import fnmatch -import glob -import json -import os -import re -import sys - -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from pytorchsim import contract # noqa: E402 -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") -_DMA = re.compile(r"Core \[(\d+)\] : DMA active_cycles: (\d+), DMA idle_cycles: (\d+), " - r"DRAM BW: ([\d.]+) GB/s \((\d+) responses\)") -_VPU = re.compile(r"Core \[(\d+)\] : Vpu utilization\(%\): ([\d.]+), " - r"active_cycles: (\d+), idle_cycles: (\d+)") -_TOTCYC = re.compile(r"Core \[(\d+)\] : Total_cycles: (\d+)") -_INST = re.compile(r"Core \[(\d+)\] : (\w+) +inst_count: (\d+)" - r"(?: \(GEMM: (\d+), Vector: (\d+)(?:, XLU: (\d+))?\))?") -_DRAM_CH = re.compile(r"\[DRAM\] channel (\d+) \| ([\d.]+) GB/s avg\., ([\d.]+)% of utilization " - r"\| (\d+) reads, (\d+) writes") -_DRAM_WINDOW = re.compile(r"\[DRAM\] all \d+ channels combined \| ([\d.]+) GB/s " - r"aggregate, ([\d.]+)% of utilization") -_DRAM_TOTAL = re.compile(r"\[DRAM\] channels \d+\.\.\d+ combined \| ([\d.]+) GB/s " - r"aggregate, ([\d.]+)% of utilization") -_KERNEL_DONE = re.compile(r"\[Scheduler (\d+)\] Kernel (\d+) .* finished at cycle (\d+)") -_TOTAL_EXEC = re.compile(r"Total execution cycles: (\d+)") - -_FINAL_MARKERS = ("=== DRAM statistics ===", "[DRAM] Per-channel average bandwidth", - "===== Instructions count =====") - -_WANTED_CONFIG = ("num_cores", "core_freq_mhz", "core_stats_print_period_cycles", - "vpu_num_lanes", "vpu_vector_length_bits", - "vpu_spad_size_kb_per_lane", "dram_channels", "dram_freq_mhz", - "core_spad_size_kb") - - -def kernel_name(tog_so): - """Name a kernel by its `triton_` dir and the test dir above it.""" - parts = [p for p in tog_so.split(os.sep) if p] - kdir = next((p for p in reversed(parts) if p.startswith("triton_")), None) - if kdir is None: - kdir = parts[-2] if len(parts) > 1 else tog_so - i = parts.index(kdir) if kdir in parts else -1 - source = parts[i - 1] if i > 0 else "" - if source in ("outputs", ".triton_sweep", "scratchpad"): - source = "" - return kdir, source - - -def _blank_core(): - return {"vu": None, "dma": None, "cycles": 0, "inst": {}} - - -def _core(cores, cid): - return cores.setdefault(int(cid), _blank_core()) - - -def parse_log(path): - """Parse one TOGSim info-level log into a run dict, or None if it has no stats. The vector - unit is the unit table's Vpu row.""" - with open(path, errors="replace") as fh: - text = fh.read() - if "Total execution cycles" not in text: - return None - - cut = min((text.index(m) for m in _FINAL_MARKERS if m in text), default=len(text)) - head, tail = text[:cut], text[cut:] - run = {"log": os.path.basename(path), "config": {}, "windows": [], - "cores": {}, "dram_channels": [], "kernels": []} - - m = _CMDLINE.search(head) - run["tog_so"] = m.group(1) if m else "" - run["kernel"], run["source"] = kernel_name(run["tog_so"]) if m else ("?", "") - - for line in head.splitlines(): - cm = _CONFIG_INT.match(line.strip()) - if cm and cm.group(1) in _WANTED_CONFIG: - run["config"].setdefault(cm.group(1), int(cm.group(2))) - m = _PEAK_BW.search(head) - if m: - run["config"]["peak_dram_gbps"] = float(m.group(1)) - run["config"]["dram_req_bytes"] = int(m.group(4)) - - interval = run["config"].get("core_stats_print_period_cycles", 0) - cur = None - for line in head.splitlines(): - if "========= Core stat =========" in line: - cur = {"vu": {}, "dma": {}, "dram_gbps": None, "dram_util": None} - run["windows"].append(cur) - continue - if cur is None: - continue - m = _VPU.search(line) - if m: - cur["vu"][int(m.group(1))] = float(m.group(2)) - continue - m = _DMA.search(line) - if m: - cur["dma"][int(m.group(1))] = { - "util": 100.0 * int(m.group(2)) / interval if interval else 0.0, - "gbps": float(m.group(4)), "responses": int(m.group(5))} - continue - m = _DRAM_WINDOW.search(line) - if m: - cur["dram_gbps"], cur["dram_util"] = float(m.group(1)), float(m.group(2)) - for m in _KERNEL_DONE.finditer(head): - run["kernels"].append({"id": int(m.group(2)), "end": int(m.group(3))}) - - for m in _INST.finditer(tail): - c = _core(run["cores"], m.group(1))["inst"] - c[m.group(2)] = int(m.group(3)) - if m.group(4) is not None: - c["GEMM"], c["VECTOR"] = int(m.group(4)), int(m.group(5)) - for m in _VPU.finditer(tail): - _core(run["cores"], m.group(1))["vu"] = {"util": float(m.group(2)), "active": int(m.group(3))} - for m in _DMA.finditer(tail): - _core(run["cores"], m.group(1))["dma"] = { - "active": int(m.group(2)), "gbps": float(m.group(4)), "responses": int(m.group(5))} - for m in _TOTCYC.finditer(tail): - _core(run["cores"], m.group(1))["cycles"] = int(m.group(2)) - for m in _DRAM_CH.finditer(tail): - run["dram_channels"].append({"ch": int(m.group(1)), "gbps": float(m.group(2)), - "util": float(m.group(3)), "reads": int(m.group(4)), - "writes": int(m.group(5))}) - m = _DRAM_TOTAL.search(tail) - if m: - run["dram_gbps"], run["dram_util"] = float(m.group(1)), float(m.group(2)) - m = _TOTAL_EXEC.search(tail) - run["cycles"] = int(m.group(1)) if m else 0 - - for cid, c in run["cores"].items(): - c["dma"] = c["dma"] or {"active": 0, "gbps": 0.0, "responses": 0} - c["dma"]["util"] = 100.0 * c["dma"]["active"] / c["cycles"] if c["cycles"] else 0.0 - run["interval"] = interval - return run - - -def summarize(run): - """Fold a run's per-core totals into the numbers the page leads with.""" - cores = run["cores"] - n = max(1, len(cores)) - vu = [c["vu"]["util"] for c in cores.values() if c["vu"]] - dma = [c["dma"]["util"] for c in cores.values()] - inst = {} - for c in cores.values(): - for k, v in c["inst"].items(): - inst[k] = inst.get(k, 0) + v - freq = run["config"].get("core_freq_mhz", 0) - return {"cycles": run["cycles"], - "us": run["cycles"] / (freq * 1.0) if freq else 0.0, - "vu": sum(vu) / len(vu) if vu else 0.0, - "dma": sum(dma) / len(dma) if dma else 0.0, - "dram_gbps": run.get("dram_gbps", 0.0), "dram_util": run.get("dram_util", 0.0), - "inst": inst, "cores": n} - - -def series(run): - """Return the per-window utilization series, averaged across cores.""" - out = {"cycle": [], "vu": [], "dma": [], "dram": [], "gbps": []} - for i, w in enumerate(run["windows"]): - vu = list(w["vu"].values()) - dma = [d["util"] for d in w["dma"].values()] - out["cycle"].append((i + 1) * run["interval"]) - out["vu"].append(round(sum(vu) / len(vu), 2) if vu else 0.0) - out["dma"].append(round(sum(dma) / len(dma), 2) if dma else 0.0) - out["dram"].append(w["dram_util"] or 0.0) - out["gbps"].append(w["dram_gbps"] or 0.0) - return out - - -def read_timing(path): - """Load one the compiler timing.json, or None if it is unreadable or mid-write.""" - try: - with open(path) as fh: - rec = json.load(fh) - except (OSError, ValueError): - return None - return rec if isinstance(rec, dict) and rec.get("stages") else None - - -def find_timing(roots): - """Map each workdir holding a the compiler timing.json to its record.""" - out = {} - for root in roots: - if os.path.isdir(root): - files = glob.glob(os.path.join(root, "**", "timing.json"), recursive=True) - elif os.path.basename(root) == "timing.json": - files = [root] - else: - files = glob.glob(root) - for f in files: - rec = read_timing(f) - if rec: - out[os.path.dirname(os.path.abspath(f))] = rec - return out - - -def read_breakdown(path): - """Load one PyTorchSim breakdown.json, or None if it is unreadable.""" - try: - with open(path) as fh: - rec = json.load(fh) - except (OSError, ValueError): - return None - return rec if isinstance(rec, dict) and rec.get("components") else None - - -def find_breakdowns(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, "**", name), recursive=True) - elif fnmatch.fnmatch(os.path.basename(root), name): - files = [root] - else: - files = glob.glob(root) - for f in sorted(files): - rec = read_breakdown(f) - if rec: - out.append(dict(rec, path=os.path.abspath(f))) - return out - - -def breakdown_groups(rec): - """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] - cur = groups.setdefault(g, {"calls": 0, "seconds": 0.0, "parts": []}) - cur["calls"] += e["calls"] - cur["seconds"] += e["seconds"] - 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 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: - out.append({"name": "elsewhere", "calls": 0, "seconds": elsewhere, "parts": []}) - return out - - -def timing_from_breakdowns(breakdowns): - """Pull the torchsim-compile records a breakdown embeds, keyed by kernel label.""" - out = {} - for bd in breakdowns: - for e in bd.get(wallclock.TORCHSIM_COMPILE) or []: - if e.get("kind", "compile") != "compile": - continue - rec = e.get("timing") - if isinstance(rec, dict) and rec.get("stages"): - out.setdefault(e.get("kernel") or rec.get("label"), rec) - return out - - -def merge_timing(records): - """Sum per-kernel the compiler records into one of the same shape, in stage order.""" - stages, passes, tools, order = {}, {}, {}, [] - for rec in records: - for s in rec.get("stages", []): - if s["name"] not in stages: - order.append(s["name"]) - stages[s["name"]] = stages.get(s["name"], 0.0) + s["seconds"] - for stage, entries in (rec.get("passes") or {}).items(): - acc = passes.setdefault(stage, {}) - for e in entries: - acc[e["name"]] = acc.get(e["name"], 0.0) + e["seconds"] - for stage, entries in (rec.get("tools") or {}).items(): - acc = tools.setdefault(stage, {}) - for t, e in entries.items(): - cur = acc.setdefault(t, {"calls": 0, "seconds": 0.0}) - cur["calls"] += e["calls"] - cur["seconds"] += e["seconds"] - return {"label": None, "total": sum(stages.values()), - "stages": [{"name": n, "seconds": stages[n]} for n in order], - "passes": {s: [{"name": n, "seconds": dt} for n, dt in v.items()] - for s, v in passes.items()}, - "tools": tools, "kernels": len(records)} - - -def collect(paths): - """Expand dirs and globs into parsed runs, newest log last.""" - files = [] - for p in paths: - if os.path.isdir(p): - files += sorted(glob.glob(os.path.join(p, "*.log"))) - else: - files += sorted(glob.glob(p)) or ([p] if os.path.exists(p) else []) - runs = [] - for f in sorted(set(files)): - try: - r = parse_log(f) - except Exception as exc: - print(f"skip {f}: {exc}", file=sys.stderr) - continue - if r: - runs.append(r) - return runs - - -def build_payload(runs, timing=None, breakdowns=None): - """Shape parsed runs into the JSON the page renders from, collapsing replays.""" - timing = timing or {} - items, seen = [], {} - for r in runs: - key = (r["kernel"], r["cycles"]) - if key in seen: - prev = seen[key] - prev["repeats"] += 1 - prev["source"] = prev["source"] or r["source"] - continue - item = {"log": r["log"], "kernel": r["kernel"], "source": r["source"], "repeats": 1, - "workdir": contract.workdir_of(r["tog_so"]) if r["tog_so"] else "", - "config": r["config"], "summary": summarize(r), "series": series(r), - "dram_channels": r["dram_channels"], "interval": r["interval"], - "cores": {str(k): {"vu": v["vu"], "dma": v["dma"], - "cycles": v["cycles"], "inst": v["inst"]} - for k, v in r["cores"].items()}} - seen[key] = item - items.append(item) - items.sort(key=lambda i: -i["summary"]["cycles"]) - - by_base = {} - for wd in timing: - by_base.setdefault(os.path.basename(wd), wd) - records, index, used = [], {}, set() - for item in items: - wd = item["workdir"] - if wd not in timing: - wd = by_base.get(os.path.basename(wd), wd) - rec = timing.get(wd) - if rec is None: - item["timing"] = None - continue - if wd not in index: - index[wd] = len(records) - records.append(dict(rec, workdir=wd, kernel=item["kernel"])) - item["timing"] = index[wd] - used.add(wd) - orphans = [] - for wd, rec in sorted(timing.items()): - if wd not in used: - orphans.append(len(records)) - records.append(dict(rec, workdir=wd, kernel=rec.get("label") or os.path.basename(wd))) - merged = merge_timing(records) if records else None - - per_kernel = {} - for bd in breakdowns or []: - for label, comps in (bd.get("kernels") or {}).items(): - acc = per_kernel.setdefault(label, {}) - for comp, dt in comps.items(): - acc[comp] = acc.get(comp, 0.0) + dt - for item in items: - label = records[item["timing"]].get("label") if item["timing"] is not None else None - item["wall"] = per_kernel.get(label) if label else None - - bds = [{"path": bd.get("path", ""), "wall": bd.get("wall") or 0.0, - "measured": bd.get("measured") or 0.0, "kernels": len(bd.get("kernels") or {}), - "groups": breakdown_groups(bd)} for bd in (breakdowns or [])] - return {"runs": items, "logs": len(runs), - "timing": {"records": records, "merged": merged, "orphans": orphans}, - "breakdowns": bds} - - -_PAGE_HEAD = """TOGSim Utilization -""" - - -def render(payload): - """Emit the self-contained HTML page for a parsed payload.""" - data = json.dumps(payload, separators=(",", ":")).replace(" -

TOGSim Utilization

-

- -
-

Selected kernel

-

-
-
-
- -
-

Utilization over time

-

-
- - - - - drag to zoom · shift-drag or arrows to pan · wheel · double-click to reset -
-
-
- -
-

Kernels

-

Click a row to load it above. Sorted by cycles; click a header to re-sort.

-
- - - - - - - - - - -
KernelBound byCyclesTime (us)VectorDMADRAMGB/sCompileCOMPMOVINMOVOUT
-
-
- -
-

Compile time

-

-
-
-
-

Pipeline stages

-
-
-
-

Passes and tools

-
-
-
-
- -
-

DRAM

-

Bandwidth over time

-

-
-

Per channel

-

-
-
- -
- - - -""" - - -def join_workdir_timing(runs, timing): - """Add to `timing` the timing.json of each run's workdir, the one its tog_so is in, that no root gave.""" - for r in runs: - if not r["tog_so"]: - continue - wd = contract.workdir_of(r["tog_so"]) - if wd not in timing: - rec = read_timing(os.path.join(wd, "timing.json")) - if rec: - timing[wd] = rec - - -def main(argv=None): - """Parse the given logs and write the viewer page.""" - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("paths", nargs="*", default=["togsim_results"], - help="log files, globs, or directories (default: togsim_results)") - ap.add_argument("-o", "--out", default="util.html", help="output HTML path") - ap.add_argument("--timing", nargs="*", default=None, metavar="ROOT", - help="extra roots to scan for the compiler timing.json; the workdir each log's " - "tog_so is in is always checked") - ap.add_argument("--breakdown", nargs="*", default=None, metavar="ROOT", - help="roots to scan for PyTorchSim breakdown_.json (TORCHSIM_BREAKDOWN=1), " - "which adds Spike, gem5 and TOGSim wall clock") - args = ap.parse_args(argv) - - runs = collect(args.paths or ["togsim_results"]) - breakdowns = find_breakdowns(args.breakdown or []) - timing = find_timing(args.timing or []) - embedded = timing_from_breakdowns(breakdowns) - join_workdir_timing(runs, timing) - seen_labels = {rec.get("label") for rec in timing.values()} - for label, rec in embedded.items(): - if label not in seen_labels: - timing["label:" + label] = rec - if not runs and not timing and not breakdowns: - print("no TOGSim logs, no timing.json and no breakdown.json found", file=sys.stderr) - return 1 - with open(args.out, "w") as fh: - fh.write(render(build_payload(runs, timing, breakdowns))) - print(f"{len(runs)} run(s), {len(timing)} compile record(s), " - f"{len(breakdowns)} breakdown(s) -> {args.out}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/system/test_breakdown_viewer.py b/tests/system/test_breakdown_viewer.py deleted file mode 100644 index 0fdfbccb..00000000 --- a/tests/system/test_breakdown_viewer.py +++ /dev/null @@ -1,85 +0,0 @@ -"""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; a breakdown that -cannot be written is logged; a log's compile clock is its workdir's, above its launch directory.""" -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 import contract # noqa: E402 -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 - - -def test_a_breakdown_that_cannot_be_written_is_logged(): - with tempfile.TemporaryDirectory() as root, \ - mock.patch.dict(os.environ, {"TORCHSIM_BREAKDOWN": "1", "TORCHSIM_DUMP_PATH": root}), \ - mock.patch.object(wallclock, "REC", wallclock.Record()), \ - mock.patch.object(wallclock.logger, "warning") as warned: - wallclock.REC.add(wallclock.SPIKE, KERNEL, 0.1) - with mock.patch("builtins.open", side_effect=OSError("read-only")): - wallclock._at_exit() - assert warned.called and "could not write" in warned.call_args[0][0], warned.call_args - - -def test_a_launch_log_joins_its_workdir_timing(): - """TOGSim is handed the launch directory's tog.so: the timing.json joined is the workdir's above it.""" - with tempfile.TemporaryDirectory() as root: - workdir = os.path.join(root, KERNEL) - launch = contract.dir_for(workdir) - with open(os.path.join(workdir, "timing.json"), "w") as f: - json.dump(TIMING, f) - timing = {} - VIEWER["join_workdir_timing"]([{"tog_so": os.path.join(launch, "tog.so")}], timing) - assert list(timing) == [workdir] and timing[workdir]["label"] == KERNEL, timing - -if __name__ == "__main__": - test_viewer_finds_the_file_wallclock_writes() - test_viewer_reads_the_compile_records() - test_a_breakdown_that_cannot_be_written_is_logged() - test_a_launch_log_joins_its_workdir_timing() - print("PASS")