File size: 13,295 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# SPDX-License-Identifier: Apache-2.0
"""ENC megakernel device runner (debug / bring-up): run the program for ``--nl`` blocks on a golden case and compare
x (fp32 dump), q / k / v of block nl and the attention output of block nl - 1 with the float32 reference.

    bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_run.py --size S \
        --case img_384x512 --nl 1
"""

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.mk_enc import arena as A  # noqa: E402
from tt_depthpro2.tt.mk_enc.program import MkEnc  # noqa: E402


def open_device(dispatch: str = "eth", trace: bool = False):
    import ttnn

    kw = {"trace_region_size": 8 << 20} if trace else {}
    if dispatch == "eth":
        kw["dispatch_core_config"] = ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH)
    return ttnn.open_device(device_id=0, **kw)


def report(name, dev, ref, geo=None):
    print(f"  {name:12s} pcc {H.pcc(dev, ref):.6f} rel {H.rel_err(dev, ref):.3e} max|d| "
          f"{(dev - ref).abs().max().item():.3e} max|ref| {ref.abs().max().item():.3e}", flush=True)


def prof_report(p, geo, nl):
    """per-phase times (us at 1.35 GHz... the stamps are AICLK cycles) from the BRISC / TRISC stamps of every core"""
    clk = 1350.0
    t0 = p[:, 0].min()
    rel = lambda i: (p[:, i] - t0).double() / clk  # noqa: E731
    print(f"PROF E phase: {rel(1).max().item():.1f} us (from boot)")
    tot_a = tot_w = tot_b = 0.0
    for l in range(nl):
        a0, a1, w0, w1 = (rel(2 + 4 * l + k) for k in range(4))
        ta = (a1 - a0).max().item()
        tw = (w1 - w0).max().item()
        tb = (w0 - a1).max().item()
        tot_a, tot_w, tot_b = tot_a + ta, tot_w + tw, tot_b + tb
        tri = ((p[:, 193 + 2 * l] - p[:, 192 + 2 * l]).double() / clk)
        print(f"PROF blk {l:2d}: att {ta:8.1f} (trisc max {tri.max().item():8.1f} mean {tri.mean().item():8.1f}) "
              f"barrier {tb:6.1f} wave {tw:8.1f} us; end {rel(5 + 4 * l).max().item():9.1f}")
    print(f"PROF total: att {tot_a:.1f} wave {tot_w:.1f} barrier {tot_b:.1f} us")
    if nl > 1:  # block 1, wave 0 detail (relative to the TRISC's wave start, per core then max / mean)
        base = p[:, 256].double()
        names = {257: "proj end", 258: "stats_out(LN2) end", 259: "fc1 end", 260: "fc2 end", 261: "tail (LN1+QKV) end",
                 262: "fc1: INX landed", 263: "fc1: stats_in done", 264: "proj: INF landed", 265: "fc2: INF landed",
                 266: "qkv: INX landed", 267: "qkv: stats_in done"}
        for i, n in names.items():
            d = (p[:, i].double() - base) / clk
            print(f"PROF w1 trisc {n:22s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us")
        ab = p[:, 384].double()
        ok = (p[:, 384:390] > 0).all(1) & ((p[:, 389].double() - ab) > 0) & ((p[:, 389].double() - ab) < 1e7)
        if ok.any():
            for i, n in {385: "S packed", 386: "rowmax", 387: "m_new", 388: "P packed", 389: "PV done"}.items():
                d = ((p[:, i].double() - ab) / clk)[ok]
                print(f"PROF att item (q0, c0) {n:10s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us "
                      f"({int(ok.sum())} cores)")
        bb = p[:, 320].double()
        for i, n in {321: "IA gather done", 322: "LN2 gather done", 323: "FC1 gather done", 324: "tail done"}.items():
            d = (p[:, i].double() - bb) / clk
            print(f"PROF w1 brisc {n:22s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us")


