Initial commit

This commit is contained in:
timur 2026-07-25 14:51:45 +05:00
commit ece9957d48
21 changed files with 1125 additions and 0 deletions

6
.dockerignore Normal file
View File

@ -0,0 +1,6 @@
.git
.venv
__pycache__
.pytest_cache
tests

13
.env.example Normal file
View File

@ -0,0 +1,13 @@
HF_TOKEN=
API_KEY=
LOG_LEVEL=INFO
# Host paths mounted into the container. Model downloads survive rebuilds.
MODEL_STORAGE_PATH=./models
DATA_STORAGE_PATH=./data
# Override only when a different CUDA 13.3 image variant is required.
CUDA_IMAGE=nvidia/cuda:13.3.0-cudnn-runtime-ubuntu24.04
# MODEL_SERVER_QWEN_MODEL=Qwen/Qwen2.5-7B-Instruct
# MODEL_SERVER_WHISPER_MODEL=large-v3-turbo
# MODEL_SERVER_PYANNOTE_MODEL=pyannote/speaker-diarization-community-1
# MODEL_SERVER_EMOTION_MODEL=xbgoose/hubert-large-speech-emotion-recognition-russian-dusha-finetuned
# MODEL_SERVER_QWEN_LOAD_IN_4BIT=true

45
.gitignore vendored Normal file
View File

@ -0,0 +1,45 @@
# Local configuration and secrets
.env
.env.*
!.env.example
# Python virtual environments
.venv/
venv/
env/
# Python bytecode and caches
__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
.coverage.*
htmlcov/
# Package and build output
build/
dist/
*.egg-info/
*.egg
# Runtime data and downloaded models
data/
models/
uploads/
.cache/
# Editors and operating systems
.idea/
.vscode/
*.swp
*.swo
.DS_Store
Thumbs.db
# Logs and temporary files
*.log
*.tmp
*.pid

30
Dockerfile Normal file
View File

@ -0,0 +1,30 @@
ARG CUDA_IMAGE=nvidia/cuda:13.3.0-cudnn-runtime-ubuntu24.04
FROM ${CUDA_IMAGE}
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PATH=/opt/venv/bin:$PATH \
MODEL_SERVER_DATA_DIR=/data \
MODEL_SERVER_MODELS_DIR=/models \
HF_HOME=/models/huggingface \
TORCH_HOME=/models/torch \
XDG_CACHE_HOME=/models/cache
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
python3 \
python3-venv \
python3-dev \
libpython3.12 \
build-essential \
ffmpeg \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /srv/app
COPY pyproject.toml ./
COPY app ./app
RUN python3 -m venv /opt/venv \
&& python -m pip install --upgrade pip \
&& python -m pip install .
RUN mkdir -p /data /models
EXPOSE 8000
CMD ["python3", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]

102
README.md Normal file
View File

