File size: 11,609 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Staged device bring-up of the GLM-OCR DEC megakernel (tt/mk_dec) against the official fp32 goldens.

    bin/devrun -t 900 --reset-on-timeout -- python -u bundles/glm-ocr/code/tt_glmocr/tests/dev_mk_dec.py \
        --stage noop [--cases line_en] [--recipe attn=bfp8,mlp=bfp8,head=bf16] [--attk 4]

noop  : one launch with STATE done (JIT compile, boot barrier, go word, clean exit)
boot  : F_BOOTONLY launch (boot barrier + go handoff only)
stream: F_ARM_STREAM (the MM weight streams only, TRISC pops pages)
proto : F_NOCOMPUTE (every exchange / CB handshake, no LLK math), 1 layer then 16
layer1: ttnn prefill + one step with K_NL = 1 and F_DUMP (residual after layer 0 vs the CPU reference)
tf1   : ttnn prefill (KV into the DEC KV tensor) + 4 teacher-forced steps: logits vs golden (PCC, top-1, TVD)
tf    : teacher-forced over --tf-steps golden steps of every case (TVD mean / p95, top-1)
gen   : free-running device greedy decode (tokens vs golden), ms / token
bench : traced batches, ms / token (+ the layer-1 phase profile)
Every stage checks the abort words of every core (dbg dump) and stops at the first abort.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np
import torch

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_glmocr import frontend as FE  # noqa: E402
from tt_glmocr import metrics as M  # noqa: E402
from tt_glmocr.reference import model as R  # noqa: E402
from tt_glmocr.tests._paths import ASSETS, MODEL  # noqa: E402


