laya / code /tt_laya /tests /mk_prof.py
changh95's picture
tt-model push laya (container)
f882f26 verified
Raw History Blame Contribute Delete
4.93 kB
# SPDX-License-Identifier: Apache-2.0
"""Megakernel timing arms (ONE device process): per-phase time stamps (LM_PROF) and the weight stream alone
(LM_STREAM_ONLY), on synthetic rows.
bin/devrun -t 900 --reset-on-timeout -- python -u -m tt_laya.tests.mk_prof --variant prof --specs 1x32,4x96
"""
from __future__ import annotations
import argparse
import json
import os
import time
import numpy as np
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ".."))
CKPT = os.environ.get("LAYA_WEIGHTS_ROOT") or os.path.join(ROOT, "assets", "laya", "ckpt")
TPH = {1: "norm1", 2: "qkv", 4: "att", 5: "o+res", 6: "norm2", 7: "ffn_up", 8: "down"}
def rows_of(spec, tok):
from tt_laya import text as T
B, Ln = (int(x) for x in spec.split("x"))
return [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)]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--profile", default="english")
ap.add_argument("--variant", default="prof", help="prof | stream | none")
ap.add_argument("--specs", default="1x32,4x96,20x32")
ap.add_argument("--fidelity", default="HiFi4")
ap.add_argument("--slots", type=int, default=0)
ap.add_argument("--weights", default="bf16")
ap.add_argument("--iters", type=int, default=10)
ap.add_argument("--out", default="")
ap.add_argument("--qch", default="", help="comma list of attention query-tile chunks to time per spec (0: auto)")
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)
var = () if a.variant == "none" else tuple(v for v in a.variant.split("+") if v)
out = {"variant": a.variant, "fidelity": a.fidelity, "specs": {}}
dev = open_device()
try:
eng = MkEngine(dev, sd, ck.arch, fidelity=a.fidelity, pad_id=tok.pad_id, spin=1 << 22, variant=var,
slots=a.slots or None, weight_dtype=a.weights)
qchs = [int(q) for q in a.qch.split(",") if q] or [0]
for spec, qch in [(s, q) for s in a.specs.split(",") for q in qchs]:
rows = rows_of(spec, tok)
eng.qch = qch or None
eng.run(rows)
ms = eng.bench_device(rows, a.iters)
dbg = eng.read_debug()
rec = {"device_ms": ms, "aborts": len(dbg["aborted"]), "qch": qch}
if a.qch:
spec = "%s@q%d" % (spec, qch)
line = "%-8s device %.3f ms aborts %d" % (spec, ms, len(dbg["aborted"]))
if "prof" in var:
eng.run(rows) # one plain launch for the stamps
p = eng.read_prof().astype(np.int64)
nl = ck.arch.layers + ck.arch.head_layers
band = [i for i in range(eng.geo.n) if (i // eng.geo.C) < min(eng.geo.NB, -(-sum(
-(-len(r.ids) // 32) for r in rows)))]
per = {}
for l in (1, 13, 27, 28, 29):
if l >= nl:
continue
d = {}
for ph, nm in TPH.items():
nxt = ph + 1 if ph + 1 in TPH else (ph + 2 if ph + 2 in TPH else None)
a0 = p[band, l * 16 + ph]
a1 = p[band, l * 16 + nxt] if nxt else p[band, (l + 1) * 16 + 1]
dt = ((a1 - a0) & 0xFFFFFFFF) / 1350.0 # us at 1.35 GHz
d[nm] = [round(float(np.median(dt)), 1), round(float(dt.max()), 1)]
per[l] = d
line += "\n layer %2d " % l + " ".join("%s %s/%s" % (k, v[0], v[1]) for k, v in d.items())
t0 = p[band, 1 * 16 + 1]
t1 = p[band, (nl - 1) * 16 + 1]
rec["per_layer_us"] = float(np.median(((t1 - t0) & 0xFFFFFFFF) / 1350.0)) / (nl - 2)
rec["phases_us"] = per
line += "\n per layer (median, layers 1..%d): %.1f us" % (nl - 1, rec["per_layer_us"])
out["specs"][spec] = rec
print(line, flush=True)
eng.close()
finally:
close_device(dev)
if a.out:
with open(a.out, "w") as f:
json.dump(out, f, indent=1)
if __name__ == "__main__":
main()