Files
lincodex/ml/src/lincodex_ml/inference/giga.py
T

150 lines
6.2 KiB
Python

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