feat(ml): fuse two embedding models and protect the ML service with a token

This commit is contained in:
shira committed 2026-10-11 14:40:52 +03:00
1 parent bc00d6901f
commit b24e5ff906
63 files changed
+2287 -276

No files matched your search

+13 -8
View File
@@ -24,24 +24,28 @@ COPY ml/.python-version ml/pyproject.toml ml/uv.lock ./ml/
COPY ml/src ./ml/src
RUN uv sync --project ml --python /usr/local/bin/python --locked --no-dev --no-editable
# The model files are fetched once, at build time, from the pinned revision
# The model files are fetched once, at build time, from the pinned revisions
# and verified against the SHA-256 of the lock file. Only safetensors weights,
# configs, and the tokenizer are fetched: no remote code, no pickle weights.
FROM base AS model
COPY ml/src/lincodex_ml/model_files.py /tmp/model_files.py
COPY ml/model/giga-embeddings-480m.lock.json /tmp/model.lock.json
RUN python /tmp/model_files.py fetch --lock /tmp/model.lock.json --out /opt/lincodex/model \
&& rm /tmp/model_files.py /tmp/model.lock.json
COPY ml/model/giga-embeddings-480m.lock.json ml/model/qwen3-embedding-0.6b.lock.json /tmp/locks/
RUN python /tmp/model_files.py fetch --lock /tmp/locks/giga-embeddings-480m.lock.json --out /opt/lincodex/models/giga-480m \
&& python /tmp/model_files.py fetch --lock /tmp/locks/qwen3-embedding-0.6b.lock.json --out /opt/lincodex/models/qwen3-0.6b \
&& rm -r /tmp/model_files.py /tmp/locks
FROM base
ENV PATH="/opt/venv/bin:${PATH}" \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
ML_EMBEDDER=giga \
ML_MODEL_DIR=/opt/lincodex/model \
ML_EMBEDDER=giga,qwen3 \
ML_GIGA_MODEL_DIR=/opt/lincodex/models/giga-480m \
ML_QWEN3_MODEL_DIR=/opt/lincodex/models/qwen3-0.6b \
ML_TORCH_THREADS=4 \
ML_LISTEN_HOST=0.0.0.0 \
ML_LISTEN_PORT=8000 \
HF_HUB_OFFLINE=1 \
TRANSFORMERS_OFFLINE=1 \
HF_HUB_DISABLE_TELEMETRY=1
@@ -55,7 +59,7 @@ RUN python -m pip uninstall --yes pip \
COPY --from=build --chown=lincodex:lincodex /opt/venv /opt/venv
# Read-only for the service user: root owns the weights.
COPY --from=model /opt/lincodex/model /opt/lincodex/model
COPY --from=model /opt/lincodex/models /opt/lincodex/models
USER 10001:10001
EXPOSE 8000
@@ -63,4 +67,5 @@ EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
CMD ["uvicorn", "lincodex_ml.main:app", "--host", "0.0.0.0", "--port", "8000"]
# The entry point refuses to listen on 0.0.0.0 without ML_SERVICE_TOKEN.
CMD ["python", "-m", "lincodex_ml.serve"]
+24 -10
View File
@@ -1,10 +1,15 @@
.DEFAULT_GOAL := help
UV ?= uv
API_PREPARED ?= 0
# Local directory of the pinned model weights for test-model and run.
ML_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/giga-480m
MODEL_LOCK := model/giga-embeddings-480m.lock.json
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract test-model model-fetch check verify
# Local directories of the pinned model weights for test-model and run.
ML_GIGA_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/giga-480m
ML_QWEN3_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/qwen3-0.6b
GIGA_LOCK := model/giga-embeddings-480m.lock.json
QWEN3_LOCK := model/qwen3-embedding-0.6b.lock.json
# Where cuda-requirements writes the runtime requirements of a CUDA host.
CUDA_REQUIREMENTS ?= dist/requirements-cuda.txt
CUDA_TORCH_LOCAL ?= cu128
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract test-model model-fetch cuda-requirements check verify
help: ## Show available ML service commands.
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -28,8 +33,8 @@ check-pydantic-compat: ## Generate Pydantic models from the OpenAPI 3.2 compatib
build: ## Build the service wheel.
$(UV) build
run: ## Run the operational API on port 8000.
$(UV) run uvicorn lincodex_ml.main:app --host 0.0.0.0 --port 8000
run: ## Run the operational API on 127.0.0.1:8000 (ML_LISTEN_HOST and ML_LISTEN_PORT change it).
$(UV) run python -m lincodex_ml.serve
fmt: ## Format Python source.
$(UV) run ruff format src tests scripts
@@ -52,11 +57,20 @@ test: ## Run service tests.
test-contract: ## Check implementation against the shared OpenAPI contract.
$(UV) run pytest tests/test_contract.py
model-fetch: ## Download the pinned model files into ML_MODEL_DIR and verify their SHA-256 (about 1 GB).
$(UV) run python -m lincodex_ml.model_files fetch --lock $(MODEL_LOCK) --out "$(ML_MODEL_DIR)"
model-fetch: ## Download the pinned files of both models into ML_GIGA_MODEL_DIR and ML_QWEN3_MODEL_DIR and verify their SHA-256 (about 2.2 GB).
$(UV) run python -m lincodex_ml.model_files fetch --lock $(GIGA_LOCK) --out "$(ML_GIGA_MODEL_DIR)"
$(UV) run python -m lincodex_ml.model_files fetch --lock $(QWEN3_LOCK) --out "$(ML_QWEN3_MODEL_DIR)"
test-model: ## Run the slow parity test of the real model against the research vectors (needs model-fetch).
ML_MODEL_DIR="$(ML_MODEL_DIR)" $(UV) run pytest -m slow -p no:cacheprovider tests/test_giga_model.py
test-model: ## Run the slow parity tests of both real models against the research vectors (needs model-fetch; ML_TEST_DEVICE=cuda on a GPU).
ML_GIGA_MODEL_DIR="$(ML_GIGA_MODEL_DIR)" ML_QWEN3_MODEL_DIR="$(ML_QWEN3_MODEL_DIR)" $(UV) run pytest -m slow -p no:cacheprovider tests/test_giga_model.py tests/test_qwen3_model.py
cuda-requirements: ## Write the locked runtime requirements with the CUDA build of the locked torch version to CUDA_REQUIREMENTS (for a GPU host).
@mkdir -p "$(dir $(CUDA_REQUIREMENTS))"
@version=$$($(UV) export --frozen --no-dev --no-hashes --no-emit-project --format requirements.txt | sed -n 's/^torch==\([0-9.]*\).*/\1/p' | head -n 1) && \
test -n "$$version" && \
$(UV) export --frozen --no-dev --no-hashes --no-emit-project --format requirements.txt | grep -v '^torch==' > "$(CUDA_REQUIREMENTS)" && \
printf 'torch==%s+%s\n' "$$version" "$(CUDA_TORCH_LOCAL)" >> "$(CUDA_REQUIREMENTS)" && \
printf 'wrote %s (torch %s+%s)\n' "$(CUDA_REQUIREMENTS)" "$$version" "$(CUDA_TORCH_LOCAL)"
check: ## Run formatting, lint, type, tests, and package build.
$(MAKE) fmt-check lint typecheck test build
+4 -4
View File
@@ -2,15 +2,15 @@
[Русский](README.md) | English
A separate Python service using FastAPI. It serves `POST /v1/embeddings` with the pinned Giga-Embeddings-instruct-480M model on CPU for semantic matching (the optional `model` field names the model; a request for a model the service has not loaded gets 400), plus `/healthz`, `/readyz`, and metrics. `/readyz` returns 503 until the model is loaded and warmed up, and always without a model (`ML_EMBEDDER=none`, the default outside the image). The model files are fetched at image build time by `model/giga-embeddings-480m.lock.json` and verified by SHA-256; see [deployment](../docs/en/DEPLOY.md#separate-ml-compose-project).
A separate Python service using FastAPI. It serves `POST /v1/embeddings` with the pinned Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models for semantic matching (the `ML_EMBEDDER` list; the optional `model` field selects the model, and a request for a model the service has not loaded gets 400), plus `/healthz`, `/readyz`, and metrics. It runs on CPU or CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); a lack of device memory gives 503, not a crash. Every route except `/healthz` and `/readyz` requires a bearer token (`ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE`); without a token the service answers loopback callers only, and `python -m lincodex_ml.serve` does not listen on a non-loopback address. `/readyz` returns 503 until the models are loaded and warmed up, and always without a model (`ML_EMBEDDER=none`, the default outside the image). The model files are pinned by the lock files `model/*.lock.json` and verified by SHA-256; see [deployment](../docs/en/DEPLOY.md#separate-ml-compose-project) and [the GPU host](../docs/en/DEPLOY.md#ml-service-on-a-gpu-host).
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
- `codegen/` configures Pydantic model generation from `api/ml/`.
- `tests/` checks service health, the embedding contract with a fake encoder, the model lock, and (marked `slow`, `make -C ml test-model`) the real model against the study vectors.
- `model/` pins the model revision and the SHA-256 of its files.
- `tests/` checks service health, the embedding contract with a fake encoder, several models, the token, a lack of device memory, the model locks, and (marked `slow`, `make -C ml test-model`) the real models against the study vectors.
- `model/` pins the model revisions and the SHA-256 of their files.
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
From the repository root, `make -C ml check` runs checks and `make -C ml run` starts the service locally. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
From the repository root, `make -C ml check` runs checks, `make -C ml run` starts the service locally on 127.0.0.1:8000, and `make -C ml cuda-requirements` writes the dependency list of a GPU host. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
See [development](../docs/en/DEVELOPMENT.md) and [deployment](../docs/en/DEPLOY.md).
+4 -4
View File
@@ -2,15 +2,15 @@
Русский | [English](README.en.md)
Отдельный Python-сервис на FastAPI. Он отдает `POST /v1/embeddings` с закрепленной моделью Giga-Embeddings-instruct-480M на CPU для семантического подбора (необязательное поле `model` называет модель; запрос модели, которую сервис не загрузил, получает 400), а также `/healthz`, `/readyz` и метрики. `/readyz` отвечает 503, пока модель не загружена и не прогрета, и всегда без модели (`ML_EMBEDDER=none`, значение по умолчанию вне образа). Файлы модели скачиваются при сборке образа по `model/giga-embeddings-480m.lock.json` и проверяются по SHA-256; см. [развертывание](../docs/ru/DEPLOY.md#отдельный-ml-compose).
Отдельный Python-сервис на FastAPI. Он отдает `POST /v1/embeddings` с закрепленными моделями Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B для семантического подбора (список `ML_EMBEDDER`, необязательное поле `model` выбирает модель; запрос модели, которую сервис не загрузил, получает 400), а также `/healthz`, `/readyz` и метрики. Работает на CPU или CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); нехватка видеопамяти дает 503, а не падение процесса. Все маршруты, кроме `/healthz` и `/readyz`, требуют bearer-токен (`ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE`); без токена сервис отвечает только loopback-клиентам, а `python -m lincodex_ml.serve` не слушает не-loopback адрес. `/readyz` отвечает 503, пока модели не загружены и не прогреты, и всегда без моделей (`ML_EMBEDDER=none`, значение по умолчанию вне образа). Файлы моделей закреплены lock-файлами `model/*.lock.json` и проверяются по SHA-256; см. [развертывание](../docs/ru/DEPLOY.md#отдельный-ml-compose) и [GPU-хост](../docs/ru/DEPLOY.md#ml-сервис-на-gpu-хосте).
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
- `tests/` - проверки состояния сервиса, контракта эмбеддингов на фиктивном кодировщике, lock-файла модели и (маркер `slow`, `make -C ml test-model`) реальной модели против векторов исследования.
- `model/` - закрепленная ревизия модели и SHA-256 ее файлов.
- `tests/` - проверки состояния сервиса, контракта эмбеддингов на фиктивном кодировщике, нескольких моделей, токена, нехватки видеопамяти, lock-файлов и (маркер `slow`, `make -C ml test-model`) реальных моделей против векторов исследования.
- `model/` - закрепленные ревизии моделей и SHA-256 их файлов.
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально на 127.0.0.1:8000, `make -C ml cuda-requirements` - список зависимостей для GPU-хоста. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md) и [развертывание](../docs/ru/DEPLOY.md).
+37
View File
@@ -0,0 +1,37 @@
{
"id": "Qwen/Qwen3-Embedding-0.6B",
"revision": "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3",
"license": "Apache-2.0",
"source": "https://huggingface.co",
"note": "Only these files are fetched. The checkpoint is a stock Qwen3 model that lincodex_ml.inference.qwen3 loads with the pinned transformers release; the repository has no remote code and no pickle (.bin) weight file. The sentence-transformers files pin the query prompt and the last-token pooling that the service reproduces.",
"files": {
"1_Pooling/config.json": {
"size": 313,
"sha256": "37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd"
},
"config.json": {
"size": 727,
"sha256": "b5bf1f51fc45be473a54718cef92448d90a1be001bf9b9a44b8c7f10a19feaa9"
},
"config_sentence_transformers.json": {
"size": 215,
"sha256": "10667c72ddb772627bf1780cb7f86af8e2ae0032b8c243c731172064105c6961"
},
"model.safetensors": {
"size": 1191586416,
"sha256": "0437e45c94563b09e13cb7a64478fc406947a93cb34a7e05870fc8dcd48e23fd"
},
"modules.json": {
"size": 349,
"sha256": "84e40c8e006c9b1d6c122e02cba9b02458120b5fb0c87b746c41e0207cf642cf"
},
"tokenizer.json": {
"size": 11423705,
"sha256": "def76fb086971c7867b829c23a26261e38d9d74e02139253b38aeb9df8b4b50a"
},
"tokenizer_config.json": {
"size": 9706,
"sha256": "253153d0738ceb4c668d2eff957714dd2bea0b56de772a9fdccd96cbf517e6a0"
}
}
}
+62
View File
@@ -0,0 +1,62 @@
"""Bearer token check of every route except the health probes.
The service is internal: only the Go backend calls it. With a configured
token every request outside /healthz and /readyz must carry
`Authorization: Bearer <token>`; the comparison takes constant time and the
token never reaches a log or a response. Without a token the service answers
only peers on the loopback interface, so a service that is reachable from the
network can never run open by accident (the serve entry point also refuses to
listen on a non-loopback address without a token).
"""
from __future__ import annotations
import hmac
from typing import Final
from fastapi import status
from starlette.requests import Request
from starlette.types import ASGIApp, Receive, Scope, Send
from lincodex_ml.api.problems import problem_for_status
from lincodex_ml.config import ServiceToken, is_loopback_host
# Probes stay open: they carry no data and the orchestrator calls them
# without credentials.
PUBLIC_PATHS: Final = frozenset({"/healthz", "/readyz"})
_SCHEME: Final = "bearer"
class BearerAuthMiddleware:
def __init__(self, app: ASGIApp, token: ServiceToken | None) -> None:
self._app = app
self._expected = token.reveal().encode() if token is not None else None
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or scope.get("path") in PUBLIC_PATHS:
await self._app(scope, receive, send)
return
if self._allowed(scope):
await self._app(scope, receive, send)
return
request = Request(scope)
response = problem_for_status(
request, status.HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": "Bearer"}
)
await response(scope, receive, send)
def _allowed(self, scope: Scope) -> bool:
if self._expected is None:
client = scope.get("client")
return client is not None and is_loopback_host(str(client[0]))
presented = b""
for name, value in scope.get("headers", []):
if name == b"authorization":
scheme, _, credentials = value.partition(b" ")
if scheme.decode("latin-1").lower() == _SCHEME:
presented = credentials.strip()
break
# compare_digest takes the same time whatever prefix matches; an
# empty or missing token is compared too, so its absence is not
# faster to detect than a wrong value.
return hmac.compare_digest(presented, self._expected) and presented != b""
+13 -10
View File
@@ -17,7 +17,12 @@ from lincodex_ml.api.models import (
)
from lincodex_ml.api.problems import ServiceUnavailableError
from lincodex_ml.inference.embedder import InputKind
from lincodex_ml.inference.runtime import EmbeddingRuntime, NotReadyError
from lincodex_ml.inference.runtime import (
CapacityError,
EmbeddingRuntime,
NotReadyError,
UnknownModelError,
)
router = APIRouter(tags=["inference"])
@@ -32,7 +37,7 @@ def get_runtime(request: Request) -> EmbeddingRuntime:
operation_id="CreateMLEmbeddings",
response_model=EmbeddingResponse,
status_code=status.HTTP_200_OK,
summary="Encode texts into normalized vectors with the pinned embedding model.",
summary="Encode texts into normalized vectors with a pinned embedding model.",
)
async def create_embeddings(
payload: EmbeddingRequest,
@@ -41,14 +46,12 @@ async def create_embeddings(
kind = InputKind(payload.kind.root)
texts = [text.root for text in payload.texts]
try:
# The service loads one model today; the field keeps the contract ready
# for several (an ensemble), and a model it does not serve is refused.
if payload.model is not None and payload.model != runtime.info().model_id:
raise RequestValidationError(
[{"loc": ("body", "model"), "type": "value_error", "msg": "model not served"}]
)
info, vectors = await run_in_threadpool(runtime.encode, kind, texts)
except NotReadyError as error:
info, vectors = await run_in_threadpool(runtime.encode, kind, texts, payload.model)
except UnknownModelError as error:
raise RequestValidationError(
[{"loc": ("body", "model"), "type": "value_error", "msg": "model not served"}]
) from error
except (NotReadyError, CapacityError) as error:
raise ServiceUnavailableError from error
return EmbeddingResponse(
model=EmbeddingModel(
+5 -4
View File
@@ -1,7 +1,7 @@
from fastapi import APIRouter, Request, Response, status
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
from lincodex_ml.inference.runtime import EmbeddingRuntime
router = APIRouter(tags=["health"])
@@ -30,10 +30,11 @@ async def get_healthz() -> MLHealthResponse:
summary="Check whether an inference runtime is available.",
)
async def get_readyz(request: Request, response: Response) -> MLReadinessResponse:
# Ready only after the model is loaded and a warm-up encode finished;
# a disabled or failed runtime stays not ready.
# Ready only after every model is loaded and a warm-up encode finished;
# a disabled or failed runtime stays not ready, and so does one that ran
# out of device memory during the last cool-down.
runtime: EmbeddingRuntime = request.app.state.embedding_runtime
if runtime.state is RuntimeState.READY:
if runtime.ready():
return MLReadinessResponse(status="ready")
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return MLReadinessResponse(status="not_ready")
+1 -1
View File
@@ -198,7 +198,7 @@ class EmbeddingRequest(BaseModel):
model: Annotated[
str | None,
Field(
description="Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.",
description="Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.",
max_length=200,
min_length=1,
pattern="^[A-Za-z0-9._/-]+$",
+8 -1
View File
@@ -129,7 +129,7 @@ _STATUS_DEFINITIONS: Final[Mapping[int, _Definition]] = {
ProblemCode("service_unavailable"),
status.HTTP_503_SERVICE_UNAVAILABLE,
"Service unavailable",
"The model is not ready yet. Retry later.",
"The model is not ready or has no free capacity now. Retry later.",
),
}
# Seconds a client waits before it asks a service that is still loading.
@@ -185,6 +185,13 @@ class BodyLimitMiddleware:
await self._app(scope, limited_receive, send)
def problem_for_status(
request: Request, status_code: int, headers: Mapping[str, str] | None = None
) -> JSONResponse:
"""The problem response of an HTTP status, for middleware outside the routes."""
return _problem_response(request, _definition_for_status(status_code), headers=headers)
def _too_large(request: Request) -> JSONResponse:
return _problem_response(request, _STATUS_DEFINITIONS[status.HTTP_413_CONTENT_TOO_LARGE])
+187 -18
View File
@@ -2,14 +2,17 @@
from __future__ import annotations
import ipaddress
import os
import re
from collections.abc import Mapping
from dataclasses import dataclass
from dataclasses import dataclass, field
from enum import StrEnum
from pathlib import Path
from typing import Final
DEFAULT_MODEL_DIR: Final = Path("/opt/lincodex/model")
from lincodex_ml.model_files import LOCK_FILE_NAME
# Four intra-op threads meet the latency targets of the research CPU benchmark
# (profile p95 352 ms, search over 100k vectors p95 591 ms) for Giga-480M.
DEFAULT_TORCH_THREADS: Final = 4
@@ -18,39 +21,115 @@ DEFAULT_TORCH_THREADS: Final = 4
DEFAULT_MICRO_BATCH: Final = 1
DEFAULT_MAX_TOKENS: Final = 1024
DEFAULT_MAX_BODY_BYTES: Final = 2 * 1024 * 1024
DEFAULT_LISTEN_HOST: Final = "127.0.0.1"
DEFAULT_LISTEN_PORT: Final = 8000
# The minimum length of the service token: 32 random characters carry far
# more entropy than an online guess can reach.
MIN_TOKEN_LENGTH: Final = 32
_MAX_TOKEN_LENGTH: Final = 512
_MAX_TORCH_THREADS: Final = 64
_MAX_MICRO_BATCH: Final = 32
_MAX_TOKENS_LIMIT: Final = 8192
_MAX_CUDA_MEMORY_MB: Final = 1024 * 1024
_TOKEN_PATTERN: Final = re.compile(r"^[\x21-\x7e]+$")
_DEVICE_PATTERN: Final = re.compile(r"^(cpu|cuda|cuda:[0-9]{1,2})$")
class EmbedderKind(StrEnum):
"""Which encoder the service loads."""
"""An encoder the service can load."""
# The pinned Giga-Embeddings model from the image.
# Giga-Embeddings-instruct-480M at the pinned revision.
GIGA = "giga"
# Qwen3-Embedding-0.6B at the pinned revision.
QWEN3 = "qwen3"
# A deterministic hash encoder for tests and stands without the model. It
# is never a model result and reports its own model id.
FAKE = "fake"
# No encoder: the service stays not ready and refuses inference.
NONE = "none"
# Where the image keeps the weights of each model; a host without the image
# points the per-model directory variables elsewhere.
DEFAULT_MODEL_DIRS: Final[Mapping[EmbedderKind, Path]] = {
EmbedderKind.GIGA: Path("/opt/lincodex/models/giga-480m"),
EmbedderKind.QWEN3: Path("/opt/lincodex/models/qwen3-0.6b"),
}
_MODEL_ENV_PREFIX: Final[Mapping[EmbedderKind, str]] = {
EmbedderKind.GIGA: "ML_GIGA",
EmbedderKind.QWEN3: "ML_QWEN3",
}
class DType(StrEnum):
"""Precision of the weights and activations of a real model."""
FLOAT32 = "float32"
FLOAT16 = "float16"
BFLOAT16 = "bfloat16"
class SettingsError(ValueError):
"""An environment value is invalid."""
class ServiceToken:
"""The shared bearer token. Its value never appears in a repr or a log."""
__slots__ = ("_value",)
def __init__(self, value: str) -> None:
self._value = value
def reveal(self) -> str:
return self._value
def __repr__(self) -> str:
return "ServiceToken([redacted])"
__str__ = __repr__
@dataclass(frozen=True, slots=True)
class ModelLocation:
"""The weight directory of one model and the lock file that pins it."""
directory: Path
lock: Path
@dataclass(frozen=True, slots=True)
class Settings:
embedder: EmbedderKind
model_dir: Path
# Encoders in load order; the first one serves requests without a model
# id. Empty means no encoder: the service stays not ready.
embedders: tuple[EmbedderKind, ...]
model_locations: Mapping[EmbedderKind, ModelLocation]
torch_threads: int
micro_batch: int
max_tokens: int
verify_weights: bool
max_body_bytes: int
device: str = "cpu"
dtype: DType = DType.FLOAT32
# The CUDA allocator limit of the process in MiB; 0 means no limit.
cuda_memory_limit_mb: int = 0
token: ServiceToken | None = field(default=None, repr=False)
listen_host: str = DEFAULT_LISTEN_HOST
listen_port: int = DEFAULT_LISTEN_PORT
# Exit the process when a model fails to load for any reason other than
# a lack of device memory, so a supervisor such as systemd restarts it.
exit_on_load_failure: bool = False
def location(self, kind: EmbedderKind) -> ModelLocation:
return self.model_locations.get(kind) or _default_location(kind)
def _integer(environ: Mapping[str, str], name: str, default: int, maximum: int) -> int:
def _default_location(kind: EmbedderKind) -> ModelLocation:
directory = DEFAULT_MODEL_DIRS.get(kind, Path("/nonexistent"))
return ModelLocation(directory=directory, lock=directory / LOCK_FILE_NAME)
def _integer(
environ: Mapping[str, str], name: str, default: int, maximum: int, minimum: int = 1
) -> int:
raw = environ.get(name, "").strip()
if raw == "":
return default
@@ -58,8 +137,8 @@ def _integer(environ: Mapping[str, str], name: str, default: int, maximum: int)
value = int(raw)
except ValueError as error:
raise SettingsError(f"{name} must be an integer") from error
if value < 1 or value > maximum:
raise SettingsError(f"{name} must be between 1 and {maximum}")
if value < minimum or value > maximum:
raise SettingsError(f"{name} must be between {minimum} and {maximum}")
return value
@@ -74,16 +153,99 @@ def _boolean(environ: Mapping[str, str], name: str, default: bool) -> bool:
raise SettingsError(f"{name} must be true or false")
def _embedders(environ: Mapping[str, str]) -> tuple[EmbedderKind, ...]:
raw = environ.get("ML_EMBEDDER", "").strip()
if raw in {"", "none"}:
return ()
kinds: list[EmbedderKind] = []
for part in raw.split(","):
try:
kind = EmbedderKind(part.strip())
except ValueError as error:
raise SettingsError(
"ML_EMBEDDER must be none, fake, or a comma list of giga and qwen3"
) from error
if kind in kinds:
raise SettingsError("ML_EMBEDDER names a model twice")
kinds.append(kind)
if EmbedderKind.FAKE in kinds and len(kinds) > 1:
raise SettingsError("ML_EMBEDDER fake cannot be combined with a real model")
return tuple(kinds)
def _locations(environ: Mapping[str, str]) -> dict[EmbedderKind, ModelLocation]:
locations: dict[EmbedderKind, ModelLocation] = {}
for kind, prefix in _MODEL_ENV_PREFIX.items():
raw_dir = environ.get(f"{prefix}_MODEL_DIR", "").strip()
directory = Path(raw_dir) if raw_dir else DEFAULT_MODEL_DIRS[kind]
raw_lock = environ.get(f"{prefix}_MODEL_LOCK", "").strip()
locations[kind] = ModelLocation(
directory=directory, lock=Path(raw_lock) if raw_lock else directory / LOCK_FILE_NAME
)
return locations
def _device(environ: Mapping[str, str]) -> str:
raw = environ.get("ML_DEVICE", "").strip().lower() or "cpu"
if not _DEVICE_PATTERN.fullmatch(raw):
raise SettingsError("ML_DEVICE must be cpu, cuda, or cuda:<index>")
return raw
def _dtype(environ: Mapping[str, str], device: str) -> DType:
raw = environ.get("ML_DTYPE", "").strip().lower() or DType.FLOAT32.value
try:
dtype = DType(raw)
except ValueError as error:
raise SettingsError("ML_DTYPE must be float32, float16, or bfloat16") from error
# Half precision on CPU is slower than float32 and was never validated.
if dtype is not DType.FLOAT32 and device == "cpu":
raise SettingsError("ML_DTYPE other than float32 needs ML_DEVICE=cuda")
return dtype
def _token(environ: Mapping[str, str]) -> ServiceToken | None:
inline = environ.get("ML_SERVICE_TOKEN", "")
path = environ.get("ML_SERVICE_TOKEN_FILE", "").strip()
if inline and path:
raise SettingsError("set ML_SERVICE_TOKEN or ML_SERVICE_TOKEN_FILE, not both")
if path:
try:
inline = Path(path).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as error:
raise SettingsError("ML_SERVICE_TOKEN_FILE cannot be read") from error
value = inline.strip()
if value == "":
return None
# The messages never quote the value.
if not _TOKEN_PATTERN.fullmatch(value) or len(value) > _MAX_TOKEN_LENGTH:
raise SettingsError("the service token must be printable ASCII without white space")
if len(value) < MIN_TOKEN_LENGTH:
raise SettingsError(f"the service token must have at least {MIN_TOKEN_LENGTH} characters")
return ServiceToken(value)
def is_loopback_host(host: str) -> bool:
"""Whether a listen or peer address can only be reached from this host."""
if host == "localhost":
return True
try:
return ipaddress.ip_address(host.strip("[]")).is_loopback
except ValueError:
return False
def load_settings(environ: Mapping[str, str] | None = None) -> Settings:
source = os.environ if environ is None else environ
raw_kind = source.get("ML_EMBEDDER", "").strip() or EmbedderKind.NONE.value
try:
kind = EmbedderKind(raw_kind)
except ValueError as error:
raise SettingsError("ML_EMBEDDER must be giga, fake, or none") from error
device = _device(source)
cuda_memory_limit_mb = _integer(
source, "ML_CUDA_MEMORY_LIMIT_MB", 0, _MAX_CUDA_MEMORY_MB, minimum=0
)
if cuda_memory_limit_mb and device == "cpu":
raise SettingsError("ML_CUDA_MEMORY_LIMIT_MB needs ML_DEVICE=cuda")
return Settings(
embedder=kind,
model_dir=Path(source.get("ML_MODEL_DIR", "").strip() or DEFAULT_MODEL_DIR),
embedders=_embedders(source),
model_locations=_locations(source),
torch_threads=_integer(
source, "ML_TORCH_THREADS", DEFAULT_TORCH_THREADS, _MAX_TORCH_THREADS
),
@@ -93,4 +255,11 @@ def load_settings(environ: Mapping[str, str] | None = None) -> Settings:
max_body_bytes=_integer(
source, "ML_MAX_BODY_BYTES", DEFAULT_MAX_BODY_BYTES, 16 * DEFAULT_MAX_BODY_BYTES
),
device=device,
dtype=_dtype(source, device),
cuda_memory_limit_mb=cuda_memory_limit_mb,
token=_token(source),
listen_host=source.get("ML_LISTEN_HOST", "").strip() or DEFAULT_LISTEN_HOST,
listen_port=_integer(source, "ML_LISTEN_PORT", DEFAULT_LISTEN_PORT, 65535),
exit_on_load_failure=_boolean(source, "ML_EXIT_ON_LOAD_FAILURE", False),
)
+8
View File
@@ -34,6 +34,14 @@ class Embedder(Protocol):
"""Encode one micro-batch; the result follows the order of texts."""
...
def recover(self, error: BaseException) -> bool:
"""Clean up after a failed encode.
Returns True when the failure was a lack of device memory: the encoder
released its cached memory, and the same request may pass later.
"""
...
def micro_batches(texts: Sequence[str], size: int) -> list[list[int]]:
"""Split request positions into micro-batches of similar length.
+15 -3
View File
@@ -21,9 +21,14 @@ FAKE_DIMENSION: Final = 32
class FakeEmbedder:
def __init__(self, dimension: int = FAKE_DIMENSION, max_tokens: int = 1024) -> None:
def __init__(
self,
dimension: int = FAKE_DIMENSION,
max_tokens: int = 1024,
model_id: str = FAKE_MODEL_ID,
) -> None:
self._info = ModelInfo(
model_id=FAKE_MODEL_ID,
model_id=model_id,
revision=FAKE_REVISION,
dimension=dimension,
max_tokens=max_tokens,
@@ -37,11 +42,18 @@ class FakeEmbedder:
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
return [self._vector(kind, text) for text in texts]
def recover(self, error: BaseException) -> bool:
return False
def _vector(self, kind: InputKind, text: str) -> list[float]:
values: list[float] = []
counter = 0
while len(values) < self._info.dimension:
block = hashlib.sha256(f"{kind.value}\x00{counter}\x00{text}".encode()).digest()
seed = f"{self._info.model_id}\x00{kind.value}\x00{counter}\x00{text}"
if self._info.model_id == FAKE_MODEL_ID:
# The original seed, so vectors stored by earlier stands stay valid.
seed = f"{kind.value}\x00{counter}\x00{text}"
block = hashlib.sha256(seed.encode()).digest()
for (raw,) in struct.iter_unpack(">i", block):
values.append(raw / 2**31)
counter += 1
+29 -21
View File
@@ -1,4 +1,4 @@
"""Giga-Embeddings-instruct-480M on CPU, reproducing the research recipe.
"""Giga-Embeddings-instruct-480M, reproducing the research recipe.
The model is a Qwen3 decoder turned into a bidirectional encoder. Its Hugging
Face repository ships that wrapper as remote code; the service does not
@@ -11,7 +11,8 @@ The encoding recipe matches the research run (sentence-transformers 5.7.0,
float32): the query side gets the model's retrieval prompt, the document side
gets none; the prompt and the text are joined and stripped; tokens are
truncated to max_tokens; the last hidden states are mean-pooled over the
attention mask including the prompt tokens and L2-normalized.
attention mask including the prompt tokens and L2-normalized. Pooling and
normalization run in float32 whatever the precision of the weights.
"""
from __future__ import annotations
@@ -26,10 +27,11 @@ from transformers import PreTrainedTokenizerFast
from transformers.masking_utils import create_bidirectional_mask
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
from transformers.utils import logging as transformers_logging
from lincodex_ml.config import DType
from lincodex_ml.inference.embedder import InputKind, ModelInfo
from lincodex_ml.model_files import LOCK_FILE_NAME, load_lock, verify_directory
from lincodex_ml.inference.torch_support import is_out_of_memory, release_cached_memory, torch_dtype
from lincodex_ml.model_files import load_lock, verify_directory
# The "query" prompt of config_sentence_transformers.json at the pinned
# revision. Startup checks that the file still says the same.
@@ -79,25 +81,34 @@ class Qwen3BidirectionalModel(Qwen3Model): # type: ignore[no-untyped-call]
class GigaEmbedder:
"""Loads the verified files of one directory and encodes on CPU."""
"""Loads the verified files of one directory and encodes on one device."""
def __init__(self, model_dir: Path, max_tokens: int, verify_weights: bool) -> None:
lock = load_lock(model_dir / LOCK_FILE_NAME)
def __init__(
self,
model_dir: Path,
lock_path: Path,
max_tokens: int,
verify_weights: bool,
device: torch.device | None = None,
dtype: DType = DType.FLOAT32,
) -> None:
lock = load_lock(lock_path)
if verify_weights:
verify_directory(lock, model_dir)
_check_query_prompt(model_dir)
self._device = device if device is not None else torch.device("cpu")
self._tokenizer = PreTrainedTokenizerFast.from_pretrained(
str(model_dir), local_files_only=True
)
model = Qwen3BidirectionalModel.from_pretrained(
str(model_dir),
dtype=torch.float32,
dtype=torch_dtype(dtype),
attn_implementation="sdpa",
local_files_only=True,
use_safetensors=True,
)
model.eval() # type: ignore[no-untyped-call]
self._model = model
self._model = model.to(self._device) # type: ignore[arg-type]
self._max_tokens = max_tokens
self._info = ModelInfo(
model_id=lock.model_id,
@@ -122,15 +133,20 @@ class GigaEmbedder:
max_length=self._max_tokens,
return_tensors="pt",
)
attention_mask: torch.Tensor = encoded["attention_mask"]
hidden = self._model.encode_hidden(encoded["input_ids"], attention_mask)
weights = attention_mask.unsqueeze(-1).to(hidden.dtype)
attention_mask: torch.Tensor = encoded["attention_mask"].to(self._device)
input_ids: torch.Tensor = encoded["input_ids"].to(self._device)
hidden = self._model.encode_hidden(input_ids, attention_mask).to(torch.float32)
weights = attention_mask.unsqueeze(-1).to(torch.float32)
summed = (hidden * weights).sum(dim=1)
counts = weights.sum(dim=1).clamp(min=1e-9)
pooled = torch.nn.functional.normalize(summed / counts, p=2, dim=1)
vectors: list[list[float]] = pooled.to(torch.float32).tolist()
vectors: list[list[float]] = pooled.cpu().tolist()
return vectors
def recover(self, error: BaseException) -> bool:
release_cached_memory(self._device)
return is_out_of_memory(error)
def _check_query_prompt(model_dir: Path) -> None:
document = json.loads(
@@ -139,11 +155,3 @@ def _check_query_prompt(model_dir: Path) -> None:
prompts = document.get("prompts", {})
if prompts.get("query") != QUERY_PROMPT or prompts.get("document", "") != DOCUMENT_PROMPT:
raise RuntimeError("the model prompts differ from the reviewed recipe")
def configure_torch(threads: int) -> None:
"""Fix the thread pools so results and latency do not depend on the host."""
torch.set_num_threads(threads)
torch.set_num_interop_threads(1)
# The loader's progress bar would print raw text into the JSON log.
transformers_logging.disable_progress_bar() # type: ignore[no-untyped-call]
+138
View File
@@ -0,0 +1,138 @@
"""Qwen3-Embedding-0.6B, reproducing the research recipe.
The checkpoint is a stock Qwen3 decoder (causal attention) published with a
sentence-transformers configuration, so it loads into the Qwen3Model class of
the pinned transformers release without any code from the model repository.
The encoding recipe matches the research run (sentence-transformers 5.7.0,
float32) and the model card: the query side gets the model's own "query"
prompt, the document side gets none; the prompt and the text are joined
without a separator and stripped; the tokenizer appends the end-of-text token
and truncates to max_tokens before it; the hidden state of the last
non-padding token is the vector (last-token pooling, prompt included), which
is L2-normalized. Pooling and normalization run in float32 whatever the
precision of the weights.
"""
from __future__ import annotations
import json
from collections.abc import Sequence
from pathlib import Path
from typing import Any, Final
import torch
from transformers import PreTrainedTokenizerFast
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
from lincodex_ml.config import DType
from lincodex_ml.inference.embedder import InputKind, ModelInfo
from lincodex_ml.inference.torch_support import is_out_of_memory, release_cached_memory, torch_dtype
from lincodex_ml.model_files import load_lock, verify_directory
# The "query" prompt of config_sentence_transformers.json at the pinned
# revision; startup checks that the file still says the same.
QUERY_PROMPT: Final = (
"Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:"
)
DOCUMENT_PROMPT: Final = ""
# Changes whenever the prompt or the pooling recipe changes; callers store it
# with each vector.
PROMPT_VERSION: Final = "qwen3-card-last-v1"
# The sentence-transformers pooling configuration the recipe relies on.
_POOLING: Final = {
"pooling_mode_cls_token": False,
"pooling_mode_mean_tokens": False,
"pooling_mode_max_tokens": False,
"pooling_mode_mean_sqrt_len_tokens": False,
"pooling_mode_weightedmean_tokens": False,
"pooling_mode_lasttoken": True,
"include_prompt": True,
}
class Qwen3Embedder:
"""Loads the verified files of one directory and encodes on one device."""
def __init__(
self,
model_dir: Path,
lock_path: Path,
max_tokens: int,
verify_weights: bool,
device: torch.device | None = None,
dtype: DType = DType.FLOAT32,
) -> None:
lock = load_lock(lock_path)
if verify_weights:
verify_directory(lock, model_dir)
_check_recipe(model_dir)
self._device = device if device is not None else torch.device("cpu")
tokenizer = PreTrainedTokenizerFast.from_pretrained(str(model_dir), local_files_only=True)
# Right padding: the last real token of a row is at its mask length - 1.
tokenizer.padding_side = "right"
self._tokenizer = tokenizer
model = Qwen3Model.from_pretrained(
str(model_dir),
dtype=torch_dtype(dtype),
attn_implementation="sdpa",
local_files_only=True,
use_safetensors=True,
)
model.eval() # type: ignore[no-untyped-call]
self._model = model.to(self._device) # type: ignore[arg-type]
self._max_tokens = max_tokens
self._info = ModelInfo(
model_id=lock.model_id,
revision=lock.revision,
dimension=int(model.config.hidden_size),
max_tokens=max_tokens,
prompt_version=PROMPT_VERSION,
)
@property
def info(self) -> ModelInfo:
return self._info
@torch.inference_mode()
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
prompt = QUERY_PROMPT if kind is InputKind.QUERY else DOCUMENT_PROMPT
prepared = [(prompt + text).strip() for text in texts]
encoded: Any = self._tokenizer(
prepared,
padding=True,
truncation="longest_first",
max_length=self._max_tokens,
return_tensors="pt",
)
attention_mask: torch.Tensor = encoded["attention_mask"].to(self._device)
input_ids: torch.Tensor = encoded["input_ids"].to(self._device)
output: Any = self._model(input_ids=input_ids, attention_mask=attention_mask)
hidden: torch.Tensor = output.last_hidden_state
last = attention_mask.sum(dim=1) - 1
rows = torch.arange(hidden.shape[0], device=hidden.device)
pooled = hidden[rows, last].to(torch.float32)
normalized = torch.nn.functional.normalize(pooled, p=2, dim=1)
vectors: list[list[float]] = normalized.cpu().tolist()
return vectors
def recover(self, error: BaseException) -> bool:
release_cached_memory(self._device)
return is_out_of_memory(error)
def _check_recipe(model_dir: Path) -> None:
"""Refuse a model directory whose prompts or pooling differ from the recipe."""
document = json.loads(
(model_dir / "config_sentence_transformers.json").read_text(encoding="utf-8")
)
prompts = document.get("prompts", {})
if prompts.get("query") != QUERY_PROMPT or prompts.get("document", "") != DOCUMENT_PROMPT:
raise RuntimeError("the model prompts differ from the reviewed recipe")
pooling = json.loads((model_dir / "1_Pooling" / "config.json").read_text(encoding="utf-8"))
if any(pooling.get(name) != value for name, value in _POOLING.items()):
raise RuntimeError("the model pooling differs from the reviewed recipe")
modules = json.loads((model_dir / "modules.json").read_text(encoding="utf-8"))
types = [module.get("type") for module in modules]
if types[-1:] != ["sentence_transformers.models.Normalize"]:
raise RuntimeError("the model does not end with the normalization the recipe expects")
+220 -62
View File
@@ -1,22 +1,29 @@
"""Loading state and serialized execution of the encoder.
"""Loading state and serialized execution of the encoders.
The encoder loads in a background thread after startup, so the process
answers /healthz at once. Readiness turns ready only after a warm-up encode
of both input kinds has finished. Encoding runs one request at a time: the
model already uses every configured CPU thread, and parallel requests would
only compete for them.
The encoders load in a background thread after startup, so the process
answers /healthz at once. Readiness turns ready only after every configured
encoder has loaded and finished a warm-up encode of both input kinds.
Encoding runs one request at a time: a model already uses every configured
CPU thread or the whole GPU, and parallel requests would only compete.
On a GPU that another service shares, an allocation can fail while that
service holds the memory. Such a failure never stops the process: a failed
load is retried with a growing pause, and a failed request answers 503 and
keeps the service not ready for a short cool-down, after which it serves again.
"""
from __future__ import annotations
import gc
import logging
import sys
import threading
import time
from collections.abc import Callable, Sequence
from enum import StrEnum
from typing import Final
from prometheus_client import Counter, Histogram
from prometheus_client import Counter, Gauge, Histogram
from lincodex_ml.config import EmbedderKind, Settings
from lincodex_ml.inference.embedder import Embedder, InputKind, ModelInfo, encode_ordered
@@ -30,18 +37,29 @@ _WARMUP_TEXTS: Final = (
"Разработка сервиса уведомлений с повторной доставкой и дедупликацией.", # noqa: RUF001
)
_WARMUP_ROUNDS: Final = 3
# How long readiness stays not ready after a request ran out of device memory.
OOM_COOL_DOWN_SECONDS: Final = 30.0
# Pauses between load attempts that ran out of device memory.
_LOAD_RETRY_FIRST_SECONDS: Final = 15.0
_LOAD_RETRY_MAX_SECONDS: Final = 300.0
ENCODE_SECONDS: Final = Histogram(
"lincodex_ml_embedding_request_seconds",
"Time to encode one embedding request, by input kind.",
["kind"],
buckets=(0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0),
buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0),
)
ENCODED_TEXTS: Final = Counter(
"lincodex_ml_embedding_texts_total",
"Texts encoded, by input kind.",
["kind"],
)
OUT_OF_MEMORY: Final = Counter(
"lincodex_ml_out_of_memory_total",
"Loads and requests that failed for lack of device memory.",
["stage"],
)
READY: Final = Gauge("lincodex_ml_ready", "1 while every configured encoder is ready.")
class RuntimeState(StrEnum):
@@ -52,15 +70,43 @@ class RuntimeState(StrEnum):
class NotReadyError(Exception):
"""The encoder is not loaded and warmed up."""
"""The encoders are not loaded and warmed up."""
class CapacityError(Exception):
"""The device ran out of memory; the same request may pass later."""
class UnknownModelError(Exception):
"""The request names a model that the service does not serve."""
EmbedderFactory = Callable[[], Embedder]
class EmbeddingRuntime:
def __init__(self, settings: Settings, factory: Callable[[], Embedder] | None) -> None:
def __init__(
self,
settings: Settings,
factories: EmbedderFactory | Sequence[EmbedderFactory] | None,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], None] = time.sleep,
on_failure: Callable[[], None] | None = None,
) -> None:
self._settings = settings
self._factory = factory
self._state = RuntimeState.DISABLED if factory is None else RuntimeState.LOADING
self._embedder: Embedder | None = None
if factories is None:
self._factories: tuple[EmbedderFactory, ...] = ()
elif callable(factories):
self._factories = (factories,)
else:
self._factories = tuple(factories)
self._clock = clock
self._sleep = sleep
self._on_failure = on_failure
self._state = RuntimeState.LOADING if self._factories else RuntimeState.DISABLED
self._embedders: dict[str, Embedder] = {}
self._default: str | None = None
self._cool_down_until = 0.0
self._state_lock = threading.Lock()
self._encode_lock = threading.Lock()
self._thread: threading.Thread | None = None
@@ -70,9 +116,14 @@ class EmbeddingRuntime:
with self._state_lock:
return self._state
def ready(self) -> bool:
"""Ready and not cooling down after an out-of-memory request."""
with self._state_lock:
return self._state is RuntimeState.READY and self._clock() >= self._cool_down_until
def start(self) -> None:
"""Load and warm up the encoder in the background."""
if self._factory is None or self._thread is not None:
"""Load and warm up the encoders in the background."""
if not self._factories or self._thread is not None:
return
self._thread = threading.Thread(target=self._load, name="embedder-load", daemon=True)
self._thread.start()
@@ -83,69 +134,176 @@ class EmbeddingRuntime:
return self.state
def _load(self) -> None:
factory = self._factory
if factory is None:
return
started = time.monotonic()
try:
embedder = factory()
for _ in range(_WARMUP_ROUNDS):
for kind in InputKind:
encode_ordered(embedder, kind, _WARMUP_TEXTS, self._settings.micro_batch)
except Exception as error:
# The message can quote file paths or text; the type is enough to act on.
logger.error("embedding model failed to load: %s", type(error).__name__)
with self._state_lock:
self._state = RuntimeState.FAILED
return
started = self._clock()
pause = _LOAD_RETRY_FIRST_SECONDS
while True:
try:
embedders = self._load_all()
break
except Exception as error:
out_of_memory = _released_after(error, None)
if not out_of_memory:
# The message can quote file paths or text; the type is
# enough to act on.
logger.error("embedding model failed to load: %s", type(error).__name__)
if not out_of_memory:
with self._state_lock:
self._state = RuntimeState.FAILED
if self._on_failure is not None:
self._on_failure()
return
# The failed attempt is unreachable now; collect it so that its
# device memory returns before the next attempt.
gc.collect()
_release_device_cache()
OUT_OF_MEMORY.labels(stage="load").inc()
logger.warning(
"embedding model load ran out of device memory; retrying",
extra={"retry_seconds": pause},
)
self._sleep(pause)
pause = min(pause * 2, _LOAD_RETRY_MAX_SECONDS)
with self._state_lock:
self._embedder = embedder
self._embedders = {embedder.info.model_id: embedder for embedder in embedders}
self._default = embedders[0].info.model_id
self._state = RuntimeState.READY
READY.set(1)
logger.info(
"embedding model is ready",
extra={"seconds": round(time.monotonic() - started, 1)},
"embedding models are ready",
extra={
"seconds": round(self._clock() - started, 1),
"models": [embedder.info.model_id for embedder in embedders],
},
)
def info(self) -> ModelInfo:
with self._state_lock:
if self._embedder is None:
raise NotReadyError
return self._embedder.info
def _load_all(self) -> list[Embedder]:
embedders: list[Embedder] = []
try:
for factory in self._factories:
embedder = factory()
embedders.append(embedder)
for _ in range(_WARMUP_ROUNDS):
for kind in InputKind:
encode_ordered(embedder, kind, _WARMUP_TEXTS, self._settings.micro_batch)
if len({embedder.info.model_id for embedder in embedders}) != len(embedders):
raise RuntimeError("two encoders report the same model id")
except BaseException as error:
# Free what the attempt loaded before a retry.
for embedder in embedders:
embedder.recover(error)
embedders.clear()
raise
return embedders
def encode(self, kind: InputKind, texts: Sequence[str]) -> tuple[ModelInfo, list[list[float]]]:
def models(self) -> list[ModelInfo]:
"""The served models, the default first."""
with self._state_lock:
embedder = self._embedder
if self._default is None:
raise NotReadyError
default = self._embedders[self._default]
return [default.info] + [
embedder.info for embedder in self._embedders.values() if embedder is not default
]
def info(self) -> ModelInfo:
"""The default model."""
return self.models()[0]
def _select(self, model_id: str | None) -> Embedder:
with self._state_lock:
if self._default is None:
raise NotReadyError
embedder = self._embedders.get(self._default if model_id is None else model_id)
if embedder is None:
raise NotReadyError
raise UnknownModelError
return embedder
def encode(
self, kind: InputKind, texts: Sequence[str], model_id: str | None = None
) -> tuple[ModelInfo, list[list[float]]]:
embedder = self._select(model_id)
with self._encode_lock, ENCODE_SECONDS.labels(kind=kind.value).time():
vectors = encode_ordered(embedder, kind, texts, self._settings.micro_batch)
try:
vectors = encode_ordered(embedder, kind, texts, self._settings.micro_batch)
except Exception as error:
if not _released_after(error, embedder):
raise
OUT_OF_MEMORY.labels(stage="request").inc()
with self._state_lock:
self._cool_down_until = self._clock() + OOM_COOL_DOWN_SECONDS
logger.warning("an embedding request ran out of device memory")
raise CapacityError from None
ENCODED_TEXTS.labels(kind=kind.value).inc(len(texts))
return embedder.info, vectors
def embedder_factory(settings: Settings) -> Callable[[], Embedder] | None:
"""Return how to build the configured encoder, or None when disabled."""
match settings.embedder:
case EmbedderKind.NONE:
return None
case EmbedderKind.FAKE:
def _released_after(error: BaseException, embedder: Embedder | None) -> bool:
"""Whether an error is a lack of device memory, after releasing the cache."""
if embedder is not None:
return embedder.recover(error)
# A load failure has no encoder yet. Only a loaded torch can raise an
# out-of-memory error, so a service without one never imports it here.
if "torch" not in sys.modules:
return False
from lincodex_ml.inference.torch_support import is_out_of_memory
def build_fake() -> Embedder:
from lincodex_ml.inference.fake import FakeEmbedder
return is_out_of_memory(error)
return FakeEmbedder(max_tokens=settings.max_tokens)
return build_fake
case EmbedderKind.GIGA:
def _release_device_cache() -> None:
if "torch" not in sys.modules:
return
from lincodex_ml.inference.torch_support import release_all_cached_memory
def build_giga() -> Embedder:
# Imported here: torch and transformers load in seconds and
# only a service that runs the model needs them.
from lincodex_ml.inference.giga import GigaEmbedder, configure_torch
release_all_cached_memory()
configure_torch(settings.torch_threads)
return GigaEmbedder(
settings.model_dir, settings.max_tokens, settings.verify_weights
)
return build_giga
def embedder_factories(settings: Settings) -> list[EmbedderFactory]:
"""Return how to build every configured encoder, in configuration order."""
factories: list[EmbedderFactory] = []
for kind in settings.embedders:
factories.append(_factory(settings, kind))
return factories
def _factory(settings: Settings, kind: EmbedderKind) -> EmbedderFactory:
if kind is EmbedderKind.FAKE:
def build_fake() -> Embedder:
from lincodex_ml.inference.fake import FakeEmbedder
return FakeEmbedder(max_tokens=settings.max_tokens)
return build_fake
def build_model() -> Embedder:
# Imported here: torch and transformers load in seconds and only a
# service that runs a real model needs them.
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
configure_torch(settings.torch_threads)
device = prepare_device(settings.device, settings.cuda_memory_limit_mb)
location = settings.location(kind)
if kind is EmbedderKind.GIGA:
from lincodex_ml.inference.giga import GigaEmbedder
return GigaEmbedder(
location.directory,
location.lock,
settings.max_tokens,
settings.verify_weights,
device,
settings.dtype,
)
from lincodex_ml.inference.qwen3 import Qwen3Embedder
return Qwen3Embedder(
location.directory,
location.lock,
settings.max_tokens,
settings.verify_weights,
device,
settings.dtype,
)
return build_model
@@ -0,0 +1,89 @@
"""Device, precision, and memory handling shared by the real encoders.
Only modules that run a real model import this file, because importing torch
takes seconds and a fake or disabled service never needs it.
"""
from __future__ import annotations
import logging
from typing import Final
import torch
from transformers.utils import logging as transformers_logging
from lincodex_ml.config import DType
logger = logging.getLogger(__name__)
_DTYPES: Final = {
DType.FLOAT32: torch.float32,
DType.FLOAT16: torch.float16,
DType.BFLOAT16: torch.bfloat16,
}
_MIB: Final = 1024 * 1024
def torch_dtype(dtype: DType) -> torch.dtype:
return _DTYPES[dtype]
def configure_torch(threads: int) -> None:
"""Fix the thread pools so results and latency do not depend on the host."""
torch.set_num_threads(threads)
# The inter-op pool can be sized only once per process, before it starts;
# the second model of a service finds it configured already.
if torch.get_num_interop_threads() != 1:
torch.set_num_interop_threads(1)
# The loader's progress bar would print raw text into the JSON log.
transformers_logging.disable_progress_bar() # type: ignore[no-untyped-call]
def prepare_device(device: str, memory_limit_mb: int) -> torch.device:
"""Resolve the device and cap the CUDA allocator of this process.
The limit makes the allocator raise an out-of-memory error instead of
taking memory that another process on a shared GPU needs; the CUDA
context itself (a few hundred MiB) is outside the allocator and the cap.
Deterministic kernels are requested so that the same text gives the same
vector on every call.
"""
resolved = torch.device(device)
if resolved.type != "cuda":
return resolved
if not torch.cuda.is_available():
raise RuntimeError("ML_DEVICE names CUDA, but no CUDA device is available")
index = resolved.index if resolved.index is not None else torch.cuda.current_device()
resolved = torch.device("cuda", index)
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
if memory_limit_mb > 0:
total = torch.cuda.get_device_properties(index).total_memory
fraction = min(1.0, memory_limit_mb * _MIB / total)
torch.cuda.set_per_process_memory_fraction(fraction, index)
return resolved
def is_out_of_memory(error: BaseException) -> bool:
"""Whether an error is a device allocation failure that may pass later."""
return isinstance(error, torch.OutOfMemoryError)
def release_cached_memory(device: torch.device) -> None:
"""Return the cached blocks of the allocator after a failed allocation."""
if device.type == "cuda":
torch.cuda.empty_cache()
def release_all_cached_memory() -> None:
"""Return the cached blocks of every device, for example after a failed load."""
if torch.cuda.is_available() and torch.cuda.is_initialized(): # type: ignore[no-untyped-call]
torch.cuda.empty_cache()
def peak_memory_mb(device: torch.device) -> int:
"""The allocator peak of the process on the device in MiB, 0 on CPU."""
if device.type != "cuda":
return 0
return int(torch.cuda.max_memory_allocated(device) // _MIB)
+24 -3
View File
@@ -1,3 +1,4 @@
import logging
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
@@ -5,14 +6,15 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from prometheus_client import REGISTRY, make_asgi_app
from lincodex_ml.api.auth import BearerAuthMiddleware
from lincodex_ml.api.embeddings import router as embeddings_router
from lincodex_ml.api.health import router as health_router
from lincodex_ml.api.problems import BodyLimitMiddleware, install_problem_handlers
from lincodex_ml.config import Settings, load_settings
from lincodex_ml.inference.runtime import EmbeddingRuntime, embedder_factory
from lincodex_ml.inference.runtime import EmbeddingRuntime, embedder_factories
from lincodex_ml.infra.logging import configure_logging
# The model is read from the image only; the Hugging Face libraries must never
# The models are read from local files only; the Hugging Face libraries must never
# reach the network or print progress bars into the JSON log.
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
@@ -20,13 +22,29 @@ os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
def _exit_after_load_failure() -> None:
"""End the process so that its supervisor restarts it.
Called from the load thread after the failure was logged; no request is
in progress then, because every request answered 503 while loading.
"""
logging.getLogger(__name__).error("exiting after the model load failure")
os._exit(3)
def create_app(
settings: Settings | None = None, runtime: EmbeddingRuntime | None = None
) -> FastAPI:
configure_logging()
effective = load_settings() if settings is None else settings
embedding_runtime = (
EmbeddingRuntime(effective, embedder_factory(effective)) if runtime is None else runtime
EmbeddingRuntime(
effective,
embedder_factories(effective),
on_failure=_exit_after_load_failure if effective.exit_on_load_failure else None,
)
if runtime is None
else runtime
)
@asynccontextmanager
@@ -39,6 +57,9 @@ def create_app(
application.state.embedding_runtime = embedding_runtime
install_problem_handlers(application)
application.add_middleware(BodyLimitMiddleware, max_body_bytes=effective.max_body_bytes)
# Added last, so it runs first: an unauthenticated request is refused
# before its body is read.
application.add_middleware(BearerAuthMiddleware, token=effective.token)
application.include_router(health_router)
application.include_router(embeddings_router)
application.mount("/metrics", make_asgi_app(registry=REGISTRY))
+51
View File
@@ -0,0 +1,51 @@
"""Entry point of the service: `python -m lincodex_ml.serve`.
It reads the listen address from ML_LISTEN_HOST and ML_LISTEN_PORT and
refuses to listen on a non-loopback address without a service token, so the
embeddings route is never open to a network. Run the service through this
module, not through the uvicorn command line, which cannot apply that check.
"""
from __future__ import annotations
import logging
import sys
import uvicorn
from lincodex_ml.config import SettingsError, is_loopback_host, load_settings
from lincodex_ml.infra.logging import configure_logging
logger = logging.getLogger("lincodex_ml.serve")
def main() -> int:
configure_logging()
try:
settings = load_settings()
except SettingsError as error:
# Setting messages name the variable and never quote a secret.
logger.error("invalid settings: %s", error)
return 2
if settings.token is None and not is_loopback_host(settings.listen_host):
logger.error(
"refusing to listen on a non-loopback address without a service token; "
"set ML_SERVICE_TOKEN_FILE or ML_SERVICE_TOKEN"
)
return 2
from lincodex_ml.main import create_app
uvicorn.run(
create_app(settings),
host=settings.listen_host,
port=settings.listen_port,
workers=1,
log_config=None,
server_header=False,
proxy_headers=False,
)
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
{"source": "research run qwen3-emb-0.6b, float32, sentence-transformers 5.7.0 on CUDA (reports/step3 caches); synthetic texts written for the study", "model": "Qwen/Qwen3-Embedding-0.6B", "revision": "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3", "cases": [{"kind": "query", "text": "Title: Junior backend-разработчик в команду товарного каталога\nGrade: junior\nDomain: e-commerce, товарный каталог\nRequired skills: Python; REST API; SQL\nDesired skills: FastAPI или Django; pydantic\nTasks:\n- разрабатывать эндпоинты создания и редактирования карточек товаров\n- валидировать входящие данные от контент-менеджеров и внешних систем\n- делать постраничную выдачу и регулярные выгрузки для других систем\nDescription: Вакансия: Junior backend-разработчик. Мы развиваем внутренний сервис товарного каталога, через который контент-менеджеры заводят карточки, а остальные системы забирают данные. Нужно писать эндпоинты для создания и редактирования карточек, аккуратно проверять входные данные, делать постраничную выдачу и регулярные выгрузки в другие системы. Ожидаем уверенный Python, понимание REST и SQL. Будет плюсом опыт с FastAPI или Django и pydantic. Наставничество есть.", "vector": [0.0602012, 0.0124066, -0.00837608, -0.115849, 0.0229714, -0.0449449, 0.0400122, 0.0186199, -0.00262195, 0.027917, 0.0115094, 0.000379152, 0.0552954, -0.00858507, -0.0528446, 0.0245004, -0.0605631, 0.0374188, -0.00460552, 0.0603005, -0.00414506, 0.0224963, 0.00617129, 0.0920065, -0.0528705, 0.00388604, -0.00378349, 0.0508754, 0.0240473, -0.0719818, 0.0396926, -0.0525244, -0.0855952, -0.0116856, -0.0157775, -0.0102084, -0.00526572, -0.00796006, -0.0160493, -0.0297368, 0.00406728, 0.0168165, 0.0646498, 0.00876707, 0.0549871, 0.0423338, -0.0239126, 0.000764695, -0.00399904, 0.017483, -0.0283778, 0.0267792, 0.00549343, -0.0443869, 0.00771952, 0.0909804, 0.0371597, 0.01389, -0.00961419, -0.0128616, -0.025547, -0.00974861, -0.0433427, -0.00446814, -0.0170152, -0.027677, 0.0247146, 0.0634491, -0.0116979, -0.0214617, 0.015703, -0.0443664, -0.0266521, 0.0655657, -0.00101198, -0.0222626, -0.0410097, 0.0145328, -0.00270477, 0.0360168, -0.0389881, 0.00160317, -0.00716379, 0.0389457, 0.0131134, 0.0305296, -0.0542479, 0.0148947, 0.073781, 0.0135235, -0.0465107, 0.000482755, -0.0262602, 0.0843561, 0.0721028, -0.00949527, -0.000411064, -0.0189709, 0.0149664, -0.00340449, -0.0288007, 0.00626825, 0.00581747, -0.0265795, -0.0226354, 0.0365, -0.0728306, -9.14146e-05, -0.000612176, -0.00620869, -0.0203464, -0.00915578, 0.0238467, 0.0323428, -0.0091572, 0.00530451, -0.0114913, -0.0185306, 0.0243089, 0.00311003, 0.00358606, -0.0205419, 0.0333829, -0.00381886, -0.00959042, 0.023225, -0.0110733, -0.0030246, 0.0144974, -0.0231456, -0.0169505, -0.0123519, 0.00108274, -0.00476542, 0.00202406, 0.00983555, 0.0353283, 0.00340459, 0.0238342, 0.0210707, -0.0302298, -0.000957774, -0.0357876, 8.6956e-05, -0.00317794, 0.0275074, 2.96926e-05, -0.00522985, -0.0203424, -0.034108, 0.0282373, 0.0232936, 0.00558298, -0.017145, -0.0224415, 0.0390445, 0.0176887, -0.0204843, -0.00637747, 0.00863677, -0.0067378, -0.0241422, 0.0108148, -0.0254529, -0.0103555, 0.00521044, 0.0171894, -0.0309625, -0.0220943, -0.026691, -0.01241, 0.0150758, 0.00336508, -0.00769786, -0.00773804, 0.019265, -0.0438933, -0.0260157, 0.0359295, -0.0273923, -0.0321467, -0.0569879, -0.00392302, -0.0256407, 0.00749932, 0.0250187, 0.00792559, -0.00756945, -0.00372752, -0.000173198, -0.0145194, 0.010585, -0.0436066, -0.0223215, 0.00134221, -0.0077836, 0.0259203, -0.0117231, -0.0303712, 0.00692453, -0.00119344, -0.068066, 0.0261531, -0.00601992, -0.00955028, 0.0315477, 0.0212862, -0.00440249, -0.0365007, -0.0470244, -0.032537, 0.000758911, 0.00886744, 0.0143412, 0.0291826, 0.0253873, 0.0306272, 0.0160996, 0.0125119, 0.0111439, 0.0196644, 0.00969219, -0.0375632, 0.0237727, -0.0197809, -0.00282755, -0.0189743, 0.0262661, 0.030764, 0.00804198, -0.0476831, -0.00346554, -0.00169148, 0.0549661, 0.0173557, -0.0132749, -0.0122172, 0.00490362, 0.0077466, 0.0259259, 0.0423622, 0.02566, -0.0186705, 0.0112911, -0.0338476, 0.0140017, -0.0238772, 0.0217582, -0.013552, 0.00732205, 0.0236143, 0.00532941, -0.0210365, 0.0894465, 0.0385867, -0.0634436, 0.0226703, -0.00490849, -0.000202779, 0.000529942, 0.0851105, -0.00573467, 0.0111772, 0.0346563, 0.0201242, 0.00518378, -0.00829974, 0.0529882, -0.0122595, -0.0267392, -0.0358635, 0.0131867, -0.0123355, 0.00716906, -0.0230974Line truncated
+9 -16
View File
@@ -2,6 +2,7 @@ import json
import logging
import math
from collections.abc import Sequence
from dataclasses import replace
from pathlib import Path
import httpx
@@ -9,7 +10,7 @@ import pytest
import yaml
from fastapi import FastAPI
from lincodex_ml.config import EmbedderKind, Settings, load_settings
from lincodex_ml.config import Settings, load_settings
from lincodex_ml.inference.embedder import InputKind, ModelInfo, micro_batches
from lincodex_ml.inference.fake import FakeEmbedder
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
@@ -25,18 +26,7 @@ def anyio_backend() -> str:
def _settings(**overrides: object) -> Settings:
base = load_settings({"ML_EMBEDDER": "fake"})
values = {
"embedder": base.embedder,
"model_dir": base.model_dir,
"torch_threads": base.torch_threads,
"micro_batch": base.micro_batch,
"max_tokens": base.max_tokens,
"verify_weights": base.verify_weights,
"max_body_bytes": base.max_body_bytes,
}
values.update(overrides)
return Settings(**values) # type: ignore[arg-type]
return replace(load_settings({"ML_EMBEDDER": "fake"}), **overrides) # type: ignore[arg-type]
class RecordingEmbedder:
@@ -54,6 +44,9 @@ class RecordingEmbedder:
self.batches.append(list(texts))
return self.inner.encode_batch(kind, texts)
def recover(self, error: BaseException) -> bool:
return False
def _ready_app(settings: Settings, embedder: object | None = None) -> FastAPI:
built = embedder if embedder is not None else FakeEmbedder()
@@ -117,7 +110,7 @@ async def test_micro_batch_size_bounds_every_forward_pass() -> None:
@pytest.mark.anyio
async def test_service_answers_503_until_the_model_is_ready() -> None:
application = create_app(_settings(embedder=EmbedderKind.NONE))
application = create_app(_settings(embedders=()))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
@@ -210,7 +203,7 @@ async def test_request_texts_never_reach_the_log(caplog: pytest.LogCaptureFixtur
def test_embedding_operation_matches_the_shared_contract() -> None:
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
operation = contract["paths"]["/v1/embeddings"]["post"]
implementation = create_app(_settings(embedder=EmbedderKind.NONE)).openapi()
implementation = create_app(_settings(embedders=())).openapi()
actual = implementation["paths"]["/v1/embeddings"]["post"]
assert actual["operationId"] == operation["operationId"]
assert set(operation["responses"]) >= {"200", "400", "413", "503"}
@@ -228,7 +221,7 @@ def test_settings_reject_invalid_values() -> None:
with pytest.raises(SettingsError):
load_settings(environ)
settings = load_settings({})
assert settings.embedder is EmbedderKind.NONE
assert settings.embedders == ()
assert (settings.torch_threads, settings.micro_batch, settings.max_tokens) == (4, 1, 1024)
+352
View File
@@ -0,0 +1,352 @@
"""Several models in one service, device memory failures, and the bearer token."""
import logging
from collections.abc import Sequence
from dataclasses import replace
from pathlib import Path
import httpx
import pytest
from fastapi import FastAPI
from lincodex_ml import serve
from lincodex_ml.config import (
DType,
EmbedderKind,
ServiceToken,
Settings,
SettingsError,
is_loopback_host,
load_settings,
)
from lincodex_ml.inference import runtime as runtime_module
from lincodex_ml.inference.embedder import InputKind, ModelInfo
from lincodex_ml.inference.fake import FakeEmbedder
from lincodex_ml.inference.runtime import (
OOM_COOL_DOWN_SECONDS,
EmbeddingRuntime,
RuntimeState,
)
from lincodex_ml.main import create_app
TOKEN = "t0k3n-" + "x" * 40
OTHER_MODEL = "lincodex/fake-second-embedder"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def _settings(**overrides: object) -> Settings:
return replace(load_settings({"ML_EMBEDDER": "fake"}), **overrides) # type: ignore[arg-type]
class Clock:
def __init__(self) -> None:
self.now = 1000.0
def __call__(self) -> float:
return self.now
class DeviceFull(Exception):
"""Stands for a CUDA out-of-memory error."""
class FlakyEmbedder:
"""Runs out of device memory while `full` is set."""
def __init__(self) -> None:
self.inner = FakeEmbedder(model_id=OTHER_MODEL)
self.full = False
self.released = 0
@property
def info(self) -> ModelInfo:
return self.inner.info
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
if self.full:
raise DeviceFull
return self.inner.encode_batch(kind, texts)
def recover(self, error: BaseException) -> bool:
self.released += 1
return isinstance(error, DeviceFull)
def _ready(settings: Settings, *embedders: object, clock: Clock | None = None) -> FastAPI:
runtime = EmbeddingRuntime(
settings,
[lambda embedder=embedder: embedder for embedder in embedders], # type: ignore[misc]
clock=clock or Clock(),
)
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
return create_app(settings, runtime)
async def _call(
application: FastAPI,
method: str,
path: str,
client: tuple[str, int] = ("127.0.0.1", 50000),
**kwargs: object,
) -> httpx.Response:
transport = httpx.ASGITransport(app=application, client=client)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
return await http.request(method, path, **kwargs) # type: ignore[arg-type]
# ---------------------------------------------------------------- settings
def test_settings_accept_an_ordered_model_list_and_cuda_options(tmp_path: Path) -> None:
token_file = tmp_path / "token"
token_file.write_text(TOKEN + "\n", encoding="utf-8")
settings = load_settings(
{
"ML_EMBEDDER": "giga, qwen3",
"ML_DEVICE": "cuda",
"ML_DTYPE": "float16",
"ML_CUDA_MEMORY_LIMIT_MB": "2300",
"ML_SERVICE_TOKEN_FILE": str(token_file),
"ML_GIGA_MODEL_DIR": "/models/giga",
"ML_QWEN3_MODEL_DIR": "/models/qwen3",
"ML_QWEN3_MODEL_LOCK": "/locks/qwen3.lock.json",
"ML_LISTEN_HOST": "192.168.10.25",
"ML_LISTEN_PORT": "8790",
}
)
assert settings.embedders == (EmbedderKind.GIGA, EmbedderKind.QWEN3)
assert (settings.device, settings.dtype, settings.cuda_memory_limit_mb) == (
"cuda",
DType.FLOAT16,
2300,
)
assert settings.token is not None and settings.token.reveal() == TOKEN
assert settings.location(EmbedderKind.GIGA).lock == Path("/models/giga/model.lock.json")
assert settings.location(EmbedderKind.QWEN3).lock == Path("/locks/qwen3.lock.json")
assert (settings.listen_host, settings.listen_port) == ("192.168.10.25", 8790)
assert TOKEN not in repr(settings) and TOKEN not in str(settings.token)
@pytest.mark.parametrize(
"environ",
[
{"ML_EMBEDDER": "giga,giga"},
{"ML_EMBEDDER": "fake,giga"},
{"ML_EMBEDDER": "giga,gpt"},
{"ML_DEVICE": "tpu"},
{"ML_DTYPE": "float16"},
{"ML_DEVICE": "cuda", "ML_DTYPE": "int8"},
{"ML_CUDA_MEMORY_LIMIT_MB": "2000"},
{"ML_SERVICE_TOKEN": "short"},
{"ML_SERVICE_TOKEN": "x" * 20 + " " + "y" * 20},
{"ML_SERVICE_TOKEN": TOKEN, "ML_SERVICE_TOKEN_FILE": "/run/token"},
{"ML_SERVICE_TOKEN_FILE": "/nonexistent/token"},
{"ML_LISTEN_PORT": "70000"},
],
)
def test_settings_reject_invalid_combinations(environ: dict[str, str]) -> None:
with pytest.raises(SettingsError) as raised:
load_settings(environ)
assert TOKEN not in str(raised.value)
def test_loopback_detection() -> None:
assert all(is_loopback_host(host) for host in ("127.0.0.1", "::1", "[::1]", "localhost"))
assert not any(is_loopback_host(host) for host in ("0.0.0.0", "192.168.10.25", "ml", "::"))
# ---------------------------------------------------------------- several models
@pytest.mark.anyio
async def test_the_model_field_selects_one_of_the_loaded_models() -> None:
application = _ready(_settings(), FakeEmbedder(), FakeEmbedder(model_id=OTHER_MODEL))
body = {"kind": "query", "texts": ["Kafka consumer idempotency"]}
default = await _call(application, "POST", "/v1/embeddings", json=body)
second = await _call(application, "POST", "/v1/embeddings", json={**body, "model": OTHER_MODEL})
unknown = await _call(application, "POST", "/v1/embeddings", json={**body, "model": "x/y"})
assert default.status_code == 200 and second.status_code == 200
assert default.json()["model"]["id"] == "lincodex/fake-hash-embedder"
assert second.json()["model"]["id"] == OTHER_MODEL
assert default.json()["vectors"] != second.json()["vectors"]
assert unknown.status_code == 400
assert unknown.json()["errors"][0]["pointer"] == "/model"
def test_readiness_needs_every_model_and_a_broken_one_fails_the_service() -> None:
def broken() -> FakeEmbedder:
raise OSError("weights are missing")
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, broken])
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert not runtime.ready()
def test_a_permanent_load_failure_calls_the_exit_hook_and_memory_does_not() -> None:
calls: list[str] = []
def broken() -> FakeEmbedder:
raise OSError("weights are missing")
runtime = EmbeddingRuntime(_settings(), [broken], on_failure=lambda: calls.append("exit"))
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert calls == ["exit"]
assert load_settings({"ML_EXIT_ON_LOAD_FAILURE": "true"}).exit_on_load_failure
def test_two_encoders_with_one_model_id_are_refused() -> None:
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, FakeEmbedder])
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
# ---------------------------------------------------------------- device memory
@pytest.mark.anyio
async def test_out_of_memory_answers_503_and_cools_readiness_down_without_crashing() -> None:
clock = Clock()
flaky = FlakyEmbedder()
application = _ready(_settings(), flaky, clock=clock)
body = {"kind": "document", "texts": ["Stack: go, kafka"]}
flaky.full = True
failed = await _call(application, "POST", "/v1/embeddings", json=body)
readiness = await _call(application, "GET", "/readyz")
assert failed.status_code == 503
assert failed.json()["code"] == "service_unavailable"
assert failed.headers["retry-after"] == "5"
assert readiness.status_code == 503
assert flaky.released >= 1
flaky.full = False
clock.now += OOM_COOL_DOWN_SECONDS + 1
recovered = await _call(application, "POST", "/v1/embeddings", json=body)
assert recovered.status_code == 200
assert (await _call(application, "GET", "/readyz")).status_code == 200
def test_a_load_that_runs_out_of_memory_is_retried(monkeypatch: pytest.MonkeyPatch) -> None:
attempts: list[int] = []
pauses: list[float] = []
def factory() -> FakeEmbedder:
attempts.append(1)
if len(attempts) < 3:
raise DeviceFull
return FakeEmbedder()
monkeypatch.setattr(
runtime_module, "_released_after", lambda error, _: isinstance(error, DeviceFull)
)
runtime = EmbeddingRuntime(_settings(), [factory], sleep=pauses.append)
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
assert len(attempts) == 3
assert pauses == [15.0, 30.0]
# ---------------------------------------------------------------- bearer token
@pytest.mark.anyio
async def test_a_configured_token_guards_every_route_but_the_probes(
caplog: pytest.LogCaptureFixture,
) -> None:
application = _ready(_settings(token=ServiceToken(TOKEN)), FakeEmbedder())
body = {"kind": "query", "texts": ["Go"]}
remote = ("192.168.10.30", 41000)
with caplog.at_level(logging.DEBUG):
missing = await _call(application, "POST", "/v1/embeddings", remote, json=body)
wrong = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "Bearer " + TOKEN[:-1] + "y"},
)
basic = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "Basic " + TOKEN},
)
metrics = await _call(application, "GET", "/metrics/", remote)
accepted = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "bearer " + TOKEN},
)
health = await _call(application, "GET", "/healthz", remote)
ready = await _call(application, "GET", "/readyz", remote)
for refused in (missing, wrong, basic, metrics):
assert refused.status_code == 401
assert refused.headers["www-authenticate"] == "Bearer"
assert refused.json()["code"] == "unauthenticated"
assert TOKEN not in refused.text
assert accepted.status_code == 200
assert health.status_code == 200 and ready.status_code == 200
assert TOKEN not in caplog.text
@pytest.mark.anyio
async def test_without_a_token_only_loopback_callers_are_served() -> None:
application = _ready(_settings(), FakeEmbedder())
body = {"kind": "query", "texts": ["Go"]}
local = await _call(application, "POST", "/v1/embeddings", json=body)
remote = await _call(application, "POST", "/v1/embeddings", ("10.0.0.7", 5000), json=body)
assert local.status_code == 200
assert remote.status_code == 401
@pytest.mark.anyio
async def test_an_unauthenticated_body_is_never_read() -> None:
application = _ready(_settings(token=ServiceToken(TOKEN), max_body_bytes=1024), FakeEmbedder())
response = await _call(
application,
"POST",
"/v1/embeddings",
("10.0.0.7", 5000),
json={"kind": "query", "texts": ["x" * 4000]},
)
assert response.status_code == 401
# ---------------------------------------------------------------- entry point
def test_serve_refuses_a_network_address_without_a_token(monkeypatch: pytest.MonkeyPatch) -> None:
started: list[object] = []
monkeypatch.setattr(serve.uvicorn, "run", lambda *args, **kwargs: started.append(kwargs))
for name in ("ML_SERVICE_TOKEN", "ML_SERVICE_TOKEN_FILE", "ML_EMBEDDER"):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("ML_LISTEN_HOST", "0.0.0.0")
assert serve.main() == 2
assert started == []
monkeypatch.setenv("ML_SERVICE_TOKEN", TOKEN)
assert serve.main() == 0
assert started and started[0]["host"] == "0.0.0.0" # type: ignore[index]
monkeypatch.delenv("ML_SERVICE_TOKEN")
monkeypatch.setenv("ML_LISTEN_HOST", "127.0.0.1")
assert serve.main() == 0
+15 -9
View File
@@ -1,7 +1,9 @@
"""Parity of the real model with the research vectors.
"""Parity of the real Giga model with the research vectors.
Marked slow: it needs the pinned weights in ML_MODEL_DIR (fetch them with
`make -C ml model-fetch`) and runs only with `make -C ml test-model`.
Marked slow: it needs the pinned weights in ML_GIGA_MODEL_DIR (fetch them with
`make -C ml model-fetch`) and runs only with `make -C ml test-model`. The
files are verified against the checked-in lock file. ML_TEST_DEVICE=cuda runs
it on the GPU in float32.
"""
import json
@@ -13,8 +15,10 @@ import pytest
from lincodex_ml.inference.embedder import InputKind
GOLDEN = Path(__file__).resolve().parent / "data" / "giga_golden.json"
# CPU float32 against the research CUDA float32 run; measured differences are
ROOT = Path(__file__).resolve().parents[1]
GOLDEN = ROOT / "tests" / "data" / "giga_golden.json"
LOCK = ROOT / "model" / "giga-embeddings-480m.lock.json"
# float32 against the research CUDA float32 run; measured differences are
# below 1e-6 per component.
MAX_COMPONENT_DIFFERENCE = 1e-4
@@ -23,17 +27,19 @@ pytestmark = pytest.mark.slow
@pytest.fixture(scope="module")
def model_dir() -> Path:
raw = os.environ.get("ML_MODEL_DIR", "")
raw = os.environ.get("ML_GIGA_MODEL_DIR", "")
if not raw:
pytest.skip("ML_MODEL_DIR is not set")
pytest.skip("ML_GIGA_MODEL_DIR is not set")
return Path(raw)
def test_real_model_reproduces_the_research_vectors_deterministically(model_dir: Path) -> None:
from lincodex_ml.inference.giga import GigaEmbedder, configure_torch
from lincodex_ml.inference.giga import GigaEmbedder
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
configure_torch(4)
embedder = GigaEmbedder(model_dir, max_tokens=1024, verify_weights=True)
device = prepare_device(os.environ.get("ML_TEST_DEVICE", "cpu"), 0)
embedder = GigaEmbedder(model_dir, LOCK, max_tokens=1024, verify_weights=True, device=device)
golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
assert embedder.info.model_id == golden["model"]
assert embedder.info.revision == golden["revision"]
+54
View File
@@ -0,0 +1,54 @@
"""Parity of the real Qwen3-Embedding model with the research vectors.
Marked slow: it needs the pinned weights in ML_QWEN3_MODEL_DIR (fetch them with
`make -C ml model-fetch`) and runs only with `make -C ml test-model`. The
files are verified against the checked-in lock file. ML_TEST_DEVICE=cuda runs
it on the GPU in float32.
"""
import json
import math
import os
from pathlib import Path
import pytest
from lincodex_ml.inference.embedder import InputKind
ROOT = Path(__file__).resolve().parents[1]
GOLDEN = ROOT / "tests" / "data" / "qwen3_golden.json"
LOCK = ROOT / "model" / "qwen3-embedding-0.6b.lock.json"
# float32 against the research CUDA float32 run; measured differences are
# below 1e-6 per component.
MAX_COMPONENT_DIFFERENCE = 1e-4
pytestmark = pytest.mark.slow
@pytest.fixture(scope="module")
def model_dir() -> Path:
raw = os.environ.get("ML_QWEN3_MODEL_DIR", "")
if not raw:
pytest.skip("ML_QWEN3_MODEL_DIR is not set")
return Path(raw)
def test_real_model_reproduces_the_research_vectors_deterministically(model_dir: Path) -> None:
from lincodex_ml.inference.qwen3 import Qwen3Embedder
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
configure_torch(4)
device = prepare_device(os.environ.get("ML_TEST_DEVICE", "cpu"), 0)
embedder = Qwen3Embedder(model_dir, LOCK, max_tokens=1024, verify_weights=True, device=device)
golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
assert embedder.info.model_id == golden["model"]
assert embedder.info.revision == golden["revision"]
assert embedder.info.dimension == 1024
for case in golden["cases"]:
kind = InputKind(case["kind"])
first = embedder.encode_batch(kind, [case["text"]])[0]
second = embedder.encode_batch(kind, [case["text"]])[0]
assert first == second
assert math.isclose(math.sqrt(sum(value * value for value in first)), 1.0, abs_tol=1e-5)
difference = max(abs(a - b) for a, b in zip(first, case["vector"], strict=True))
assert difference < MAX_COMPONENT_DIFFERENCE