File size: 18,531 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# SPDX-License-Identifier: Apache-2.0
"""HTTP server of laya on one p150 (FastAPI under uvicorn; tt-model kind ``tt-dit-server``):

    python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_laya.server.app:app

Routes (request / response shapes of the official ``laya-serve``, which TypeSafe Jev clients also speak):

* ``POST /v1/systemone`` -- ``state`` (string, JSON object or conversation list), ``questions`` ({id: {type
  choice | score | noul, instructions, criteria, labels, option_order}}), optional ``max_len``, ``head_max_len``,
  ``lang``, ``min_confidence`` (float or {bucket: float}), ``model`` (must name the served profile). Answers carry
  ``x_jev_confidence`` on choice / score (as the official server) and ``routing`` names the checkpoint.
* ``POST /v1/systemone/batch`` -- ``states`` (list) + the same fields -> ``{"results": [...], "total_usage": {...}}``
  (the official key; ``usage`` carries the same numbers).
* ``POST /predict`` / ``POST /predict_batch`` -- the Python API's exact output (``Laya.predict`` / ``predict_batch``).
* ``GET /info``, ``GET /health`` (+ ``/v1/health``), ``GET /``.

Concurrency: one device thread; concurrent requests merge into shared engine calls of <= ``LAYA_MAX_BATCH`` states
(server/batcher.py). The chip itself is opened and closed on the main thread (the lifespan's): tt-metal tears its
cluster down at interpreter exit on the main thread, and UMD's per-chip lock must be released by the thread that took
it (a chip opened on the device thread aborted the process at exit: ``pthread_mutex_unlock failed ...
CHIP_IN_USE_0_PCIe``). The model is built and run on the device thread. Errors: 400 malformed body (incl. an unpaired
UTF-16 surrogate, as the official server), 401 bad bearer token (when ``LAYA_API_KEY`` is set), 413 too many states /
a state longer than ``LAYA_MAX_STATE_CHARS`` (official: 50,000) / body too large, 422 invalid question / parameter
(the message names it), 429 queue full, 503 starting / queue timeout, 500 ``inference failed``. Importing this module
has no side effects (no ttnn, no torch, no device).
"""
from __future__ import annotations

import asyncio
import hmac
import json
import logging
import os
import re
import time
from contextlib import asynccontextmanager
from typing import Any, Callable, Dict, List, Optional

from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse, Response

from .. import __version__
from .. import config as C
from ..ttaw.server.app import parse_mesh_shape
from .batcher import Batcher, QueueFull, QueueTimeout, ShuttingDown

__all__ = ["app", "create_app", "load_config", "parse_mesh_shape", "default_model_factory"]

LOG = logging.getLogger("tt_laya.server")
MODEL_NAME = "laya"
HARDWARE = "Tenstorrent Blackhole p150 (single chip)"
TASK = ("typed decisions with calibrated probabilities (choice / score / yes-no questions about a text, email, "
        "ticket or JSON state), the classic laya decision model")


def load_config(env: Optional[Dict[str, str]] = None) -> C.ServeConfig:
    env = os.environ if env is None else env
    mesh = parse_mesh_shape(env.get("TT_MESH_SHAPE"))
    if tuple(mesh) != (1, 1):
        raise RuntimeError(f"TT_MESH_SHAPE={env.get('TT_MESH_SHAPE')!r}: this package runs on ONE p150 (mesh 1x1)")
    try:
        return C.resolve_config(env)
    except ValueError as e:
        raise RuntimeError(str(e)) from None


def default_model_factory(cfg: C.ServeConfig, device=None):
    from ..api import Laya

    return Laya.from_pretrained(config=cfg, device=device)


# An unpaired UTF-16 surrogate: json.loads accepts a lone \udXXX escape, but the string cannot be encoded as UTF-8
# (the tokenizer raises). The official laya-serve answers such a body 400 with this text.
_LONE_SURROGATE = re.compile("[\ud800-\udfff]")
LONE_SURROGATE_DETAIL = ("request body contains an unpaired surrogate escape; those cannot be encoded as UTF-8")