def probe_report(prb, w, x, args, geo, gh, gw):
    """item 0 of block 0 (head 0, q = prefix tile of frame 0): S16 0..1, M, MFN 0..1, AP 0..1, ST 0..3 (chunk 0),
    M, MFN 0..1, ST 0..3 (chunk 1)"""
    tok0, _ = H.ref_run(w, x, args.size, 0, args.mode)
    rq = H.ref_qkv(tok0, w, 0, args.size, args.mode, gh, gw)
    qi = H.to_internal(rq["q"], geo)[:, :, :64]
    ki = H.to_internal(rq["k"], geo)[:, :, :64]
    vi = H.to_internal(rq["v"], geo)[:, :, :64]
    keys = [0] + list(range(geo.T, geo.T + geo.Pt))
    mask = torch.zeros(32, 32)
    mask[:, 5:] = -1e9
    S = [qi[0] @ ki[k].T + (mask if k < geo.T else 0) for k in keys]
    kc = geo.kc
    m0 = torch.stack(S[:kc], 0).amax(0).amax(-1)
    P0 = [torch.exp(s - m0[:, None]) for s in S[:kc]]
    O0 = sum(p @ vi[k] for p, k in zip(P0, keys[:kc]))
    l0 = sum(p.sum(-1) for p in P0)
    names = ["S16_0", "S16_1", "M_c0", "mnew_c0", "alpha_c0", "P_0", "P_1", "O0_c0", "O1_c0", "l_c0", "m_c0",
             "M_c1", "mnew_c1", "alpha_c1", "O0_c1", "O1_c1", "l_c1", "m_c1"]
    ref = {"S16_0": S[0], "S16_1": S[1], "M_c0": m0, "mnew_c0": m0[:, None].expand(32, 32), "P_0": P0[0],
           "P_1": P0[1], "O0_c0": O0[:, :32], "O1_c0": O0[:, 32:], "l_c0": l0[:, None].expand(32, 32),
           "m_c0": m0[:, None].expand(32, 32)}
    for i, n in enumerate(names):
        d = prb[i]
        line = f"  probe {i:2d} {n:9s} dev[0,:4] {d[0, :4].tolist()} dev[5,:2] {d[5, :2].tolist()}"
        if n in ref:
            r = ref[n]
            if r.dim() == 1:
                line += f" | ref[0] {r[0].item():.4g} ref[5] {r[5].item():.4g}"
            else:
                line += f" | ref[0,:4] {[round(v, 4) for v in r[0, :4].tolist()]}"
        print(line, flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--size", default="S")
    ap.add_argument("--case", default="img_384x512")
    ap.add_argument("--mode", default="depth")
    ap.add_argument("--nl", type=int, default=0)
    ap.add_argument("--frames", type=int, default=0, help="use the first n frames of the case (0: all)")
    ap.add_argument("--rb", type=int, default=0)
    ap.add_argument("--qb", type=int, default=0)
    ap.add_argument("--kc", type=int, default=32)
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--reps", type=int, default=1)
    ap.add_argument("--dispatch", default="eth")
    ap.add_argument("--probe", action="store_true")
    ap.add_argument("--colerr", action="store_true")
    ap.add_argument("--resize", type=int, nargs=2, default=None, help="bilinear resize to H W (multiples of 32)")
    ap.add_argument("--tframes", type=int, default=0, help="clip of n frames: repeat the case's frames + noise")
    ap.add_argument("--noref", action="store_true", help="skip the CPU reference (timing runs)")
    ap.add_argument("--det", type=int, default=0, help="rerun n times and compare x / q / k / v / o bitwise")
    ap.add_argument("--prof", action="store_true", help="ME_PROF build: per-phase device time stamps")
    ap.add_argument("--bench", type=int, default=0, help="trace replays to time (full model, nl = L)")
    args = ap.parse_args()
    import ttnn

    gsize = "S" if args.mode == "fov" else args.size
    g = H.load_case(args.case, gsize)
    x = R.pad_to_multiple(g["x_norm"].float())
    if args.frames:
        x = x[:args.frames]
    if args.mode == "fov":
        x = R.fov_resize(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)
        reps = -(-args.tframes // x.shape[0])
        x = x.repeat(reps, 1, 1, 1)[:args.tframes]
        x = x + 0.1 * torch.randn(x.shape, generator=gen)
        x = torch.roll(x, shifts=1, dims=-1) if False else x
    T, _, hp, wp = x.shape
    gh, gw = hp // 16, wp // 16
    w = H.load_weights("fov" if args.mode == "fov" else args.size)
    dev = open_device(args.dispatch, trace=args.bench > 0)
    try:
        t0 = time.perf_counter()
        mk = MkEnc(dev, w, args.size, T, gh, gw, mode=args.mode, rb=args.rb, qb=args.qb, kc=args.kc,
                   fidelity=args.fidelity, probe=args.probe, prof=args.prof)
        geo = mk.geo
        print(geo.summary(), f"init {time.perf_counter() - t0:.1f}s", flush=True)
        patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                  device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        nl = args.nl
        for r in range(args.reps):
            t0 = time.perf_counter()
            mk.run(patches, nl=nl, dump=True)
            ttnn.synchronize_device(dev)
            print(f"run {r}: {1e3 * (time.perf_counter() - t0):.2f} ms", flush=True)
        if args.bench:
            for _ in range(2):
                mk.run(patches, nl=nl, dump=True)
            ttnn.synchronize_device(dev)
            tid = ttnn.begin_trace_capture(dev, cq_id=0)
            mk.run(patches, nl=nl, dump=True)
            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.bench):
                ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
            ttnn.synchronize_device(dev)
            dt = (time.perf_counter() - t0) / args.bench
            print(f"BENCH {geo.summary()} nl={nl}: {1e3 * dt:.3f} ms / run (trace, {args.bench} replays)", flush=True)
            ttnn.release_trace(dev, tid)
        xi = mk.read_x()
        qd, kd, vd, od = (mk.read_stage(n) for n in "qkvo")
        taps0 = [ttnn.to_torch(t).float().reshape(-1, geo.dim) for t in mk.taps]
        for r in range(args.det):
            mk.run(patches, nl=nl, dump=True)
            ttnn.synchronize_device(dev)
            diffs = []
            for n, a in (("x", xi), ("q", qd), ("k", kd), ("v", vd), ("o", od)):
                b = mk.read_x() if n == "x" else mk.read_stage(n)
                if not torch.equal(a, b):
                    d = (a != b).reshape(geo.Mt, 32, -1).any(1).any(-1).nonzero().flatten().tolist()
                    diffs.append(f"{n}: row tiles {d[:12]} ({len(d)}) max|d| {(a - b).abs().max().item():.3e}")
            for i, t in enumerate(mk.taps):
                b = ttnn.to_torch(t).float().reshape(-1, geo.dim)
                a = taps0[i]
                if not torch.equal(a, b):
                    d = (a != b).reshape(-1, 32, geo.dim).any(1).any(-1).nonzero().flatten().tolist()
                    diffs.append(f"tap{i}: tiles {d[:12]} ({len(d)}) max|d| {(a - b).abs().max().item():.3e}")
            print(f"DET rerun {r}: " + ("identical" if not diffs else "; ".join(diffs)), flush=True)
        dtaps = [H.taps_from_device(ttnn.to_torch(t).float(), geo) for t in mk.taps]
        prb = mk.read_probe() if args.probe else None
        if args.prof:
            prof_report(mk.read_prof(), geo, nl)
    finally:
        ttnn.close_device(dev)
    if args.noref:
        return
    for n, d in (("q", qd), ("k", kd), ("v", vd), ("o", od), ("x", xi)):
        bad = ~torch.isfinite(d)
        if bad.any():
            per = bad.reshape(geo.Mt, 32, -1, 64).any(1).any(-1)  # [Mt, heads]
            print(f"  non-finite {n}: {int(bad.sum())} values; row tiles x heads:\n{per.int()}", flush=True)
            print(f"  {n} finite sample row tile 0 head 0: {d[0, :6, :4]}")
    tok, taps = H.ref_run(w, x, args.size, nl, args.mode)
    if prb is not None:
        probe_report(prb, w, x, args, geo, gh, gw)
    print(f"x after {nl} blocks:")
    for i, tp in enumerate(taps):
        gk = f"tap{i}"
        if args.mode == "depth" and gk in g and nl == geo.L and not (args.frames or args.resize or args.tframes):
            report(f"tap{i} gold", dtaps[i], g[gk].float())
        report(f"tap{i} ref", dtaps[i], tp)
    xd = H.from_internal(xi, geo)
    report("x prefix", xd[:, :5], tok[:, :5])
    report("x patches", xd[:, 5:], tok[:, 5:])
    if args.colerr:
        e = (xd[:, 5:] - tok[:, 5:]).abs().reshape(-1, xd.shape[-1] // 32, 32).amax((0, 2))
        r = tok[:, 5:].abs().reshape(-1, xd.shape[-1] // 32, 32).amax((0, 2))
        print("  x patches max|d| per tile column:", [round(v, 3) for v in e.tolist()])
        print("  x patches max|ref| per tile column:", [round(v, 3) for v in r.tolist()])
        pe = (xd[:, 5:] - tok[:, 5:]).abs().amax(-1)[0]
        bad = (pe > 0.1 * tok[:, 5:].abs().amax()).nonzero().flatten()
        print("  bad patch rows:", bad[:40].tolist(), "count", bad.numel())
    if nl < geo.L:
        rq = H.ref_qkv(tok, w, nl, args.size, args.mode, gh, gw)
        joint = args.mode == "depth" and nl in geo.joint
        for n, d in (("q", qd), ("k", kd), ("v", vd)):
            dd = H.from_internal(d, geo)
            report(f"{n} patches", dd[:, 5:], rq[n][:, 5:])
            if not joint:
                report(f"{n} prefix", dd[:, :5], rq[n][:, :5])
        if joint and geo.pool:
            report("pool k", kd[geo.Mt - 1, :5], rq["pool_k"])
            report("pool v", vd[geo.Mt - 1, :5], rq["pool_v"])
    if nl >= 1:
        tin, _ = H.ref_run(w, x, args.size, nl - 1, args.mode)
        ra = H.ref_attn(tin, w, nl - 1, args.size, args.mode, gh, gw)
        oo = H.from_internal(od, geo)
        report("attn patches", oo[:, 5:], ra[:, 5:])
        if not (nl - 1 in geo.freeze):
            report("attn prefix", oo[:, :5], ra[:, :5])


if __name__ == "__main__":
    main()