File size: 4,188 Bytes
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
# SPDX-License-Identifier: Apache-2.0
"""ENC megakernel device time per (size, shape) under trace (the configs of code/scripts/bench_baseline.py), weights
uploaded once per size (MkEncWeights) and shared by every shape; finiteness and replay determinism checked.

    bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_bench.py --sizes S,B \
        --configs 480x640x1,256x320x4,480x640x4,480x640x16,736x1280x1,1088x1920x1
"""

from __future__ import annotations

import argparse
import gc
import json
import os
import sys
import time

import torch

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

from tt_depthpro2.reference import model as R  # noqa: E402
from tt_depthpro2.tests import mk_enc_ref as H  # 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



def frames(hp: int, wp: int, T: int) -> torch.Tensor:
    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 main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--sizes", default="S")
    ap.add_argument("--configs", default="480x640x1")
    ap.add_argument("--reps", type=int, default=5)
    ap.add_argument("--mode", default="depth")
    args = ap.parse_args()
    import ttnn

    dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH),
                           trace_region_size=16 << 20)
    try:
        for size in args.sizes.split(","):
            w = H.load_weights("fov" if args.mode == "fov" else size)
            t0 = time.perf_counter()
            wts = MkEncWeights(dev, w, size, args.mode)
            up = time.perf_counter() - t0
            print(f"{size}: weights {wts.dram_bytes / 2**20:.0f} MB uploaded in {up:.1f} s", flush=True)
            for cfg in args.configs.split(","):
                hp, wp, T = (int(v) for v in cfg.split("x"))
                x = frames(hp, wp, T)
                patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768),
                                          dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev,
                                          memory_config=ttnn.DRAM_MEMORY_CONFIG)
                t0 = time.perf_counter()
                mk = MkEnc(dev, wts, size, T, hp // 16, wp // 16, mode=args.mode)
                print(f"RUN {size} {hp}x{wp}x{T}: {mk.geo.summary()}", flush=True)
                mk.run(patches)
                ttnn.synchronize_device(dev)
                first = time.perf_counter() - t0
                raw = [ttnn.to_torch(t).clone() for t in mk.taps]
                fin = all(bool(torch.isfinite(r.float()).all()) for r in raw)
                tid = ttnn.begin_trace_capture(dev, cq_id=0)
                mk.run(patches)
                ttnn.end_trace_capture(dev, tid, cq_id=0)
                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)
                ms = 1e3 * (time.perf_counter() - t0) / args.reps
                same = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(raw, mk.taps))
                ttnn.release_trace(dev, tid)
                rec = {"size": size, "mode": args.mode, "hp": hp, "wp": wp, "T": T, "enc_ms": ms,
                       "first_run_s": first, "finite": fin, "replays_bitexact": same, "geometry": mk.geo.summary(),
                       "time": time.strftime("%Y-%m-%d %H:%M:%S")}
                print(json.dumps(rec), flush=True)
                H.append_log("bench.jsonl", rec)
                del mk, patches, raw
                gc.collect()
            del wts
            gc.collect()
    finally:
        ttnn.close_device(dev)


if __name__ == "__main__":
    main()