def has_lone_surrogate(value: Any) -> bool:
    """True if any string (key or value) of the parsed body holds an unpaired surrogate (iterative walk)."""
    stack = [value]
    while stack:
        item = stack.pop()
        if isinstance(item, str):
            if _LONE_SURROGATE.search(item):
                return True
        elif isinstance(item, dict):
            stack.extend(item.keys())
            stack.extend(item.values())
        elif isinstance(item, (list, tuple)):
            stack.extend(item)
    return False


def state_chars(state: Any) -> int:
    """Length of the state text that gets tokenized (the official measure: the string itself, else its
    ``json.dumps(..., ensure_ascii=False)``)."""
    return len(state) if isinstance(state, str) else len(json.dumps(state, ensure_ascii=False))


class State:
    def __init__(self):
        self.model = None
        self.config: Optional[C.ServeConfig] = None
        self.ready = False
        self.error: Optional[str] = None
        self.batcher: Optional[Batcher] = None
        self.device = None   # opened / closed by the lifespan on the main thread (default factory, device engines)
        self.model_factory: Optional[Callable] = None
        self.boot_s: Optional[float] = None
        self.requests = 0


def _json(obj, status: int = 200, headers: Optional[Dict[str, str]] = None) -> Response:
    try:
        import orjson

        body = orjson.dumps(obj)
    except ImportError:  # pragma: no cover
        body = json.dumps(obj, ensure_ascii=False).encode()
    return Response(content=body, status_code=status, media_type="application/json", headers=headers)


