File size: 14,389 Bytes
9b1a077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
260
# SPDX-License-Identifier: Apache-2.0
"""Staged device bring-up of the DEC-MoE megakernel (tt/mk_moe) against the CPU reference / official goldens.

    bin/devrun -t 900 --reset-on-timeout -- python -u common/dsocr/tt_dsocr/tests/dev_mk_moe.py --stage noop

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 incl. the segmented expert gathers with ids 0..5; TRISC pops pages)
proto  : F_NOCOMPUTE (every exchange / CB handshake incl. the router and the routing record, no LLK math), 1 layer, 12
layer1 : ttnn prefill (KV) + one step with K_NL = 1 and F_DUMP: residual after layer 0 vs the CPU reference
layer2 : K_NL = 2, F_DUMP + F_ROUTE_LOG: residual after layer 1 (the first MoE layer) and its routing vs the reference
tf1    : ttnn prefill + 4 teacher-forced steps: logits vs golden (PCC, top-1, TVD)
tf     : teacher-forced over --tf-steps golden steps (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 torch

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr.reference import model as R  # noqa: E402
from tt_dsocr.tests._paths import GOLDEN, MODELS, RUNS  # noqa: E402


def pcc(a, b):
    a, b = a.double().flatten(), b.double().flatten()
    a, b = a - a.mean(), b - b.mean()
    return float((a @ b) / (a.norm() * b.norm() + 1e-30))


def tvd_top(logits, top_v, top_i, lse) -> float:
    p = torch.softmax(logits.float(), -1)
    gp = (top_v.float() - lse.float()).exp()
    gi = top_i.long()
    return 0.5 * float((p[gi] - gp).abs().sum() + ((1 - p[gi].sum()) - (1 - gp.sum())).abs())


def _arm_faulthandler():
    """Dump the Python stacks on a fatal signal (SIGSEGV / SIGABRT / ...; devrun's timeout kill shows where a job was).
    No periodic watchdog: ``faulthandler.dump_traceback_later(repeat=True)`` segfaults Python 3.12 when it fires while
    the main thread switches generators (the verifier's report, 2026-12-02), so the former DSOCR_FAULT_S is gone; use
    pytest's ``-o faulthandler_timeout`` or ``python -u`` progress prints instead."""
    import faulthandler

    faulthandler.enable(file=sys.stderr)


def main():
    _arm_faulthandler()
    ap = argparse.ArgumentParser()
    ap.add_argument("--stage", default="noop")
    ap.add_argument("--variant", default="deepseek-ocr")
    ap.add_argument("--cases", default="formula_quad__tiny")
    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=1)  # 1: one synchronized launch per poll (FAULTS #1)
    ap.add_argument("--spin", type=int, default=1 << 22)
    ap.add_argument("--tf-steps", type=int, default=64)
    ap.add_argument("--force-route", action="store_true", help="TF stages: golden routing (F_FORCE_ROUTE)")
    ap.add_argument("--tag", default="")
    args = ap.parse_args()
    import ttnn
    from tt_dsocr.ttaw.device import open_device, close_device
    from tt_dsocr.tt.mk_moe import geometry as G

    recipe = dict(kv.split("=") for kv in args.recipe.split(",") if kv)
    gdir = GOLDEN[args.variant]
    cases = []
    for c in args.cases.split(","):
        d = os.path.join(gdir, c)
        cases.append((c, json.load(open(os.path.join(d, "meta.json"))),
                      torch.load(os.path.join(d, "tensors.pt"), weights_only=True),
                      torch.load(os.path.join(d, "steps.pt"), weights_only=True),
                      torch.load(os.path.join(d, "ref_step0.pt"), weights_only=True)
                      if os.path.exists(os.path.join(d, "ref_step0.pt")) else None))
    need_pre = args.stage not in ("noop", "boot", "stream", "proto")  # a comma list of later stages runs in order
    W = R.Weights(MODELS[args.variant])
    log = lambda s: print(s, flush=True)  # noqa: E731
    res = {"stage": args.stage, "recipe": recipe, "attk": args.attk, "cases": {}}
    dev = open_device(0, dispatch="eth", trace_region_size=256 << 20, worker_l1_size=1461248 - (64 << 10))
    try:
        if need_pre:
            from tt_dsocr.tt.mk_moe.engine import MkDecoder

            Ls = [m["n_prompt"] for _, m, _, _, _ in cases]
            buckets = sorted({max(128, -(-L // 128) * 128) for L in Ls})
            eng = MkDecoder(dev, W, buckets, args.max_pos, recipe=recipe, batch=args.batch, attk=args.attk, log=log)
            tlk = eng.tlk
        else:
            from tt_dsocr.tt.mk_moe.program import DecMoE

            eng = None
            tlk = DecMoE(dev, W, recipe, max_pos=args.max_pos, attk=args.attk, log=log,
                         dummy_arena=os.environ.get("DSOCR_MK_DUMMY", "0") == "1")
        log(f"[mk] geometry: MM {[(m.w, m.xy, m.bank, m.noc, m.xn) for m in tlk.geo.mm]}, ATT {tlk.geo.att[:4]}.., "
            f"hub {tlk.geo.hub}, routers {tlk.geo.rt} (banks {tlk.geo.rt_bank})")

        def check(tag):
            ttnn.synchronize_device(dev)
            bad = tlk.aborts()
            if bad:
                log(f"[mk] {tag}: ABORTS on {len(bad)} cores, first {bad[:6]}")
                res["aborts"] = bad[:32]
                raise SystemExit(3)
            log(f"[mk] {tag}: no aborts")

        st = args.stage
        stages = [x for x in args.stage.split(",") if x]
        if st in ("noop", "boot", "stream", "proto"):
            flags = {"noop": 0, "boot": G.F_BOOTONLY, "stream": G.F_ARM_STREAM, "proto": G.F_NOCOMPUTE}[st]
            L = 100
            nls = [int(x) for x in os.environ.get("DSOCR_MK_NLS", "").split(",") if x] or (
                [1, 12] if st == "proto" else [12])
            for nl in nls:
                done = st == "noop"
                tlk.write_state(tlk.state_host(L, 5, 64, done=done))
                t0 = time.time()
                tlk.run(n_layers=nl, flags=flags, spin=args.spin)
                check(f"{st} nl={nl}")
                dt = time.time() - t0
                ts = []
                for _ in range(4):  # one launch at a time, synchronized (back-to-back launches: see FAULTS #1)
                    tlk.write_state(tlk.state_host(L, 5, 64, done=done))
                    t1 = time.time()
                    tlk.run(n_layers=nl, flags=flags, spin=args.spin)
                    ttnn.synchronize_device(dev)
                    ts.append(time.time() - t1)
                    check(f"{st} nl={nl} again")
                res[f"{st}_nl{nl}"] = {"first_s": dt, "eager_ms": min(ts) * 1e3}
                log(f"[mk] {st} nl={nl}: first {dt:.2f} s, eager {min(ts) * 1e3:.2f} ms / launch (synchronized)")
            return
        embed = W.get("model.embed_tokens.weight")
        for name, meta, gt, gs, ref in cases:
            r = {}
            ids, L, gen = meta["input_ids"], meta["n_prompt"], meta["gen_ids"]
            rows = embed[torch.tensor(ids)].clone()
            rows[gt["seq_mask"]] = gt["img_emb"]
            lg0 = eng.prefill(rows, L)
            r["prefill_top1"] = int(lg0.argmax()) == gen[0]
            log(f"[{name}] prefill: top1 {int(lg0.argmax())} vs golden {gen[0]}, pcc {pcc(lg0, gs['logits16'][0]):.5f}")
            for st in stages:
                if st in ("layer1", "layer2"):
                    nl = 1 if st == "layer1" else 2
                    xin = W.get("model.embed_tokens.weight")[gen[0]]
                    for tag, extra in (("x0 only", G.F_DBG_NO_ATT | G.F_DBG_NO_MLP), ("x0 + attention", G.F_DBG_NO_MLP),
                                       ("x0 + mlp(x0)", G.F_DBG_NO_ATT)):
                        if nl != 1:
                            break
                        tlk.write_state(tlk.state_host(L, gen[0], 1 << 20, ntok=1))
                        tlk.run(n_layers=nl, flags=G.F_DUMP | G.F_NOSAMPLE | extra, spin=args.spin)
                        check(f"{st} {tag}")
                        raw = ttnn.to_torch(tlk.logits).float().reshape(G.NW, -1)
                        x = torch.zeros(1280)
                        for m in tlk.geo.mm:
                            x[m.xoff * 32:(m.xoff + m.xn) * 32] = raw[m.w, :m.xn * 32]
                        exp_ = None
                        if tag == "x0 only":
                            exp_ = xin
                        elif tag == "x0 + attention" and ref is not None and "attn0" in ref:
                            exp_ = xin + ref["attn0"]
                        elif tag == "x0 + mlp(x0)":
                            p0 = "model.layers.0."
                            hh = R.rms_norm(xin[None], W.get(p0 + "post_attention_layernorm.weight"))[0]
                            gg = torch.nn.functional.linear(hh, W.get(p0 + "mlp.gate_proj.weight"))
                            uu = torch.nn.functional.linear(hh, W.get(p0 + "mlp.up_proj.weight"))
                            exp_ = xin + torch.nn.functional.linear(torch.nn.functional.silu(gg) * uu,
                                                                    W.get(p0 + "mlp.down_proj.weight"))
                        if exp_ is not None:
                            log(f"[{name}] {st} {tag}: PCC {pcc(x, exp_):.6f} max|err| {float((x - exp_).abs().max()):.4f}")
                        else:
                            log(f"[{name}] {st} {tag}: |x| max {float(x.abs().max()):.4f}, x[:6] {x[:6].tolist()}")
                    tlk.write_state(tlk.state_host(L, gen[0], 1 << 20, ntok=1))
                    tlk.run(n_layers=nl, flags=G.F_DUMP | G.F_NOSAMPLE | G.F_ROUTE_LOG, spin=args.spin)
                    check(st)
                    raw = ttnn.to_torch(tlk.logits).float().reshape(G.NW, -1)
                    x = torch.zeros(1280)
                    for m in tlk.geo.mm:
                        x[m.xoff * 32:(m.xoff + m.xn) * 32] = raw[m.w, :m.xn * 32]
                    if ref is not None:
                        xr = ref["res"][nl - 1]
                        r["dump_pcc"] = pcc(x, xr)
                        r["dump_maxerr"] = float((x - xr).abs().max())
                        log(f"[{name}] {st}: residual after layer {nl - 1}: PCC {r['dump_pcc']:.6f}, max|err| "
                            f"{r['dump_maxerr']:.4f} (|x| max {float(xr.abs().max()):.3f})")
                        if nl == 2:
                            ids_d, w_d = tlk.read_routes()
                            r["route_dev"] = ids_d[1].tolist()
                            r["route_ref"] = ref["route_ids"][0].tolist()
                            log(f"[{name}] layer 1 routing: device {sorted(ids_d[1].tolist())} w {w_d[1].round(4)}; ref "
                                f"{sorted(ref['route_ids'][0].tolist())} w {ref['route_w'][0].numpy().round(4)}")
                    res["cases"][name] = r
                if st in ("tf1", "tf"):
                    T = min(4 if st == "tf1" else args.tf_steps, len(gen))
                    tv, t1 = [], 0
                    flags = 0
                    if args.force_route:
                        flags = G.F_FORCE_ROUTE
                    t0 = time.time()
                    for s in range(1, T):
                        if args.force_route:
                            rid = gt["dec_route_ids"][:, s - 1].long()
                            rw = gt["dec_route_w"][:, s - 1].float()
                            tlk.write_forced_routes(torch.cat([torch.zeros(1, 6, dtype=torch.long), rid]),
                                                    torch.cat([torch.zeros(1, 6), rw]))
                        l = eng.tf_step(L, s, gen[s - 1], flags)
                        tv.append(tvd_top(l, gs["top_v"][s], gs["top_i"][s], gs["lse"][s]))
                        t1 += int(int(l.argmax()) == int(gs["top_i"][s][0]))
                        if s <= 3:
                            log(f"[{name}] TF step {s}: top1 {int(l.argmax())} vs {int(gs['top_i'][s][0])}, TVD {tv[-1]:.5f}"
                                + (f", pcc16 {pcc(l, gs['logits16'][s]):.5f}" if s < 16 else ""))
                    check(st)
                    tvs = torch.tensor(tv)
                    r.update(tf_steps=len(tv), tf_tvd_mean=float(tvs.mean()), tf_tvd_p95=float(tvs.quantile(0.95)),
                             tf_tvd_max=float(tvs.max()), tf_top1=t1 / len(tv), eager_ms=(time.time() - t0) * 1e3 / len(tv))
                    log(f"[{name}] TF {len(tv)} steps: TVD mean {r['tf_tvd_mean']:.5f} p95 {r['tf_tvd_p95']:.5f} max "
                        f"{r['tf_tvd_max']:.4f}, top-1 {r['tf_top1']:.4f}")
                if st in ("gen", "bench"):
                    if st == "bench" and eng.trace is None:
                        eng.capture(prefill=False)
                    eng.start(L, gen[0], min(len(gen) + 8, 4096))
                    t0 = time.time()
                    n, done = 1, False
                    while not done:
                        eng.run_batch()
                        n, done, stop, ring = eng.poll()
                    dt = time.time() - t0
                    check(st)
                    out = [int(ring[i % G.S_TOKENS_MAX]) for i in range(n)]
                    same = 0
                    while same < min(len(out), len(gen)) and out[same] == gen[same]:
                        same += 1
                    r.update(gen_tokens=n, ms_per_token=1e3 * dt / max(1, n - 1), prefix_match=same,
                             identical=out == gen)
                    log(f"[{name}] {st}: {n} tokens ({'traced' if eng.trace else 'eager'}) {r['ms_per_token']:.2f} ms / "
                        f"token, identical {out == gen}, first {same} match (stop {stop})")
                    if st == "bench":
                        r["prof"] = tlk.read_prof()
                        log(f"[{name}] layer-1 profile (us): {r['prof']}")
            res["cases"][name] = r
    finally:
        os.makedirs(RUNS, exist_ok=True)
        json.dump(res, open(os.path.join(RUNS, f"mk_{args.stage.replace(',', '+')}_{args.tag or 'run'}.json"), "w"), indent=1,
                  default=str)
        close_device(dev)


if __name__ == "__main__":
    main()