@ -0,0 +1,102 @@
# Single-GPU speech and language API
A FastAPI service that runs Whisper transcription, Pyannote speaker diarization, Russian speech emotion recognition, and Qwen chat inference on one NVIDIA GPU. A single FIFO worker serializes every inference request. When the task type changes, the current model is released and the next is loaded; downloaded weights remain in the Hugging Face/container cache and the operating-system page cache (RAM), making later loads faster.
The defaults are chosen for a 16 GB GPU: `faster-whisper` large-v3-turbo in FP16, Pyannote 3.1, and Qwen2.5-7B-Instruct in 4-bit. Do not start multiple Uvicorn workers because each worker would own a queue and could use the GPU concurrently.
## Run
Accept the conditions for `pyannote/speaker-diarization-community-1` on Hugging Face and create a read token, then:
```bash
cp .env.example .env
# set HF_TOKEN in .env
docker compose up --build
```
The Docker image uses NVIDIA CUDA 13.3.0 with cuDNN. Override `CUDA_IMAGE` in
`.env` to select another CUDA 13.3 image variant. Model downloads are stored
on the host in `./models` and temporary uploaded data in `./data`; set
`MODEL_STORAGE_PATH` or `DATA_STORAGE_PATH` in `.env` to use other locations.
These bind mounts keep model weights outside the image and preserve them across
container rebuilds.
Set `LOG_LEVEL` in `.env` to `DEBUG`, `INFO`, `WARNING`, `ERROR`, or `CRITICAL`.
The default is `INFO`; container logs are available through
`docker compose logs -f api`.
An API key is optional. Set `API_KEY` to enable it and send `Authorization: Bearer <key>`.
## API
Requests wait for their queued job by default. Set `async_job=true` (multipart field for audio, JSON field for chat) to immediately receive a job ID, then poll `GET /v1/jobs/{id}`.
```bash
curl -F file=@speech.wav -F language=en http://localhost:8000/v1/audio/transcriptions
curl -F file=@meeting.wav -F min_speakers=2 http://localhost:8000/v1/audio/diarizations
curl -F file=@speech.wav http://localhost:8000/v1/audio/emotions
curl http://localhost:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"messages":[{"role":"user","content":"Hello"}],"max_tokens":128}'
```
Swagger documentation is at `/docs`; readiness is at `/healthz`. Audio uploads default to a 500 MB limit. Configuration uses `MODEL_SERVER_`-prefixed environment variables; see `app/config.py` for all settings.
For local development (with a CUDA-enabled PyTorch environment already available):
```bash
python -m venv .venv
. .venv/bin/activate
pip install -e '.[test]'
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 1
pytest
```
## Production without Docker
On an apt-based Linux host with a working NVIDIA driver, install the service
from the repository checkout:
```bash
sudo ./scripts/install-host.sh
sudoedit /etc/llmserver/llmserver.env
sudo systemctl restart llmserver
curl http://127.0.0.1:8000/healthz
```
The installer creates a dedicated `llmserver` account, a virtual environment
under `/opt/llmserver`, and a single-worker systemd service. Configuration is
kept in `/etc/llmserver/llmserver.env`, uploads in `/var/lib/llmserver`, and the
Hugging Face model cache in `/var/cache/llmserver`. It is safe to rerun the
installer to update the application; those persistent directories are retained.
Useful service commands:
```bash
systemctl status llmserver
journalctl -u llmserver -f
sudo systemctl restart llmserver
```
To disable the service while preserving the application, configuration, cached
models, and uploaded data:
```bash
sudo ./scripts/uninstall-host.sh
```
The Python environment installs CUDA 12 cuBLAS alongside PyTorch's CUDA
runtime. This is intentional: the prebuilt CTranslate2 wheel used by
Faster-Whisper currently requires `libcublas.so.12`. The server preloads that
library from the Python package, so no manual `LD_LIBRARY_PATH` is required.
## Notes
- Persist `/models` so model weights are not downloaded again. The Compose file
maps it to `${MODEL_STORAGE_PATH:-./models}` on the host.
- The queue is in memory. Jobs do not survive process restarts and this service must be deployed as one process/replica.
- Pyannote returns speaker time ranges. Combine its result with Whisper segments in a client if speaker-attributed transcripts are needed.
- Qwen 7B at 4-bit leaves headroom for KV cache on 16 GB. Reduce `max_tokens` or use a smaller Qwen model for unusually long prompts.

