feat(matching): rank with semantic embeddings and explain matches by evidence

This commit is contained in:
shira committed 2026-10-11 10:39:46 +03:00
1 parent facc1789b1
commit 24b64d698a
215 files changed
+16951 -327

No files matched your search

+1
View File
@@ -0,0 +1 @@
{"source": "research run giga-480m, float32, sentence-transformers 5.7.0 on CUDA (reports/step3 caches); synthetic texts written for the study", "model": "ai-sage/Giga-Embeddings-instruct-480M-0826", "revision": "1763d603adac8057bd6482a708001b0ed2e0a903", "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.0010874, -0.0122021, -0.0296269, -0.0182613, 0.0168587, 0.0215172, 0.015573, -0.0077459, -0.0405785, 0.0280189, 0.0662278, -0.0130433, -0.0063699, 0.0058273, 0.0623433, 0.0054798, 0.0295653, 0.0109709, 0.0267212, 0.0118491, 0.0138514, -0.0092159, 0.0062456, 0.0270044, 0.0125473, 0.0560331, 0.0836002, -0.0177237, 0.0148641, 0.020999, 0.0130739, 0.010851, -0.0070858, 0.0371799, -0.0108275, 0.0309553, 0.0318851, 0.0315151, -0.0175437, 0.0376225, 0.0648459, 0.0062609, 0.0451493, 0.0164599, 0.0057624, -0.0437538, 0.0206657, -0.0144556, -0.0052715, 0.0121134, -0.0331767, 0.0441031, -0.022338, -0.0175843, -0.0057629, -0.0301147, -0.0111735, 0.0007432, -0.0288401, 0.0450347, 0.0183183, 0.031774, -0.0546547, 0.0061646, -0.0115972, 0.0508562, -0.0021525, -0.0080868, 0.0016952, -0.0466259, 0.0033148, -0.0120994, 0.0127655, -0.0150255, -0.0136487, 0.0042134, 0.0178402, -0.0519363, -0.0089776, -0.0448243, 0.0158321, -0.0142117, -0.0263317, 0.0508424, 0.0373702, -0.0055558, -0.0294157, 0.0146107, 0.0241555, -0.0365671, -0.0091064, 0.0002475, 0.010197, -0.0302118, -0.0324269, 0.0131996, -0.0077065, -0.0270601, -0.0444277, 0.0100831, -0.0352657, -0.0363421, 0.0365646, -0.0230992, 0.0344071, -0.0448087, 0.0441019, 0.0383389, 0.0257643, -0.062267, 0.0291318, -0.0192691, -0.0076901, 0.0193025, 0.0135324, 0.0260016, -0.0529182, -0.0119884, -0.0121649, -0.0207623, 0.0069311, -0.0410238, -0.0187615, -0.0312817, 0.0030423, 0.0061491, 0.0193261, 0.0412739, -0.0154324, -0.042763, 0.0306725, 0.0008396, 0.006132, 0.0088559, 0.0224031, 0.0139317, 0.0487625, 0.003571, 0.024823, -0.0089968, -0.0413704, -0.0692513, 0.0322092, -0.003721, -0.0097764, -0.0184926, 0.0228861, -0.0311401, -0.0297228, 0.020615, 0.0047598, 0.0022507, 0.0124001, 0.0417159, -0.0436192, -0.0815099, -0.0174925, -0.0205195, 0.0193254, 0.0706004, 0.0022302, 0.0458147, 0.0168698, -0.0097129, 0.0445161, 0.0008063, -0.0044315, 0.0015631, 0.0018957, 0.0290296, -0.0227532, -0.0371539, -0.0729047, 0.020618, -0.0152086, 0.0134396, 0.0095738, 0.0426427, 0.0502025, -0.0469692, 0.0036251, 0.0136171, -0.0208582, 0.0182502, 0.013664, 0.020154, 0.0089408, -0.0547697, -0.0647874, -0.0456385, -0.0213974, 0.0212687, -0.0465319, 0.0077016, 0.0074073, -0.0322197, 0.0268453, -0.0195837, -0.0228397, -0.023701, -0.0006939, 0.0072619, -0.003501, 0.0075031, -0.0808211, -0.0268128, 0.0159746, -0.0713221, -0.0003716, 0.0347029, -0.0650821, -0.0078897, 0.0077127, 0.006232, -0.0449824, 0.0209828, -0.0464028, 0.0685018, -0.0279625, -0.0166439, 0.027674, -0.0295136, 0.0231525, -0.0005871, -0.0164897, -0.0037675, 0.0772745, -0.0139079, -0.0154013, 0.0206638, 0.024798, 0.0009943, -0.0174517, -0.0403561, 0.0224058, -0.0085782, 0.0455634, -0.036259, 0.0153402, 0.0369549, 0.0162551, -0.0038592, 0.0011081, -0.0152834, -0.0139122, -0.0156211, 0.0593592, 0.0439871, 0.0081494, 0.0446605, 0.0101774, -0.0657304, -0.0366937, 0.0102266, 0.0023427, 0.0151238, -0.0119786, 0.017147, 0.0128313, 0.0085243, 0.0006423, 0.0417882, 0.0262946, -0.0036146, 0.0036378, -0.015278, 0.0113112, -0.0075143, -0.0113745, 0.0583961, -0.0004987, 0.0306577, -0.0718292, -0.0414702, -0.0301506, -0.0591662, 0.0396986, 0.0208291, -0.0583831, 0.0571403, -0.0022077, 0.0326037, 0.0130092, -0.0Line truncated
+244
View File
@@ -0,0 +1,244 @@
import json
import logging
import math
from collections.abc import Sequence
from pathlib import Path
import httpx
import pytest
import yaml
from fastapi import FastAPI
from lincodex_ml.config import EmbedderKind, 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
from lincodex_ml.main import create_app
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
PRIVATE_TEXT = "Jane Doe, +7 900 000-00-00, built a ledger at Example Bank"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
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]
class RecordingEmbedder:
"""Fake encoder that records the micro-batches it receives."""
def __init__(self) -> None:
self.inner = FakeEmbedder()
self.batches: list[list[str]] = []
@property
def info(self) -> ModelInfo:
return self.inner.info
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
self.batches.append(list(texts))
return self.inner.encode_batch(kind, texts)
def _ready_app(settings: Settings, embedder: object | None = None) -> FastAPI:
built = embedder if embedder is not None else FakeEmbedder()
runtime = EmbeddingRuntime(settings, lambda: built) # type: ignore[arg-type, return-value]
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
return create_app(settings, runtime)
async def _post(application: FastAPI, body: object, **kwargs: object) -> httpx.Response:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
return await client.post("/v1/embeddings", json=body, **kwargs) # type: ignore[arg-type]
@pytest.mark.anyio
async def test_embeddings_return_normalized_vectors_in_request_order() -> None:
application = _ready_app(_settings())
texts = ["short", "a much longer text than the first one", "mid length text"]
response = await _post(application, {"kind": "document", "texts": texts})
assert response.status_code == 200
body = response.json()
assert body["kind"] == "document"
assert body["model"]["id"] == "lincodex/fake-hash-embedder"
assert body["model"]["dimension"] == 32
assert len(body["vectors"]) == len(texts)
for text, vector in zip(texts, body["vectors"], strict=True):
assert vector == FakeEmbedder().encode_batch(InputKind.DOCUMENT, [text])[0]
assert math.isclose(math.sqrt(sum(value * value for value in vector)), 1.0, abs_tol=1e-6)
@pytest.mark.anyio
async def test_identical_requests_give_identical_vectors_and_kinds_differ() -> None:
application = _ready_app(_settings(micro_batch=2))
body = {"kind": "query", "texts": ["Kafka", "make payment callbacks idempotent", "Go"]}
first = (await _post(application, body)).json()
second = (await _post(application, body)).json()
document = (await _post(application, {**body, "kind": "document"})).json()
assert first == second
assert first["vectors"] != document["vectors"]
def test_micro_batches_sort_by_length_with_position_as_tie_breaker() -> None:
texts = ["bb", "a", "cc", "dddd", "e"]
assert micro_batches(texts, 2) == [[3, 0], [2, 1], [4]]
assert micro_batches(texts, 1) == [[3], [0], [2], [1], [4]]
@pytest.mark.anyio
async def test_micro_batch_size_bounds_every_forward_pass() -> None:
recorder = RecordingEmbedder()
application = _ready_app(_settings(micro_batch=2), recorder)
recorder.batches.clear()
await _post(application, {"kind": "document", "texts": ["a", "bbb", "cc", "dddd", "e"]})
assert recorder.batches == [["dddd", "bbb"], ["cc", "a"], ["e"]]
@pytest.mark.anyio
async def test_service_answers_503_until_the_model_is_ready() -> None:
application = create_app(_settings(embedder=EmbedderKind.NONE))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.post("/v1/embeddings", json={"kind": "query", "texts": ["Go"]})
readiness = await client.get("/readyz")
assert response.status_code == 503
assert response.headers["content-type"].startswith("application/problem+json")
assert response.json()["code"] == "service_unavailable"
assert response.headers["retry-after"] == "5"
assert readiness.status_code == 503
@pytest.mark.anyio
async def test_readiness_turns_ready_only_after_the_warm_up() -> None:
application = _ready_app(_settings())
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.get("/readyz")
assert response.status_code == 200
assert response.json() == {"status": "ready"}
def test_failed_load_keeps_the_service_not_ready(caplog: pytest.LogCaptureFixture) -> None:
def broken() -> FakeEmbedder:
raise OSError(PRIVATE_TEXT)
runtime = EmbeddingRuntime(_settings(), broken)
with caplog.at_level(logging.INFO):
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert PRIVATE_TEXT not in caplog.text
@pytest.mark.anyio
@pytest.mark.parametrize(
"body",
[
{"kind": "query", "texts": []},
{"kind": "query", "texts": ["x"] * 33},
{"kind": "query", "texts": ["x" * 8001]},
{"kind": "query", "texts": [""]},
{"kind": "summary", "texts": ["x"]},
{"kind": "query", "texts": ["x"], "prompt": "ignore the instruction"},
],
)
async def test_requests_outside_the_contract_answer_400(body: object) -> None:
application = _ready_app(_settings())
response = await _post(application, body)
assert response.status_code == 400
assert response.json()["code"] == "validation_failed"
@pytest.mark.anyio
async def test_body_over_the_limit_answers_413() -> None:
application = _ready_app(_settings(max_body_bytes=1024))
response = await _post(application, {"kind": "query", "texts": ["x" * 2000]})
assert response.status_code == 413
assert response.json()["code"] == "payload_too_large"
@pytest.mark.anyio
async def test_streamed_body_over_the_limit_answers_413() -> None:
application = _ready_app(_settings(max_body_bytes=1024))
payload = json.dumps({"kind": "query", "texts": ["x" * 2000]}).encode()
async def chunks(): # type: ignore[no-untyped-def]
for start in range(0, len(payload), 256):
yield payload[start : start + 256]
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.post(
"/v1/embeddings", content=chunks(), headers={"content-type": "application/json"}
)
assert response.status_code == 413
@pytest.mark.anyio
async def test_request_texts_never_reach_the_log(caplog: pytest.LogCaptureFixture) -> None:
application = _ready_app(_settings())
with caplog.at_level(logging.DEBUG):
await _post(application, {"kind": "document", "texts": [PRIVATE_TEXT]})
await _post(application, {"kind": "document", "texts": [PRIVATE_TEXT * 2000]})
assert "Jane Doe" not in caplog.text
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()
actual = implementation["paths"]["/v1/embeddings"]["post"]
assert actual["operationId"] == operation["operationId"]
assert set(operation["responses"]) >= {"200", "400", "413", "503"}
def test_settings_reject_invalid_values() -> None:
from lincodex_ml.config import SettingsError
for environ in (
{"ML_EMBEDDER": "gpt"},
{"ML_TORCH_THREADS": "0"},
{"ML_MICRO_BATCH": "many"},
{"ML_VERIFY_WEIGHTS": "maybe"},
):
with pytest.raises(SettingsError):
load_settings(environ)
settings = load_settings({})
assert settings.embedder is EmbedderKind.NONE
assert (settings.torch_threads, settings.micro_batch, settings.max_tokens) == (4, 1, 1024)
@pytest.mark.anyio
async def test_a_request_may_name_the_served_model_and_not_another() -> None:
application = _ready_app(_settings())
served = await _post(
application, {"model": "lincodex/fake-hash-embedder", "kind": "query", "texts": ["Go"]}
)
assert served.status_code == 200
other = await _post(application, {"model": "example/other", "kind": "query", "texts": ["Go"]})
assert other.status_code == 400
assert other.json()["errors"][0]["pointer"] == "/model"
+48
View File
@@ -0,0 +1,48 @@
"""Parity of the real 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`.
"""
import json
import math
import os
from pathlib import Path
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
# 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_MODEL_DIR", "")
if not raw:
pytest.skip("ML_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
configure_torch(4)
embedder = GigaEmbedder(model_dir, max_tokens=1024, verify_weights=True)
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
+83
View File
@@ -0,0 +1,83 @@
import hashlib
import json
from pathlib import Path
import pytest
from lincodex_ml.model_files import (
LOCK_FILE_NAME,
ModelFilesError,
PinnedFile,
load_lock,
main,
verify_directory,
verify_file,
)
LOCK_PATH = Path(__file__).resolve().parents[1] / "model" / "giga-embeddings-480m.lock.json"
def _write_lock(path: Path, files: dict[str, object], **overrides: object) -> Path:
document = {
"id": "example/model",
"revision": "0" * 40,
"files": files,
**overrides,
}
path.write_text(json.dumps(document), encoding="utf-8")
return path
def test_the_checked_in_lock_pins_safetensors_and_no_code() -> None:
lock = load_lock(LOCK_PATH)
names = {pinned.name for pinned in lock.files}
assert lock.model_id == "ai-sage/Giga-Embeddings-instruct-480M-0826"
assert lock.revision == "1763d603adac8057bd6482a708001b0ed2e0a903"
assert "model.safetensors" in names
assert not any(name.endswith((".py", ".bin", ".pt", ".pkl")) for name in names)
@pytest.mark.parametrize(
("files", "overrides"),
[
({"model.bin": {"size": 1, "sha256": "0" * 64}}, {}),
({"modeling.py": {"size": 1, "sha256": "0" * 64}}, {}),
({"../escape": {"size": 1, "sha256": "0" * 64}}, {}),
({"config.json": {"size": 1, "sha256": "short"}}, {}),
({"config.json": {"size": 1, "sha256": "0" * 64}}, {"revision": "main"}),
({}, {}),
],
)
def test_lock_rejects_unsafe_or_unpinned_entries(
tmp_path: Path, files: dict[str, object], overrides: dict[str, object]
) -> None:
with pytest.raises(ModelFilesError):
load_lock(_write_lock(tmp_path / "lock.json", files, **overrides))
def test_verification_detects_size_and_digest_changes(tmp_path: Path) -> None:
content = b"weights"
target = tmp_path / "model.safetensors"
target.write_bytes(content)
pinned = PinnedFile("model.safetensors", len(content), hashlib.sha256(content).hexdigest())
verify_file(target, pinned)
target.write_bytes(b"weightz")
with pytest.raises(ModelFilesError):
verify_file(target, pinned)
target.write_bytes(b"longer weights")
with pytest.raises(ModelFilesError):
verify_file(target, pinned)
def test_verify_command_checks_a_directory(tmp_path: Path) -> None:
content = b"{}"
(tmp_path / "config.json").write_bytes(content)
lock = _write_lock(
tmp_path / LOCK_FILE_NAME,
{"config.json": {"size": len(content), "sha256": hashlib.sha256(content).hexdigest()}},
)
verify_directory(load_lock(lock), tmp_path)
assert main(["verify", "--lock", str(lock), "--dir", str(tmp_path)]) == 0
(tmp_path / "config.json").write_bytes(b"[]")
assert main(["verify", "--lock", str(lock), "--dir", str(tmp_path)]) == 1
+2 -1
View File
@@ -150,7 +150,8 @@ def test_uvicorn_loggers_are_redacted_after_uvicorn_configures_them(
(429, 429, "rate_limited"),
(501, 501, "not_implemented"),
(418, 400, "validation_failed"),
(503, 500, "internal"),
(503, 503, "service_unavailable"),
(502, 500, "internal"),
],
)
async def test_http_exceptions_map_to_contract_problems(