File size: 5,133 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
# SPDX-License-Identifier: Apache-2.0
"""One megakernel device run (ONE device process; through bin/devrun with --reset-on-timeout for new kernel code):

    bin/devrun -t 900 --reset-on-timeout -- python -u -m tt_laya.tests.mk_run --case ticket00_readme --spin 4194304

Builds the mk engine, runs golden case(s) eagerly (or traced with --trace), prints the per-core abort / progress
report of the debug dump and the logit errors vs the official fp32 goldens (next to the official bf16 drift).
Exit 2 when any core aborted, 3 on non-finite logits.
"""
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("--profile", default="english")
    ap.add_argument("--case", default="ticket00_readme", help="comma-separated golden case ids")
    ap.add_argument("--spin", type=int, default=1 << 22)
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--slots", type=int, default=0)
    ap.add_argument("--repeat", type=int, default=1)
    ap.add_argument("--variant", default="", help="+-separated program variants (mmb, prof, ...)")
    ap.add_argument("--weights", default="bf16")
    ap.add_argument("--out", default="")
    ap.add_argument("--engine-mod", default="engine", help="tt_laya.tt.mk module providing MkEngine (development)")
    a = ap.parse_args()

    import torch

    torch.set_num_threads(2)
    from tt_laya import text as T
    from tt_laya import weights as Wt
    from tt_laya.device import close_device, open_device
    import importlib

    MkEngine = importlib.import_module("tt_laya.tt.mk." + a.engine_mod).MkEngine

    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)
    cases = []
    for cid in a.case.split(","):
        doc = json.load(open(os.path.join(GOLD, a.profile, cid + ".json")))
        z = np.load(os.path.join(GOLD, a.profile, cid + ".npz"))
        kw = doc["kwargs"]
        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))
        cases.append((cid, rows, z))
    summary = {"cases": {}}
    rc = 0
    dev = open_device()
    try:
        t0 = time.perf_counter()
        eng = MkEngine(dev, sd, ck.arch, fidelity=a.fidelity, pad_id=tok.pad_id, trace=a.trace, spin=a.spin,
                       slots=a.slots or None, variant=tuple(v for v in a.variant.split("+") if v),
                       weight_dtype=a.weights)
        print("engine built %.1fs  grid %s  ring %s pages  timings %s" % (time.perf_counter() - t0, eng.describe()["grid"],
                                                                          eng.slots, eng.timings), flush=True)
        for cid, rows, z in cases:
            for rep in range(a.repeat):
                t1 = time.perf_counter()
                L, A = eng.run(rows)
                dt = (time.perf_counter() - t1) * 1e3
                dbg = eng.read_debug()
                errs = []
                for i, r in enumerate(rows):
                    K = len(r.markers)
                    errs.append((float(np.abs(L[i] - z["logits_fp32"][i, :K]).max()),
                                 float(np.abs(z["logits_bf16"][i, :K] - z["logits_fp32"][i, :K]).max())))
                print("%-20s rep %d  %.1f ms  aborts %d  max|dlogit| %s" % (
                    cid, rep, dt, len(dbg["aborted"]), " ".join("%.4f(%.4f)" % e for e in errs)), flush=True)
                if dbg["aborted"]:
                    for ab in dbg["aborted"][:12]:
                        print("   abort", ab, flush=True)
                    steps = sorted(set(dbg["step"]))
                    print("   steps seen:", steps[:40], flush=True)
                    rc = 2
                if rep == 0:
                    print("   logits", [np.round(x, 3).tolist() for x in L[:2]], "golden",
                          [np.round(z["logits_fp32"][i, :len(rows[i].markers)], 3).tolist() for i in range(min(2, len(rows)))],
                          flush=True)
                if not np.all(np.isfinite(np.concatenate(L))):
                    rc = rc or 3
                summary["cases"].setdefault(cid, []).append({"ms": dt, "errs": errs, "aborts": dbg["aborted"]})
                if rc:
                    break
            if rc:
                break
        eng.close()
    finally:
        close_device(dev)
    if a.out:
        with open(a.out, "w") as f:
            json.dump(summary, f, indent=1, default=str)
    sys.exit(rc)


if __name__ == "__main__":
    main()