# SPDX-License-Identifier: Apache-2.0 """HTTP server of EmbeddingGemma 2 (FastAPI under uvicorn; tt-model kind ``tt-dit-server``). python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_embgemma.server.app:app Routes: * ``POST /v1/embeddings`` -- OpenAI-compatible, text: ``input`` (string or list of strings), ``model`` (echoed), ``encoding_format`` (``float`` | ``base64`` = little-endian float32), ``dimensions`` (768 | 512 | 256 | 128: Matryoshka truncation + re-normalization), ``user`` (ignored). Extension fields: ``prompt_name`` / ``prompt`` (task prefix; default ``EMBGEMMA_DEFAULT_PROMPT`` or none). Token-id inputs are refused (HTTP 400). * ``POST /embed`` -- native, every modality: ``inputs`` (list; each a string or an object with ``text`` / ``image`` (base64) / ``audio`` (base64 WAV or ``{"array", "sampling_rate"}``) / ``video`` (``{"frames": [base64 images], "fps"}`` or a base64 container file when PyAV is installed) keys, or ``{"content": [...]}`` typed items, interleaved in order), ``prompt_name`` / ``prompt``, ``dimensions``, ``normalize``, ``output`` (``sentence`` | ``tokens``), ``max_length``, ``truncate`` (``right`` | ``error``), ``image_tokens`` (70 | 140 | 280 | 560 | 1120 up to ``EMBGEMMA_IMAGE_TOKENS_MAX``), ``video_fps``, ``video_max_frames``, ``video_tokens``, ``encoding_format``. * ``POST /similarity`` -- ``source`` and ``targets`` (inputs as in /embed) + the same options: cosine scores. * ``GET /info`` (configuration, limits, engines, prompts), ``GET /health`` / ``/v1/health`` (always 200: ``ok``, or ``error`` with the reason if start-up failed), ``GET /v1/models``, ``GET /``. The port accepts connections only after the warm-up (uvicorn runs the lifespan start-up first; ``tt serve`` waits for it). Concurrency: one device thread; inputs of concurrent requests are merged into device launches of <= ``EMBGEMMA_MAX_BATCH`` sequences (server/batcher.py); host preprocessing (tokenizer, image resize, log-mel) runs in the request's worker thread. 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 aborts the process at exit: ``pthread_mutex_unlock failed ... CHIP_IN_USE_0_PCIe``, found in the all-MiniLM-L6-v2 port). The model is still built and run on the device thread. Errors: 400 invalid input, 413 too many inputs / images (``EMBGEMMA_MAX_IMAGES``) / body too large, 422 schema, 429 queue full, 503 start-up failed / shutting down / 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 base64 import logging import os import time from contextlib import asynccontextmanager from typing import Any, Callable, Dict, List, Literal, Optional, Union from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse, Response from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr 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", "EmbeddingsRequest", "EmbedRequest", "SimilarityRequest", "default_model_factory"] LOG = logging.getLogger("tt_embgemma.server") MODEL_NAME = C.MODEL_NAME HARDWARE = "Tenstorrent Blackhole p150 (single chip)" TASK = ("multimodal embeddings (text incl. code, images, video, audio -> one 768-d space; Matryoshka 512 / 256 / " "128) for retrieval, classification, clustering and similarity") 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 EmbeddingGemma2 return EmbeddingGemma2.from_pretrained(config=cfg, device=device) # ---------------------------------------------------------------------------------------------- schemas class EmbeddingsRequest(BaseModel): model_config = ConfigDict(extra="ignore") # OpenAI clients send extra fields input: Any model: Optional[str] = None encoding_format: Optional[Literal["float", "base64"]] = "float" dimensions: Optional[StrictInt] = None user: Optional[str] = None prompt_name: Optional[StrictStr] = None prompt: Optional[StrictStr] = None class Options(BaseModel): model_config = ConfigDict(extra="forbid") prompt_name: Optional[StrictStr] = None prompt: Optional[StrictStr] = None dimensions: StrictInt = 768 normalize: StrictBool = True max_length: Optional[StrictInt] = None truncate: Literal["right", "error"] = "right" image_tokens: StrictInt = 280 video_tokens: StrictInt = 140 video_fps: float = 1.0 video_max_frames: Optional[StrictInt] = None class EmbedRequest(Options): inputs: Union[StrictStr, Dict[str, Any], List[Union[StrictStr, Dict[str, Any]]]] output: Literal["sentence", "tokens"] = "sentence" encoding_format: Literal["float", "base64"] = "float" class SimilarityRequest(Options): source: Union[StrictStr, Dict[str, Any]] targets: List[Union[StrictStr, Dict[str, Any]]] target_prompt_name: Optional[StrictStr] = None 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.model_factory: Optional[Callable] = None self.device = None # opened / closed by the lifespan on the MAIN thread (default factory, device engines) self.boot_s: Optional[float] = None self.requests = 0 def _b64(vec) -> str: import numpy as np return base64.b64encode(np.ascontiguousarray(vec, dtype=" Response: try: import orjson body = orjson.dumps(obj, option=orjson.OPT_SERIALIZE_NUMPY) except ImportError: # pragma: no cover import json import numpy as np body = json.dumps(obj, default=lambda o: o.tolist() if isinstance(o, np.ndarray) else str(o)).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(preps, want): return state.model.run(preps, want_tokens=want) 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.text_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("embeddinggemma-2 ready in %.1f s (engine %s)", state.boot_s, getattr(state.model, "engine_name", "?")) 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="EmbeddingGemma 2 on Tenstorrent p150", version=__version__, lifespan=lifespan) app.state.embgemma = 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") @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 64.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 (EMBGEMMA_MAX_BODY_MB)"}, status_code=413) return await call_next(request) def _prepare(raw_inputs: List[Any], opts: Options, prompt_names: Optional[List[Optional[str]]] = None): """Host preprocessing (worker thread) -> (prepared list, P.Options).""" from ..api import InputError, parse_input from ..media import MediaError m = state.model try: opt = m.options(dimensions=opts.dimensions, normalize=opts.normalize, max_length=opts.max_length, truncate=opts.truncate, image_tokens=opts.image_tokens, video_tokens=opts.video_tokens, video_fps=opts.video_fps, video_max_frames=opts.video_max_frames) preps = [] n_img = 0 cap = state.config.max_images for i, x in enumerate(raw_inputs): pn = opts.prompt_name if prompt_names is None else prompt_names[i] pr = m.resolve_prompt(opts.prompt if prompt_names is None or i == 0 else None, pn) p = m.prepare(parse_input(x, pr), opt) n_img += len(p.images) + sum(len(v) for v in p.videos) if n_img > cap: # bounds the host memory of one request (~8 MB of patches per image / frame) raise HTTPException(413, f"more than {cap} images / video frames in one request " "(EMBGEMMA_MAX_IMAGES): split the request") preps.append(p) return preps, opt except (InputError, MediaError) as e: raise HTTPException(400, str(e)) from None async def run_inputs(raw_inputs: List[Any], opts: Options, want_tokens: bool = False, prompt_names: Optional[List[Optional[str]]] = None) -> Dict: need_ready() cfg = state.config if not raw_inputs: raise HTTPException(400, "no inputs") if len(raw_inputs) > cfg.max_inputs: raise HTTPException(413, f"{len(raw_inputs)} inputs > EMBGEMMA_MAX_INPUTS={cfg.max_inputs}") t0 = time.perf_counter() loop = asyncio.get_running_loop() preps, opt = await loop.run_in_executor(None, lambda: _prepare(raw_inputs, opts, prompt_names)) t1 = time.perf_counter() try: futs = state.batcher.submit(preps, want_tokens) 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: parts = await asyncio.gather(*[asyncio.wrap_future(f) for f in futs]) 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, f"inference failed: {type(e).__name__}: {e}") from None import numpy as np from ..pipeline import finish sums = np.concatenate([p[0] for p in parts], 0) ntok = [int(x) for p in parts for x in p[1]] toks = [t for p in parts for t in p[2]] if want_tokens else None out = finish(sums, ntok, opt.dimensions, opt.normalize) if not want_tokens else None t2 = time.perf_counter() state.requests += 1 timing = {"preprocess_ms": round(1e3 * (t1 - t0), 3), "device_ms": round(1e3 * sum(p[3] for p in parts), 3), "total_ms": round(1e3 * (t2 - t0), 3), "device_batches": len(parts), "batch_inputs": [int(p[4]) for p in parts]} return {"out": out, "tokens": toks, "n_tokens": ntok, "opt": opt, "timing": timing, "truncated": [bool(p.seq.truncated) for p in preps]} @app.get("/") async def root(): return {"model": MODEL_NAME, "routes": ["POST /v1/embeddings", "POST /embed", "POST /similarity", "GET /info", "GET /health", "GET /v1/health", "GET /v1/models"]} @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.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("/v1/models") async def models(): return {"object": "list", "data": [{"id": MODEL_NAME, "object": "model", "owned_by": "changh95", "created": 0}]} @app.get("/info") async def info(): d = {"model": MODEL_NAME, "repo": C.REPO, "weights": C.WEIGHTS_REPO, "task": TASK, "hardware": HARDWARE, "version": __version__, "ready": state.ready, "error": state.error, "boot_s": state.boot_s, "requests": state.requests, "api": {"openai": "/v1/embeddings (input, model, encoding_format float|base64, dimensions 768|512|256|128, " "prompt_name, prompt)", "native": "/embed (inputs: text / image / video / audio / content, prompt_name, prompt, dimensions, " "normalize, output sentence|tokens, max_length, truncate right|error, image_tokens, " "video_fps, video_max_frames, video_tokens, encoding_format)", "similarity": "/similarity (source, targets, + /embed options)"}} if state.config is not None: cfg = state.config d["config"] = cfg.as_dict() d["limits"] = {"max_inputs": cfg.max_inputs, "max_images": cfg.max_images, "max_batch": cfg.max_batch, "max_seq_len": cfg.max_seq_len, "image_tokens_max": cfg.image_tokens_max, "video_max_frames": cfg.video_max_frames, "audio_max_seconds": cfg.audio_max_seconds, "dimensions": [768, 512, 256, 128], "modalities": list(cfg.modalities)} if state.ready: d["model_info"] = state.model.info d["prompts"] = dict(state.model.tok.prompts) d["device"] = d["model_info"].get("device", {}) d["engine"] = d["model_info"].get("engine") if state.batcher is not None: d["batcher"] = state.batcher.status() return d @app.post("/v1/embeddings") async def embeddings(req: EmbeddingsRequest): inp = req.input if isinstance(inp, str): texts = [inp] elif isinstance(inp, list) and all(isinstance(t, str) for t in inp): texts = list(inp) elif isinstance(inp, list) and inp and all(isinstance(t, (int, list)) for t in inp): raise HTTPException(400, "token-id input is not supported: send strings (the server tokenizes with the " "model's tokenizer); images / audio / video go to POST /embed") else: raise HTTPException(400, "input must be a string or a list of strings") if not texts: raise HTTPException(400, "input is empty") dims = 768 if req.dimensions is None else req.dimensions pn = req.prompt_name if pn is None and req.prompt is None and state.config is not None: pn = state.config.default_prompt opts = Options(prompt_name=pn, prompt=req.prompt, dimensions=dims) r = await run_inputs(texts, opts) fmt = req.encoding_format or "float" ntok = sum(r["n_tokens"]) data = [{"object": "embedding", "index": i, "embedding": _vec(v, fmt)} for i, v in enumerate(r["out"])] return _json({"object": "list", "data": data, "model": req.model or MODEL_NAME, "usage": {"prompt_tokens": ntok, "total_tokens": ntok}}, headers={"X-Timing-Ms": str(r["timing"]["total_ms"])}) @app.post("/embed") async def embed(req: EmbedRequest): raw = req.inputs if isinstance(req.inputs, list) else [req.inputs] r = await run_inputs(raw, req, want_tokens=req.output == "tokens") fmt = req.encoding_format if req.output == "tokens": emb = [[_vec(v, fmt) for v in t] for t in r["tokens"]] dim = 768 else: emb = [_vec(v, fmt) for v in r["out"]] dim = req.dimensions return _json({"model": MODEL_NAME, "dim": dim, "output": req.output, "normalize": req.normalize, "encoding_format": fmt, "n_tokens": r["n_tokens"], "truncated": r["truncated"], "embeddings": emb, "timing_ms": r["timing"]}) @app.post("/similarity") async def similarity(req: SimilarityRequest): if not req.targets: raise HTTPException(400, "targets is empty") names = [req.prompt_name] + [req.target_prompt_name] * len(req.targets) r = await run_inputs([req.source] + list(req.targets), req, prompt_names=names) e = r["out"] sims = (e[1:] @ e[0]).tolist() return {"model": MODEL_NAME, "scores": [float(s) for s in sims], "dimensions": req.dimensions, "timing_ms": r["timing"]} return app app = create_app()