File size: 5,239 Bytes
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
# SPDX-License-Identifier: Apache-2.0
"""ENC megakernel vs the ttnn baseline engine (tt/ttnn_enc.py) on the device, for shapes whose CPU reference is too
slow: same patches, taps compared (PCC / rel err), both engines timed under trace (device time per run).

    bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_xcheck.py --size L \
        --case img_vga --resize 736 1280 --tframes 16 [--no-ttnn]
"""

from __future__ import annotations

import argparse
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 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  # noqa: E402


def trace_time(dev, fn, reps):
    import ttnn

    fn()
    ttnn.synchronize_device(dev)
    tid = ttnn.begin_trace_capture(dev, cq_id=0)
    out = fn()
    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(reps):
        ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
    ttnn.synchronize_device(dev)
    dt = (time.perf_counter() - t0) / reps
    ttnn.release_trace(dev, tid)
    return out, dt


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--size", default="L")
    ap.add_argument("--case", default="img_vga")
    ap.add_argument("--resize", type=int, nargs=2, default=None)
    ap.add_argument("--tframes", type=int, default=0)
    ap.add_argument("--reps", type=int, default=3)
    ap.add_argument("--no-ttnn", action="store_true")
    ap.add_argument("--determinism", type=int, default=0, help="extra trace replays compared bitwise")
    ap.add_argument("--save", default=None, help="torch.save the mk (and ttnn) taps [T, N, C] to this path")
    args = ap.parse_args()
    import ttnn

    g = H.load_case(args.case, args.size)
    x = R.pad_to_multiple(g["x_norm"].float())
    if args.resize:
        x = torch.nn.functional.interpolate(x, size=tuple(args.resize), mode="bilinear", align_corners=False)
    if args.tframes:
        gen = torch.Generator().manual_seed(0)
        x = x.repeat(-(-args.tframes // x.shape[0]), 1, 1, 1)[:args.tframes]
        x = x + 0.1 * torch.randn(x.shape, generator=gen)
    T, _, hp, wp = x.shape
    w = H.load_weights(args.size)
    dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH),
                           trace_region_size=16 << 20)
    try:
        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)
        t0 = time.perf_counter()
        mk = MkEnc(dev, w, args.size, T, hp // 16, wp // 16)
        print(mk.geo.summary(), f"init {time.perf_counter() - t0:.1f} s", flush=True)
        taps_mk, dt_mk = trace_time(dev, lambda: mk.run(patches), args.reps)
        print(f"MK   {args.size} T={T} {hp}x{wp}: {1e3 * dt_mk:.2f} ms / run", flush=True)
        dmk = [ttnn.to_torch(t).float().reshape(T, mk.geo.Np, -1)[:, :mk.geo.N] for t in taps_mk]
        bad = [int((~torch.isfinite(d)).sum()) for d in dmk]
        print(f"MK non-finite tap values: {bad}", flush=True)
        if args.determinism:
            raw = [ttnn.to_torch(t).clone() for t in taps_mk]
            tid = ttnn.begin_trace_capture(dev, cq_id=0)
            mk.run(patches)
            ttnn.end_trace_capture(dev, tid, cq_id=0)
            mism = 0
            for _ in range(args.determinism):
                ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
                mism += sum(int(not torch.equal(a, ttnn.to_torch(t))) for a, t in zip(raw, mk.taps))
            ttnn.release_trace(dev, tid)
            print(f"MK determinism: {args.determinism} replays, {mism} mismatching taps", flush=True)
        if not args.no_ttnn:
            from tt_depthpro2.tt import ttnn_enc

            eng = ttnn_enc.Engine(dev, w, StageShape(T, hp, wp), size=args.size)
            taps_tt, dt_tt = trace_time(dev, lambda: eng.run(patches), args.reps)
            print(f"TTNN {args.size} T={T} {hp}x{wp}: {1e3 * dt_tt:.2f} ms / run", flush=True)
            dtt = [ttnn.to_torch(t).float().reshape(T, mk.geo.Np, -1)[:, :mk.geo.N] for t in taps_tt]
            for i, (a, b) in enumerate(zip(dmk, dtt)):
                print(f"  tap{i} mk vs ttnn: pcc {H.pcc(a, b):.6f} rel {H.rel_err(a, b):.3e}", flush=True)
                if f"tap{i}" in g and not (args.resize or args.tframes):
                    r = g[f"tap{i}"].float()
                    print(f"  tap{i} vs golden: mk pcc {H.pcc(a, r):.6f} rel {H.rel_err(a, r):.3e} | ttnn pcc "
                          f"{H.pcc(b, r):.6f} rel {H.rel_err(b, r):.3e}", flush=True)
        if args.save:
            torch.save({"mk": dmk, "ttnn": dtt if not args.no_ttnn else None}, args.save)
    finally:
        ttnn.close_device(dev)


if __name__ == "__main__":
    main()