def aborts(tlk, G):
    d = tlk.read_dbg()
    bad = []
    for i in range(d.shape[0]):
        if int(d[i, G.W_ABORT * 4]) == G.ABORT_MAGIC:
            bad.append((i, [int(d[i, (G.W_DBG + k) * 4]) for k in range(6)], int(d[i, G.W_STEP * 4])))
    return bad


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--stage", default="noop")
    ap.add_argument("--cases", default="line_en")
    ap.add_argument("--recipe", default="attn=bfp8,mlp=bfp8,head=bf16")
    ap.add_argument("--attk", type=int, default=4)
    ap.add_argument("--max-pos", type=int, default=2048)
    ap.add_argument("--batch", type=int, default=8)
    ap.add_argument("--spin", type=int, default=1 << 22)
    ap.add_argument("--tf-steps", type=int, default=64)
    ap.add_argument("--tag", default="")
    args = ap.parse_args()
    import ttnn
    from tt_glmocr.ttaw.device import open_device, close_device
    from tt_glmocr.tt.mk_dec import geometry as G
    from tt_glmocr.tt.mk_dec.engine import MkDecoder
    from tt_glmocr.tt.ttnn_vision import TtnnVision, default_buckets

    recipe = dict(kv.split("=") for kv in args.recipe.split(",") if kv)
    entries = {e["name"]: e for e in json.load(open(os.path.join(ASSETS, "images.json")))}
    tok = FE.Tokenizer(MODEL)
    cases = []
    for n in args.cases.split(","):
        g = json.load(open(os.path.join(ASSETS, "golden", n, "gen_fp32.json")))
        img = FE.preprocess(os.path.join(ASSETS, entries[n]["file"]))
        pr = FE.build_prompt(tok, entries[n]["prompt"], img)
        cases.append((n, img, pr, g))
    need_pre = args.stage not in ("noop", "boot", "stream", "proto")
    W = R.Weights(MODEL, torch.bfloat16)
    pb = sorted({max(128, -(-pr.L // 128) * 128) for _, _, pr, _ in cases})
    res = {"stage": args.stage, "recipe": recipe, "attk": args.attk, "cases": {}}
    log = lambda s: print(s, flush=True)  # noqa: E731
    dev = open_device(0, dispatch="eth", trace_region_size=256 << 20)
    try:
        t0 = time.time()
        mk = MkDecoder(dev, W, pb, args.max_pos, recipe=recipe, batch=args.batch, attk=args.attk, log=log)
        tlk = mk.tlk
        log(f"engine {time.time() - t0:.1f}s geometry mm={[m.xy for m in tlk.geo.mm][:4]}.. att={tlk.geo.att} "
            f"hub={tlk.geo.hub}")
        V = None
        if need_pre:
            vb_all = default_buckets()
            vb = sorted({next(b for b in vb_all if b >= img.n_patches) for _, img, _, _ in cases})
            V = TtnnVision(dev, W, vb)

        def launch(flags=0, nl=G.N_LAYERS_FULL, stop=0):
            t = time.time()
            tlk.run(n_layers=nl, flags=flags, spin=args.spin, stop=stop)
            ttnn.synchronize_device(dev)
            return time.time() - t

        if args.stage == "noop":
            tlk.write_state(tlk.state_host(1, 59253, 1, done=True))
            dt = launch()
            res["noop_s"] = dt
            res["noop_aborts"] = aborts(tlk, G)
            log(f"noop launch {dt:.2f}s; aborts {res['noop_aborts']}")
        elif args.stage in ("boot", "stream", "proto"):
            L = 100
            for nl in ((1, G.N_LAYERS_FULL) if args.stage == "proto" else (G.N_LAYERS_FULL,)):
                tlk.write_state(tlk.state_host(L, 10, 4, delta=-20))
                fl = {"boot": G.F_BOOTONLY, "stream": G.F_ARM_STREAM, "proto": G.F_NOCOMPUTE}[args.stage]
                dt = launch(flags=fl, nl=nl)
                ab = aborts(tlk, G)
                res[f"{args.stage}_nl{nl}_s"] = dt
                res[f"{args.stage}_nl{nl}_aborts"] = ab
                log(f"{args.stage} nl={nl}: {dt:.3f}s aborts {ab}")
                if ab:
                    break
                if args.stage == "stream":
                    ts = []
                    for _ in range(5):
                        tlk.write_state(tlk.state_host(L, 10, 4, delta=-20))
                        ts.append(launch(flags=fl, nl=nl))
                    res["stream_ms"] = 1000 * min(ts)
                    log(f"stream-only step {1000 * min(ts):.2f} ms (eager, host timed)")
        else:
            for n, img, pr, g in cases:
                r = res["cases"].setdefault(n, {"L": pr.L})
                y, nt, _ = V.run(img.patches, img.grid_h, img.grid_w)
                emb = ttnn.to_torch(y).reshape(-1, R.T_D)[:nt]
                rows = W["model.language_model.embed_tokens.weight"][torch.tensor(pr.ids)].clone()
                rows[pr.image_start:pr.image_start + pr.n_image] = emb.to(rows.dtype)
                lg0 = mk.prefill(rows, torch.from_numpy(pr.pos3d), pr.L)
                ref = torch.load(os.path.join(ASSETS, "golden", n, "logits_fp32.pt"), weights_only=True)
                toks = g["tokens"]
                if args.stage == "layer1":
                    tlk.write_state(tlk.state_host(pr.L, toks[0], 1 << 20, ntok=1, delta=pr.rope_delta))
                    launch(flags=G.F_DUMP | G.F_NOSAMPLE, nl=1)
                    ab = aborts(tlk, G)
                    lg = ttnn.to_torch(tlk.logits).float()
                    x = torch.cat([lg[w, :64] for w in range(G.NW)])[:R.T_D]
                    # CPU: layer 0 on the prompt + token 0 (fp32 reference) -> residual of the last row
                    Wf = R.Weights(MODEL, torch.float32)
                    dec = R.Decoder(Wf)
                    allrows = torch.cat([rows.float(), Wf["model.language_model.embed_tokens.weight"][toks[0]][None]])
                    pos = np.concatenate([pr.pos3d, np.full((3, 1), pr.L + pr.rope_delta)], 1)
                    st = {}
                    dec.forward(allrows, torch.from_numpy(pos), st)
                    ref0 = st["t_layer0"][-1]
                    r["layer1_pcc"] = M.pcc(x, ref0)
                    r["layer1_maxabs"] = float((x - ref0).abs().max())
                    r["aborts"] = ab
                    log(f"{n} layer1 PCC {r['layer1_pcc']:.6f} maxabs {r['layer1_maxabs']:.4f} aborts {ab}")
                    continue
                ns = 4 if args.stage == "tf1" else min(args.tf_steps, len(toks))
                if args.stage in ("tf1", "tf"):
                    out = [lg0]
                    for s in range(1, ns):
                        out.append(mk.tf_step(pr.L, s, toks[s - 1], pr.rope_delta))
                        ab = aborts(tlk, G)
                        if ab:
                            log(f"ABORT at step {s}: {ab}")
                            r["aborts"] = ab
                            break
                    lg = torch.stack(out)
                    tv, t1 = M.tvd_vs_pack(lg, ref, lg.shape[0])
                    full = ref["full16"].float()
                    pc = [M.pcc(lg[s], full[s]) for s in range(min(lg.shape[0], full.shape[0]))]
                    s_ = M.summarize(tv)
                    r.update({"tf_steps": lg.shape[0], "tf_tvd_mean": s_["mean"], "tf_tvd_p95": s_["p95"],
                              "tf_tvd_max": s_["max"], "tf_top1": sum(t1) / len(t1), "logits_pcc_min": min(pc)})
                    log(f"{n} TF {json.dumps({k: v for k, v in r.items() if k.startswith(('tf', 'logits'))})}")
                if args.stage in ("gen", "bench"):
                    maxnew = len(toks) + 8
                    tok0 = int(torch.argmax(lg0))
                    mk.start(pr.L, tok0, maxnew, pr.rope_delta)
                    t = time.time()
                    while True:
                        mk.run_batch()
                        ntok, done, stop, ring = mk.poll()
                        if done or ntok >= maxnew:
                            break
                    dt = time.time() - t
                    got = [int(ring[i % G.S_TOKENS_MAX]) for i in range(ntok)]
                    ab = aborts(tlk, G)
                    r.update({"gen_n": ntok, "gen_stop": stop, "gen_equal": got == toks,
                              "gen_first_diff": next((i for i, (a, b) in enumerate(zip(got, toks)) if a != b), None),
                              "gen_ms_per_tok": 1000 * dt / max(1, ntok - 1), "aborts": ab,
                              "text": tok.decode(got), "cer": M.cer(tok.decode(got), g["text"])})
                    log(f"{n} GEN n={ntok} stop={stop} equal={got == toks} first_diff={r['gen_first_diff']} "
                        f"{r['gen_ms_per_tok']:.2f} ms/tok (eager batches) cer={r['cer']:.4f} aborts={ab}")
                    if args.stage == "bench":
                        mk.capture(prefill=False)
                        top = args.max_pos - 2 * args.batch * 6
                        for ctx in sorted({pr.L, min(top, 1024), min(top, 2048), top}):
                            # no stop token (a garbage context must not hit EOS and turn launches into no-ops)
                            mk.start(ctx, tok0, 1 << 20, pr.rope_delta, eos=(0xFFFFFFF0, 0xFFFFFFF1))
                            mk.run_batch()
                            ttnn.synchronize_device(dev)
                            t = time.perf_counter()
                            for _ in range(5):
                                mk.run_batch()
                            ttnn.synchronize_device(dev)
                            ms = 1000 * (time.perf_counter() - t) / (5 * args.batch)
                            r[f"bench_ms_ctx{ctx}"] = ms
                            log(f"{n} bench ctx {ctx}: {ms:.3f} ms/token (traced, {args.batch} launches/trace)")
                        r["prof"] = tlk.read_prof()
                        log(f"prof {json.dumps(r['prof'])}")
                        mk.release()
    finally:
        close_device(dev)
    os.makedirs(os.path.join(ASSETS, "runs"), exist_ok=True)
    json.dump(res, open(os.path.join(ASSETS, "runs", f"mk_{args.stage}{args.tag}.json"), "w"), indent=1,
              ensure_ascii=False, default=str)
    bad = any(v for k, v in res.items() if k.endswith("aborts")) or any(c.get("aborts") for c in res["cases"].values())
    if bad:
        print("RESULT: ABORTS", flush=True)
        sys.exit(3)
    print("RESULT: OK", flush=True)


if __name__ == "__main__":
    main()