# SPDX-License-Identifier: Apache-2.0 """Python API of the laya decision model on one p150, mirroring the official ``laya.Agent`` (classic checkpoint): from tt_laya.api import Laya agent = Laya.from_pretrained() # LAYA_* environment (tt_laya/config.py), english profile out = agent.predict(state, questions) # one state, every question in shared device launches outs = agent.predict_batch(states, questions) # many states agent.close() ``predict`` returns exactly the official response shape: ``{"model": "laya-rl-agent", "answers": {...}, "usage": {...}}`` (choice / score / noul answers with probabilities, ``confidence``, ``answer_confidence``, ``action.act_probability``; the opt-in ``min_confidence`` gate fields). Engines: ``mk`` (the megakernel), ``ttnn`` (stock ops; also the path for rows longer than 512 tokens), ``cpu`` (float32 reference), ``fake`` (host tests). """ from __future__ import annotations import math import os import threading import time from typing import Any, Dict, List, Optional, Sequence, Tuple, Union import numpy as np from . import config as C from . import decode as Dc from . import text as T from . import weights as Wt __all__ = ["Laya", "QuestionError", "jev_confidence"] QuestionError = T.QuestionError def jev_confidence(answer: Dict[str, Any]) -> Optional[float]: """TypeSafe Jev's confidence of a choice / score answer (the official server's ``x_jev_confidence``): choice ``(max p - 1/n) / (1 - 1/n)``; score ``max(0, 1 - sum p_i |i - mode| / D)``, D the same sum for a uniform p.""" kind, pr = answer.get("type"), answer.get("probabilities") if kind not in ("choice", "score") or not isinstance(pr, dict) or not pr: return None try: p = [float(pr[k]) for k in (sorted(pr, key=int) if kind == "score" else pr)] except (TypeError, ValueError): return None if not all(math.isfinite(v) and v >= 0 for v in p): return None n = len(p) if n == 1: return 1.0 s = sum(p) p = [v / s for v in p] if s else [1.0 / n] * n if kind == "choice": return (max(p) - 1.0 / n) / (1.0 - 1.0 / n) mode = max(range(n), key=p.__getitem__) spread = sum(v * abs(i - mode) for i, v in enumerate(p)) center = (n - 1) / 2 uniform = sum(abs(i - center) for i in range(n)) / n return max(0.0, 1.0 - spread / uniform) class FakeEngine: """Deterministic stand-in for host tests: logits from the token ids (no device, no weights).""" name = "fake" max_tokens = 1 << 30 def run(self, rows): L, A = [], [] for r in rows: s = sum(r.ids) % 9973 L.append(np.array([((s * (j + 3)) % 97) / 10.0 - 4.8 for j in range(len(r.markers))], dtype=np.float32)) A.append(np.array([0.9, 0.1], dtype=np.float32)) return L, A def describe(self): return {"engine": "fake"} def close(self): pass class CpuEngine: name = "cpu" max_tokens = 1 << 30 def __init__(self, sd, arch): from .reference.model import Reference self.ref = Reference(sd, arch) def run(self, rows): L, A = self.ref.run_rows(rows) return [x.numpy().astype(np.float32) for x in L], [x.numpy().astype(np.float32) for x in A] def describe(self): return {"engine": "cpu"} def close(self): pass class Laya: def __init__(self, ck: Optional[Wt.Checkpoint], tok, engines: Dict[str, Any], cal: Dc.Calibration, cfg: C.ServeConfig, device=None, timings: Optional[Dict] = None): self.ck, self.tok, self.engines, self.cal, self.cfg, self.device = ck, tok, engines, cal, cfg, device self.timings = timings or {} self.max_len = cfg.max_len or (ck.max_len if ck else 512) self.default_max_len = ck.max_len if ck else 512 self.default_head_max_len = ck.head_max_len if ck else 192 self._lock = threading.Lock() # ------------------------------------------------------------------ construction @classmethod def from_pretrained(cls, config: Optional[C.ServeConfig] = None, *, profile: Optional[str] = None, engine: Optional[str] = None, weights_dir: Optional[str] = None, device=None, backend: Optional[str] = None) -> "Laya": import dataclasses cfg = config or C.resolve_config() repl = {k: v for k, v in (("profile", profile), ("engine", engine), ("weights_dir", weights_dir)) if v} if repl: cfg = dataclasses.replace(cfg, **repl) t0 = time.perf_counter() if backend == "fake": tok = _FakeTokenizer() return cls(None, tok, {"main": FakeEngine()}, Dc.Calibration([1.0, 1.0, 1.0]), cfg) ck = Wt.load_checkpoint(cfg.profile, root=cfg.weights_dir, revision=cfg.revision) tok = T.Tokenizer(os.path.join(ck.path, "tokenizer")) cal = _calibration(ck.cfg, cfg) timings = {"load_s": time.perf_counter() - t0} if cfg.cpu_threads: import torch torch.set_num_threads(cfg.cpu_threads) sd = Wt.load_state_dict(ck) engines: Dict[str, Any] = {} if cfg.engine == "cpu": engines["main"] = CpuEngine(sd, ck.arch) return cls(ck, tok, engines, cal, cfg, None, timings) own = device is None if own: from .device import open_device device = open_device(dispatch=cfg.dispatch) t1 = time.perf_counter() if cfg.engine == "mk": from .tt.mk.engine import MkEngine engines["main"] = MkEngine(device, sd, ck.arch, fidelity=cfg.fidelity, weight_dtype=cfg.weights, pad_id=tok.pad_id, trace=cfg.trace, timings=timings) if cfg.engine == "ttnn" or cfg.max_len > C.MK_MAX_TOKENS: from .tt.ttnn_engine import TtnnEngine seq = cfg.seq_buckets if cfg.engine == "ttnn" else tuple(s for s in cfg.seq_buckets if s > C.MK_MAX_TOKENS) eng = TtnnEngine(device, sd, ck.arch, batch_buckets=cfg.batch_buckets, seq_buckets=seq, trace=cfg.trace, fidelity=cfg.fidelity, weight_dtype=cfg.weights) eng.pad_id = tok.pad_id engines["main" if cfg.engine == "ttnn" else "long"] = eng timings["engine_s"] = time.perf_counter() - t1 agent = cls(ck, tok, engines, cal, cfg, device, timings) agent._own_device = own if cfg.warmup: t2 = time.perf_counter() agent.warmup() timings["warmup_s"] = time.perf_counter() - t2 return agent def warmup(self): """Compile everything a first request would: with LAYA_MAX_LEN > 512 the long-row (tt-nn) buckets of batch x length <= LAYA_WARMUP_LONG_TOKENS (and always (1, longest)), one long request, then one short request (the megakernel's programs and traces), last, so that no long-row allocation releases its traces afterwards (tt/traces.py).""" q = {"w": {"type": "noul", "instructions": "Is this a warm-up?"}} if "long" in self.engines: eng = self.engines["long"] smax = max(eng.seq_buckets) todo = sorted({(b, s) for s in eng.seq_buckets for b in eng.batch_buckets if b * s <= self.cfg.warmup_long_tokens} | {(1, smax)}) t0 = time.perf_counter() eng.warm(todo) self.timings["warmup_long_s"] = time.perf_counter() - t0 self.timings["warmup_long_buckets"] = ["%dx%d" % bs for bs in todo] self.predict("warm up " * (self.max_len // 2), q, max_len=self.max_len) self.predict("warm-up request", q) # ------------------------------------------------------------------ host halves def prepare(self, states: Sequence[Any], questions: Dict[str, Any], max_len: Optional[int] = None, head_max_len: Optional[int] = None) -> Tuple[List[T.Question], List[List[T.Row]]]: ml = self.default_max_len if max_len is None else max_len hl = self.default_head_max_len if head_max_len is None else head_max_len ml, hl = T.check_lengths(ml, hl, self.max_len) qs = T.normalise_questions(questions) if len(qs) > self.cfg.max_questions: raise QuestionError(f"{len(qs)} questions > {self.cfg.max_questions} per request (LAYA_MAX_QUESTIONS)") for q in qs: if q.n_options > self.cfg.max_options: raise QuestionError(f"question {q.qid!r}: {q.n_options} options > {self.cfg.max_options} " "(LAYA_MAX_OPTIONS; split the choice into a coarse-to-fine pair)") per = [T.build_rows(self.tok, s, qs, ml, hl) for s in states] if qs else [[] for _ in states] return qs, per def infer(self, rows: List[T.Row]) -> Tuple[List[np.ndarray], List[np.ndarray]]: """Raw scorer logits / action probabilities per row (megakernel; rows past 512 tokens on the ttnn engine).""" main = self.engines["main"] long_eng = self.engines.get("long") if long_eng is None or all(len(r.ids) <= main.max_tokens for r in rows): return main.run(rows) short = [i for i, r in enumerate(rows) if len(r.ids) <= main.max_tokens] longi = [i for i, r in enumerate(rows) if len(r.ids) > main.max_tokens] L, A = [None] * len(rows), [None] * len(rows) for idx, eng in ((short, main), (longi, long_eng)): if idx: l, a = eng.run([rows[i] for i in idx]) for j, i in enumerate(idx): L[i], A[i] = l[j], a[j] return L, A def finish(self, qs, per, logits, acts, lang=None, min_confidence=None) -> List[Dict]: out, o = [], 0 for rows in per: n = len(rows) if n == 0: out.append({"model": Dc.MODEL_NAME, "answers": {}, "usage": {"input_tokens": 0, "output_tokens": 0}}) continue out.append(Dc.result(qs, rows, logits[o:o + n], [float(a[0]) for a in acts[o:o + n]], self.cal, lang)) o += n Dc.apply_gate(out, min_confidence) return out # ------------------------------------------------------------------ official surface def predict_batch(self, states: Sequence[Any], questions: Dict[str, Any], batch_size: Optional[int] = None, lang: Optional[str] = None, max_len: Optional[int] = None, head_max_len: Optional[int] = None, min_confidence=None) -> List[Dict]: if isinstance(states, (str, bytes, dict)): raise TypeError("predict_batch expects a list of states; pass a single state to predict()") states = list(states) if any(s is None for s in states): raise QuestionError("state must not be None; pass a string, dict, or list") mc = Dc.check_min_confidence(min_confidence) if min_confidence is not None else None qs, per = self.prepare(states, questions, max_len, head_max_len) rows = [r for p in per for r in p] if not rows: return self.finish(qs, per, [], [], lang, mc) with self._lock: logits, acts = self.infer(rows) return self.finish(qs, per, logits, acts, lang, mc) def predict(self, state: Any, questions: Dict[str, Any], lang: Optional[str] = None, max_len: Optional[int] = None, head_max_len: Optional[int] = None, min_confidence=None) -> Dict: return self.predict_batch([state], questions, lang=lang, max_len=max_len, head_max_len=head_max_len, min_confidence=min_confidence)[0] system_one = predict # ------------------------------------------------------------------ info @property def info(self) -> Dict: d = {"profile": self.cfg.profile, "engine": self.engines["main"].name, "engines": {k: v.describe() for k, v in self.engines.items()}, "max_len": self.max_len, "default_max_len": self.default_max_len, "default_head_max_len": self.default_head_max_len, "calibration": self.cal.describe(), "timings": {k: round(v, 3) for k, v in self.timings.items() if isinstance(v, float)}, "warmed_long_buckets": self.timings.get("warmup_long_buckets", [])} if self.ck is not None: d["checkpoint"] = {"repo": Wt.HF_REPO, "subfolder": Wt.PROFILES[self.ck.profile], "revision": self.ck.revision or Wt.HF_REVISION, "encoder": self.ck.cfg.get("encoder"), "layers": self.ck.arch.layers, "hidden": self.ck.arch.hidden} if self.device is not None: try: from .device import describe_device d["device"] = describe_device(self.device) except Exception: # noqa: BLE001 d["device"] = {} return d def close(self): for e in self.engines.values(): try: e.close() except Exception: # noqa: BLE001 pass if self.device is not None and getattr(self, "_own_device", False): from .device import close_device close_device(self.device) self.device = None def _calibration(ckcfg: Dict, cfg: C.ServeConfig) -> Dc.Calibration: t, tbo = ckcfg.get("temperature", [1.0, 1.0, 1.0]), ckcfg.get("temperature_by_options", {}) over = C.load_json_opt(cfg.calibration) if over: t = over.get("temperature", t) tbo = over.get("temperature_by_options", tbo) return Dc.Calibration(t, tbo, C.load_json_opt(cfg.lang_temperatures)) class _FakeTokenizer: """Whitespace tokenizer for host tests (ids 10..).""" mask_token = "[MASK]" cls_id, sep_id, mask_id, pad_id = 1, 2, 3, 0 def encode(self, text: str) -> List[int]: return [10 + (sum(map(ord, w)) % 30000) for w in text.split()] encode_cached = encode