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 @@
"""Text embedding runtime of the ML service."""
+63
View File
@@ -0,0 +1,63 @@
"""The encoder interface and the deterministic order of a request."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from enum import StrEnum
from typing import Protocol
class InputKind(StrEnum):
"""Side of the retrieval pair; see EmbeddingInputKind in the contract."""
QUERY = "query"
DOCUMENT = "document"
@dataclass(frozen=True, slots=True)
class ModelInfo:
model_id: str
revision: str
dimension: int
max_tokens: int
prompt_version: str
class Embedder(Protocol):
"""Encodes texts into L2-normalized float32 vectors."""
@property
def info(self) -> ModelInfo: ...
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
"""Encode one micro-batch; the result follows the order of texts."""
...
def micro_batches(texts: Sequence[str], size: int) -> list[list[int]]:
"""Split request positions into micro-batches of similar length.
Texts are ordered by length, longest first, with the request position as
the tie-breaker, so the same request is always split the same way and a
batch pads as little as possible.
"""
order = sorted(range(len(texts)), key=lambda index: (-len(texts[index]), index))
return [order[start : start + size] for start in range(0, len(order), size)]
def encode_ordered(
embedder: Embedder, kind: InputKind, texts: Sequence[str], micro_batch: int
) -> list[list[float]]:
"""Encode texts in deterministic micro-batches and restore request order."""
vectors: list[list[float] | None] = [None] * len(texts)
for batch in micro_batches(texts, micro_batch):
encoded = embedder.encode_batch(kind, [texts[index] for index in batch])
for index, vector in zip(batch, encoded, strict=True):
vectors[index] = vector
result: list[list[float]] = []
for encoded_vector in vectors:
if encoded_vector is None:
raise RuntimeError("an encoder skipped a text")
result.append(encoded_vector)
return result
+51
View File
@@ -0,0 +1,51 @@
"""A deterministic stand-in encoder for tests and stands without the model.
Its vectors come from SHA-256 of the kind and the text, so they are stable and
unrelated texts are nearly orthogonal. It reports its own model id, so no
caller can mistake its output for a model result.
"""
from __future__ import annotations
import hashlib
import math
import struct
from collections.abc import Sequence
from typing import Final
from lincodex_ml.inference.embedder import InputKind, ModelInfo
FAKE_MODEL_ID: Final = "lincodex/fake-hash-embedder"
FAKE_REVISION: Final = "fake-v1"
FAKE_DIMENSION: Final = 32
class FakeEmbedder:
def __init__(self, dimension: int = FAKE_DIMENSION, max_tokens: int = 1024) -> None:
self._info = ModelInfo(
model_id=FAKE_MODEL_ID,
revision=FAKE_REVISION,
dimension=dimension,
max_tokens=max_tokens,
prompt_version="fake-v1",
)
@property
def info(self) -> ModelInfo:
return self._info
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
return [self._vector(kind, text) for text in texts]
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()
for (raw,) in struct.iter_unpack(">i", block):
values.append(raw / 2**31)
counter += 1
values = values[: self._info.dimension]
norm = math.sqrt(sum(value * value for value in values)) or 1.0
# float32 rounding keeps the fake in the precision of a real model.
return [struct.unpack("<f", struct.pack("<f", value / norm))[0] for value in values]
+149
View File
@@ -0,0 +1,149 @@
"""Giga-Embeddings-instruct-480M on CPU, 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
execute it. Qwen3BidirectionalModel below is the same computation written
against the pinned transformers release: every attention layer is
non-causal, the padding mask is bidirectional, and weights, RoPE, RMSNorm,
and QK-norm are stock Qwen3, so the checkpoint loads without key remapping.
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.
"""
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.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.inference.embedder import InputKind, ModelInfo
from lincodex_ml.model_files import LOCK_FILE_NAME, 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 query, retrieve relevant passages\nQuery: "
DOCUMENT_PROMPT: Final = ""
# Changes whenever the prompt or the pooling recipe changes; callers store it
# with each vector.
PROMPT_VERSION: Final = "giga-card-mean-v1"
class Qwen3BidirectionalConfig(Qwen3Config): # type: ignore[no-untyped-call]
model_type = "qwen3_bidirec"
class Qwen3BidirectionalModel(Qwen3Model): # type: ignore[no-untyped-call]
"""Qwen3 with bidirectional self-attention, as the model card defines it."""
config_class = Qwen3BidirectionalConfig
def __init__(self, config: Qwen3BidirectionalConfig) -> None:
super().__init__(config)
for layer in self.layers:
attention: Any = layer.self_attn
attention.is_causal = False
def encode_hidden(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
inputs_embeds = self.embed_tokens(input_ids)
cache_position = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
position_ids = cache_position.unsqueeze(0)
mask = create_bidirectional_mask(
config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask
)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
attention_mask=mask,
position_ids=position_ids,
past_key_values=None,
use_cache=False,
cache_position=cache_position,
position_embeddings=position_embeddings,
)
result: torch.Tensor = self.norm(hidden_states)
return result
class GigaEmbedder:
"""Loads the verified files of one directory and encodes on CPU."""
def __init__(self, model_dir: Path, max_tokens: int, verify_weights: bool) -> None:
lock = load_lock(model_dir / LOCK_FILE_NAME)
if verify_weights:
verify_directory(lock, model_dir)
_check_query_prompt(model_dir)
self._tokenizer = PreTrainedTokenizerFast.from_pretrained(
str(model_dir), local_files_only=True
)
model = Qwen3BidirectionalModel.from_pretrained(
str(model_dir),
dtype=torch.float32,
attn_implementation="sdpa",
local_files_only=True,
use_safetensors=True,
)
model.eval() # type: ignore[no-untyped-call]
self._model = model
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"]
hidden = self._model.encode_hidden(encoded["input_ids"], attention_mask)
weights = attention_mask.unsqueeze(-1).to(hidden.dtype)
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()
return vectors
def _check_query_prompt(model_dir: Path) -> None:
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")
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]
+151
View File
@@ -0,0 +1,151 @@
"""Loading state and serialized execution of the encoder.
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.
"""
from __future__ import annotations
import logging
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 lincodex_ml.config import EmbedderKind, Settings
from lincodex_ml.inference.embedder import Embedder, InputKind, ModelInfo, encode_ordered
logger = logging.getLogger(__name__)
# Warm-up texts: the first passes allocate kernels and buffers, so the
# first real request does not pay for them.
_WARMUP_TEXTS: Final = (
"Backend developer: idempotent payment callbacks, PostgreSQL, Kafka.",
"Разработка сервиса уведомлений с повторной доставкой и дедупликацией.", # noqa: RUF001
)
_WARMUP_ROUNDS: Final = 3
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),
)
ENCODED_TEXTS: Final = Counter(
"lincodex_ml_embedding_texts_total",
"Texts encoded, by input kind.",
["kind"],
)
class RuntimeState(StrEnum):
DISABLED = "disabled"
LOADING = "loading"
READY = "ready"
FAILED = "failed"
class NotReadyError(Exception):
"""The encoder is not loaded and warmed up."""
class EmbeddingRuntime:
def __init__(self, settings: Settings, factory: Callable[[], Embedder] | None) -> None:
self._settings = settings
self._factory = factory
self._state = RuntimeState.DISABLED if factory is None else RuntimeState.LOADING
self._embedder: Embedder | None = None
self._state_lock = threading.Lock()
self._encode_lock = threading.Lock()
self._thread: threading.Thread | None = None
@property
def state(self) -> RuntimeState:
with self._state_lock:
return self._state
def start(self) -> None:
"""Load and warm up the encoder in the background."""
if self._factory is None or self._thread is not None:
return
self._thread = threading.Thread(target=self._load, name="embedder-load", daemon=True)
self._thread.start()
def wait(self, timeout: float | None = None) -> RuntimeState:
if self._thread is not None:
self._thread.join(timeout)
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
with self._state_lock:
self._embedder = embedder
self._state = RuntimeState.READY
logger.info(
"embedding model is ready",
extra={"seconds": round(time.monotonic() - started, 1)},
)
def info(self) -> ModelInfo:
with self._state_lock:
if self._embedder is None:
raise NotReadyError
return self._embedder.info
def encode(self, kind: InputKind, texts: Sequence[str]) -> tuple[ModelInfo, list[list[float]]]:
with self._state_lock:
embedder = self._embedder
if embedder is None:
raise NotReadyError
with self._encode_lock, ENCODE_SECONDS.labels(kind=kind.value).time():
vectors = encode_ordered(embedder, kind, texts, self._settings.micro_batch)
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 build_fake() -> Embedder:
from lincodex_ml.inference.fake import FakeEmbedder
return FakeEmbedder(max_tokens=settings.max_tokens)
return build_fake
case EmbedderKind.GIGA:
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
configure_torch(settings.torch_threads)
return GigaEmbedder(
settings.model_dir, settings.max_tokens, settings.verify_weights
)
return build_giga