CrazyH0rse's picture
Upload folder using huggingface_hub
4807d4b verified
Raw History Blame Contribute Delete
1.64 kB
"""An HTTP server for a Discerna model: `POST /v1/decide` takes a request and returns its answers.
discerna serve --model <owner>/Discerna-v1-475M # or a local model folder
Errors: a request beyond the model's limits is HTTP 413 with "unsupported" in the body, an invalid
body is 422, anything else is 500.
"""
from __future__ import annotations
import threading
from fastapi import FastAPI, HTTPException
from discerna import __version__
from discerna.contract import DecisionRequest
from discerna.engine import Discerna, Unsupported
def create_app(model: Discerna) -> FastAPI:
app = FastAPI(title="Discerna", version=__version__)
lock = threading.Lock() # one forward pass at a time: torch models are not thread-safe
@app.get("/healthz")
def healthz() -> dict:
return {"ok": True}
@app.get("/v1/models")
def models() -> dict:
return {"data": [{"id": model.name, "modalities": ["text", "image"] if model.accepts_images else ["text"],
"device": str(model.device), "dtype": str(model.dtype).removeprefix("torch.")}]}
@app.post("/v1/decide")
def decide(request: DecisionRequest) -> dict:
with lock:
result = model.decide_batch([request])[0]
if isinstance(result, Unsupported):
raise HTTPException(status_code=413, detail={"error": "unsupported", "reason": str(result)})
if isinstance(result, Exception):
raise HTTPException(status_code=500, detail={"error": type(result).__name__, "reason": str(result)})
return result.model_dump(mode="json", exclude_none=True)
return app