ostra / backend /app /engine /embedder.py
sumandas's picture
Add transformers 5.x compatibility shim for legacy custom-code HF models (nomic-bert, jina, gte)
6979b06 verified
Raw History Blame Contribute Delete
22.5 kB
from __future__ import annotations
import gc
import logging
import re
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Callable
import numpy as np
from app.config import MAX_CACHED_MODELS, get_model_meta
from app.engine.hardware import detect_hardware
from app.schemas import DenseTokenAnatomy
logger = logging.getLogger(__name__)
WORD_SPLIT_RE = re.compile(r"\S+")
@dataclass
class TokenTelemetry:
token_counts: np.ndarray # int32 [N]
is_truncated: np.ndarray # bool [N]
truncation_ratio: np.ndarray # float32 [N] (0..1 fraction of tokens lost)
truncated_char_offsets: list[int | None]
subword_fertility: np.ndarray # float32 [N] (tokens / words)
max_seq_len: int
def _l2_normalize(vecs: np.ndarray) -> np.ndarray:
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
return (vecs / np.maximum(norms, 1e-12)).astype(np.float32)
def ensure_transformers_v4_compat() -> None:
"""Restore removed transformers 4.x ModuleUtilsMixin helpers on PreTrainedModel.
Transformers 5.x removed `get_extended_attention_mask`, `invert_attention_mask`,
and `get_head_mask` from `PreTrainedModel`, which breaks legacy `trust_remote_code=True`
HF models (e.g., `nomic-ai/nomic-embed-text-v1.5`, `jina-embeddings`, `gte-*`).
"""
import torch
from transformers import PreTrainedModel
if not hasattr(PreTrainedModel, "get_extended_attention_mask"):
def get_extended_attention_mask(
self,
attention_mask: torch.Tensor,
input_shape: tuple[int, ...],
device: torch.device | None = None,
dtype: torch.dtype | None = None,
) -> torch.Tensor:
if dtype is None:
dtype = getattr(self, "dtype", torch.float32)
if not (attention_mask.dim() == 2 and getattr(self.config, "is_decoder", False)):
if attention_mask.dim() == 3:
extended_attention_mask = attention_mask[:, None, :, :]
elif attention_mask.dim() == 2:
extended_attention_mask = attention_mask[:, None, None, :]
else:
raise ValueError(
f"Wrong shape for attention_mask (shape {attention_mask.shape})"
)
else:
batch_size, seq_length = input_shape
seq_ids = torch.arange(seq_length, device=attention_mask.device)
causal_mask = (
seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
<= seq_ids[None, :, None]
).to(attention_mask.dtype)
extended_attention_mask = (
causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
)
extended_attention_mask = extended_attention_mask.to(dtype=dtype)
extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(dtype).min
return extended_attention_mask
PreTrainedModel.get_extended_attention_mask = get_extended_attention_mask # type: ignore[attr-defined]
if not hasattr(PreTrainedModel, "invert_attention_mask"):
def invert_attention_mask(self, encoder_attention_mask: torch.Tensor) -> torch.Tensor:
dtype = getattr(self, "dtype", torch.float32)
if encoder_attention_mask.dim() == 3:
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
elif encoder_attention_mask.dim() == 2:
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
else:
raise ValueError(
f"Wrong shape for encoder_attention_mask (shape {encoder_attention_mask.shape})"
)
encoder_extended_attention_mask = encoder_extended_attention_mask.to(dtype=dtype)
return (1.0 - encoder_extended_attention_mask) * torch.finfo(dtype).min
PreTrainedModel.invert_attention_mask = invert_attention_mask # type: ignore[attr-defined]
if not hasattr(PreTrainedModel, "get_head_mask"):
def get_head_mask(
self,
head_mask: torch.Tensor | None,
num_hidden_layers: int,
is_attention_chunked: bool = False,
):
if head_mask is None:
return [None] * num_hidden_layers
if head_mask.dim() == 1:
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
head_mask = head_mask.expand(num_hidden_layers, -1, -1, -1, -1)
elif head_mask.dim() == 2:
head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
if is_attention_chunked:
head_mask = head_mask.unsqueeze(-1)
return head_mask
PreTrainedModel.get_head_mask = get_head_mask # type: ignore[attr-defined]
class BaseEmbeddingBackend:
backend_name: str = "cpu"
device_label: str = "CPU"
max_seq_len: int = 512
dim: int = 384
tokenizer: object = None
def encode_batch(self, texts: list[str]) -> np.ndarray:
raise NotImplementedError
class MLXEmbeddingBackend(BaseEmbeddingBackend):
"""Native Apple Silicon MLX backend via mlx-embeddings."""
def __init__(self, model_id: str, max_seq_len_override: int | None = None) -> None:
import mlx.core as mx # type: ignore
from mlx_embeddings import load as mlx_load # type: ignore
self._mx = mx
self.model_id = model_id
hw = detect_hardware()
self.backend_name = "mlx"
self.device_label = hw.device_label
model, tokenizer = mlx_load(model_id)
self.model = model
self.tokenizer = tokenizer
# Determine reliable max_seq_len
meta = get_model_meta(model_id)
tok_max = getattr(tokenizer, "model_max_length", 512)
if not isinstance(tok_max, int) or tok_max <= 0 or tok_max > 16384:
tok_max = meta["max_seq_len"] if meta else 512
self.max_seq_len = min(max_seq_len_override or tok_max, 2048)
# Warm probe to determine exact output dim & output attribute
probe = self.encode_batch(["warmup probe"])
self.dim = int(probe.shape[1])
def encode_batch(self, texts: list[str]) -> np.ndarray:
mx = self._mx
# mlx-embeddings wraps HF tokenizer; get underlying callable if wrapped
tok = getattr(self.tokenizer, "_tokenizer", self.tokenizer)
encoded = tok(
texts,
padding=True,
truncation=True,
max_length=self.max_seq_len,
return_tensors="np",
)
input_ids = mx.array(encoded["input_ids"])
attention_mask = mx.array(encoded["attention_mask"])
try:
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
except TypeError:
outputs = self.model(input_ids)
if hasattr(outputs, "text_embeds") and outputs.text_embeds is not None:
embeds = outputs.text_embeds
elif hasattr(outputs, "pooler_output") and outputs.pooler_output is not None:
embeds = outputs.pooler_output
elif hasattr(outputs, "last_hidden_state") and outputs.last_hidden_state is not None:
# Mean pooling with attention mask
hidden = outputs.last_hidden_state
mask = mx.expand_dims(attention_mask.astype(hidden.dtype), axis=-1)
embeds = mx.sum(hidden * mask, axis=1) / mx.maximum(mx.sum(mask, axis=1), 1e-9)
elif isinstance(outputs, (tuple, list)):
embeds = outputs[0]
if embeds.ndim == 3:
mask = mx.expand_dims(attention_mask.astype(embeds.dtype), axis=-1)
embeds = mx.sum(embeds * mask, axis=1) / mx.maximum(mx.sum(mask, axis=1), 1e-9)
else:
embeds = outputs
mx.eval(embeds)
arr = np.asarray(embeds, dtype=np.float32)
if arr.ndim == 1:
arr = arr[None, :]
return _l2_normalize(arr)
class SentenceTransformerBackend(BaseEmbeddingBackend):
"""Fallback embedding backend via sentence-transformers (PyTorch MPS/CUDA/CPU)."""
def __init__(
self,
model_id: str,
preferred_device: str = "auto",
max_seq_len_override: int | None = None,
) -> None:
from sentence_transformers import SentenceTransformer
hw = detect_hardware()
if preferred_device == "cpu":
device = "cpu"
elif preferred_device == "mps" and hw.mps_available:
device = "mps"
elif hw.cuda_available:
device = "cuda"
elif hw.mps_available:
device = "mps"
else:
device = "cpu"
self.model_id = model_id
self.backend_name = device
self.device_label = (
f"PyTorch {device.upper()}"
if device != "mps"
else "PyTorch MPS · Apple Silicon"
)
ensure_transformers_v4_compat()
self.model = SentenceTransformer(
model_id, device=device, trust_remote_code=True
)
self.tokenizer = self.model.tokenizer
seq_len = getattr(self.model, "max_seq_length", 512) or 512
self.max_seq_len = min(max_seq_len_override or int(seq_len), 2048)
self.model.max_seq_length = self.max_seq_len
get_dim = getattr(
self.model, "get_embedding_dimension", None
) or getattr(self.model, "get_sentence_embedding_dimension", None)
self.dim = int((get_dim() if callable(get_dim) else None) or 384)
def encode_batch(self, texts: list[str]) -> np.ndarray:
arr = self.model.encode(
texts,
batch_size=len(texts),
show_progress_bar=False,
convert_to_numpy=True,
normalize_embeddings=True,
)
arr = np.asarray(arr, dtype=np.float32)
if arr.ndim == 1:
arr = arr[None, :]
return _l2_normalize(arr)
class TextEmbedder:
"""
Production embedding runner with:
- Auto-routing (MLX primary on Apple Silicon, SentenceTransformers fallback)
- Length-sorted dynamic batching
- Exact silent token truncation & subword fertility telemetry
- Query Dual-Anatomy subword breakdown
"""
def __init__(
self,
model_id: str,
preferred_device: str = "auto",
max_seq_len_override: int | None = None,
backend_override: BaseEmbeddingBackend | None = None,
) -> None:
self.model_id = model_id
self._lock = threading.Lock()
if backend_override is not None:
self.backend = backend_override
else:
self.backend = self._load_backend(
model_id, preferred_device, max_seq_len_override
)
@staticmethod
def _load_backend(
model_id: str,
preferred_device: str,
max_seq_len_override: int | None,
) -> BaseEmbeddingBackend:
hw = detect_hardware()
try_mlx = (
preferred_device in ("auto", "mlx")
and hw.is_apple_silicon
and hw.mlx_embeddings_available
)
if try_mlx:
try:
logger.info("Loading %s on Apple Silicon MLX...", model_id)
return MLXEmbeddingBackend(model_id, max_seq_len_override)
except Exception as exc:
logger.warning(
"MLX backend could not load %s (%s); falling back to SentenceTransformers.",
model_id,
exc,
)
return SentenceTransformerBackend(
model_id,
preferred_device="cpu" if preferred_device == "cpu" else preferred_device,
max_seq_len_override=max_seq_len_override,
)
@property
def backend_name(self) -> str:
return self.backend.backend_name
@property
def device_label(self) -> str:
return self.backend.device_label
@property
def max_seq_len(self) -> int:
return self.backend.max_seq_len
@property
def dim(self) -> int:
return self.backend.dim
def _raw_tokenizer(self):
tok = self.backend.tokenizer
return getattr(tok, "_tokenizer", tok)
def inspect_truncation_and_fertility(
self, texts: list[str], prefix: str = ""
) -> TokenTelemetry:
"""Compute exact token count, truncation ratio, exact char cutoff offset, and fertility."""
n = len(texts)
max_len = self.max_seq_len
token_counts = np.zeros(n, dtype=np.int32)
is_truncated = np.zeros(n, dtype=bool)
truncation_ratio = np.zeros(n, dtype=np.float32)
truncated_offsets: list[int | None] = [None] * n
fertility = np.ones(n, dtype=np.float32)
tok = self._raw_tokenizer()
prefix_len = len(prefix)
for i, text in enumerate(texts):
full = f"{prefix}{text}" if prefix else text
word_count = max(len(WORD_SPLIT_RE.findall(text)), 1)
if tok is not None:
try:
enc = tok(
full,
add_special_tokens=True,
truncation=False,
return_offsets_mapping=True,
)
ids = enc["input_ids"]
total_toks = len(ids)
token_counts[i] = total_toks
content_toks = max(total_toks - 2, 1)
fertility[i] = float(content_toks) / float(word_count)
if total_toks > max_len:
is_truncated[i] = True
truncation_ratio[i] = float(total_toks - max_len) / float(total_toks)
offsets = enc.get("offset_mapping")
if offsets and len(offsets) >= max_len:
# Find last real token inside the max_len-1 budget (reserving [SEP])
cutoff_idx = max(max_len - 2, 0)
char_end = offsets[cutoff_idx][1]
if char_end == 0 and cutoff_idx > 0:
for back in range(cutoff_idx - 1, -1, -1):
if offsets[back][1] > 0:
char_end = offsets[back][1]
break
adj = max(int(char_end) - prefix_len, 0)
truncated_offsets[i] = min(adj, len(text))
else:
# Proportional fallback
truncated_offsets[i] = int(len(text) * (max_len / total_toks))
continue
except Exception:
pass
# Lightweight fallback when tokenizer doesn't support offset_mapping
approx_toks = int(round(word_count * 1.35)) + 2
token_counts[i] = approx_toks
fertility[i] = float(approx_toks) / float(word_count)
if approx_toks > max_len:
is_truncated[i] = True
truncation_ratio[i] = float(approx_toks - max_len) / float(approx_toks)
truncated_offsets[i] = int(len(text) * (max_len / approx_toks))
return TokenTelemetry(
token_counts=token_counts,
is_truncated=is_truncated,
truncation_ratio=truncation_ratio,
truncated_char_offsets=truncated_offsets,
subword_fertility=fertility,
max_seq_len=max_len,
)
def encode_corpus(
self,
texts: list[str],
prefix: str = "",
batch_size: int = 64,
progress_cb: Callable[[int, int, float], None] | None = None,
) -> np.ndarray:
"""Length-sorted dynamic batch embedding returning L2-normalized float32 [N, D]."""
n = len(texts)
if n == 0:
return np.zeros((0, self.dim), dtype=np.float32)
prefixed = [f"{prefix}{t}" if prefix else t for t in texts]
order = sorted(range(n), key=lambda idx: len(prefixed[idx]))
out = np.zeros((n, self.dim), dtype=np.float32)
t0 = time.perf_counter()
done = 0
with self._lock:
for start in range(0, n, batch_size):
batch_indices = order[start : start + batch_size]
batch_texts = [prefixed[idx] for idx in batch_indices]
vecs = self.backend.encode_batch(batch_texts)
for local_i, orig_idx in enumerate(batch_indices):
out[orig_idx] = vecs[local_i]
done += len(batch_indices)
elapsed = max(time.perf_counter() - t0, 1e-6)
if progress_cb is not None:
progress_cb(done, n, done / elapsed)
return out
def encode_texts(self, texts: list[str], prefix: str = "") -> np.ndarray:
if not texts:
return np.zeros((0, self.dim), dtype=np.float32)
prefixed = [f"{prefix}{t}" if prefix else t for t in texts]
with self._lock:
return self.backend.encode_batch(prefixed)
def analyze_query_tokens(
self, query: str, prefix: str = ""
) -> tuple[list[DenseTokenAnatomy], int, float, bool]:
"""Return (tokens, total_token_count, avg_fertility, has_high_fertility)."""
tok = self._raw_tokenizer()
tokens_out: list[DenseTokenAnatomy] = []
unk_token = getattr(tok, "unk_token", "[UNK]") if tok is not None else "[UNK]"
if prefix:
if tok is not None:
try:
p_toks = tok.tokenize(prefix)
except Exception:
p_toks = prefix.strip().split()
else:
p_toks = prefix.strip().split()
for pt in p_toks:
tokens_out.append(
DenseTokenAnatomy(
token=str(pt),
word=prefix.strip(),
is_prefix=True,
is_unk=False,
word_fertility=1,
high_fertility=False,
)
)
words = WORD_SPLIT_RE.findall(query)
word_fertilities: list[int] = []
for w in words:
if tok is not None:
try:
subwords = tok.tokenize(w)
except Exception:
subwords = [w]
else:
subwords = [w]
if not subwords:
subwords = [w]
fert = len(subwords)
word_fertilities.append(fert)
high_fert = fert >= 3
for sw in subwords:
is_unk = str(sw) == str(unk_token)
tokens_out.append(
DenseTokenAnatomy(
token=str(sw),
word=w,
is_prefix=False,
is_unk=is_unk,
word_fertility=fert,
high_fertility=high_fert or is_unk,
)
)
total_tokens = len(tokens_out) + 2 # + [CLS]/[SEP]
avg_fert = float(np.mean(word_fertilities)) if word_fertilities else 1.0
has_high = any(t.high_fertility or t.is_unk for t in tokens_out)
return tokens_out, total_tokens, round(avg_fert, 2), has_high
def _resolve_device_key(preferred_device: str) -> str:
"""Resolve requested device onto the actual host backend so cache keys never duplicate weights."""
hw = detect_hardware()
if preferred_device == "cpu":
return "cpu"
if preferred_device == "mlx" and hw.mlx_embeddings_available:
return "mlx"
if preferred_device == "mps" and hw.mps_available:
return "mps"
return hw.recommended_backend
class EmbedderCache:
"""Bounded thread-safe LRU model cache so HF Spaces never OOM when users try multiple models."""
def __init__(self, max_models: int = MAX_CACHED_MODELS) -> None:
self._cache: OrderedDict[tuple[str, str, int | None], TextEmbedder] = OrderedDict()
self._lock = threading.Lock()
self._max_models = max(1, int(max_models))
def get(
self,
model_id: str,
preferred_device: str = "auto",
max_seq_len_override: int | None = None,
) -> TextEmbedder:
resolved_device = _resolve_device_key(preferred_device)
# Normalize default curated max_seq_len so demo runs & newly indexed runs share one model instance
meta = get_model_meta(model_id)
norm_max_seq = (
None
if (meta is not None and max_seq_len_override == meta.get("max_seq_len"))
else max_seq_len_override
)
key = (model_id, resolved_device, norm_max_seq)
with self._lock:
existing = self._cache.get(key)
if existing is not None:
self._cache.move_to_end(key)
return existing
# Load outside lock so concurrent requests don't stall on download/init
loaded = TextEmbedder(
model_id=model_id,
preferred_device=resolved_device,
max_seq_len_override=norm_max_seq,
)
evicted: TextEmbedder | None = None
with self._lock:
existing = self._cache.get(key)
if existing is not None:
self._cache.move_to_end(key)
return existing
self._cache[key] = loaded
if len(self._cache) > self._max_models:
_, evicted = self._cache.popitem(last=False)
if evicted is not None:
del evicted
gc.collect()
try:
import torch # type: ignore
if torch.cuda.is_available():
torch.cuda.empty_cache()
if (
hasattr(torch.backends, "mps")
and torch.backends.mps.is_available()
and hasattr(torch, "mps")
and hasattr(torch.mps, "empty_cache")
):
torch.mps.empty_cache()
except Exception:
pass
return loaded
embedder_cache = EmbedderCache()