"""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 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. Pooling and normalization run in float32 whatever the precision of the weights. """ 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 lincodex_ml.config import DType from lincodex_ml.inference.embedder import InputKind, ModelInfo 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. 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 one device.""" 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_dtype(dtype), attn_implementation="sdpa", local_files_only=True, use_safetensors=True, ) model.eval() # type: ignore[no-untyped-call] self._model = model.to(self._device) # type: ignore[arg-type] 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"].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.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( (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")