2
app/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Single GPU inference service."""

54
app/config.py Normal file
View File

@ -0,0 +1,54 @@
from functools import lru_cache
import logging
from pathlib import Path
from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="MODEL_SERVER_", env_file=".env", extra="ignore"
)
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices("MODEL_SERVER_API_KEY", "API_KEY"),
)
data_dir: Path = Path("/tmp/model-server")
models_dir: Path = Path("/models")
log_level: str = "INFO"
device: str = "cuda"
whisper_model: str = "large-v3-turbo"
whisper_compute_type: str = "float16"
pyannote_model: str = "pyannote/speaker-diarization-community-1"
emotion_model: str = "xbgoose/hubert-large-speech-emotion-recognition-russian-dusha-finetuned"
huggingface_token: str | None = Field(
default=None,
validation_alias=AliasChoices("MODEL_SERVER_HUGGINGFACE_TOKEN", "HF_TOKEN"),
)
qwen_model: str = "Qwen/Qwen2.5-7B-Instruct"
qwen_load_in_4bit: bool = True
qwen_max_new_tokens: int = 1024
max_upload_mb: int = 500
@lru_cache
def get_settings() -> Settings:
settings = Settings()
settings.data_dir.mkdir(parents=True, exist_ok=True)
settings.models_dir.mkdir(parents=True, exist_ok=True)
return settings
def configure_logging(level: str) -> None:
numeric_level = getattr(logging, level.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f"Invalid log level: {level}")
logging.basicConfig(
level=numeric_level,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
force=True,
)
for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
logging.getLogger(logger_name).setLevel(numeric_level)

121
app/main.py Normal file
View File

@ -0,0 +1,121 @@
from contextlib import asynccontextmanager
import logging
from pathlib import Path
from typing import Annotated
from uuid import uuid4
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Request, UploadFile, status
from .config import Settings, configure_logging, get_settings
from .models import ModelManager
from .queue import JobQueue
from .schemas import ChatRequest, Job, JobResponse, JobStatus, TaskType
logger = logging.getLogger(__name__)
def require_auth(settings: Settings = Depends(get_settings), authorization: str | None = Header(default=None)) -> None:
if settings.api_key and authorization != f"Bearer {settings.api_key}":
logger.warning("Rejected request with invalid or missing API credentials")
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
@asynccontextmanager
async def lifespan(app: FastAPI):
settings = get_settings()
configure_logging(settings.log_level)
logger.info("Starting model server (device=%s, models_dir=%s)", settings.device, settings.models_dir)
app.state.queue = JobQueue(ModelManager(settings))
await app.state.queue.start()
yield
await app.state.queue.stop()
logger.info("Model server stopped")
app = FastAPI(title="Single GPU Model Server", version="0.1.0", lifespan=lifespan)
def queue_for(request: Request) -> JobQueue:
return request.app.state.queue
async def save_upload(upload: UploadFile, settings: Settings) -> Path:
suffix = Path(upload.filename or "audio").suffix
path = settings.data_dir / f"{uuid4().hex}{suffix}"
size = 0
with path.open("wb") as target:
while chunk := await upload.read(1024 * 1024):
size += len(chunk)
if size > settings.max_upload_mb * 1024 * 1024:
target.close()
path.unlink(missing_ok=True)
raise HTTPException(status_code=413, detail="Audio file is too large")
target.write(chunk)
await upload.close()
logger.debug("Stored upload path=%s size_bytes=%d", path, size)
return path
async def response_or_job(queue: JobQueue, job: Job, asynchronous: bool):
if asynchronous:
return JobResponse(id=job.id, status=job.status)
finished = await queue.wait(job.id)
if finished.status == JobStatus.FAILED:
raise HTTPException(status_code=500, detail=finished.error)
return finished.result
@app.get("/healthz")
async def health() -> dict[str, str]:
return {"status": "ok"}
@app.get("/v1/jobs/{job_id}", dependencies=[Depends(require_auth)], response_model=Job)
async def get_job(job_id: str, queue: Annotated[JobQueue, Depends(queue_for)]) -> Job:
if job_id not in queue.jobs:
raise HTTPException(status_code=404, detail="Job not found")
return queue.jobs[job_id]
@app.post("/v1/audio/transcriptions", dependencies=[Depends(require_auth)])
async def transcribe(
queue: Annotated[JobQueue, Depends(queue_for)],
settings: Annotated[Settings, Depends(get_settings)],
file: UploadFile = File(...), language: str | None = Form(default=None), async_job: bool = Form(default=False),
):
path = await save_upload(file, settings)
job = await queue.submit(TaskType.WHISPER, {"language": language}, path)
return await response_or_job(queue, job, async_job)
@app.post("/v1/audio/diarizations", dependencies=[Depends(require_auth)])
async def diarize(
queue: Annotated[JobQueue, Depends(queue_for)],
settings: Annotated[Settings, Depends(get_settings)],
file: UploadFile = File(...), min_speakers: int | None = Form(default=None),
max_speakers: int | None = Form(default=None), async_job: bool = Form(default=False),
):
path = await save_upload(file, settings)
job = await queue.submit(TaskType.PYANNOTE, {"min_speakers": min_speakers, "max_speakers": max_speakers}, path)
return await response_or_job(queue, job, async_job)
@app.post("/v1/audio/emotions", dependencies=[Depends(require_auth)])
async def recognize_emotion(
queue: Annotated[JobQueue, Depends(queue_for)],
settings: Annotated[Settings, Depends(get_settings)],
file: UploadFile = File(...),
async_job: bool = Form(default=False),
):
path = await save_upload(file, settings)
job = await queue.submit(TaskType.EMOTION, {}, path)
return await response_or_job(queue, job, async_job)
@app.post("/v1/chat/completions", dependencies=[Depends(require_auth)])
async def chat(body: ChatRequest, queue: Annotated[JobQueue, Depends(queue_for)]):
job = await queue.submit(
TaskType.QWEN,
{"messages": [m.model_dump() for m in body.messages], "max_tokens": body.max_tokens, "temperature": body.temperature},
)
return await response_or_job(queue, job, body.async_job)

168
app/models.py Normal file
View File

@ -0,0 +1,168 @@
import gc
import ctypes
import logging
from importlib.util import find_spec
from pathlib import Path
from typing import Any
from .config import Settings
logger = logging.getLogger(__name__)
def _preload_ctranslate2_cuda_libraries() -> None:
"""Load pip-installed CUDA 12 cuBLAS for CTranslate2.
CTranslate2 dynamically opens ``libcublas.so.12`` by soname. Python wheels
install it outside the system loader path, so load it by absolute path and
expose it globally before importing faster_whisper.
"""
spec = find_spec("nvidia.cublas")
if spec is None or not spec.submodule_search_locations:
return
library_dir = Path(next(iter(spec.submodule_search_locations))) / "lib"
for name in ("libcublasLt.so.12", "libcublas.so.12"):
library = library_dir / name
if library.exists():
ctypes.CDLL(str(library), mode=ctypes.RTLD_GLOBAL)
class ModelManager:
"""Owns the only GPU model. Switching task types releases GPU memory first."""
def __init__(self, settings: Settings):
self.settings = settings
self._kind: str | None = None
self._model: Any = None
self._tokenizer: Any = None
def _release(self) -> None:
if self._kind:
logger.info("Releasing model kind=%s", self._kind)
self._model = None
self._tokenizer = None
self._kind = None
gc.collect()
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
except ImportError:
pass
def _switch_to(self, kind: str) -> None:
if self._kind != kind:
self._release()
else:
logger.debug("Reusing loaded model kind=%s", kind)
def transcribe(self, audio: Path, language: str | None = None) -> dict[str, Any]:
self._switch_to("whisper")
if self._model is None:
logger.info("Loading Whisper model=%s", self.settings.whisper_model)
_preload_ctranslate2_cuda_libraries()
from faster_whisper import WhisperModel
self._model = WhisperModel(
self.settings.whisper_model,
device=self.settings.device,
compute_type=self.settings.whisper_compute_type,
download_root=str(self.settings.models_dir / "faster-whisper"),
)
self._kind = "whisper"
segments, info = self._model.transcribe(str(audio), language=language, vad_filter=True)
items = [
{"id": i, "start": s.start, "end": s.end, "text": s.text.strip()}
for i, s in enumerate(segments)
]
return {
"text": " ".join(s["text"] for s in items),
"language": info.language,
"language_probability": info.language_probability,
"segments": items,
}
def diarize(self, audio: Path, min_speakers: int | None = None, max_speakers: int | None = None) -> dict[str, Any]:
self._switch_to("pyannote")
if self._model is None:
logger.info("Loading Pyannote model=%s", self.settings.pyannote_model)
import torch
from pyannote.audio import Pipeline
self._model = Pipeline.from_pretrained(
self.settings.pyannote_model,
token=self.settings.huggingface_token,
cache_dir=self.settings.models_dir / "huggingface",
)
self._model.to(torch.device(self.settings.device))
self._kind = "pyannote"
kwargs = {k: v for k, v in {"min_speakers": min_speakers, "max_speakers": max_speakers}.items() if v is not None}
output = self._model(str(audio), **kwargs)
annotation = getattr(output, "speaker_diarization", output)
segments = [
{"start": turn.start, "end": turn.end, "speaker": speaker}
for turn, _, speaker in annotation.itertracks(yield_label=True)
]
return {"segments": segments}
def recognize_emotion(self, audio: Path) -> dict[str, Any]:
self._switch_to("emotion")
if self._model is None:
logger.info("Loading emotion model=%s", self.settings.emotion_model)
from transformers import pipeline
self._model = pipeline(
"audio-classification",
model=self.settings.emotion_model,
device=self.settings.device,
model_kwargs={"cache_dir": self.settings.models_dir / "huggingface"},
)
self._kind = "emotion"
predictions = self._model(str(audio), top_k=None)
scores = [
{"label": prediction["label"], "score": float(prediction["score"])}
for prediction in predictions
]
return {
"emotion": scores[0]["label"],
"score": scores[0]["score"],
"scores": scores,
"model": self.settings.emotion_model,
}
def chat(self, messages: list[dict[str, str]], max_tokens: int | None, temperature: float) -> dict[str, Any]:
self._switch_to("qwen")
if self._model is None:
logger.info("Loading chat model=%s", self.settings.qwen_model)
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
quantization = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16) if self.settings.qwen_load_in_4bit else None
self._tokenizer = AutoTokenizer.from_pretrained(
self.settings.qwen_model, cache_dir=self.settings.models_dir / "huggingface"
)
self._model = AutoModelForCausalLM.from_pretrained(
self.settings.qwen_model,
dtype="auto",
device_map={"": self.settings.device},
quantization_config=quantization,
cache_dir=self.settings.models_dir / "huggingface",
)
self._kind = "qwen"
prompt = self._tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = self._tokenizer([prompt], return_tensors="pt").to(self.settings.device)
output = self._model.generate(
**inputs,
max_new_tokens=max_tokens or self.settings.qwen_max_new_tokens,
temperature=temperature,
do_sample=temperature > 0,
)
generated = output[0][inputs.input_ids.shape[1] :]
text = self._tokenizer.decode(generated, skip_special_tokens=True)
return {"message": {"role": "assistant", "content": text}, "model": self.settings.qwen_model}
def close(self) -> None:
self._release()

84
app/queue.py Normal file
View File

@ -0,0 +1,84 @@
import asyncio
import logging
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any
from .schemas import Job, JobStatus, TaskType
if TYPE_CHECKING:
from .models import ModelManager
logger = logging.getLogger(__name__)
class JobQueue:
def __init__(self, manager: "ModelManager"):
self.manager = manager
self.jobs: dict[str, Job] = {}
self._queue: asyncio.Queue[tuple[Job, dict[str, Any], Path | None]] = asyncio.Queue()
self._worker: asyncio.Task | None = None
self._waiters: dict[str, asyncio.Future[Job]] = {}
async def start(self) -> None:
logger.info("Starting single-GPU job worker")
self._worker = asyncio.create_task(self._run(), name="single-gpu-worker")
async def stop(self) -> None:
logger.info("Stopping job worker after queued work completes")
# Finish accepted work before releasing the active model. Cancelling a
# to_thread call does not stop its inference thread.
await self._queue.join()
if self._worker:
self._worker.cancel()
try:
await self._worker
except asyncio.CancelledError:
pass
await asyncio.to_thread(self.manager.close)
async def submit(self, task: TaskType, payload: dict[str, Any], file_path: Path | None = None) -> Job:
job = Job(task=task)
self.jobs[job.id] = job
self._waiters[job.id] = asyncio.get_running_loop().create_future()
await self._queue.put((job, payload, file_path))
logger.info("Queued job id=%s task=%s queue_size=%d", job.id, task.value, self._queue.qsize())
return job
async def wait(self, job_id: str) -> Job:
job = self.jobs[job_id]
if job.status in (JobStatus.SUCCEEDED, JobStatus.FAILED):
return job
logger.debug("Waiting for job id=%s", job_id)
return await asyncio.shield(self._waiters[job_id])
async def _run(self) -> None:
handlers: dict[TaskType, Callable[..., Any]] = {
TaskType.WHISPER: self.manager.transcribe,
TaskType.PYANNOTE: self.manager.diarize,
TaskType.EMOTION: self.manager.recognize_emotion,
TaskType.QWEN: self.manager.chat,
}
while True:
job, payload, file_path = await self._queue.get()
job.status = JobStatus.RUNNING
job.started_at = datetime.now(timezone.utc)
logger.info("Started job id=%s task=%s", job.id, job.task.value)
try:
args = (file_path,) if file_path else ()
job.result = await asyncio.to_thread(handlers[job.task], *args, **payload)
job.status = JobStatus.SUCCEEDED
logger.info("Completed job id=%s task=%s", job.id, job.task.value)
except Exception as exc:
job.status = JobStatus.FAILED
job.error = f"{type(exc).__name__}: {exc}"
logger.exception("Failed job id=%s task=%s", job.id, job.task.value)
finally:
job.finished_at = datetime.now(timezone.utc)
if file_path:
file_path.unlink(missing_ok=True)
waiter = self._waiters.get(job.id)
if waiter and not waiter.done():
waiter.set_result(job)
self._queue.task_done()

48
app/schemas.py Normal file
View File

@ -0,0 +1,48 @@
from datetime import datetime, timezone
from enum import StrEnum
from typing import Any, Literal
from uuid import uuid4
from pydantic import BaseModel, Field
class TaskType(StrEnum):
WHISPER = "whisper"
PYANNOTE = "pyannote"
EMOTION = "emotion"
QWEN = "qwen"
class JobStatus(StrEnum):
QUEUED = "queued"
RUNNING = "running"
SUCCEEDED = "succeeded"
FAILED = "failed"
class Job(BaseModel):
id: str = Field(default_factory=lambda: uuid4().hex)
task: TaskType
status: JobStatus = JobStatus.QUEUED
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
started_at: datetime | None = None
finished_at: datetime | None = None
result: Any = None
error: str | None = None
class ChatMessage(BaseModel):
role: Literal["system", "user", "assistant"]
content: str
class ChatRequest(BaseModel):
messages: list[ChatMessage]
max_tokens: int | None = Field(default=None, ge=1, le=8192)
temperature: float = Field(default=0.7, ge=0, le=2)
async_job: bool = False
class JobResponse(BaseModel):
id: str
status: JobStatus

28
compose.yaml Normal file
View File

@ -0,0 +1,28 @@
services:
api:
build:
context: .
args:
CUDA_IMAGE: ${CUDA_IMAGE:-nvidia/cuda:13.3.0-cudnn-runtime-ubuntu24.04}
ports:
- "9000:8000"
environment:
MODEL_SERVER_HUGGINGFACE_TOKEN: ${HF_TOKEN:-}
MODEL_SERVER_API_KEY: ${API_KEY:-}
MODEL_SERVER_LOG_LEVEL: ${LOG_LEVEL:-INFO}
MODEL_SERVER_WHISPER_MODEL: deepdml/faster-whisper-large-v3-turbo-ct2
MODEL_SERVER_QWEN_MODEL: Qwen/Qwen2.5-3B-Instruct
HF_HUB_OFFLINE: "1"
volumes:
# Bind mounts keep large model files and uploads outside Docker's
# writable layer. Override either location in .env when desired.
- ${MODEL_STORAGE_PATH:-./models}:/models
- ${DATA_STORAGE_PATH:-./data}:/data
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
restart: unless-stopped

View File

@ -0,0 +1,16 @@
# Required for gated Pyannote models. Accept the model terms on Hugging Face first.
HF_TOKEN=
# Strongly recommended when the API is reachable by other machines.
API_KEY=
# Optional model and runtime overrides.
# MODEL_SERVER_DEVICE=cuda
# MODEL_SERVER_WHISPER_MODEL=large-v3-turbo
# MODEL_SERVER_WHISPER_COMPUTE_TYPE=float16
# MODEL_SERVER_PYANNOTE_MODEL=pyannote/speaker-diarization-community-1
# MODEL_SERVER_EMOTION_MODEL=xbgoose/hubert-large-speech-emotion-recognition-russian-dusha-finetuned
# MODEL_SERVER_QWEN_MODEL=Qwen/Qwen2.5-7B-Instruct
# MODEL_SERVER_QWEN_LOAD_IN_4BIT=true
# MODEL_SERVER_QWEN_MAX_NEW_TOKENS=1024
# MODEL_SERVER_MAX_UPLOAD_MB=500

32
deploy/llmserver.service Normal file
View File

@ -0,0 +1,32 @@
[Unit]
Description=Single GPU speech and language API
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=llmserver
Group=llmserver
WorkingDirectory=/var/lib/llmserver
EnvironmentFile=/etc/llmserver/llmserver.env
Environment=PYTHONUNBUFFERED=1
Environment=HF_HOME=/var/cache/llmserver/huggingface
Environment=MODEL_SERVER_DATA_DIR=/var/lib/llmserver/uploads
ExecStart=/opt/llmserver/venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 1
Restart=on-failure
RestartSec=5s
TimeoutStopSec=90s
# systemd creates these directories and assigns them to User/Group.
StateDirectory=llmserver
CacheDirectory=llmserver
# Basic service hardening. GPU devices remain available to the process.
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=/var/lib/llmserver /var/cache/llmserver
[Install]
WantedBy=multi-user.target

33
pyproject.toml Normal file
View File

@ -0,0 +1,33 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "single-gpu-model-server"
version = "0.1.0"
description = "Sequential API server for Whisper, Pyannote, HuBERT emotion recognition, and Qwen"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115,<1",
"uvicorn[standard]>=0.30,<1",
"python-multipart>=0.0.9,<1",
"pydantic-settings>=2.4,<3",
"torch>=2.4,<3",
"transformers>=4.45,<5",
"accelerate>=0.34,<2",
"bitsandbytes>=0.43,<1; platform_system == 'Linux'",
"faster-whisper>=1.0,<2",
# CTranslate2 wheels currently target CUDA 12 even when PyTorch uses CUDA 13.
"nvidia-cublas-cu12>=12,<13; platform_system == 'Linux' and platform_machine == 'x86_64'",
"pyannote.audio>=4.0.4,<5",
]
[project.optional-dependencies]
test = ["httpx>=0.27,<1", "pytest>=8,<9", "pytest-asyncio>=0.23,<1"]
[tool.hatch.build.targets.wheel]
packages = ["app"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]

68
scripts/install-host.sh Executable file
View File

@ -0,0 +1,68 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${EUID} -ne 0 ]]; then
echo "Run this installer as root: sudo $0" >&2
exit 1
fi
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd -- "${SCRIPT_DIR}/.." && pwd)
INSTALL_DIR=/opt/llmserver
CONFIG_DIR=/etc/llmserver
SERVICE_FILE=/etc/systemd/system/llmserver.service
if ! command -v apt-get >/dev/null 2>&1; then
echo "This installer currently supports apt-based Linux distributions." >&2
exit 1
fi
echo "Installing operating-system dependencies..."
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y \
python3 python3-venv python3-pip ffmpeg
PYTHON_BIN=${PYTHON_BIN:-python3}
python_version=$("${PYTHON_BIN}" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
if ! "${PYTHON_BIN}" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))'; then
echo "Python 3.11 or newer is required; found ${python_version}." >&2
echo "Install it, then rerun with: sudo PYTHON_BIN=/path/to/python3.11 $0" >&2
exit 1
fi
if ! getent group llmserver >/dev/null; then
groupadd --system llmserver
fi
if ! id -u llmserver >/dev/null 2>&1; then
useradd --system --gid llmserver --home-dir /var/lib/llmserver \
--shell /usr/sbin/nologin llmserver
fi
install -d -m 0755 "${INSTALL_DIR}" "${CONFIG_DIR}"
if [[ ! -x "${INSTALL_DIR}/venv/bin/python" ]]; then
"${PYTHON_BIN}" -m venv "${INSTALL_DIR}/venv"
fi
echo "Installing the application and Python dependencies..."
"${INSTALL_DIR}/venv/bin/python" -m pip install --upgrade pip
"${INSTALL_DIR}/venv/bin/python" -m pip install --upgrade "${PROJECT_DIR}"
if [[ ! -e "${CONFIG_DIR}/llmserver.env" ]]; then
install -m 0600 "${PROJECT_DIR}/deploy/llmserver.env.example" \
"${CONFIG_DIR}/llmserver.env"
echo "Created ${CONFIG_DIR}/llmserver.env; add HF_TOKEN before using diarization."
else
echo "Preserving existing ${CONFIG_DIR}/llmserver.env."
fi
install -m 0644 "${PROJECT_DIR}/deploy/llmserver.service" "${SERVICE_FILE}"
systemctl daemon-reload
systemctl enable llmserver.service
systemctl restart llmserver.service
echo
echo "Installation complete."
echo "Configuration: ${CONFIG_DIR}/llmserver.env"
echo "Status: systemctl status llmserver"
echo "Logs: journalctl -u llmserver -f"
echo "Health check: curl http://127.0.0.1:8000/healthz"

22
scripts/uninstall-host.sh Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${EUID} -ne 0 ]]; then
echo "Run this uninstaller as root: sudo $0" >&2
exit 1
fi
systemctl disable --now llmserver.service 2>/dev/null || true
if [[ -e /etc/systemd/system/llmserver.service ]]; then
mv /etc/systemd/system/llmserver.service \
"/etc/systemd/system/llmserver.service.removed.$(date +%s)"
fi
systemctl daemon-reload
echo "The service was disabled and its unit was archived."
echo "Application, configuration, model cache, and data were preserved:"
echo " /opt/llmserver"
echo " /etc/llmserver"
echo " /var/cache/llmserver"
echo " /var/lib/llmserver"
echo "Remove those directories manually only if their contents are no longer needed."

38
tests/test_config.py Normal file
View File

@ -0,0 +1,38 @@
from pathlib import Path
from app.config import Settings
def test_short_environment_names(monkeypatch, tmp_path):
monkeypatch.setenv("HF_TOKEN", "hf_test")
monkeypatch.setenv("API_KEY", "secret")
settings = Settings(_env_file=None, data_dir=tmp_path)
assert settings.huggingface_token == "hf_test"
assert settings.api_key == "secret"
def test_prefixed_environment_names(monkeypatch, tmp_path):
monkeypatch.delenv("HF_TOKEN", raising=False)
monkeypatch.delenv("API_KEY", raising=False)
monkeypatch.setenv("MODEL_SERVER_HUGGINGFACE_TOKEN", "hf_prefixed")
monkeypatch.setenv("MODEL_SERVER_API_KEY", "prefixed-secret")
settings = Settings(_env_file=None, data_dir=tmp_path)
assert settings.huggingface_token == "hf_prefixed"
assert settings.api_key == "prefixed-secret"
def test_default_emotion_model(tmp_path):
settings = Settings(_env_file=None, data_dir=tmp_path)
assert settings.emotion_model == "xbgoose/hubert-large-speech-emotion-recognition-russian-dusha-finetuned"
def test_logging_and_model_storage_defaults(tmp_path):
settings = Settings(_env_file=None, data_dir=tmp_path)
assert settings.log_level == "INFO"
assert settings.models_dir == Path("/models")

75
tests/test_models.py Normal file
View File

@ -0,0 +1,75 @@
from pathlib import Path
from types import ModuleType
import sys
from app.config import Settings
from app import models
def test_preloads_pip_cublas_in_dependency_order(monkeypatch, tmp_path):
package = tmp_path / "cublas"
library_dir = package / "lib"
library_dir.mkdir(parents=True)
for name in ("libcublasLt.so.12", "libcublas.so.12"):
(library_dir / name).touch()
class Spec:
submodule_search_locations = [str(package)]
loaded = []
monkeypatch.setattr(models, "find_spec", lambda _: Spec())
monkeypatch.setattr(models.ctypes, "CDLL", lambda path, mode: loaded.append(Path(path).name))
models._preload_ctranslate2_cuda_libraries()
assert loaded == ["libcublasLt.so.12", "libcublas.so.12"]
def test_emotion_recognition_uses_configured_pipeline(monkeypatch, tmp_path):
audio = tmp_path / "speech.wav"
audio.touch()
calls = []
class FakePipeline:
def __call__(self, path, top_k):
calls.append((path, top_k))
return [
{"label": "positive", "score": 0.75},
{"label": "neutral", "score": 0.25},
]
def fake_pipeline(task, model, device, model_kwargs):
calls.append((task, model, device, model_kwargs))
return FakePipeline()
transformers = ModuleType("transformers")
transformers.pipeline = fake_pipeline
monkeypatch.setitem(sys.modules, "transformers", transformers)
settings = Settings(
_env_file=None,
data_dir=tmp_path,
models_dir=tmp_path / "models",
device="cpu",
emotion_model="test/emotion",
)
result = models.ModelManager(settings).recognize_emotion(audio)
assert calls == [
(
"audio-classification",
"test/emotion",
"cpu",
{"cache_dir": tmp_path / "models" / "huggingface"},
),
(str(audio), None),
]
assert result == {
"emotion": "positive",
"score": 0.75,
"scores": [
{"label": "positive", "score": 0.75},
{"label": "neutral", "score": 0.25},
],
"model": "test/emotion",
}

69
tests/test_queue.py Normal file
View File

@ -0,0 +1,69 @@
import asyncio
import time
from app.queue import JobQueue
from app.schemas import JobStatus, TaskType
class FakeManager:
def __init__(self):
self.events = []
def chat(self, messages, max_tokens, temperature):
value = messages[0]["content"]
self.events.append(("start", value))
time.sleep(0.02)
self.events.append(("end", value))
return {"value": value}
def transcribe(self, *args, **kwargs):
return {}
def diarize(self, *args, **kwargs):
return {}
def recognize_emotion(self, *args, **kwargs):
return {}
def close(self):
pass
async def test_jobs_are_strictly_sequential():
manager = FakeManager()
queue = JobQueue(manager)
await queue.start()
try:
one = await queue.submit(TaskType.QWEN, {"messages": [{"content": "one"}], "max_tokens": 1, "temperature": 0})
two = await queue.submit(TaskType.QWEN, {"messages": [{"content": "two"}], "max_tokens": 1, "temperature": 0})
await asyncio.gather(queue.wait(one.id), queue.wait(two.id))
assert manager.events == [("start", "one"), ("end", "one"), ("start", "two"), ("end", "two")]
assert one.status == two.status == JobStatus.SUCCEEDED
finally:
await queue.stop()
async def test_failure_does_not_stop_worker():
manager = FakeManager()
queue = JobQueue(manager)
await queue.start()
original = manager.chat
calls = 0
def flaky(*args, **kwargs):
nonlocal calls
calls += 1
if calls == 1:
raise RuntimeError("boom")
return original(*args, **kwargs)
manager.chat = flaky
try:
bad = await queue.submit(TaskType.QWEN, {"messages": [{"content": "bad"}], "max_tokens": 1, "temperature": 0})
good = await queue.submit(TaskType.QWEN, {"messages": [{"content": "good"}], "max_tokens": 1, "temperature": 0})
await queue.wait(bad.id)
await queue.wait(good.id)
assert bad.status == JobStatus.FAILED
assert good.status == JobStatus.SUCCEEDED
finally:
await queue.stop()

71
verify_concurrency.py Normal file
View File

@ -0,0 +1,71 @@
import asyncio
import time
import httpx
URL = "http://127.0.0.1:8899/v1/audio/transcriptions"
AUDIO_FILE = "/home/timur/Projects/TP_VOICE_REC/WAV_INPUT/in-2798088-89174593307-20260604-153517-1780569317.96149.WAV"
REQUESTS = 5
async def submit(client: httpx.AsyncClient, number: int):
started = time.perf_counter()
with open(AUDIO_FILE, "rb") as audio:
response = await client.post(
URL,
files={"file": ("speech.wav", audio, "audio/wav")},
data={"async_job": "true"},
)
response.raise_for_status()
job = response.json()
print(f"submitted {number}: {job['id']}")
return number, job["id"], started
async def wait_for_job(client: httpx.AsyncClient, number: int, job_id: str):
while True:
response = await client.get(
f"http://127.0.0.1:8899/v1/jobs/{job_id}"
)
response.raise_for_status()
job = response.json()
if job["status"] in {"succeeded", "failed"}:
print(
f"finished {number}: status={job['status']} "
f"started={job['started_at']} "
f"finished={job['finished_at']}"
)
return job
await asyncio.sleep(0.1)
async def main():
async with httpx.AsyncClient(timeout=300) as client:
submissions = await asyncio.gather(
*(submit(client, number) for number in range(REQUESTS))
)
jobs = await asyncio.gather(
*(
wait_for_job(client, number, job_id)
for number, job_id, _ in submissions
)
)
ordered = sorted(jobs, key=lambda job: job["started_at"])
for previous, current in zip(ordered, ordered[1:]):
assert previous["finished_at"] <= current["started_at"], (
"GPU jobs overlapped"
)
assert all(job["status"] == "succeeded" for job in jobs)
print("Verified: all requests succeeded without overlapping inference.")
asyncio.run(main())