changh95's picture
tt-model push auto_speed-p150 (container)
7fedee6 verified
Raw History Blame Contribute Delete
7.16 kB
# SPDX-License-Identifier: Apache-2.0
"""Device probes for the optimisation decisions (run under bin/devrun):
python -m tt_visionpilot.tests.dev_probe [--nets ...] [--json OUT]
1. upload: host -> device copy of one 1024 x 512 RGB uint8 image in several row-major shapes (pages of 3 B to 3 KB);
2. steps: eager time of every plan step (synchronised after each step, second run: programs cached) by kind;
3. mean: the CTX mean as a matmul with bf16 vs float32 output, and ttnn.mean, against numpy.
"""
from __future__ import annotations
import argparse
import json
import time
from collections import defaultdict
from pathlib import Path
import numpy as np
from ..graph import Graph
from ..models import NETWORKS
def main(argv=None) -> int:
import torch
import ttnn
from ..host.rows_numpy import RowsNumpy
from ..plan import Plan
from ..tt.backend import TtBackend
from ..ttaw.device import close_device, open_device
from ..ttaw.precision import compute_kernel_config
ap = argparse.ArgumentParser()
ap.add_argument("--nets", nargs="*", default=list(NETWORKS))
ap.add_argument("--data", default="/weights/port")
ap.add_argument("--json", default=None)
args = ap.parse_args(argv)
dev = open_device(0, dispatch="eth", num_command_queues=1, l1_small_size=32768, trace_region_size=64 << 20,
allow_fallback=False)
rep = {"upload": {}, "steps": {}, "mean": {}}
try:
# ---- 1. upload shapes
rng = np.random.default_rng(0)
img = rng.integers(0, 256, (512, 1024, 3), np.uint8)
shapes = {"rows3": (1, 1, 512 * 1024, 3), "s2d2_12": (1, 1, 257 * 513, 12), "s2d4_48": (1, 1, 129 * 257, 48),
"imgrow_3072": (1, 1, 512, 3072), "planar_1024": (1, 1, 1536, 1024)}
for key, shp in shapes.items():
n = int(np.prod(shp))
a = np.zeros(n, np.uint8)
a[: img.size] = img.ravel()[: min(n, img.size)]
host = ttnn.from_torch(torch.from_numpy(a.reshape(shp)), dtype=ttnn.uint8, layout=ttnn.ROW_MAJOR_LAYOUT)
devt = ttnn.allocate_tensor_on_device(host.spec, dev) if hasattr(ttnn, "allocate_tensor_on_device") \
else ttnn.to_device(host, dev)
ts = []
for _ in range(12):
ttnn.synchronize_device(dev)
t = time.perf_counter()
ttnn.copy_host_to_device_tensor(host, devt)
ttnn.synchronize_device(dev)
ts.append((time.perf_counter() - t) * 1e3)
rep["upload"][key] = {"shape": shp, "median_ms": float(np.median(ts[2:])), "max_ms": float(max(ts[2:]))}
print("upload", key, shp, f"{np.median(ts[2:]):.2f} ms")
ttnn.deallocate(devt)
# ---- 3. mean precision (on a real CTX input, computed below per net)
mm_bf = compute_kernel_config("HiFi4", fp32_acc=True, packer_l1_acc=True)
# ---- 2. per-step times
for name in args.nets:
spec = NETWORKS[name]
g = Graph(Path(args.data) / "folded" / f"{name}.onnx")
z = np.load(Path(args.data) / "golden" / f"{name}.npz")
plan = Plan(g, spec)
be = TtBackend(dev)
feeds_np = {k: z[f"0/in/{k}"] for k in spec.inputs}
times = {}
def hook(s, outs, times=times):
ttnn.synchronize_device(dev)
now = time.perf_counter()
times[s.index] = (now - hook.t) * 1e3
hook.t = now
for run in range(2):
feeds = {k: be.input_map(v) for k, v in feeds_np.items()}
ttnn.synchronize_device(dev)
hook.t = time.perf_counter()
cut = plan.run(be, feeds, hook=hook)
for v in cut.values():
be.release(v)
by_kind = defaultdict(float)
for s in plan.steps:
by_kind[s.kind] += times[s.index]
top = sorted(plan.steps, key=lambda s: -times[s.index])[:15]
rep["steps"][name] = {"total_ms": float(sum(times.values())), "by_kind": dict(by_kind),
"top": [{"step": s.index, "kind": s.kind, "out": s.outputs[0], "ms": times[s.index],
"in": [plan.meta[i] for i in s.inputs],
"params": {k: (list(v) if isinstance(v, tuple) else v)
for k, v in s.params.items()
if k in ("stride", "padding", "groups", "act", "kernel")}}
for s in top]}
print(f"== {name}: eager sum {sum(times.values()):.1f} ms;", {k: round(v, 2) for k, v in by_kind.items()})
for s in top:
print(f" {times[s.index]:6.2f} ms step {s.index:3d} {s.kind:10s} {s.outputs[0][:24]:24s} in "
f"{[plan.meta[i] for i in s.inputs]} "
f"{ {k: v for k, v in s.params.items() if k in ('stride', 'groups', 'kernel')} } "
f"{tuple(s.params['weight'].shape) if 'weight' in s.params else ''}")
# mean precision on the first mean step's real input
ms = [s for s in plan.steps if s.kind == "mean"]
if ms:
s0 = ms[0]
host = RowsNumpy()
ref = {}
plan.run(host, {k: host.input_map(v) for k, v in feeds_np.items()},
hook=lambda s, outs: ref.update({o: v for o, v in zip(s.outputs, outs)}))
x_np = ref[s0.inputs[0]]
rows, c = x_np.shape
xt = ttnn.from_torch(torch.from_numpy(x_np[None, None]), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
device=dev)
ones = ttnn.from_torch(torch.full((1, 1, 1, rows), 1.0 / rows), dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=dev)
exact = x_np.astype(np.float64).mean(0)
xb = ttnn.to_torch(xt).float().numpy().reshape(-1, c)[:rows].astype(np.float64).mean(0)
res = {"bf16_input_mean": xb}
res["mm_bf16_out"] = ttnn.to_torch(ttnn.matmul(ones, xt, compute_kernel_config=mm_bf)).float().numpy().reshape(-1)[:c]
res["mm_fp32_out"] = ttnn.to_torch(ttnn.matmul(ones, xt, compute_kernel_config=mm_bf,
dtype=ttnn.float32)).float().numpy().reshape(-1)[:c]
res["ttnn_mean"] = ttnn.to_torch(ttnn.mean(xt, dim=2, keepdim=True)).float().numpy().reshape(-1)[:c]
rep["mean"][name] = {k: float(np.linalg.norm(v - exact) / np.linalg.norm(exact)) for k, v in res.items()}
print(" mean relL2 vs fp64:", {k: f"{v:.3g}" for k, v in rep["mean"][name].items()})
finally:
close_device(dev)
if args.json:
Path(args.json).write_text(json.dumps(rep, indent=1, default=str))
return 0
if __name__ == "__main__":
raise SystemExit(main())