def create_app(model_factory: Optional[Callable] = None) -> FastAPI:
    state = State()
    state.model_factory = model_factory

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        t0 = time.perf_counter()
        try:
            cfg = load_config()
            state.config = cfg

            def run(rows):
                return state.model.infer(rows)

            state.batcher = Batcher(run, cfg.max_batch, cfg.batch_window_ms, cfg.queue_depth, cfg.queue_timeout_s)
            loop = asyncio.get_running_loop()
            if state.model_factory is None:
                device = None
                if cfg.engine != "cpu":   # main thread: see the module docstring
                    from ..device import open_device

                    device = state.device = open_device(dispatch=cfg.dispatch)
                build = lambda: default_model_factory(cfg, device)  # noqa: E731
            else:
                build = lambda: state.model_factory(cfg)  # noqa: E731
            state.model = await loop.run_in_executor(None, lambda: state.batcher.call(build))
            state.ready = True
            state.boot_s = time.perf_counter() - t0
            LOG.info("laya ready in %.1f s (profile %s, engine %s)", state.boot_s, cfg.profile, cfg.engine)
        except Exception as e:  # noqa: BLE001 -- /health reports it; requests get 503
            state.error = f"{type(e).__name__}: {e}"
            LOG.exception("start-up failed")
        yield
        state.ready = False
        if state.batcher is not None:
            m = state.model
            state.batcher.close((lambda: m.close()) if m is not None else None)
        if state.device is not None:
            dev, state.device = state.device, None
            if state.batcher is not None and state.batcher.alive:
                LOG.error("the device thread did not stop: the chip is left open (it needs a reset)")
            else:
                from ..device import close_device

                close_device(dev)

    app = FastAPI(title="laya on Tenstorrent p150", version=__version__, lifespan=lifespan)
    app.state.laya = state

    def need_ready():
        if state.error:
            raise HTTPException(503, f"model failed to start: {state.error}")
        if not state.ready:
            raise HTTPException(503, "model is starting")

    def check_auth(authorization: Optional[str]):
        key = state.config.api_key if state.config else None
        if not key:
            return
        scheme, _, token = (authorization or "").partition(" ")
        if scheme.lower() != "bearer" or not hmac.compare_digest(token.strip().encode(), key.encode()):
            raise HTTPException(401, "invalid or missing bearer token")

    @app.middleware("http")
    async def body_limit(request: Request, call_next):
        cl = request.headers.get("content-length")
        lim = (state.config.max_body_mb if state.config else 32.0) * 1e6
        if cl is not None and cl.isdigit() and int(cl) > lim:
            return JSONResponse({"detail": f"body larger than {lim / 1e6:g} MB (LAYA_MAX_BODY_MB)"}, status_code=413)
        return await call_next(request)

    async def body_of(request: Request) -> Dict:
        try:
            body = json.loads(await request.body())
        except (ValueError, UnicodeDecodeError):
            raise HTTPException(400, "request body must be valid JSON") from None
        if not isinstance(body, dict):
            raise HTTPException(400, "request body must be a JSON object")
        if has_lone_surrogate(body):
            raise HTTPException(400, LONE_SURROGATE_DETAIL)
        return body

    def common_kwargs(body: Dict) -> Dict:
        from ..decode import check_min_confidence
        from ..text import QuestionError

        kw = {}
        for k in ("max_len", "head_max_len"):
            v = body.get(k)
            if v is not None:
                if isinstance(v, bool) or not isinstance(v, int):
                    raise HTTPException(422, f"{k} must be an integer")
                kw[k] = v
        lang = body.get("lang")
        if lang is not None:
            if not isinstance(lang, str) or not lang.strip() or len(lang) > 35:
                raise HTTPException(422, "lang must be a language code such as 'en' or 'pt-BR'")
            kw["lang"] = lang
        mc = body.get("min_confidence")
        if mc is not None:
            try:
                kw["min_confidence"] = check_min_confidence(mc)
            except QuestionError as e:
                raise HTTPException(422, str(e)) from None
        model = body.get("model")
        if model is not None and model not in (state.config.profile, MODEL_NAME, "laya-rl-agent",
                                               "convaiinnovations/laya"):
            raise HTTPException(422, f"model {model!r}: this server serves the {state.config.profile!r} checkpoint "
                                     "(LAYA_PROFILE); omit 'model' or name it")
        return kw

    async def run(states: List[Any], questions: Any, kw: Dict) -> List[Dict]:
        from ..text import QuestionError

        need_ready()
        cfg = state.config
        if len(states) > cfg.max_inputs:
            raise HTTPException(413, f"{len(states)} states > LAYA_MAX_INPUTS={cfg.max_inputs}")
        m = state.model
        try:
            qs, per = m.prepare(states, questions, kw.get("max_len"), kw.get("head_max_len"))
        except QuestionError as e:
            raise HTTPException(422, str(e)) from None
        except UnicodeError:
            raise HTTPException(400, LONE_SURROGATE_DETAIL) from None
        rows = [r for p in per for r in p]
        try:
            fut = state.batcher.submit(rows, len(states))
        except QueueFull as e:
            raise HTTPException(429, str(e), headers={"Retry-After": "1"}) from None
        except ShuttingDown as e:
            raise HTTPException(503, str(e)) from None
        try:
            logits, acts, dev_s, merged = await asyncio.wrap_future(fut)
        except (QueueTimeout, ShuttingDown) as e:
            raise HTTPException(503, str(e)) from None
        except Exception as e:  # noqa: BLE001
            LOG.exception("inference failed")
            raise HTTPException(500, "inference failed") from None
        state.requests += 1
        return m.finish(qs, per, logits, acts, kw.get("lang"), kw.get("min_confidence"))

    def routing() -> Dict:
        from ..weights import HF_REPO, PROFILES

        sub = PROFILES[state.config.profile]
        return {"model": state.config.profile, "repo": HF_REPO + ("/" + sub if sub else ""),
                "reason": "this server serves one checkpoint (LAYA_PROFILE)"}

    def jevify(res: Dict) -> Dict:
        from ..api import jev_confidence

        ans = {}
        for qid, a in res.get("answers", {}).items():
            c = jev_confidence(a)
            ans[qid] = a if c is None else {**a, "x_jev_confidence": round(c, 4)}
        return {**res, "answers": ans, "routing": routing()}

    def check_state(st):
        try:
            n = state_chars(st)
        except (TypeError, ValueError, RecursionError):
            raise HTTPException(400, "'state' must be JSON-serializable") from None
        cap = state.config.max_state_chars if state.config else 0
        if cap and n > cap:
            raise HTTPException(413, "state too large (%d > %d chars; LAYA_MAX_STATE_CHARS)" % (n, cap))

    @app.get("/")
    async def root():
        return {"model": MODEL_NAME, "routes": ["POST /v1/systemone", "POST /v1/systemone/batch", "POST /predict",
                                                "POST /predict_batch", "GET /info", "GET /health"]}

    @app.get("/health")
    @app.get("/v1/health")
    async def health():
        st = "ok" if state.ready else ("error" if state.error else "starting")
        d = {"status": st, "model": MODEL_NAME}
        if state.config is not None:
            d["profile"] = state.config.profile
        if state.error:
            d["error"] = state.error
        if state.ready:
            info = state.model.info
            d["engine"] = info.get("engine")
            d["device"] = info.get("device", {})
        return d

    @app.get("/info")
    async def info():
        d = {"model": MODEL_NAME, "repo": C.REPO, "task": TASK, "hardware": HARDWARE, "version": __version__,
             "ready": state.ready, "error": state.error, "boot_s": state.boot_s, "requests": state.requests,
             "api": {"systemone": "POST /v1/systemone {state, questions, max_len?, head_max_len?, lang?, "
                                  "min_confidence?, model?}",
                     "batch": "POST /v1/systemone/batch {states, questions, ...}",
                     "python": "POST /predict, POST /predict_batch (the Laya.predict / predict_batch output)"}}
        if state.config is not None:
            d["config"] = state.config.as_dict()
            d["limits"] = {"max_inputs": state.config.max_inputs, "max_batch": state.config.max_batch,
                           "max_len": state.config.max_len, "max_questions": state.config.max_questions,
                           "max_options": state.config.max_options}
        if state.ready:
            d["model_info"] = state.model.info
            d["engine"] = d["model_info"].get("engine")
            d["device"] = d["model_info"].get("device", {})
        if state.batcher is not None:
            d["batcher"] = state.batcher.status()
        return d

    @app.post("/v1/systemone")
    async def systemone(request: Request, authorization: Optional[str] = Header(default=None)):
        check_auth(authorization)
        body = await body_of(request)
        if "questions" not in body:
            raise HTTPException(400, "request body must be an object with a 'questions' field")
        if body.get("state") is None:
            raise HTTPException(400, "'state' is required")
        if not isinstance(body["questions"], dict):
            raise HTTPException(400, "'questions' must be an object")
        check_state(body["state"])
        kw = common_kwargs(body)
        t0 = time.perf_counter()
        res = (await run([body["state"]], body["questions"], kw))[0]
        ms = (time.perf_counter() - t0) * 1e3
        return _json(jevify(res), headers={"Server-Timing": f"inference;dur={ms:.2f}",
                                           "X-Inference-Time-Ms": f"{ms:.2f}"})

    @app.post("/v1/systemone/batch")
    async def systemone_batch(request: Request, authorization: Optional[str] = Header(default=None)):
        check_auth(authorization)
        body = await body_of(request)
        if "questions" not in body or "states" not in body:
            raise HTTPException(400, "request body must be an object with 'states' and 'questions' fields")
        states = body["states"]
        if not isinstance(states, list) or not states:
            raise HTTPException(400, "'states' must be a non-empty list")
        if any(s is None for s in states):
            raise HTTPException(400, "every state must be a string, object or list")
        if not isinstance(body["questions"], dict):
            raise HTTPException(400, "'questions' must be an object")
        for s in states:
            check_state(s)
        kw = common_kwargs(body)
        t0 = time.perf_counter()
        results = [jevify(r) for r in await run(states, body["questions"], kw)]
        ms = (time.perf_counter() - t0) * 1e3
        usage = {"input_tokens": sum(r.get("usage", {}).get("input_tokens", 0) for r in results),
                 "output_tokens": 0}
        # "total_usage" is the official laya-serve key; "usage" (earlier versions of this server) is kept
        return _json({"results": results, "total_usage": usage, "usage": usage},
                     headers={"X-Inference-Time-Ms": f"{ms:.2f}"})

    @app.post("/predict")
    async def predict(request: Request, authorization: Optional[str] = Header(default=None)):
        check_auth(authorization)
        body = await body_of(request)
        if body.get("state") is None or not isinstance(body.get("questions"), dict):
            raise HTTPException(400, "body: {state, questions, ...}")
        check_state(body["state"])
        return _json((await run([body["state"]], body["questions"], common_kwargs(body)))[0])

    @app.post("/predict_batch")
    async def predict_batch(request: Request, authorization: Optional[str] = Header(default=None)):
        check_auth(authorization)
        body = await body_of(request)
        states = body.get("states")
        if not isinstance(states, list) or not states or not isinstance(body.get("questions"), dict):
            raise HTTPException(400, "body: {states: [...], questions, ...}")
        for s in states:
            check_state(s)
        return _json(await run(states, body["questions"], common_kwargs(body)))

    return app


app = create_app()