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

+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]