2023-08-25 06:28:51 +02:00
|
|
|
import asyncio
|
2023-11-17 04:42:44 +02:00
|
|
|
import gc
|
|
|
|
import os
|
|
|
|
import sys
|
2023-09-09 11:02:44 +02:00
|
|
|
import threading
|
2023-11-17 04:42:44 +02:00
|
|
|
import time
|
2023-08-25 06:28:51 +02:00
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
2023-06-05 16:40:48 +02:00
|
|
|
from typing import Any
|
2023-09-09 11:02:44 +02:00
|
|
|
from zipfile import BadZipFile
|
2023-06-07 03:48:51 +02:00
|
|
|
|
2023-08-29 15:58:00 +02:00
|
|
|
import orjson
|
|
|
|
from fastapi import FastAPI, Form, HTTPException, UploadFile
|
|
|
|
from fastapi.responses import ORJSONResponse
|
2023-11-13 18:18:46 +02:00
|
|
|
from onnxruntime.capi.onnxruntime_pybind11_state import InvalidProtobuf, NoSuchFile
|
2023-08-29 15:58:00 +02:00
|
|
|
from starlette.formparsers import MultiPartParser
|
2023-06-25 05:18:09 +02:00
|
|
|
|
2023-08-25 06:28:51 +02:00
|
|
|
from app.models.base import InferenceModel
|
|
|
|
|
2023-08-30 10:22:01 +02:00
|
|
|
from .config import log, settings
|
2023-06-25 05:18:09 +02:00
|
|
|
from .models.cache import ModelCache
|
|
|
|
from .schemas import (
|
2023-06-05 16:40:48 +02:00
|
|
|
MessageResponse,
|
2023-06-25 05:18:09 +02:00
|
|
|
ModelType,
|
2023-06-05 16:40:48 +02:00
|
|
|
TextResponse,
|
|
|
|
)
|
2023-06-18 05:49:19 +02:00
|
|
|
|
2023-11-20 17:05:35 +02:00
|
|
|
MultiPartParser.max_file_size = 2**26 # spools to disk if payload is 64 MiB or larger
|
2023-05-17 19:07:17 +02:00
|
|
|
app = FastAPI()
|
|
|
|
|
2023-04-26 12:39:24 +02:00
|
|
|
|
2023-06-28 01:21:33 +02:00
|
|
|
def init_state() -> None:
|
2023-07-11 19:01:21 +02:00
|
|
|
app.state.model_cache = ModelCache(ttl=settings.model_ttl, revalidate=settings.model_ttl > 0)
|
2023-08-30 10:22:01 +02:00
|
|
|
log.info(
|
|
|
|
(
|
|
|
|
"Created in-memory cache with unloading "
|
|
|
|
f"{f'after {settings.model_ttl}s of inactivity' if settings.model_ttl > 0 else 'disabled'}."
|
|
|
|
)
|
|
|
|
)
|
2023-08-25 06:28:51 +02:00
|
|
|
# asyncio is a huge bottleneck for performance, so we use a thread pool to run blocking code
|
2023-09-01 01:30:53 +02:00
|
|
|
app.state.thread_pool = ThreadPoolExecutor(settings.request_threads) if settings.request_threads > 0 else None
|
2023-11-17 04:42:44 +02:00
|
|
|
app.state.lock = threading.Lock()
|
|
|
|
app.state.last_called = None
|
|
|
|
if settings.model_ttl > 0 and settings.model_ttl_poll_s > 0:
|
|
|
|
asyncio.ensure_future(idle_shutdown_task())
|
2023-08-30 10:22:01 +02:00
|
|
|
log.info(f"Initialized request thread pool with {settings.request_threads} threads.")
|
2023-06-28 01:21:33 +02:00
|
|
|
|
|
|
|
|
|
|
|
@app.on_event("startup")
|
|
|
|
async def startup_event() -> None:
|
|
|
|
init_state()
|
2023-06-25 05:18:09 +02:00
|
|
|
|
2023-06-18 05:49:19 +02:00
|
|
|
|
2023-06-05 16:40:48 +02:00
|
|
|
@app.get("/", response_model=MessageResponse)
|
|
|
|
async def root() -> dict[str, str]:
|
2023-04-26 12:39:24 +02:00
|
|
|
return {"message": "Immich ML"}
|
|
|
|
|
|
|
|
|
2023-06-05 16:40:48 +02:00
|
|
|
@app.get("/ping", response_model=TextResponse)
|
|
|
|
def ping() -> str:
|
2023-02-18 17:13:37 +02:00
|
|
|
return "pong"
|
|
|
|
|
2023-06-03 04:42:47 +02:00
|
|
|
|
2023-08-29 15:58:00 +02:00
|
|
|
@app.post("/predict")
|
|
|
|
async def predict(
|
|
|
|
model_name: str = Form(alias="modelName"),
|
|
|
|
model_type: ModelType = Form(alias="modelType"),
|
|
|
|
options: str = Form(default="{}"),
|
|
|
|
text: str | None = Form(default=None),
|
|
|
|
image: UploadFile | None = None,
|
|
|
|
) -> Any:
|
|
|
|
if image is not None:
|
|
|
|
inputs: str | bytes = await image.read()
|
|
|
|
elif text is not None:
|
|
|
|
inputs = text
|
|
|
|
else:
|
|
|
|
raise HTTPException(400, "Either image or text must be provided")
|
2023-09-09 11:02:44 +02:00
|
|
|
try:
|
|
|
|
kwargs = orjson.loads(options)
|
|
|
|
except orjson.JSONDecodeError:
|
|
|
|
raise HTTPException(400, f"Invalid options JSON: {options}")
|
2023-02-18 17:13:37 +02:00
|
|
|
|
2023-09-09 11:02:44 +02:00
|
|
|
model = await load(await app.state.model_cache.get(model_name, model_type, **kwargs))
|
|
|
|
model.configure(**kwargs)
|
2023-08-29 15:58:00 +02:00
|
|
|
outputs = await run(model, inputs)
|
|
|
|
return ORJSONResponse(outputs)
|
2023-06-03 04:42:47 +02:00
|
|
|
|
|
|
|
|
2023-08-29 15:58:00 +02:00
|
|
|
async def run(model: InferenceModel, inputs: Any) -> Any:
|
2023-11-17 04:42:44 +02:00
|
|
|
app.state.last_called = time.time()
|
2023-09-09 11:02:44 +02:00
|
|
|
if app.state.thread_pool is None:
|
2023-09-01 01:30:53 +02:00
|
|
|
return model.predict(inputs)
|
2023-09-09 11:02:44 +02:00
|
|
|
return await asyncio.get_running_loop().run_in_executor(app.state.thread_pool, model.predict, inputs)
|
|
|
|
|
|
|
|
|
|
|
|
async def load(model: InferenceModel) -> InferenceModel:
|
|
|
|
if model.loaded:
|
|
|
|
return model
|
|
|
|
|
|
|
|
def _load() -> None:
|
2023-11-17 04:42:44 +02:00
|
|
|
with app.state.lock:
|
2023-09-09 11:02:44 +02:00
|
|
|
model.load()
|
|
|
|
|
|
|
|
loop = asyncio.get_running_loop()
|
|
|
|
try:
|
|
|
|
if app.state.thread_pool is None:
|
|
|
|
model.load()
|
|
|
|
else:
|
|
|
|
await loop.run_in_executor(app.state.thread_pool, _load)
|
|
|
|
return model
|
|
|
|
except (OSError, InvalidProtobuf, BadZipFile, NoSuchFile):
|
|
|
|
log.warn(
|
|
|
|
(
|
|
|
|
f"Failed to load {model.model_type.replace('_', ' ')} model '{model.model_name}'."
|
|
|
|
"Clearing cache and retrying."
|
|
|
|
)
|
|
|
|
)
|
|
|
|
model.clear_cache()
|
|
|
|
if app.state.thread_pool is None:
|
|
|
|
model.load()
|
|
|
|
else:
|
|
|
|
await loop.run_in_executor(app.state.thread_pool, _load)
|
|
|
|
return model
|
2023-11-17 04:42:44 +02:00
|
|
|
|
|
|
|
|
|
|
|
async def idle_shutdown_task() -> None:
|
|
|
|
while True:
|
|
|
|
log.debug("Checking for inactivity...")
|
|
|
|
if app.state.last_called is not None and time.time() - app.state.last_called > settings.model_ttl:
|
|
|
|
log.info("Shutting down due to inactivity.")
|
|
|
|
loop = asyncio.get_running_loop()
|
|
|
|
for task in asyncio.all_tasks(loop):
|
|
|
|
if task is not asyncio.current_task():
|
|
|
|
try:
|
|
|
|
task.cancel()
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
|
|
|
sys.stderr.close()
|
|
|
|
sys.stdout.close()
|
|
|
|
sys.stdout = sys.stderr = open(os.devnull, "w")
|
|
|
|
try:
|
|
|
|
await app.state.model_cache.cache.clear()
|
|
|
|
gc.collect()
|
|
|
|
loop.stop()
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
|
|
|
await asyncio.sleep(settings.model_ttl_poll_s)
|