File size: 7,078 Bytes
b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | # SPDX-License-Identifier: Apache-2.0
"""One ENC configuration per call (run each through its own short devrun job): the megakernel's traced device time,
trace bytes, DRAM bytes, finiteness and replay determinism, and its taps vs the ttnn ENC engine on the same patches
(eager); the ttnn baseline's traced time from logs/depthpro2/baseline/bench*.jsonl. Out-of-memory / L1-budget
failures are recorded, not raised. Appends to logs/depthpro2/mk_enc/sweep.jsonl.
bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_sweep.py --size L --hw 736 1280 --T 4
"""
from __future__ import annotations
import argparse
import gc
import json
import os
import sys
import time
import traceback
import torch
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402
from tt_depthpro2.tt import StageShape # noqa: E402
from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402
from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights # noqa: E402
#: optional: directory with the ttnn baseline's bench.jsonl / bench_r2.jsonl (traced ENC times to compare with)
BASELINE_BENCH = os.environ.get("DEPTHPRO2_BASELINE_BENCH", "")
def baseline_ms(size, hp, wp, T):
best = None
for f in ("bench.jsonl", "bench_r2.jsonl"):
p = os.path.join(BASELINE_BENCH, f)
if not BASELINE_BENCH or not os.path.exists(p):
continue
for line in open(p):
d = json.loads(line)
if d.get("size") == size and (d.get("hp"), d.get("wp"), d.get("T")) == (hp, wp, T) and "enc_ms" in d:
best = (d["enc_ms"], d.get("enc_trace_mb"))
return best
def frames(hp, wp, T):
g = H.load_case("img_vga", "S")
x = torch.nn.functional.interpolate(g["x_norm"].float(), size=(hp, wp), mode="bilinear", align_corners=False)
gen = torch.Generator().manual_seed(0)
x = x.repeat(T, 1, 1, 1)
return x + 0.1 * torch.randn(x.shape, generator=gen)
def mem_mb(device, kind):
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 main():
ap = argparse.ArgumentParser()
ap.add_argument("--size", required=True)
ap.add_argument("--hw", type=int, nargs=2, required=True)
ap.add_argument("--T", type=int, required=True)
ap.add_argument("--reps", type=int, default=3)
ap.add_argument("--no-ttnn", action="store_true")
args = ap.parse_args()
import ttnn
size, (hp, wp), T = args.size, args.hw, args.T
rec = {"size": size, "hp": hp, "wp": wp, "T": T}
bl = baseline_ms(size, hp, wp, T)
if bl:
rec["ttnn_enc_ms"], rec["ttnn_enc_trace_mb"] = bl
dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH),
trace_region_size=64 << 20)
try:
w = H.load_weights(size)
d0 = mem_mb(dev, "dram")
wts = MkEncWeights(dev, w, size, "depth")
rec["weights_mb"] = mem_mb(dev, "dram") - d0
x = frames(hp, wp, T)
pt = A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768)
patches = ttnn.from_torch(pt, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
d1 = mem_mb(dev, "dram")
t0 = time.perf_counter()
try:
mk = MkEnc(dev, wts, size, T, hp // 16, wp // 16)
rec["geometry"] = mk.geo.summary()
print("RUN", rec["geometry"], flush=True)
mk.run(patches)
ttnn.synchronize_device(dev)
except Exception as e: # noqa: BLE001 (L1 budget / DRAM OOM: record and stop)
rec.update(fits=False, error=f"{type(e).__name__}: {str(e)[:300]}")
raise
rec["fits"] = True
rec["first_run_s"] = time.perf_counter() - t0
rec["mk_dram_mb"] = mem_mb(dev, "dram") - d1
raw = [ttnn.to_torch(t).clone() for t in mk.taps]
rec["finite"] = all(bool(torch.isfinite(r.float()).all()) for r in raw)
tr0 = mem_mb(dev, "trace")
tid = ttnn.begin_trace_capture(dev, cq_id=0)
mk.run(patches)
ttnn.end_trace_capture(dev, tid, cq_id=0)
rec["mk_trace_kb"] = 1024 * (mem_mb(dev, "trace") - tr0)
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
t0 = time.perf_counter()
for _ in range(args.reps):
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
rec["mk_enc_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps
rec["replays_bitexact"] = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(raw, mk.taps))
ttnn.release_trace(dev, tid)
if "ttnn_enc_ms" in rec:
rec["speedup"] = rec["ttnn_enc_ms"] / rec["mk_enc_ms"]
print(json.dumps(rec), flush=True)
if not args.no_ttnn:
from tt_depthpro2.tt import ttnn_enc
t0 = time.perf_counter()
eng = ttnn_enc.Engine(dev, w, StageShape(T, hp, wp), size=size)
out = eng.run(patches)
ttnn.synchronize_device(dev)
rec["ttnn_eager_s"] = time.perf_counter() - t0
N, Np = mk.geo.N, mk.geo.Np
cmp = []
for a, b in zip(raw, out):
a = a.float().reshape(T, Np, -1)[:, :N]
b = ttnn.to_torch(b).float().reshape(T, Np, -1)[:, :N]
cmp.append({"pcc": H.pcc(a, b), "rel": H.rel_err(a, b)})
rec["taps_mk_vs_ttnn"] = cmp
rec["ok_vs_ttnn"] = all(c["pcc"] >= 0.999 for c in cmp)
if "ttnn_enc_ms" not in rec: # no baseline bench entry (e.g. 640x480): time the ttnn engine traced here
tr0 = mem_mb(dev, "trace")
tid = ttnn.begin_trace_capture(dev, cq_id=0)
eng.run(patches)
ttnn.end_trace_capture(dev, tid, cq_id=0)
rec["ttnn_enc_trace_mb"] = mem_mb(dev, "trace") - tr0
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
t0 = time.perf_counter()
for _ in range(args.reps):
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
rec["ttnn_enc_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps
rec["ttnn_enc_ms_source"] = "measured here (traced)"
rec["speedup"] = rec["ttnn_enc_ms"] / rec["mk_enc_ms"]
ttnn.release_trace(dev, tid)
except Exception: # noqa: BLE001
traceback.print_exc()
rec.setdefault("error", traceback.format_exc().splitlines()[-1][:300])
finally:
rec["time"] = time.strftime("%Y-%m-%d %H:%M:%S")
print("REC " + json.dumps(rec), flush=True)
H.append_log("sweep.jsonl", rec)
gc.collect()
ttnn.close_device(dev)
if __name__ == "__main__":
main()
|