# SPDX-License-Identifier: Apache-2.0 """Benchmark of the ttnn baseline engines: traced device time per stage (ENC, DEC, FOV) per size / bucket / T, DRAM and trace-region use, and the largest configurations that fit. Every stage runs once eagerly (compile, conv weight preparation), is captured as its own trace (persistent input), and is replayed ``--reps`` times back to back; the reported time is the wall time per replay with the host only enqueueing ``execute_trace`` (= device time + ~tens of us of dispatch). Run under the device lock:: bin/devrun -t 3600 -- python -u bundles/depthpro2/code/scripts/bench_baseline.py --sizes S,B,L,H \\ --configs 480x640x1,256x320x4,480x640x4,480x640x16 --json logs/depthpro2/baseline/bench.jsonl ``--configs`` items are ``HpxWpxT`` (padded sizes, multiples of 32). A configuration that does not fit (allocation failure) is recorded as ``fits: false`` and the run continues. """ from __future__ import annotations import argparse import gc import json import os import sys import time import traceback CODE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, CODE) sys.path.insert(0, os.path.join(CODE, "tt_depthpro2", "tests")) import torch # noqa: E402 import baseline_helpers as H # noqa: E402 from tt_depthpro2.reference import model as ref # noqa: E402 from tt_depthpro2.tt import StageShape # noqa: E402 from tt_depthpro2.tt import ttnn_dec, ttnn_enc, ttnn_fov # noqa: E402 from tt_depthpro2.tt.model import DepthPro2Device # noqa: E402 from tt_depthpro2.tt.weights import load_weights # noqa: E402 def mem_mb(device, kind: str) -> float: import ttnn bt = {"dram": ttnn.BufferType.DRAM, "trace": ttnn.BufferType.TRACE}[kind] v = ttnn.get_memory_view(device, bt) return v.num_banks * v.total_bytes_allocated_per_bank / 2 ** 20 def free_dram_mb(device) -> float: import ttnn v = ttnn.get_memory_view(device, ttnn.BufferType.DRAM) return v.num_banks * v.total_bytes_free_per_bank / 2 ** 20 def rand_input(device, rows: int, cols: int): import ttnn return ttnn.from_torch(torch.randn(1, 1, rows, cols).mul_(0.5).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) def time_stage(device, run, inp, reps: int): """eager warm-up, capture, replay ``reps`` times -> (ms per replay, eager ms, trace MB, output).""" import ttnn t0 = time.perf_counter() out = run(inp) ttnn.synchronize_device(device) eager_ms = (time.perf_counter() - t0) * 1e3 _free(out) tr0 = mem_mb(device, "trace") tid = ttnn.begin_trace_capture(device, cq_id=0) out = run(inp) ttnn.end_trace_capture(device, tid, cq_id=0) trace_mb = mem_mb(device, "trace") - tr0 ttnn.execute_trace(device, tid, cq_id=0, blocking=False) ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, tid, cq_id=0, blocking=False) ttnn.synchronize_device(device) ms = (time.perf_counter() - t0) * 1e3 / reps return ms, eager_ms, trace_mb, out, tid def _free(out): import ttnn for t in (out if isinstance(out, (list, tuple)) else [out]): try: ttnn.deallocate(t) except Exception: # noqa: BLE001 pass def bench_config(device, size, w_enc, w_dec, w_fov, hp, wp, t, reps, fov: bool, dec_only: bool = False): import ttnn shape = StageShape(t, hp, wp) rec = {"size": size, "hp": hp, "wp": wp, "T": t, "N": shape.n} tids = [] outs = [] try: dec = ttnn_dec.Engine(device, w_dec, shape) if dec_only: # random taps (DEC time does not depend on the values); ENC measured elsewhere taps = [rand_input(device, t * shape.np_, w_enc.cfg.dim) for _ in range(4)] rec["dec_only"] = True else: enc = ttnn_enc.Engine(device, w_enc, shape) patches = rand_input(device, t * shape.np_, 768) ms, eager, tmb, taps, tid = time_stage(device, enc.run, patches, reps) tids.append(tid) outs.append(taps) rec.update(enc_ms=ms, enc_eager_ms=eager, enc_trace_mb=tmb) ms, eager, tmb, inv, tid = time_stage(device, dec.run, taps, reps) tids.append(tid) outs.append(inv) rec.update(dec_ms=ms, dec_eager_ms=eager, dec_trace_mb=tmb, dec_group=dec.group) rec["dram_mb_after"] = mem_mb(device, "dram") rec["dram_free_mb"] = free_dram_mb(device) if fov and w_fov is not None: fh, fw = DepthPro2Device.fov_size(hp, wp) fshape = StageShape(t, fh, fw) fe = ttnn_fov.Engine(device, w_fov, fshape) fp = rand_input(device, t * fshape.np_, 768) ms, eager, tmb, lg, tid = time_stage(device, fe.run, fp, reps) tids.append(tid) outs.append(lg) rec.update(fov_hw=[fh, fw], fov_ms=ms, fov_eager_ms=eager, fov_trace_mb=tmb) rec["fits"] = True if "enc_ms" in rec: rec["depth_ms"] = rec["enc_ms"] + rec["dec_ms"] rec["depth_fps"] = 1e3 * t / rec["depth_ms"] except Exception as e: # noqa: BLE001 (allocation failure = does not fit) rec["fits"] = False rec["error"] = f"{type(e).__name__}: {str(e).splitlines()[0][:300] if str(e) else ''}" traceback.print_exc() finally: for tid in tids: ttnn.release_trace(device, tid) for o in outs: _free(o) gc.collect() ttnn.synchronize_device(device) return rec def bench_e2e(device, size, ws, wf, hp, wp, t, reps): """DepthPro2Device: wall time of inverse_depth() (host unfold + upload + replay + readback) and fov_logits().""" m = DepthPro2Device(device, size, ws, wf, buckets=[(hp, wp)], max_frames=t) try: x = torch.randn(t, 3, hp, wp) m.inverse_depth(x) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth(x) call = (time.perf_counter() - t0) * 1e3 / reps rec = {"size": size, "hp": hp, "wp": wp, "T": t, "inverse_depth_call_ms": call, "compile_s": m.compile_seconds, "host_breakdown_ms": dict(m.last_timing)} if wf is not None: fh, fw = m.fov_size(hp, wp) y = torch.randn(t, 3, fh, fw) m.fov_logits(y) t0 = time.perf_counter() for _ in range(reps): m.fov_logits(y) rec["fov_logits_call_ms"] = (time.perf_counter() - t0) * 1e3 / reps return rec finally: m.close() def bench_kv(device, size, ws, hp, wp, window, reps): """Unbuffered step: wall time of inverse_depth_step (host + device), device-only replay of the step trace, the T=1 image call for comparison, and the bytes of one cache.""" import ttnn m = DepthPro2Device(device, size, ws, None, buckets=[(hp, wp)], max_frames=window, frames=(1,), kv_cache=True) try: c = m.kv_cache((hp, wp), window) x = torch.randn(1, 3, hp, wp) for _ in range(window + 1): # fill the ring m.inverse_depth_step(x, c) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth_step(x, c) step = (time.perf_counter() - t0) * 1e3 / reps breakdown = dict(m.last_timing) prog = c._slot.program ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, prog.trace, cq_id=0, blocking=False) ttnn.synchronize_device(device) step_dev = (time.perf_counter() - t0) * 1e3 / reps m.inverse_depth(x) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth(x) image = (time.perf_counter() - t0) * 1e3 / reps p1 = m._depth[(1, hp, wp)] ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, p1.trace, cq_id=0, blocking=False) ttnn.synchronize_device(device) image_dev = (time.perf_counter() - t0) * 1e3 / reps return {"size": size, "hp": hp, "wp": wp, "window": window, "step_call_ms": step, "step_device_ms": step_dev, "image_call_ms": image, "image_device_ms": image_dev, "cache_bytes": c.nbytes, "host_breakdown_ms": breakdown, "compile_s": m.compile_seconds} finally: m.close() def stress(device, size, ws, hp, wp, t, runs): """``runs`` back-to-back inverse_depth() calls on one input: every output bit-identical to the first.""" m = DepthPro2Device(device, size, ws, None, buckets=[(hp, wp)], max_frames=t) try: g, _ = H.load_golden("img_vga", "S") x = ref.pad_to_multiple(g["x_norm"]) if (t, hp, wp) == (1, 480, 640) else torch.randn(t, 3, hp, wp) first = m.inverse_depth(x) bad = 0 t0 = time.perf_counter() for _ in range(runs): bad += int(not torch.equal(first, m.inverse_depth(x))) return {"size": size, "hp": hp, "wp": wp, "T": t, "runs": runs, "mismatches": bad, "seconds": time.perf_counter() - t0} finally: m.close() def main(): ap = argparse.ArgumentParser() ap.add_argument("--sizes", default="S") ap.add_argument("--configs", default="480x640x1,256x320x4,480x640x4") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--no-fov", action="store_true") ap.add_argument("--dec-only", action="store_true", help="DEC on random taps only (kind 'stage_dec')") ap.add_argument("--e2e", default="", help="HpxWpxT list for DepthPro2Device call latency") ap.add_argument("--stress", default="", help="HpxWpxT:runs for the bit-exact replay stress (size = first of --sizes)") ap.add_argument("--kv", default="", help="HpxWpxW list: unbuffered step latency with a ring of W frames") ap.add_argument("--json", default=os.path.join(H.ROOT, "logs/depthpro2/baseline/bench.jsonl")) a = ap.parse_args() dev = H.open_device() import ttnn grid = dev.compute_with_storage_grid_size() print(f"grid {grid.x}x{grid.y}", flush=True) wf_host = None if a.no_fov else load_weights(H.fov_dir()) w_fov = None if wf_host is None else ttnn_fov.Engine.prepare_weights(dev, wf_host) def emit(rec): rec["time"] = time.strftime("%Y-%m-%d %H:%M:%S") rec["grid"] = f"{grid.x}x{grid.y}" line = json.dumps(rec) print(line, flush=True) os.makedirs(os.path.dirname(a.json), exist_ok=True) with open(a.json, "a") as f: f.write(line + "\n") try: for size in a.sizes.split(","): ws = load_weights(H.size_dir(size)) t0 = time.perf_counter() w_enc = ttnn_enc.Engine.prepare_weights(dev, ws, size) w_dec = ttnn_dec.Engine.prepare_weights(dev, ws, size) v = ttnn.get_memory_view(dev, ttnn.BufferType.DRAM) emit({"kind": "weights", "size": size, "upload_s": time.perf_counter() - t0, "dram_mb": mem_mb(dev, "dram"), "dram_total_mb": v.num_banks * v.total_bytes_per_bank / 2 ** 20}) for c in [c for c in a.configs.split(",") if c]: hp, wp, t = (int(v) for v in c.split("x")) rec = bench_config(dev, size, w_enc, w_dec, w_fov, hp, wp, t, a.reps, not a.no_fov, a.dec_only) rec["kind"] = "stage_dec" if a.dec_only else "stage" emit(rec) del w_enc, w_dec gc.collect() for c in [c for c in a.e2e.split(",") if c]: hp, wp, t = (int(v) for v in c.split("x")) rec = bench_e2e(dev, size, ws, wf_host, hp, wp, t, a.reps) rec["kind"] = "e2e" emit(rec) for c in [c for c in a.kv.split(",") if c]: hp, wp, win = (int(v) for v in c.split("x")) rec = bench_kv(dev, size, ws, hp, wp, win, a.reps) rec["kind"] = "kv" emit(rec) if a.stress and size == a.sizes.split(",")[0]: cfg, runs = a.stress.split(":") hp, wp, t = (int(v) for v in cfg.split("x")) rec = stress(dev, size, ws, hp, wp, t, int(runs)) rec["kind"] = "stress" emit(rec) del ws gc.collect() finally: H.close_device(dev) if __name__ == "__main__": main()