File size: 6,796 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
# SPDX-License-Identifier: Apache-2.0
"""Device check of an engine against the official goldens (ONE device process; run through bin/devrun):

    bin/devrun -t 900 --reset-on-timeout -- python -u -m tt_laya.tests.dev_check --engine ttnn --cases 6

Prints per case the max |logit - official fp32| next to the official bf16 drift, answer agreement, and the warm
latency of the engine call per (batch, length) bucket.  Writes a JSON summary with --out.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ".."))
GOLD = os.environ.get("LAYA_GOLDEN_DIR") or os.path.join(ROOT, "assets", "laya", "golden")
CKPT = os.environ.get("LAYA_WEIGHTS_ROOT") or os.path.join(ROOT, "assets", "laya", "ckpt")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--engine", default="ttnn")
    ap.add_argument("--profile", default="english")
    ap.add_argument("--cases", default="8", help="number of golden cases or comma-separated ids")
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--weights", default="bf16")
    ap.add_argument("--bench", default="", help="comma list of BxL to time (synthetic rows)")
    ap.add_argument("--iters", type=int, default=20)
    ap.add_argument("--no-trace", action="store_true")
    ap.add_argument("--out", default="")
    a = ap.parse_args()

    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

    ck = Wt.load_checkpoint(a.profile, root=os.path.join(CKPT, a.profile))
    tok = T.Tokenizer(os.path.join(ck.path, "tokenizer"))
    sd = Wt.load_state_dict(ck)
    gd = os.path.join(GOLD, a.profile)
    ids = sorted(f[:-5] for f in os.listdir(gd) if f.endswith(".json") and not f.startswith("_"))
    if a.cases.isdigit():
        step = max(1, len(ids) // int(a.cases))
        ids = ids[::step][: int(a.cases)]
    else:
        ids = a.cases.split(",")

    from tt_laya.device import open_device, close_device

    dev = open_device()
    summary = {"engine": a.engine, "profile": a.profile, "cases": {}, "bench": {}}
    try:
        t0 = time.perf_counter()
        if a.engine == "ttnn":
            from tt_laya.tt.ttnn_engine import TtnnEngine

            eng = TtnnEngine(dev, sd, ck.arch, batch_buckets=(1, 2, 4, 8, 16, 32), seq_buckets=(64, 128, 256, 512),
                             trace=not a.no_trace, fidelity=a.fidelity, weight_dtype=a.weights)
            eng.pad_id = tok.pad_id
        else:
            from tt_laya.tt.mk.engine import MkEngine

            eng = MkEngine(dev, sd, ck.arch, fidelity=a.fidelity, weight_dtype=a.weights, pad_id=tok.pad_id,
                           spin=1 << 22)
        print("engine built in %.1fs" % (time.perf_counter() - t0), flush=True)
        cal = Dc.Calibration(ck.cfg["temperature"], ck.cfg.get("temperature_by_options"))
        worst = 0.0
        for cid in ids:
            doc = json.load(open(os.path.join(gd, cid + ".json")))
            z = np.load(os.path.join(gd, cid + ".npz"))
            kw = doc["kwargs"]
            if kw.get("max_len", ck.max_len) > 512:
                continue
            qs = T.normalise_questions(doc["questions"])
            rows = T.build_rows(tok, doc["state"], qs, kw.get("max_len", ck.max_len),
                                kw.get("head_max_len", ck.head_max_len))
            t1 = time.perf_counter()
            L, A = eng.run(rows)
            dt = time.perf_counter() - t1
            errs, drift = [], []
            for i, r in enumerate(rows):
                K = len(r.markers)
                g = z["logits_fp32"][i, :K]
                errs.append(float(np.abs(L[i] - g).max()))
                drift.append(float(np.abs(z["logits_bf16"][i, :K] - g).max()))
            res = Dc.result(qs, rows, L, [float(x[0]) for x in A], cal)
            off = doc["official_fp32"]["answers"]
            agree = sum(1 for q in qs if _top(res["answers"][q.qid]) == _top(off[q.qid]))
            worst = max(worst, max(errs))
            summary["cases"][cid] = {"err": errs, "drift": drift, "agree": agree, "n": len(qs), "ms": dt * 1e3}
            print("%-22s rows %d  max|dlogit| %.4f (bf16 drift %.4f)  agree %d/%d  %.1f ms" % (
                cid, len(rows), max(errs), max(drift), agree, len(qs), dt * 1e3), flush=True)
            if not np.all(np.isfinite(np.concatenate(L))):
                print("NON-FINITE logits: stop", flush=True)
                sys.exit(3)
            if hasattr(eng, "read_debug"):
                dbg = eng.read_debug()
                if dbg["aborted"]:
                    print("ABORTS:", dbg["aborted"][:4], flush=True)
                    sys.exit(2)
        for spec in [s for s in a.bench.split(",") if s]:
            B, Ln = (int(x) for x in spec.split("x"))
            rows = [T.Row(ids=[tok.cls_id] + [1000 + (i * 7 + j) % 30000 for j in range(Ln - 6)] + [tok.mask_id, 500,
                                                                                                    tok.mask_id, 600,
                                                                                                    tok.sep_id],
                          markers=[Ln - 5, Ln - 3], qtype=2, n_options=2, options_distinct=2, tokens_per_option=None,
                          state_tokens=0, state_used=0) for i in range(B)]
            eng.run(rows)
            ts = []
            for _ in range(a.iters):
                t1 = time.perf_counter()
                eng.run(rows)
                ts.append(time.perf_counter() - t1)
            ts.sort()
            dev_ms = None
            if hasattr(eng, "bench_device") and (a.engine != "mk" or B * -(-Ln // 32) <= 20):
                dev_ms = eng.bench_device(rows, a.iters)
            summary["bench"][spec] = {"p50_ms": ts[len(ts) // 2] * 1e3, "min_ms": ts[0] * 1e3, "device_ms": dev_ms}
            print("bench %-8s p50 %.2f ms  min %.2f ms  device %s ms" % (spec, ts[len(ts) // 2] * 1e3, ts[0] * 1e3,
                                                                         "%.3f" % dev_ms if dev_ms else "-"), flush=True)
        summary["describe"] = eng.describe()
        if hasattr(eng, "timings"):
            summary["timings"] = eng.timings
        if a.out:
            with open(a.out, "w") as f:
                json.dump(summary, f, indent=1)
        eng.close()
    finally:
        close_device(dev)


def _top(ans):
    if ans["type"] == "choice":
        return ans["choice"]
    if ans["type"] == "score":
        return max(ans["probabilities"], key=lambda k: ans["probabilities"][k])
    return ans["noul"] >= 0.5


if __name__ == "__main__":
    main()