File size: 17,273 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# SPDX-License-Identifier: Apache-2.0
"""Accuracy gates G2-G6 of research/laya/SPEC.md on the device (ONE device process; through the device lock):

    bin/devrun -t 1800 -- python -u code/scripts/eval_gates.py --engine mk --profile english --out gates.json

Every golden case of the profile (assets/laya/golden/<profile>/, or --gold DIR) runs through the engine; the
probabilities (temperature-scaled, unrounded) and top answers are compared with the official fp32 outputs, next to
the official bf16 emulation's (the budget).  G5 replays one launch 100 times; G6 runs one row alone and inside a full
launch.  Exit 0 when every gate passes, 1 otherwise.

``--slots`` adds G7, batch-slot invariance (no goldens needed; ``--slots-only`` skips G2-G6): every slot of every
batch size against the same row run alone.
- tt-nn path (the engine of rows > 512 tokens, or every row with LAYA_ENGINE=ttnn): every bucket of ``--slot-seqs``
  (default 1024, the served long bucket) x ``--slot-batches``: B distinct rows (distinct states and questions, padded
  inside the bucket) in one call, forward and reversed; every slot within ``--slot-tol`` (0.02) logits of its row
  alone.
- megakernel (``--engine mk``): rows packed into one launch at every position (rotations), 8 and 16 rows; every slot
  within 0.03 in probability of its row alone (a packed row's logits move by up to a few times the bf16 drift with its
  start offset, documented). An answer may change only on a near-tie of the row alone (top-1 minus top-2 < 0.06 =
  twice the probability tolerance); every change is listed with that gap.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
ROOT = os.path.abspath(os.path.join(HERE, "..", "..", "..", ".."))


def top(p: np.ndarray, t: str):
    return bool(p[1] >= 0.5) if t == "noul" else int(np.argmax(p))


class _Done(Exception):
    pass


SLOT_TEXT = ("Ticket {i}. The customer writes that the invoice for workspace {i} was charged twice this month, that "
             "the support portal returned an error when they tried to download the receipt, and that the team needs "
             "a refund and a corrected invoice before the end of the quarter or they will move to another vendor. ")
SLOT_QUESTIONS = [
    ("choice", "Which department should handle this request?", {"billing": "invoices, refunds", "technical": "bugs",
                                                                "sales": "pricing", "other": None}),
    ("score", "How urgent is this request?", ["not urgent", "soon", "today", "blocking"]),
    ("noul", "Does the customer threaten to cancel?", None),
    ("noul", "Does the customer ask for a refund?", None),
    ("choice", "What is the main topic?", ["payment", "outage", "account", "feature request", "other"]),
    ("score", "How angry is the customer?", ["calm", "annoyed", "angry"]),
    ("noul", "Does the message contain personal data?", None),
    ("choice", "Which product area is affected?", {"billing": None, "portal": None, "api": None}),
]


def _slot_questions(n):
    """n distinct questions (the base set, with a numbered variant of the instruction past 8)."""
    out = {}
    for j in range(n):
        t, ins, crit = SLOT_QUESTIONS[j % len(SLOT_QUESTIONS)]
        q = {"type": t, "instructions": ins if j < len(SLOT_QUESTIONS) else "%s (check %d)" % (ins, j)}
        if crit is not None:
            q["criteria"] = crit
        out["q%02d" % j] = q
    return out


def slot_gates(a, eng, dev, sd, ck, tok, cal, g):
    """G7: every slot of every batch size vs its row alone (see the module docstring)."""
    from tt_laya import decode as Dc
    from tt_laya import text as T

    res = {}
    ok = True
    if dev is not None:
        # the tt-nn long-row engine as served for rows > 512 tokens (bucket length 1024)
        from tt_laya.tt.ttnn_engine import TtnnEngine

        from tt_laya.tt.ttnn_engine import sdpa_key_chunk

        batches = tuple(int(b) for b in a.slot_batches.split(",") if b)
        seqs = sorted(int(x) for x in a.slot_seqs.split(",") if x)
        long_eng = TtnnEngine(dev, sd, ck.arch, fidelity=a.fidelity, batch_buckets=(1,) + batches,
                              seq_buckets=tuple(seqs))
        long_eng.pad_id = tok.pad_id
        nmax = max(batches)
        qs = T.normalise_questions(_slot_questions(nmax))
        worst_all = 0.0
        for si, S in enumerate(seqs):
            lo = (seqs[si - 1] if si else (512 if S > 512 else S // 2)) + 8
            rows = []
            for j, q in enumerate(qs):     # distinct states of lo .. S tokens (padded inside the bucket)
                target = lo + (j * 167) % max(1, S - lo + 1)
                st, k = "", 1
                while True:
                    st = "".join(SLOT_TEXT.format(i=i) for i in range(k))
                    r = T.build_rows(tok, st, [q], S, ck.head_max_len)[0]
                    if len(r.ids) >= target or len(r.ids) >= S:
                        break
                    k += 1
                rows.append(r)
            alone = [long_eng.run([r])[0][0] for r in rows]
            print("G7 tt-nn bucket %d: rows of %d..%d tokens, SDPA key chunk %d" % (
                S, min(len(r.ids) for r in rows), max(len(r.ids) for r in rows), sdpa_key_chunk(S)), flush=True)
            for b in batches:
                for order in ("fwd", "rev"):
                    idx = list(range(b)) if order == "fwd" else list(range(b))[::-1]
                    lg, _ = long_eng.run([rows[i] for i in idx])
                    d = [float(np.abs(lg[s] - alone[i]).max()) for s, i in enumerate(idx)]
                    worst = max(d)
                    worst_all = max(worst_all, worst)
                    bad = [s for s, x in enumerate(d) if x > a.slot_tol]
                    res["ttnn_%dx%d_%s" % (b, S, order)] = {"max_dlogit": worst, "bad_slots": bad,
                                                             "per_slot": [round(x, 4) for x in d]}
                    ok &= not bad
                    print("G7 tt-nn %2d x %d %s: max |dlogit| vs alone %.4f  bad slots %s" % (b, S, order, worst, bad),
                          flush=True)
        long_eng.close()
        g["G7_ttnn_max_dlogit"] = worst_all
    if a.engine == "mk":
        # megakernel: every position of a packed launch (rotations of 8 and 16 short rows)
        qs = T.normalise_questions(_slot_questions(16))
        rows = [T.build_rows(tok, "".join(SLOT_TEXT.format(i=i) for i in range(1 + j % 3)), [q], ck.max_len,
                             ck.head_max_len)[0] for j, q in enumerate(qs)]
        alone = [eng.run([r])[0][0] for r in rows]
        worst_dp = worst_dl = 0.0
        flips, real_flips = [], []
        for n in (8, 16):
            for rot in range(n):
                idx = [(rot + s) % n for s in range(n)]
                lg, _ = eng.run([rows[i] for i in idx])
                for s, i in enumerate(idx):
                    q, r = qs[i], rows[i]
                    sc = cal.scale(q.qtype, len(r.markers))
                    pa, pp = Dc.probs(alone[i], sc, q.order), Dc.probs(lg[s], sc, q.order)
                    worst_dp = max(worst_dp, float(np.abs(pa - pp).max()))
                    worst_dl = max(worst_dl, float(np.abs(alone[i] - lg[s]).max()))
                    srt = np.sort(pa)[::-1]
                    gap = float(srt[0] - srt[1]) if len(srt) > 1 else 1.0
                    if top(pa, q.t) != top(pp, q.t):
                        flips.append((n, rot, s, q.qid, round(gap, 4)))
                        if gap >= 0.06:
                            real_flips.append((n, rot, s, q.qid, round(gap, 4)))
        mk_ok = worst_dp <= 0.03 and not real_flips
        ok &= mk_ok
        res["mk_rotations"] = {"max_dp": worst_dp, "max_dlogit": worst_dl, "near_tie_changes": flips,
                               "non_tie_changes": real_flips, "rows": [8, 16]}
        g["G7_mk_max_dp"] = worst_dp
        print("G7 megakernel rotations (8, 16 rows, every position): max |dp| vs alone %.4f, max |dlogit| %.4f, "
              "answer changes %d (all near-ties: %s; gaps %s)" % (worst_dp, worst_dl, len(flips), not real_flips,
                                                                 sorted({f[-1] for f in flips})), flush=True)
    g["G7_slots"] = res
    g["G7"] = bool(ok)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--engine", default="mk", choices=("mk", "ttnn", "cpu"))
    ap.add_argument("--profile", default="english")
    ap.add_argument("--gold", default="")
    ap.add_argument("--weights", default="")
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--replays", type=int, default=100)
    ap.add_argument("--max-len", type=int, default=512, help="skip cases with a longer row (the other engine)")
    ap.add_argument("--min-len", type=int, default=0, help="only cases with a row longer than this (long contexts)")
    ap.add_argument("--out", default="")
    ap.add_argument("--slots", action="store_true", help="add G7: every slot of every batch size vs the row alone")
    ap.add_argument("--slots-only", action="store_true", help="G7 only (no golden cases)")
    ap.add_argument("--slot-batches", default="2,4,8,16,32", help="tt-nn long-row batch sizes for G7")
    ap.add_argument("--slot-seqs", default="1024", help="tt-nn sequence buckets for G7 (e.g. 1024,1216 for "
                                                         "LAYA_MAX_LEN=1216; 160,192 for LAYA_SEQ_BUCKETS)")
    ap.add_argument("--slot-tol", type=float, default=0.02, help="G7 tt-nn: max |dlogit| of a slot vs its row alone")
    a = ap.parse_args()
    if a.slots_only:
        a.slots = True

    import torch

    torch.set_num_threads(2)
    from tt_laya import decode as Dc
    from tt_laya import text as T
    from tt_laya import weights as Wt

    gd = a.gold or os.path.join(ROOT, "assets", "laya", "golden", a.profile)
    wdir = a.weights or os.path.join(ROOT, "assets", "laya", "ckpt", a.profile)
    ck = Wt.load_checkpoint(a.profile, root=wdir)
    tok = T.Tokenizer(os.path.join(ck.path, "tokenizer"))
    sd = Wt.load_state_dict(ck)
    cal = Dc.Calibration(ck.cfg["temperature"], ck.cfg.get("temperature_by_options"))
    cases = sorted(f[:-5] for f in os.listdir(gd) if f.endswith(".json") and not f.startswith("_"))
    dev = None
    if a.engine == "cpu":
        from tt_laya.api import CpuEngine

        eng = CpuEngine(sd, ck.arch)
    else:
        from tt_laya.device import open_device

        dev = open_device()
        if a.engine == "mk":
            from tt_laya.tt.mk.engine import MkEngine

            eng = MkEngine(dev, sd, ck.arch, fidelity=a.fidelity, pad_id=tok.pad_id, spin=1 << 22)
        else:
            from tt_laya.tt.ttnn_engine import TtnnEngine

            seq = tuple(s for s in (64, 128, 256, 512, 1024, 2048, 4096, 8192) if s < 2 * max(a.max_len, 64))
            eng = TtnnEngine(dev, sd, ck.arch, fidelity=a.fidelity, seq_buckets=seq)
            eng.pad_id = tok.pad_id
    rep = {"engine": a.engine, "profile": a.profile, "fidelity": a.fidelity, "cases": {}}
    if a.slots_only:
        cases = []
    dp_dev, dp_bf, flips_dev, flips_bf, n_ans = [], [], 0, 0, 0
    gate_mismatch, gate_mismatch_bf, worst = [], [], []
    try:
        for cid in cases:
            doc = json.load(open(os.path.join(gd, cid + ".json")))
            z = np.load(os.path.join(gd, cid + ".npz"))
            kw = doc["kwargs"]
            ml = kw.get("max_len", ck.max_len)
            qs = T.normalise_questions(doc["questions"])
            rows = T.build_rows(tok, doc["state"], qs, ml, kw.get("head_max_len", ck.head_max_len))
            longest = max(len(r.ids) for r in rows)
            if longest > a.max_len or longest <= a.min_len:   # rows the engine does not take / not the selection
                continue
            t0 = time.perf_counter()
            L, A = eng.run(rows)
            ms = (time.perf_counter() - t0) * 1e3
            if hasattr(eng, "read_debug") and eng.read_debug()["aborted"]:
                print("ABORT in", cid, eng.read_debug()["aborted"][:3], flush=True)
                rep["aborted"] = cid
                break
            case = {"ms": ms, "dlogit": [], "drift": []}
            for i, (q, r) in enumerate(zip(qs, rows)):
                K = len(r.markers)
                s = cal.scale(q.qtype, K)
                p32 = Dc.probs(z["logits_fp32"][i, :K], s, q.order)
                pbf = Dc.probs(z["logits_bf16"][i, :K], s, q.order)
                pdv = Dc.probs(L[i], s, q.order)
                dp_dev.append(np.abs(pdv - p32))
                dp_bf.append(np.abs(pbf - p32))
                n_ans += 1
                f_dev = top(pdv, q.t) != top(p32, q.t)
                f_bf = top(pbf, q.t) != top(p32, q.t)
                flips_dev += f_dev
                flips_bf += f_bf
                if f_dev:
                    worst.append({"case": cid, "q": q.qid, "p32": p32.round(4).tolist(), "dev": pdv.round(4).tolist(),
                                  "bf16": pbf.round(4).tolist()})
                case["dlogit"].append(float(np.abs(L[i] - z["logits_fp32"][i, :K]).max()))
                case["drift"].append(float(np.abs(z["logits_bf16"][i, :K] - z["logits_fp32"][i, :K]).max()))
            mc = kw.get("min_confidence")
            if mc is not None:
                for name, logits, acts in (("dev", L, [x[0] for x in A]),
                                           ("bf16", [z["logits_bf16"][i, :len(r.markers)] for i, r in enumerate(rows)],
                                            [x[0] for x in z["act_bf16"]])):
                    res = Dc.result(qs, rows, logits, [float(v) for v in acts], cal)
                    Dc.apply_gate([res], Dc.check_min_confidence(mc))
                    off = doc["official_fp32"]["answers"]
                    for qid in off:
                        if res["answers"][qid].get("abstention") != off[qid].get("abstention"):
                            (gate_mismatch if name == "dev" else gate_mismatch_bf).append((cid, qid))
            rep["cases"][cid] = case
            print("%-22s rows %d  max|dlogit| %.4f (bf16 %.4f)  %.1f ms" % (cid, len(rows), max(case["dlogit"]),
                                                                            max(case["drift"]), ms), flush=True)
        if a.slots_only:
            rep["gates"] = g = {}
            slot_gates(a, eng, dev, sd, ck, tok, cal, g)
            print(json.dumps(g, indent=1), flush=True)
            raise _Done()
        dd, db = np.concatenate(dp_dev), np.concatenate(dp_bf)
        g = {"answers": n_ans, "flips_dev": int(flips_dev), "flips_bf16": int(flips_bf),
             "dp_max_dev": float(dd.max()), "dp_max_bf16": float(db.max()),
             "dp_mean_dev": float(dd.mean()), "dp_mean_bf16": float(db.mean()),
             "gate_mismatch_dev": gate_mismatch, "gate_mismatch_bf16": gate_mismatch_bf, "flipped": worst[:20]}
        g["G2"] = flips_dev <= flips_bf + 1
        g["G3"] = g["dp_max_dev"] <= 2 * g["dp_max_bf16"] and g["dp_mean_dev"] <= 1.5 * g["dp_mean_bf16"]
        g["G4"] = all(m in gate_mismatch_bf for m in gate_mismatch)
        # G5: determinism; G6: a row alone vs inside a full launch
        if not rep["cases"]:
            raise SystemExit("no case selected")
        first = sorted(rep["cases"])[0]
        doc = json.load(open(os.path.join(gd, first + ".json")))
        qs = T.normalise_questions(doc["questions"])
        kw0 = doc["kwargs"]
        rows = T.build_rows(tok, doc["state"], qs, kw0.get("max_len", ck.max_len), kw0.get("head_max_len",
                                                                                            ck.head_max_len))
        if a.engine != "cpu":
            L0, _ = eng.run(rows)
            same = True
            for _ in range(a.replays):
                L1, _ = eng.run(rows)
                same &= all(np.array_equal(x, y) for x, y in zip(L0, L1))
            g["G5"] = bool(same)
            # the first row alone vs placed after the other rows of its case inside one launch (another start lane
            # and other row tiles: packed rows)
            alone, _ = eng.run(rows[:1])
            many, _ = eng.run(rows[1:] + rows[:1])
            g["G6_maxdiff"] = float(np.abs(alone[0] - many[-1]).max())
            g["G6"] = g["G6_maxdiff"] <= max(rep["cases"][first]["drift"])
        if a.slots:
            slot_gates(a, eng, dev, sd, ck, tok, cal, g)
        rep["gates"] = g
        print(json.dumps({k: v for k, v in g.items() if k != "flipped"}, indent=1), flush=True)
    except _Done:
        pass
    finally:
        if hasattr(eng, "close"):
            eng.close()
        if dev is not None:
            from tt_laya.device import close_device

            close_device(dev)
    if a.out:
        with open(a.out, "w") as f:
            json.dump(rep, f, indent=1)
    keys = () if a.slots_only else ("G2", "G3", "G4", "G5", "G6")
    keys += ("G7",) if a.slots else ()
    ok = all(rep.get("gates", {}).get(k, False) is not False for k in keys)
    sys.exit(0 if ok and "aborted" not in rep else 1)


if __name__ == "__main__":
    main()