feat(ml): fuse two embedding models and protect the ML service with a token
This commit is contained in:
1 parent
bc00d6901f
commit
b24e5ff906
63 files changed
+2287
-276
No files matched your search
@@ -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
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user