File size: 6,151 Bytes
0f131e7 | 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 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Op-level hot spots without Tracy: one eager forward with every conv and ttnn call synchronised and timed
(includes ~0.1-0.3 ms host dispatch per op, so only multi-ms entries mean something). Run under bin/devrun.
bin/devrun python scripts/dev_ops.py --form gather --name valday_0040 [--top 40]
"""
import argparse
import collections
import json
import os
import sys
import time
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
TTNN_OPS = ("permute", "matmul", "grid_sample", "embedding", "upsample", "to_layout", "softmax", "sum", "add",
"multiply", "typecast", "slice", "max_pool2d", "pad", "reshape", "linear")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--form", default="gather")
ap.add_argument("--name", default="valday_0040")
ap.add_argument("--top", type=int, default=45)
ap.add_argument("--conv", default=None)
ap.add_argument("--stem", default="s2d", choices=("s2d", "direct"))
ap.add_argument("--mode", choices=("trace", "sync"), default="trace")
a = ap.parse_args()
import ttnn
from tt_meteor2.host.calib import lift_tables
from tt_meteor2.reference import config as C
from tt_meteor2.reference.weights import Meteor2Weights
from tt_meteor2.tt import model as M
from tt_meteor2.ttaw.device import close_device, open_device
from tt_meteor2.ttaw.ops import conv as convmod
from tt_meteor2.ttaw.ops.conv import FeatureMap
z = dict(np.load(f"/data/inputs/{a.name}.npz"))
w = Meteor2Weights(f"/weights/{C.ONNX_FILES[a.form]}")
dev = open_device(0, dispatch="eth", l1_small_size=32768, trace_region_size=128 << 20)
rec = collections.OrderedDict()
stack = []
try:
m = M.TtMeteor2(dev, w, **(dict({"conv_precision": a.conv} if a.conv else {}, stem=a.stem, conv_l1="table")))
if a.form == "gather":
m.set_calibration(lift_tables(z["K"][0], z["T_cam_ego"][0], w.bev_points(), w.paint_z_fill()))
xh, geo = m.host_input(z["imgs"])
x = ttnn.from_torch(xh, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
fm = FeatureMap(x, *geo)
out = m.forward(fm) # compile everything
ttnn.synchronize_device(dev)
for v in out.values():
ttnn.deallocate(v)
traces = []
def timed(label_fn, fn):
def wrapper(*args, **kw):
if stack: # nested (conv -> ttnn.conv2d): only the outer one
return fn(*args, **kw)
stack.append(1)
try:
if a.mode == "trace": # this call alone as a trace: device time of its programs
ttnn.synchronize_device(dev)
tid = ttnn.begin_trace_capture(dev, cq_id=0)
r = fn(*args, **kw)
ttnn.end_trace_capture(dev, tid, cq_id=0)
traces.append(tid)
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
ts = []
for _ in range(3):
t = time.perf_counter()
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
ts.append((time.perf_counter() - t) * 1e3)
dt = float(np.median(ts))
else:
ttnn.synchronize_device(dev)
t = time.perf_counter()
r = fn(*args, **kw)
ttnn.synchronize_device(dev)
dt = (time.perf_counter() - t) * 1e3
finally:
stack.pop()
key = label_fn(args, kw)
e = rec.setdefault(key, [0, 0.0])
e[0] += 1
e[1] += dt
return r
return wrapper
orig_call = convmod.Conv2d.__call__
convmod.Conv2d.__call__ = timed(lambda args, kw: f"conv {args[0].name} {args[0].kernel}", orig_call)
saved = {}
for op in TTNN_OPS:
if hasattr(ttnn, op):
saved[op] = getattr(ttnn, op)
def lab(args, kw, op=op):
shp = ""
if args and hasattr(args[0], "shape"):
shp = "x".join(str(int(s)) for s in args[0].shape)
return f"ttnn.{op} {shp}"
setattr(ttnn, op, timed(lab, saved[op]))
if a.mode == "trace": # tensors of one trace are read by the next: keep all
saved["deallocate"] = ttnn.deallocate
ttnn.deallocate = lambda *x, **k: None
orig_fm_dealloc = FeatureMap.deallocate
FeatureMap.deallocate = lambda self: None
try:
ttnn.synchronize_device(dev)
t = time.perf_counter()
out = m.forward(fm)
ttnn.synchronize_device(dev)
total = (time.perf_counter() - t) * 1e3
finally:
convmod.Conv2d.__call__ = orig_call
for op, f in saved.items():
setattr(ttnn, op, f)
if a.mode == "trace":
FeatureMap.deallocate = orig_fm_dealloc
for tid in traces:
ttnn.release_trace(dev, tid)
rows = sorted(rec.items(), key=lambda kv: -kv[1][1])
s = sum(v[1] for v in rec.values())
print(f"[{a.mode}] forward wall {total:.1f} ms, timed sum {s:.1f} ms, {sum(v[0] for v in rec.values())} calls")
for k, (n, ms) in rows[: a.top]:
print(f"{ms:8.2f} ms x{n:<3d} {k}")
json.dump({"total_ms": total, "ops": {k: v for k, v in rows}}, open(f"/logs/dev_ops_{a.form}_{a.name}.json", "w"), indent=1)
finally:
close_device(dev)
if __name__ == "__main__":
main()
|