Download code/tt_laya/server/app.py from changh95/laya: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/server/app.py
- Command line
-
hf download hf://changh95/laya/code/tt_laya/server/app.py
-
curl -L -o app.py https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/server/app.py
18.5 kB
| # 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 | |
| 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") | |
| 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)) | |
| async def root(): | |
| return {"model": MODEL_NAME, "routes": ["POST /v1/systemone", "POST /v1/systemone/batch", "POST /predict", | |
| "POST /predict_batch", "GET /info", "GET /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 | |
| 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 | |
| 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}"}) | |
| 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}"}) | |
| 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]) | |
| 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() | |