Text Ranking
sentence-transformers
Safetensors
Transformers
multilingual
t5gemma2
text2text-generation
reranker
encoder-decoder
FBNL
Retrieval
RAG
Instructions to use KaLM-Embedding/KaLM-Reranker-V1-Small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use KaLM-Embedding/KaLM-Reranker-V1-Small with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("KaLM-Embedding/KaLM-Reranker-V1-Small") query = "Which planet is known as the Red Planet?" passages = [ "Venus is often called Earth's twin because of its similar size and proximity.", "Mars, known for its reddish appearance, is often referred to as the Red Planet.", "Jupiter, the largest planet in our solar system, has a prominent red spot.", "Saturn, famous for its rings, is sometimes mistaken for the Red Planet." ] scores = model.predict([(query, passage) for passage in passages]) print(scores) - Transformers
How to use KaLM-Embedding/KaLM-Reranker-V1-Small with Transformers:
# Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("KaLM-Embedding/KaLM-Reranker-V1-Small") model = AutoModelForMultimodalLM.from_pretrained("KaLM-Embedding/KaLM-Reranker-V1-Small", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 12,672 Bytes
be547d4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | from __future__ import annotations
import importlib.metadata
import math
import os
from pathlib import Path
from typing import Any, Iterable, Optional, Sequence
from .constants import (
ARCHITECTURE,
DEFAULT_DECODER_PAD_TO_MULTIPLE_OF,
DEFAULT_DOCUMENT_MAX_LENGTH,
DEFAULT_ENCODER_CHUNK_SIZE,
DEFAULT_INSTRUCTION,
DEFAULT_MAX_MODEL_LEN,
DEFAULT_QUERY_MAX_LENGTH,
DEFAULT_SYSTEM_INSTRUCTION,
MODEL_ID,
NO_TOKEN_ID,
PLUGIN_NAME,
SUPPORTED_ENCODER_CHUNK_SIZES,
TEXT_MODALITY,
YES_TOKEN_ID,
decoder_text,
encoder_text,
parse_encoder_chunk_size,
validate_answer_tokens,
)
TESTED_VLLM_VERSION = "0.19.1"
def _positive_int(value: int, name: str) -> int:
parsed = int(value)
if parsed <= 0:
raise ValueError(f"{name} must be a positive integer.")
return parsed
def _sigmoid(value: float) -> float:
if value >= 0:
scale = math.exp(-value)
return 1.0 / (1.0 + scale)
scale = math.exp(value)
return scale / (1.0 + scale)
def build_hf_overrides(encoder_chunk_size: int) -> dict[str, object]:
return {
"architectures": [ARCHITECTURE],
"num_labels": 1,
"yes_token_id": YES_TOKEN_ID,
"no_token_id": NO_TOKEN_ID,
"encoder_chunk_size": encoder_chunk_size,
"decoder_pad_to_multiple_of": DEFAULT_DECODER_PAD_TO_MULTIPLE_OF,
"problem_type": "regression",
}
def _enable_plugin() -> None:
allowed = os.environ.get("VLLM_PLUGINS")
if allowed is None:
os.environ["VLLM_PLUGINS"] = PLUGIN_NAME
return
names = {item.strip() for item in allowed.split(",") if item.strip()}
if PLUGIN_NAME not in names:
raise RuntimeError(
f"VLLM_PLUGINS={allowed!r} excludes {PLUGIN_NAME!r}. Add the plugin "
"name or unset VLLM_PLUGINS."
)
def check_runtime() -> None:
installed_vllm = importlib.metadata.version("vllm")
if installed_vllm != TESTED_VLLM_VERSION:
raise RuntimeError(
f"This adapter requires vLLM {TESTED_VLLM_VERSION}; "
f"found {installed_vllm}."
)
discovered = {
entry.name: entry.value
for entry in importlib.metadata.entry_points(group="vllm.general_plugins")
}
if PLUGIN_NAME not in discovered:
raise RuntimeError(
f"vLLM plugin {PLUGIN_NAME!r} is not installed. Install the "
"vllm_support package before creating the reranker."
)
from vllm.model_executor.models import ModelRegistry
from vllm.plugins import load_general_plugins
load_general_plugins()
if ARCHITECTURE not in set(ModelRegistry.get_supported_archs()):
raise RuntimeError(f"{ARCHITECTURE} was not registered in ModelRegistry.")
class KaLMVLLMReranker:
"""Single-GPU vLLM adapter preserving the original KaLM score contract."""
def __init__(
self,
model: str | Path = MODEL_ID,
*,
query_max_length: int = DEFAULT_QUERY_MAX_LENGTH,
document_max_length: int = DEFAULT_DOCUMENT_MAX_LENGTH,
encoder_chunk_size: object = DEFAULT_ENCODER_CHUNK_SIZE,
dtype: str = "bfloat16",
tensor_parallel_size: int = 1,
max_model_len: int = DEFAULT_MAX_MODEL_LEN,
gpu_memory_utilization: float = 0.85,
batch_size: int = 32,
instruction: str = DEFAULT_INSTRUCTION,
system_instruction: str = DEFAULT_SYSTEM_INSTRUCTION,
skip_runtime_check: bool = False,
) -> None:
self.model = str(model)
self.query_max_length = _positive_int(
query_max_length, "query_max_length"
)
self.document_max_length = _positive_int(
document_max_length, "document_max_length"
)
self.encoder_chunk_size = parse_encoder_chunk_size(encoder_chunk_size)
self.dtype = str(dtype)
self.tensor_parallel_size = _positive_int(
tensor_parallel_size, "tensor_parallel_size"
)
if self.tensor_parallel_size != 1:
raise ValueError(
"The published adapter supports tensor_parallel_size=1 only."
)
self.max_model_len = _positive_int(max_model_len, "max_model_len")
self.gpu_memory_utilization = float(gpu_memory_utilization)
if not 0 < self.gpu_memory_utilization <= 1:
raise ValueError("gpu_memory_utilization must be in the interval (0, 1].")
self.batch_size = _positive_int(batch_size, "batch_size")
if not isinstance(instruction, str) or not isinstance(
system_instruction, str
):
raise TypeError("instruction and system_instruction must be strings.")
self.instruction = instruction
self.system_instruction = system_instruction
_enable_plugin()
if not skip_runtime_check:
check_runtime()
from transformers import AutoTokenizer
self.tokenizer = AutoTokenizer.from_pretrained(
self.model,
trust_remote_code=True,
)
validate_answer_tokens(self.tokenizer)
from vllm import LLM
from vllm.pooling_params import PoolingParams
self.pooling_params = PoolingParams(use_activation=False)
self.llm = LLM(
model=self.model,
runner="pooling",
trust_remote_code=True,
hf_overrides=build_hf_overrides(self.encoder_chunk_size),
dtype=self.dtype,
tensor_parallel_size=1,
max_model_len=self.max_model_len,
gpu_memory_utilization=self.gpu_memory_utilization,
enforce_eager=True,
limit_mm_per_prompt={TEXT_MODALITY: 1},
)
def close(self) -> None:
llm = getattr(self, "llm", None)
if llm is None:
return
engine = getattr(llm, "llm_engine", None)
engine_core = getattr(engine, "engine_core", None)
shutdown = getattr(engine_core, "shutdown", None)
if callable(shutdown):
shutdown()
self.llm = None
def __enter__(self) -> "KaLMVLLMReranker":
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.close()
def _encoder_ids(self, document: str) -> tuple[str, list[int]]:
text = encoder_text(document)
token_ids = self.tokenizer(
text,
add_special_tokens=False,
truncation=True,
max_length=self.document_max_length,
)["input_ids"]
if not token_ids:
raise ValueError("Encoded document prompt is empty.")
return text, list(token_ids)
def _decoder_ids(self, query: str, instruction: str) -> tuple[str, list[int]]:
text = decoder_text(
self.tokenizer,
query,
instruction=instruction,
system_instruction=self.system_instruction,
query_max_length=self.query_max_length,
)
token_ids = self.tokenizer.encode(text, add_special_tokens=False)
if not token_ids:
raise ValueError("Encoded decoder prompt is empty.")
return text, list(token_ids)
def _prompt(self, query: str, document: str, instruction: str):
from vllm.inputs import ExplicitEncoderDecoderPrompt, TokensPrompt
encoder_prompt, encoder_ids = self._encoder_ids(document)
decoder_prompt, decoder_ids = self._decoder_ids(query, instruction)
return ExplicitEncoderDecoderPrompt(
encoder_prompt=TokensPrompt(
prompt_token_ids=encoder_ids,
prompt=encoder_prompt,
multi_modal_data={TEXT_MODALITY: [encoder_prompt]},
),
decoder_prompt=TokensPrompt(
prompt_token_ids=decoder_ids,
prompt=decoder_prompt,
),
)
@staticmethod
def _validate_pairs(
pairs: Sequence[tuple[str, str]],
) -> list[tuple[str, str]]:
if isinstance(pairs, (str, bytes)) or not isinstance(pairs, Sequence):
raise TypeError("pairs must be a sequence of (query, document) pairs.")
validated: list[tuple[str, str]] = []
for index, pair in enumerate(pairs):
if (
isinstance(pair, (str, bytes))
or not isinstance(pair, Sequence)
or len(pair) != 2
):
raise ValueError(f"pairs[{index}] must contain exactly two strings.")
query, document = pair
if not isinstance(query, str) or not isinstance(document, str):
raise TypeError(f"pairs[{index}] must contain exactly two strings.")
validated.append((query, document))
return validated
@staticmethod
def _margins_from_outputs(outputs: Iterable[Any]) -> list[float]:
margins: list[float] = []
for output in outputs:
values = output.outputs.probs
if len(values) != 1:
raise RuntimeError(f"Expected one raw margin, got {values}.")
margin = float(values[0])
if not math.isfinite(margin):
raise RuntimeError(f"vLLM returned a non-finite margin: {margin}.")
margins.append(margin)
return margins
def predict(
self,
pairs: Sequence[tuple[str, str]],
*,
instruction: Optional[str] = None,
return_margin: bool = False,
) -> list[float] | list[dict[str, float]]:
validated_pairs = self._validate_pairs(pairs)
if not validated_pairs:
return []
effective_instruction = self.instruction if instruction is None else instruction
if not isinstance(effective_instruction, str):
raise TypeError("instruction must be a string or None.")
margins: list[float] = []
for start in range(0, len(validated_pairs), self.batch_size):
batch = validated_pairs[start : start + self.batch_size]
prompts = [
self._prompt(query, document, effective_instruction)
for query, document in batch
]
if self.llm is None:
raise RuntimeError("The reranker has been closed.")
outputs = self.llm.classify(
prompts,
pooling_params=self.pooling_params,
use_tqdm=False,
)
margins.extend(self._margins_from_outputs(outputs))
scores = [_sigmoid(margin) for margin in margins]
if return_margin:
return [
{"score": score, "margin": margin}
for score, margin in zip(scores, margins)
]
return scores
def rank(
self,
query: str,
documents: Sequence[str],
*,
instruction: Optional[str] = None,
top_k: Optional[int] = None,
return_margin: bool = False,
) -> list[dict[str, float | int]]:
if not isinstance(query, str):
raise TypeError("query must be a string.")
if isinstance(documents, (str, bytes)) or not isinstance(documents, Sequence):
raise TypeError("documents must be a sequence of strings.")
if any(not isinstance(document, str) for document in documents):
raise TypeError("every document must be a string.")
if top_k is not None:
top_k = int(top_k)
if top_k < 0:
raise ValueError("top_k must be non-negative or None.")
predictions = self.predict(
[(query, document) for document in documents],
instruction=instruction,
return_margin=return_margin,
)
rankings: list[dict[str, float | int]] = []
for corpus_id, prediction in enumerate(predictions):
if return_margin:
assert isinstance(prediction, dict)
item: dict[str, float | int] = {
"corpus_id": corpus_id,
"score": prediction["score"],
"margin": prediction["margin"],
}
else:
assert isinstance(prediction, float)
item = {"corpus_id": corpus_id, "score": prediction}
rankings.append(item)
rankings.sort(key=lambda item: float(item["score"]), reverse=True)
return rankings if top_k is None else rankings[:top_k]
KaLMVLLMOfflineReranker = KaLMVLLMReranker
__all__ = [
"KaLMVLLMOfflineReranker",
"KaLMVLLMReranker",
"SUPPORTED_ENCODER_CHUNK_SIZES",
"build_hf_overrides",
"check_runtime",
"parse_encoder_chunk_size",
]
|