File size: 14,091 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# 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