# SPDX-License-Identifier: Apache-2.0 """Latency / throughput of the device engines (ONE device process; through the device lock on shared machines): bin/devrun -t 1800 -- python -u code/scripts/bench.py --engine mk --out bench_mk.json bin/devrun -t 1800 -- python -u code/scripts/bench.py --engine ttnn --out bench_ttnn.json Shapes ``RxL`` = R rows (one row per question) of L tokens each. Reported per shape: device time of one launch (the trace replayed back to back; mk: one launch per <= 20 row tiles), the engine call (host rows -> device -> logits, p50 of --iters) and the full ``Laya.predict_batch`` path on real text (tokenize + rows + device + decode) for a 1-, 4- and 32-state request with 4 questions each. """ 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, "..", "..", "..", "..")) SHAPES = "1x32,1x64,1x128,1x256,1x512,4x64,4x96,4x128,5x128,10x64,20x32,32x128" QUESTIONS = { "department": {"type": "choice", "instructions": "Which department should handle this request?", "criteria": {"billing": "invoices, payments, refunds", "technical": "bugs, outages, system errors", "sales": "pricing, new contracts", "other": "everything else"}}, "urgency": {"type": "score", "instructions": "How urgent is this request?", "criteria": ["not urgent", "soon", "critical deadline or blocking issue"]}, "churn_risk": {"type": "noul", "instructions": "Does the user threaten to cancel or leave?"}, "refund_requested": {"type": "noul", "instructions": "Does the user explicitly request a refund?"}, } STATE = {"from": "user@example.com", "subject": "Duplicate charge on invoice #4411", "body": "Hi, we were billed twice for March. Please refund the duplicate today or we will cancel our plan."} def rows_of(spec, tok): from tt_laya import text as T R, L = (int(x) for x in spec.split("x")) return [T.Row(ids=[tok.cls_id] + [1000 + (i * 7 + j) % 30000 for j in range(L - 6)] + [tok.mask_id, 500, tok.mask_id, 600, tok.sep_id], markers=[L - 5, L - 3], qtype=2, n_options=2, options_distinct=2, tokens_per_option=None, state_tokens=0, state_used=0) for i in range(R)] def main(): ap = argparse.ArgumentParser() ap.add_argument("--engine", default="mk", choices=("mk", "ttnn")) ap.add_argument("--profile", default="english") ap.add_argument("--weights", default="") ap.add_argument("--fidelity", default="HiFi4") ap.add_argument("--shapes", default=SHAPES) ap.add_argument("--iters", type=int, default=30) ap.add_argument("--out", default="") a = ap.parse_args() import dataclasses import torch torch.set_num_threads(2) from tt_laya import config as C from tt_laya.api import Laya from tt_laya.device import close_device, describe_device, open_device wdir = a.weights or os.path.join(ROOT, "assets", "laya", "ckpt", a.profile) cfg = dataclasses.replace(C.resolve_config({"LAYA_PROFILE": a.profile, "LAYA_ENGINE": a.engine, "LAYA_FIDELITY": a.fidelity}), weights_dir=wdir, warmup=False) dev = open_device() out = {"engine": a.engine, "profile": a.profile, "fidelity": a.fidelity, "shapes": {}, "requests": {}} try: out["device"] = describe_device(dev) t0 = time.perf_counter() agent = Laya.from_pretrained(config=cfg, device=dev) out["start_s"] = time.perf_counter() - t0 eng = agent.engines["main"] for spec in a.shapes.split(","): rows = rows_of(spec, agent.tok) eng.run(rows) ts = [] for _ in range(a.iters): t1 = time.perf_counter() eng.run(rows) ts.append((time.perf_counter() - t1) * 1e3) ts.sort() R, L = (int(x) for x in spec.split("x")) tiles = R * -(-L // 32) dev_ms = eng.bench_device(rows, a.iters) if (a.engine == "ttnn" or tiles <= 20) else None rec = {"rows": R, "tokens": L, "row_tiles": tiles, "device_ms": dev_ms, "call_ms_p50": ts[len(ts) // 2], "call_ms_min": ts[0], "rows_per_s": R / (ts[len(ts) // 2] / 1e3)} if getattr(eng, "last_stages", None): eng.run(rows) rec["stages"] = dict(eng.last_stages) out["shapes"][spec] = rec print("%-8s tiles %3d device %s ms call p50 %.2f ms %.0f rows/s %s" % ( spec, tiles, "%.3f" % dev_ms if dev_ms else " - ", rec["call_ms_p50"], rec["rows_per_s"], " ".join("%s %.2f" % (k, v) for k, v in rec.get("stages", {}).items())), flush=True) for n in (1, 4, 32): states = [STATE] * n agent.predict_batch(states, QUESTIONS) ts = [] for _ in range(max(5, a.iters // (1 + n // 8))): t1 = time.perf_counter() agent.predict_batch(states, QUESTIONS) ts.append((time.perf_counter() - t1) * 1e3) ts.sort() out["requests"][f"{n}x4q"] = {"ms_p50": ts[len(ts) // 2], "states_per_s": n / (ts[len(ts) // 2] / 1e3)} print("predict_batch %2d states x 4 questions: p50 %.2f ms (%.0f states/s)" % ( n, ts[len(ts) // 2], n / (ts[len(ts) // 2] / 1e3)), flush=True) agent.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()