# SPDX-License-Identifier: Apache-2.0 """Per-RISC kernel time of one SCA level call (bin/devrun with TT_METAL_DEVICE_PROFILER=1): the device profiler's kernel zones of the reader (NCRISC), writer (BRISC) and the three compute TRISCs, max / mean over cores. TT_METAL_DEVICE_PROFILER=1 bin/devrun python -m tt_autoe2e.tests.dev_msda_riscs [--out-frac 0.6] [--hw 8] """ from __future__ import annotations import argparse import csv import glob import json import os import shutil from collections import defaultdict import numpy as np def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--hw", type=int, default=64) ap.add_argument("--out-frac", type=float, default=0.0, help="fraction of points placed fully outside the map") ap.add_argument("--tag", default="riscs") args = ap.parse_args(argv) import torch import ttnn from ..tt.msda_k import msda from ..tt.pairmap import pair_maps from ..ttaw.device import DeviceConfig, close_device rng = np.random.default_rng(0) dev = DeviceConfig(trace_region_size=32 << 20).open() res = {"hw": args.hw, "out_frac": args.out_frac} try: rows, heads, P, hw = 98304, 8, 8, args.hw segs = [29568 + 1152, 14944, 15648, 9696, 9472, 9696 + 8128] segs = [s - s % 32 for s in segs] segs[-1] += rows - sum(segs) loc = rng.uniform(-0.5, hw - 0.5, size=(1, 1, rows, heads * 64)) out = rng.uniform(size=loc.shape) < args.out_frac loc[out] = -50.0 loc = np.round(loc * 65536).astype(np.int32) att = rng.uniform(0, 1, size=(1, heads, rows, 32)).astype(np.float32) loc_t = ttnn.from_torch(torch.from_numpy(loc), dtype=ttnn.int32, layout=ttnn.TILE_LAYOUT, device=dev) att_t = ttnn.from_torch(torch.from_numpy(att), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev) ends = np.zeros((1, 1, 1, 16), np.int32) ends[0, 0, 0, :6] = np.cumsum(segs) // 32 seg_t = ttnn.from_torch(torch.from_numpy(ends), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev) proj = ttnn.from_torch(torch.randn(1, 1, 6 * hw * hw, 256), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG) pairs = pair_maps(proj, heads=8, sub=6, hw=(hw, hw)) for _ in range(3): o = msda(pairs, loc_t, att_t, points=P, nq=rows, segments=[0] * 6, seg_table=seg_t, loc_hs=64, loc_off=0, att_col0=0, debug=("timing",)) ttnn.synchronize_device(dev) ttnn.deallocate(o) ttnn.ReadDeviceProfiler(dev) finally: close_device(dev) logs = glob.glob("/opt/tt-metal/generated/profiler/.logs/profile_log_device.csv") if not logs: print("no profiler log") return 1 shutil.copy(logs[0], f"/logs/{args.tag}_profile_log_device.csv") # rows: PCIe slot, core_x, core_y, RISC processor type, timer_id, time[cycles since reset], data, run host ID, # zone name, type (ZONE_START / ZONE_END), source line, source file, meta starts, spans, data = {}, defaultdict(list), defaultdict(list) with open(logs[0]) as f: f.readline() # ARCH / chip freq line rd = csv.reader(f) hdr = [h.strip() for h in next(rd)] ix = {h: i for i, h in enumerate(hdr)} for row in rd: row = [c.strip() for c in row] zone = row[ix.get("zone name", 8)] if zone in ("res", "hdr", "loop", "bar", "out", "geo", "in", "w", "tl", "st", "fin"): data[(row[ix["RISC processor type"]], zone, row[ix.get("run host ID", 7)])].append(int(row[ix["data"]])) continue if not zone.endswith("-KERNEL"): continue key = (row[ix["core_x"]], row[ix["core_y"]], row[ix["RISC processor type"]], zone, row[ix.get("run host ID", 7)]) t = int(row[ix["time[cycles since reset]"]]) if row[ix.get("type", 9)] == "ZONE_START": starts[key] = t elif key in starts: spans[(key[2], key[4])].append(t - starts.pop(key)) runs = sorted({k[1] for k in spans}, key=lambda s: int(s) if s.isdigit() else s) last = runs[-1] if runs else None res["per_risc_cycles_last_run"] = {k[0]: {"max": int(max(v)), "mean": int(np.mean(v)), "cores": len(v)} for k, v in spans.items() if k[1] == last} res["timing_cycles_mean_last_run"] = {f"{k[0]}.{k[1]}": int(np.mean(v)) for k, v in data.items() if k[2] == last} res["data_types_seen"] = sorted({k[2] for k in data})[:3] print(json.dumps(res, indent=1)) with open(f"/logs/{args.tag}.json", "w") as f: json.dump(res, f, indent=1) return 0 if __name__ == "__main__": raise SystemExit(main())