File size: 4,057 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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Per-stage device time: each stage of ``TtMeteor2.forward`` captured as its own trace and replayed (bin/devrun).

    bin/devrun python scripts/dev_stages.py --form gather --name valday_0040
"""
import argparse
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__)), ".."))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--form", default="gather")
    ap.add_argument("--name", default="valday_0040")
    ap.add_argument("--iters", type=int, default=5)
    ap.add_argument("--conv", default=None)
    ap.add_argument("--l1", default="table", choices=("none", "table"))
    ap.add_argument("--stem-rm", action="store_true")
    ap.add_argument("--stem", default="s2d", choices=("s2d", "direct"))
    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.model import TtMeteor2, image_input
    from tt_meteor2.ttaw.device import close_device, open_device
    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)
    rep = {}
    try:
        m = TtMeteor2(dev, w, **(dict({"conv_precision": a.conv} if a.conv else {}, stem=a.stem, conv_l1=a.l1, stem_tile=not a.stem_rm)))
        if a.form == "gather":
            m.set_calibration(lift_tables(z["K"][0], z["T_cam_ego"][0], w.bev_points(), w.paint_z_fill()))
        xt, geo = m.host_input(z["imgs"])
        xh = ttnn.from_torch(xt, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT)
        x = ttnn.allocate_tensor_on_device(xh.shape, ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT, dev, ttnn.DRAM_MEMORY_CONFIG)
        ttnn.copy_host_to_device_tensor(xh, x)
        fm = FeatureMap(x, *geo)

        lift_fn = (lambda pol, paint: (m.lift_gather(pol), m.paint_gather(paint))) if a.form == "gather" else \
            (lambda pol, paint: (m.vt(pol, scale=0.5), m.gvt(paint)))
        stages = [
            ("image", lambda s: m.image(fm)),
            ("heads2d", lambda s: m.heads2d(*s["image"])),
            ("polar", lambda s: m.polar(s["heads2d"][0], s["heads2d"][1])),
            ("lift", lambda s: lift_fn(s["polar"], s["heads2d"][2])),
            ("bev", lambda s: m.bev(*s["lift"])),
        ]
        # eager warm-up of the chain (compiles every program), keeping each stage's outputs
        state = {}
        for name, fn in stages:
            state[name] = fn(state)
        ttnn.synchronize_device(dev)
        state = {}
        for name, fn in stages:
            state[name] = fn(state)
        ttnn.synchronize_device(dev)
        # one trace per stage, inputs = the previous stage's eager outputs (kept alive)
        traces = {}
        cap = dict(state)
        for name, fn in stages:
            tid = ttnn.begin_trace_capture(dev, cq_id=0)
            cap[name] = fn(cap)
            ttnn.end_trace_capture(dev, tid, cq_id=0)
            traces[name] = tid
        ttnn.synchronize_device(dev)
        total = 0.0
        for name, _ in stages:
            ts = []
            for _ in range(a.iters):
                t = time.time()
                ttnn.execute_trace(dev, traces[name], cq_id=0, blocking=False)
                ttnn.synchronize_device(dev)
                ts.append((time.time() - t) * 1e3)
            rep[name] = float(np.median(ts))
            total += rep[name]
            print(f"{name:8s} {rep[name]:7.2f} ms", flush=True)
        print(f"{'sum':8s} {total:7.2f} ms", flush=True)
        for tid in traces.values():
            ttnn.release_trace(dev, tid)
    finally:
        close_device(dev)
        json.dump(rep, open(f"/logs/dev_stages_{a.form}_{a.name}.json", "w"), indent=1)


if __name__ == "__main__":
    main()