Instructions to use KaLM-Embedding/KaLM-Reranker-V1-Nano 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-Nano with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("KaLM-Embedding/KaLM-Reranker-V1-Nano") 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-Nano with Transformers:
# Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("KaLM-Embedding/KaLM-Reranker-V1-Nano") model = AutoModelForMultimodalLM.from_pretrained("KaLM-Embedding/KaLM-Reranker-V1-Nano", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add sentence-transformers CrossEncoder support
Browse files# KaLM-Reranker-V1-Nano CrossEncoder validation
Validation date: 2026-07-29.
## Immutable checkpoint baseline
- `config.json`: `75926d34f90b64a3119e62535211bcd2305e8ea0ae4339773cb20dc84c8991d4`
- `model.safetensors`: `98078ef7b21ec1ee82afa1b5cbdb3923d9548d5f3bed78d290b605c65cc3f49d`
- `tokenizer.json`: `f5b325224482ec441ec5fbe2a5ac08c3758e0f9605f6e54368e31f736fcfb01d`
## Pre-adaptation CPU FP32 baseline
Reference implementation, batch size 2, query length 512, document length
1024, encoder chunk size 4:
```text
[0.9998076558113098,
0.000004796196662937291,
0.2090071737766266,
0.021608587354421616,
0.00004020768392365426]
```
## Validation matrix
| Target | Device/dtype | Status | Max absolute error | Notes |
|---|---|---:|---:|---|
| sentence-transformers 5.6.0, chunk size 4 | CPU FP32 | passed | `1.4901161193847656e-08` | `rtol=1e-5`, `atol=1e-6`; ranking `[0, 1]` |
| local 5.7.0.dev0/main, chunk size 4 | CPU FP32 | passed | `1.4901161193847656e-08` | Imported from the local source tree; ranking `[0, 1]` |
| sentence-transformers 5.6.0, pooling disabled | CPU FP32 | passed | `1.862645149230957e-09` | Reference and CrossEncoder both used `encoder_chunk_size=None` |
| sentence-transformers 5.6.0, chunk size 4 | CUDA BF16 | passed | `3.637978807091713e-12` | H100 MIG 3g.40gb; `rtol=1e-3`, `atol=2e-3` |
| local 5.7.0.dev0/main, chunk size 4 | CUDA BF16 | passed | `3.637978807091713e-12` | Imported from the local source tree; ranking `[0, 1]` |
| sentence-transformers 5.6.0, pooling disabled | CUDA BF16 | passed | `1.862645149230957e-09` | Reference and CrossEncoder both used `chunk_size=None` |
| Hub PR revision, fresh cache | CPU/CUDA | blocked | — | Hub pre-upload returned 403; no PR was created |
CUDA error 803 was resolved by preferring the host driver libraries in
`LD_LIBRARY_PATH` and setting the NVIDIA compute/utility capabilities before
starting Python.
## Environment
- Python 3.10.20
- PyTorch 2.6.0+cu126
- Transformers 5.3.0
- Stable environment: sentence-transformers 5.6.0
- Main environment: sentence-transformers 5.7.0.dev0 imported from the local
`sentence-transformers` source tree
- GPU: NVIDIA H100 80GB HBM3 MIG 3g.40gb; CUDA BF16 is supported
- CUDA recovery environment:
```bash
export NVIDIA_DRIVER_CAPABILITIES="${NVIDIA_DRIVER_CAPABILITIES:-compute,utility}"
export LD_LIBRARY_PATH="/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export CUDA_VISIBLE_DEVICES=0
```
## Interface and failure-path coverage
| Check | Status | Evidence |
|---|---:|---|
| `predict()` NumPy and Tensor output; batch sizes 1, 2, and 3; incomplete final batch; input-order restoration | passed | Five mixed-length English/Chinese/empty-input pairs match the reference at the same batch size |
| Individual `(query, document)` pair | passed | Scalar result matches the corresponding batch result |
| `rank()` default/custom instruction, `prompt_name`, `top_k`, and `return_documents` | passed | Ordering and returned document IDs/text verified |
| Empty list, empty query, empty document, malformed pair | passed | Empty shape `(0,)`; malformed input raises a typed error |
| Query/document truncation | passed | 700-query-token/1400-document-token case yields a 1024-token encoder input and an 8-aligned decoder input |
| Configurable encoder compression | passed | `model_kwargs={"chunk_size": 4}` is applied at load time; each masked group of four states is mean-pooled; `None` disables pooling |
| Default Sigmoid and Identity margin | passed | `sigmoid(yes_logit - no_logit)` matches the default score within `1e-7` |
| Single-token answers | passed | Nano tokenizer resolves `yes=4443`, `no=1904`; multi-token answer is rejected |
| Per-sample decoder endpoint and non-finite logits | passed | Unit tests cover different valid lengths and explicit NaN rejection |
| Unsupported backend | passed | `backend="onnx"` is rejected before model loading |
| `save_pretrained()` and local reload | passed | Saved custom code/config/tokenizer/weights reload and reproduce scores |
Lightweight pytest results are `7 passed, 2 skipped` in both the stable 5.6.0
environment and the local 5.7.0.dev0/main environment. Checkpoint-backed
validation was run sequentially to keep peak host memory bounded. The complete
stable-5.6.0 CUDA BF16 integration suite finished with `9 passed` in 46.97
seconds.
BF16 scores can vary slightly when the batch size changes because the padded
tensor shape changes. Batch-size coverage therefore compares each CrossEncoder
result with the reference implementation using the same batch size; all such
comparisons pass the BF16 tolerance.
## Integrity and repository isolation
- The three immutable hashes above are unchanged after all tests.
- The local sentence-transformers Git worktree remains clean; no adapter change
was made to sentence-transformers source.
- The Hub PR manifest contains only six adapter/configuration files. It excludes
the repository `README.md`, `model.safetensors`, tokenizer artifacts, and
Transformers `config.json`. The README usage section is provided separately
for manual review and editing.
## Remaining external validations
1. Grant account `cosyy` effective contributor/write access to the target
repository, or provide a token from an account that already has that access,
then run
`python create_hub_pr.py --token-file /tmp/hf_token --create-pr`.
2. Run `verify_hub_revision.py --revision refs/pr/<PR number>` for CPU FP32 and
CUDA BF16. The script uses blank model and remote-code caches and asserts
that the custom module came from that cache rather than local `PYTHONPATH`.
- config_sentence_transformers.json +13 -0
- kalm_cross_encoder.py +298 -0
- kalm_cross_encoder_config.json +6 -0
- kalm_reranker.py +59 -121
- kalm_reranker_utils.py +218 -0
- modules.json +8 -0
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "CrossEncoder",
|
| 3 |
+
"__version__": {
|
| 4 |
+
"sentence_transformers": "5.6.0",
|
| 5 |
+
"transformers": "5.3.0",
|
| 6 |
+
"pytorch": "2.6.0"
|
| 7 |
+
},
|
| 8 |
+
"prompts": {
|
| 9 |
+
"retrieval": "Given a query, retrieve documents that answer the query."
|
| 10 |
+
},
|
| 11 |
+
"default_prompt_name": "retrieval",
|
| 12 |
+
"activation_fn": "torch.nn.modules.activation.Sigmoid"
|
| 13 |
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, ClassVar
|
| 4 |
+
|
| 5 |
+
try:
|
| 6 |
+
from typing import Self
|
| 7 |
+
except ImportError:
|
| 8 |
+
from typing_extensions import Self
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from sentence_transformers.base.modules import InputModule
|
| 12 |
+
from transformers import AutoConfig, AutoModelForSeq2SeqLM, AutoTokenizer
|
| 13 |
+
|
| 14 |
+
from .kalm_reranker_utils import (
|
| 15 |
+
DEFAULT_INSTRUCTION,
|
| 16 |
+
DEFAULT_SYSTEM_INSTRUCTION,
|
| 17 |
+
answer_token_id,
|
| 18 |
+
build_decoder_text,
|
| 19 |
+
cast_floating_parameters,
|
| 20 |
+
extract_yes_no_logits,
|
| 21 |
+
forward_reranker_model,
|
| 22 |
+
normalize_requested_dtype,
|
| 23 |
+
validate_text_pairs,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class KaLMCrossEncoderModule(InputModule):
|
| 28 |
+
"""Sentence Transformers input module for KaLM encoder-decoder rerankers."""
|
| 29 |
+
|
| 30 |
+
config_file_name = "kalm_cross_encoder_config.json"
|
| 31 |
+
config_keys: ClassVar[list[str]] = [
|
| 32 |
+
"query_max_length",
|
| 33 |
+
"document_max_length",
|
| 34 |
+
"encoder_chunk_size",
|
| 35 |
+
"system_instruction",
|
| 36 |
+
]
|
| 37 |
+
save_in_root = True
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
model_name_or_path: str,
|
| 42 |
+
*,
|
| 43 |
+
query_max_length: int = 512,
|
| 44 |
+
document_max_length: int = 1024,
|
| 45 |
+
encoder_chunk_size: int | None = 4,
|
| 46 |
+
system_instruction: str = DEFAULT_SYSTEM_INSTRUCTION,
|
| 47 |
+
model_kwargs: dict[str, Any] | None = None,
|
| 48 |
+
processor_kwargs: dict[str, Any] | None = None,
|
| 49 |
+
config_kwargs: dict[str, Any] | None = None,
|
| 50 |
+
backend: str = "torch",
|
| 51 |
+
) -> None:
|
| 52 |
+
super().__init__()
|
| 53 |
+
if backend != "torch":
|
| 54 |
+
raise ValueError(
|
| 55 |
+
"KaLMCrossEncoderModule only supports backend='torch'; "
|
| 56 |
+
f"received {backend!r}."
|
| 57 |
+
)
|
| 58 |
+
if not isinstance(model_name_or_path, str) or not model_name_or_path:
|
| 59 |
+
raise ValueError("model_name_or_path must be a non-empty string.")
|
| 60 |
+
if not isinstance(query_max_length, int) or query_max_length <= 0:
|
| 61 |
+
raise ValueError("query_max_length must be a positive integer.")
|
| 62 |
+
if not isinstance(document_max_length, int) or document_max_length <= 0:
|
| 63 |
+
raise ValueError("document_max_length must be a positive integer.")
|
| 64 |
+
if encoder_chunk_size is not None and (
|
| 65 |
+
not isinstance(encoder_chunk_size, int) or encoder_chunk_size <= 0
|
| 66 |
+
):
|
| 67 |
+
raise ValueError("encoder_chunk_size must be a positive integer or None.")
|
| 68 |
+
if not isinstance(system_instruction, str):
|
| 69 |
+
raise TypeError("system_instruction must be a string.")
|
| 70 |
+
|
| 71 |
+
self.query_max_length = query_max_length
|
| 72 |
+
self.max_seq_length = document_max_length
|
| 73 |
+
self.encoder_chunk_size = encoder_chunk_size
|
| 74 |
+
self.system_instruction = system_instruction
|
| 75 |
+
self.backend = backend
|
| 76 |
+
|
| 77 |
+
model_kwargs = dict(model_kwargs or {})
|
| 78 |
+
processor_kwargs = dict(processor_kwargs or {})
|
| 79 |
+
config_kwargs = dict(config_kwargs or {})
|
| 80 |
+
|
| 81 |
+
num_labels = config_kwargs.pop("num_labels", 1)
|
| 82 |
+
if num_labels != 1:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
"KaLM reranking produces one relevance score; num_labels must be 1."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
config = AutoConfig.from_pretrained(model_name_or_path, **config_kwargs)
|
| 88 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 89 |
+
model_name_or_path, **processor_kwargs
|
| 90 |
+
)
|
| 91 |
+
if self.tokenizer.pad_token_id is None:
|
| 92 |
+
if self.tokenizer.eos_token_id is None:
|
| 93 |
+
raise ValueError(
|
| 94 |
+
"The tokenizer must define a pad token or an EOS token."
|
| 95 |
+
)
|
| 96 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 97 |
+
self.tokenizer.padding_side = "right"
|
| 98 |
+
self.processor = self.tokenizer
|
| 99 |
+
|
| 100 |
+
requested_dtype = normalize_requested_dtype(
|
| 101 |
+
model_kwargs.get("dtype", model_kwargs.get("torch_dtype"))
|
| 102 |
+
)
|
| 103 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 104 |
+
model_name_or_path,
|
| 105 |
+
config=config,
|
| 106 |
+
**model_kwargs,
|
| 107 |
+
)
|
| 108 |
+
cast_floating_parameters(self.model, requested_dtype)
|
| 109 |
+
|
| 110 |
+
self.yes_token_id = answer_token_id(self.tokenizer, "yes")
|
| 111 |
+
self.no_token_id = answer_token_id(self.tokenizer, "no")
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def document_max_length(self) -> int:
|
| 115 |
+
return self.max_seq_length
|
| 116 |
+
|
| 117 |
+
@document_max_length.setter
|
| 118 |
+
def document_max_length(self, value: int) -> None:
|
| 119 |
+
if not isinstance(value, int) or value <= 0:
|
| 120 |
+
raise ValueError("document_max_length must be a positive integer.")
|
| 121 |
+
self.max_seq_length = value
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def encoder_chunk_size(self) -> int | None:
|
| 125 |
+
return self._encoder_chunk_size
|
| 126 |
+
|
| 127 |
+
@encoder_chunk_size.setter
|
| 128 |
+
def encoder_chunk_size(self, value: int | None) -> None:
|
| 129 |
+
if value is not None and (not isinstance(value, int) or value <= 0):
|
| 130 |
+
raise ValueError("encoder_chunk_size must be a positive integer or None.")
|
| 131 |
+
self._encoder_chunk_size = value
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def chunk_size(self) -> int | None:
|
| 135 |
+
"""Alias for the encoder token mean-pooling compression rate."""
|
| 136 |
+
return self.encoder_chunk_size
|
| 137 |
+
|
| 138 |
+
@chunk_size.setter
|
| 139 |
+
def chunk_size(self, value: int | None) -> None:
|
| 140 |
+
self.encoder_chunk_size = value
|
| 141 |
+
|
| 142 |
+
def preprocess(
|
| 143 |
+
self,
|
| 144 |
+
inputs: list[Any],
|
| 145 |
+
prompt: str | None = None,
|
| 146 |
+
**kwargs: Any,
|
| 147 |
+
) -> dict[str, torch.Tensor]:
|
| 148 |
+
pairs = validate_text_pairs(inputs)
|
| 149 |
+
if not pairs:
|
| 150 |
+
return {}
|
| 151 |
+
|
| 152 |
+
instruction = DEFAULT_INSTRUCTION if prompt is None else prompt
|
| 153 |
+
if not isinstance(instruction, str):
|
| 154 |
+
raise TypeError("prompt must be a string or None.")
|
| 155 |
+
|
| 156 |
+
encoder_texts = [f"<Document>: {document}" for _, document in pairs]
|
| 157 |
+
decoder_texts = [
|
| 158 |
+
build_decoder_text(
|
| 159 |
+
self.tokenizer,
|
| 160 |
+
query,
|
| 161 |
+
instruction,
|
| 162 |
+
self.system_instruction,
|
| 163 |
+
self.query_max_length,
|
| 164 |
+
)
|
| 165 |
+
for query, _ in pairs
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
encoder_batch = self.tokenizer(
|
| 169 |
+
encoder_texts,
|
| 170 |
+
padding=True,
|
| 171 |
+
truncation=True,
|
| 172 |
+
max_length=self.document_max_length,
|
| 173 |
+
add_special_tokens=False,
|
| 174 |
+
return_tensors="pt",
|
| 175 |
+
)
|
| 176 |
+
decoder_batch = self.tokenizer(
|
| 177 |
+
decoder_texts,
|
| 178 |
+
padding=True,
|
| 179 |
+
pad_to_multiple_of=8,
|
| 180 |
+
add_special_tokens=False,
|
| 181 |
+
return_tensors="pt",
|
| 182 |
+
)
|
| 183 |
+
return {
|
| 184 |
+
"input_ids": encoder_batch["input_ids"],
|
| 185 |
+
"attention_mask": encoder_batch["attention_mask"],
|
| 186 |
+
"decoder_input_ids": decoder_batch["input_ids"],
|
| 187 |
+
"decoder_attention_mask": decoder_batch["attention_mask"],
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
def forward(
|
| 191 |
+
self,
|
| 192 |
+
features: dict[str, torch.Tensor | Any],
|
| 193 |
+
**kwargs: Any,
|
| 194 |
+
) -> dict[str, torch.Tensor | Any]:
|
| 195 |
+
outputs = forward_reranker_model(
|
| 196 |
+
self.model,
|
| 197 |
+
input_ids=features["input_ids"],
|
| 198 |
+
attention_mask=features["attention_mask"],
|
| 199 |
+
decoder_input_ids=features["decoder_input_ids"],
|
| 200 |
+
decoder_attention_mask=features["decoder_attention_mask"],
|
| 201 |
+
encoder_chunk_size=self.chunk_size,
|
| 202 |
+
)
|
| 203 |
+
yes_no_logits = extract_yes_no_logits(
|
| 204 |
+
outputs.logits,
|
| 205 |
+
features["decoder_attention_mask"],
|
| 206 |
+
self.yes_token_id,
|
| 207 |
+
self.no_token_id,
|
| 208 |
+
)
|
| 209 |
+
features["scores"] = (yes_no_logits[:, 0] - yes_no_logits[:, 1]).unsqueeze(1)
|
| 210 |
+
return features
|
| 211 |
+
|
| 212 |
+
def save(
|
| 213 |
+
self,
|
| 214 |
+
output_path: str,
|
| 215 |
+
*args: Any,
|
| 216 |
+
safe_serialization: bool = True,
|
| 217 |
+
**kwargs: Any,
|
| 218 |
+
) -> None:
|
| 219 |
+
self.model.save_pretrained(output_path, safe_serialization=safe_serialization)
|
| 220 |
+
self.tokenizer.save_pretrained(output_path)
|
| 221 |
+
self.save_config(output_path)
|
| 222 |
+
|
| 223 |
+
@classmethod
|
| 224 |
+
def load(
|
| 225 |
+
cls,
|
| 226 |
+
model_name_or_path: str,
|
| 227 |
+
subfolder: str = "",
|
| 228 |
+
token: bool | str | None = None,
|
| 229 |
+
cache_folder: str | None = None,
|
| 230 |
+
revision: str | None = None,
|
| 231 |
+
local_files_only: bool = False,
|
| 232 |
+
trust_remote_code: bool = False,
|
| 233 |
+
model_kwargs: dict[str, Any] | None = None,
|
| 234 |
+
processor_kwargs: dict[str, Any] | None = None,
|
| 235 |
+
config_kwargs: dict[str, Any] | None = None,
|
| 236 |
+
backend: str = "torch",
|
| 237 |
+
**kwargs: Any,
|
| 238 |
+
) -> Self:
|
| 239 |
+
module_config = cls.load_config(
|
| 240 |
+
model_name_or_path,
|
| 241 |
+
subfolder=subfolder,
|
| 242 |
+
token=token,
|
| 243 |
+
cache_folder=cache_folder,
|
| 244 |
+
revision=revision,
|
| 245 |
+
local_files_only=local_files_only,
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
supplied_model_kwargs = dict(model_kwargs or {})
|
| 249 |
+
supplied_config_kwargs = dict(config_kwargs or {})
|
| 250 |
+
supplied_module_kwargs = dict(kwargs)
|
| 251 |
+
chunk_size_values: list[tuple[str, int | None]] = []
|
| 252 |
+
for source_name, source in (
|
| 253 |
+
("model_kwargs", supplied_model_kwargs),
|
| 254 |
+
("config_kwargs", supplied_config_kwargs),
|
| 255 |
+
("module kwargs", supplied_module_kwargs),
|
| 256 |
+
):
|
| 257 |
+
for key in ("chunk_size", "encoder_chunk_size"):
|
| 258 |
+
if key in source:
|
| 259 |
+
chunk_size_values.append((f"{source_name}.{key}", source.pop(key)))
|
| 260 |
+
if chunk_size_values:
|
| 261 |
+
first_name, first_value = chunk_size_values[0]
|
| 262 |
+
for current_name, current_value in chunk_size_values[1:]:
|
| 263 |
+
if current_value != first_value:
|
| 264 |
+
raise ValueError(
|
| 265 |
+
"Conflicting encoder chunk sizes: "
|
| 266 |
+
f"{first_name}={first_value!r}, "
|
| 267 |
+
f"{current_name}={current_value!r}."
|
| 268 |
+
)
|
| 269 |
+
module_config["encoder_chunk_size"] = first_value
|
| 270 |
+
|
| 271 |
+
hub_kwargs = {
|
| 272 |
+
"subfolder": subfolder,
|
| 273 |
+
"token": token,
|
| 274 |
+
"cache_dir": cache_folder,
|
| 275 |
+
"revision": revision,
|
| 276 |
+
"local_files_only": local_files_only,
|
| 277 |
+
"trust_remote_code": trust_remote_code,
|
| 278 |
+
}
|
| 279 |
+
effective_model_kwargs = {**hub_kwargs, **supplied_model_kwargs}
|
| 280 |
+
effective_processor_kwargs = {**hub_kwargs, **(processor_kwargs or {})}
|
| 281 |
+
effective_config_kwargs = {**hub_kwargs, **supplied_config_kwargs}
|
| 282 |
+
|
| 283 |
+
if "model_max_length" in effective_processor_kwargs:
|
| 284 |
+
module_config["document_max_length"] = effective_processor_kwargs[
|
| 285 |
+
"model_max_length"
|
| 286 |
+
]
|
| 287 |
+
|
| 288 |
+
return cls(
|
| 289 |
+
model_name_or_path,
|
| 290 |
+
model_kwargs=effective_model_kwargs,
|
| 291 |
+
processor_kwargs=effective_processor_kwargs,
|
| 292 |
+
config_kwargs=effective_config_kwargs,
|
| 293 |
+
backend=backend,
|
| 294 |
+
**module_config,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
__all__ = ["KaLMCrossEncoderModule"]
|
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"query_max_length": 512,
|
| 3 |
+
"document_max_length": 1024,
|
| 4 |
+
"encoder_chunk_size": 4,
|
| 5 |
+
"system_instruction": "Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\"."
|
| 6 |
+
}
|
|
@@ -4,16 +4,34 @@ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
|
| 4 |
|
| 5 |
import numpy as np
|
| 6 |
import torch
|
| 7 |
-
import torch.nn.functional as F
|
| 8 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 9 |
-
from transformers.modeling_outputs import BaseModelOutput
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
class KaLMReranker:
|
|
@@ -60,8 +78,11 @@ class KaLMReranker:
|
|
| 60 |
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
|
| 61 |
if self.tokenizer.pad_token_id is None:
|
| 62 |
if self.tokenizer.eos_token_id is None:
|
| 63 |
-
raise ValueError(
|
|
|
|
|
|
|
| 64 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
|
|
|
| 65 |
self.tokenizer.padding_side = "right"
|
| 66 |
|
| 67 |
self.model = AutoModelForSeq2SeqLM.from_pretrained(
|
|
@@ -69,9 +90,7 @@ class KaLMReranker:
|
|
| 69 |
dtype=self.dtype,
|
| 70 |
**model_kwargs,
|
| 71 |
)
|
| 72 |
-
|
| 73 |
-
if parameter.is_floating_point() and parameter.dtype != self.dtype:
|
| 74 |
-
parameter.data = parameter.data.to(dtype=self.dtype)
|
| 75 |
self.model.to(device=self.device)
|
| 76 |
self.model.eval()
|
| 77 |
|
|
@@ -96,7 +115,9 @@ class KaLMReranker:
|
|
| 96 |
if isinstance(dtype, torch.dtype):
|
| 97 |
return dtype
|
| 98 |
if not isinstance(dtype, str):
|
| 99 |
-
raise TypeError(
|
|
|
|
|
|
|
| 100 |
normalized = dtype.lower().removeprefix("torch.")
|
| 101 |
supported = {
|
| 102 |
"bfloat16": torch.bfloat16,
|
|
@@ -111,17 +132,10 @@ class KaLMReranker:
|
|
| 111 |
return supported[normalized]
|
| 112 |
|
| 113 |
def _answer_token_id(self, answer: str) -> int:
|
| 114 |
-
|
| 115 |
-
if not token_ids:
|
| 116 |
-
raise ValueError(f"Failed to tokenize the answer {answer!r}.")
|
| 117 |
-
return token_ids[-1]
|
| 118 |
|
| 119 |
def _get_encoder(self):
|
| 120 |
-
|
| 121 |
-
return self.model.get_encoder()
|
| 122 |
-
if hasattr(self.model, "encoder"):
|
| 123 |
-
return self.model.encoder
|
| 124 |
-
raise AttributeError(f"Cannot find the encoder on {type(self.model).__name__}.")
|
| 125 |
|
| 126 |
@staticmethod
|
| 127 |
def _pool_encoder_chunks(
|
|
@@ -129,64 +143,22 @@ class KaLMReranker:
|
|
| 129 |
attention_mask: torch.Tensor,
|
| 130 |
chunk_size: int,
|
| 131 |
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 132 |
-
|
| 133 |
-
num_chunks = (sequence_length + chunk_size - 1) // chunk_size
|
| 134 |
-
padded_length = num_chunks * chunk_size
|
| 135 |
-
pad_length = padded_length - sequence_length
|
| 136 |
-
|
| 137 |
-
if pad_length:
|
| 138 |
-
hidden_states = F.pad(hidden_states, (0, 0, 0, pad_length))
|
| 139 |
-
attention_mask = F.pad(attention_mask, (0, pad_length))
|
| 140 |
-
|
| 141 |
-
hidden_states = hidden_states.view(
|
| 142 |
-
batch_size, num_chunks, chunk_size, hidden_size
|
| 143 |
-
)
|
| 144 |
-
chunk_mask = attention_mask.view(batch_size, num_chunks, chunk_size)
|
| 145 |
-
expanded_mask = chunk_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 146 |
-
pooled_hidden = (hidden_states * expanded_mask).sum(dim=2)
|
| 147 |
-
pooled_hidden = pooled_hidden / chunk_mask.sum(dim=2).clamp(min=1).unsqueeze(-1)
|
| 148 |
-
pooled_mask = (chunk_mask.sum(dim=2) > 0).to(attention_mask.dtype)
|
| 149 |
-
return pooled_hidden, pooled_mask
|
| 150 |
|
| 151 |
def _decoder_text(self, query: str, instruction: str) -> str:
|
| 152 |
-
|
|
|
|
| 153 |
query,
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
)["input_ids"]
|
| 158 |
-
truncated_query = self.tokenizer.decode(
|
| 159 |
-
query_ids,
|
| 160 |
-
skip_special_tokens=False,
|
| 161 |
-
clean_up_tokenization_spaces=False,
|
| 162 |
-
)
|
| 163 |
-
return (
|
| 164 |
-
"<bos><start_of_turn>user\n"
|
| 165 |
-
f"{self.system_instruction}\n\n"
|
| 166 |
-
f"<Instruct>: {instruction}\n"
|
| 167 |
-
f"<Query>: {truncated_query}<end_of_turn>\n"
|
| 168 |
-
"<start_of_turn>model\n\n\n\n"
|
| 169 |
)
|
| 170 |
|
| 171 |
@staticmethod
|
| 172 |
def _validate_pairs(
|
| 173 |
pairs: Sequence[Tuple[str, str]],
|
| 174 |
) -> List[Tuple[str, str]]:
|
| 175 |
-
|
| 176 |
-
raise TypeError("pairs must be a sequence of (query, document) pairs.")
|
| 177 |
-
validated: List[Tuple[str, str]] = []
|
| 178 |
-
for index, pair in enumerate(pairs):
|
| 179 |
-
if (
|
| 180 |
-
isinstance(pair, (str, bytes))
|
| 181 |
-
or not isinstance(pair, Sequence)
|
| 182 |
-
or len(pair) != 2
|
| 183 |
-
):
|
| 184 |
-
raise ValueError(f"pairs[{index}] must contain exactly two strings.")
|
| 185 |
-
query, document = pair
|
| 186 |
-
if not isinstance(query, str) or not isinstance(document, str):
|
| 187 |
-
raise TypeError(f"pairs[{index}] must contain exactly two strings.")
|
| 188 |
-
validated.append((query, document))
|
| 189 |
-
return validated
|
| 190 |
|
| 191 |
@torch.inference_mode()
|
| 192 |
def _predict_batch(
|
|
@@ -211,49 +183,20 @@ class KaLMReranker:
|
|
| 211 |
return_tensors="pt",
|
| 212 |
).to(self.device)
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
pooled_hidden, pooled_mask = self._pool_encoder_chunks(
|
| 229 |
-
encoder_outputs.last_hidden_state,
|
| 230 |
-
encoder_batch["attention_mask"],
|
| 231 |
-
self.chunk_size,
|
| 232 |
-
)
|
| 233 |
-
outputs = self.model(
|
| 234 |
-
encoder_outputs=BaseModelOutput(last_hidden_state=pooled_hidden),
|
| 235 |
-
attention_mask=pooled_mask,
|
| 236 |
-
decoder_input_ids=decoder_batch["input_ids"],
|
| 237 |
-
decoder_attention_mask=decoder_batch["attention_mask"],
|
| 238 |
-
return_dict=True,
|
| 239 |
-
)
|
| 240 |
-
|
| 241 |
-
sequence_lengths = decoder_batch["attention_mask"].sum(dim=1) - 1
|
| 242 |
-
batch_indices = torch.arange(outputs.logits.shape[0], device=self.device)
|
| 243 |
-
last_logits = outputs.logits[batch_indices, sequence_lengths]
|
| 244 |
-
yes_no_logits = torch.stack(
|
| 245 |
-
(
|
| 246 |
-
last_logits[:, self.yes_token_id],
|
| 247 |
-
last_logits[:, self.no_token_id],
|
| 248 |
-
),
|
| 249 |
-
dim=-1,
|
| 250 |
-
).float()
|
| 251 |
-
if not torch.isfinite(yes_no_logits).all():
|
| 252 |
-
bad_count = (~torch.isfinite(yes_no_logits).all(dim=-1)).sum().item()
|
| 253 |
-
raise RuntimeError(
|
| 254 |
-
f"The model produced non-finite yes/no logits for {bad_count} input(s). "
|
| 255 |
-
"Use bfloat16 or float32 instead of float16."
|
| 256 |
-
)
|
| 257 |
return torch.softmax(yes_no_logits, dim=-1)[:, 0].cpu().tolist()
|
| 258 |
|
| 259 |
def predict(
|
|
@@ -293,11 +236,6 @@ class KaLMReranker:
|
|
| 293 |
torch.cuda.empty_cache()
|
| 294 |
tested_batch_size = max(1, tested_batch_size * 3 // 4)
|
| 295 |
|
| 296 |
-
# The while loop's condition (`> 1`) means batch size 1 is never
|
| 297 |
-
# actually probed. If every size down to 2 OOMs, it exits without a
|
| 298 |
-
# successful probe. Only skip ahead to `tested_batch_size` when the
|
| 299 |
-
# probe actually ran; otherwise fall back to starting at 0 like the
|
| 300 |
-
# loop below always did originally, or the first item(s) get dropped.
|
| 301 |
if first_batch_scores is None:
|
| 302 |
sorted_scores: List[float] = []
|
| 303 |
loop_start = 0
|
|
@@ -316,8 +254,8 @@ class KaLMReranker:
|
|
| 316 |
if torch.cuda.is_available():
|
| 317 |
torch.cuda.empty_cache()
|
| 318 |
raise RuntimeError(
|
| 319 |
-
"CUDA ran out of memory during reranking. Retry with a smaller
|
| 320 |
-
"or shorter max_length."
|
| 321 |
) from error
|
| 322 |
inverse_indices = np.argsort(length_sorted_indices)
|
| 323 |
return [sorted_scores[index] for index in inverse_indices]
|
|
|
|
| 4 |
|
| 5 |
import numpy as np
|
| 6 |
import torch
|
|
|
|
| 7 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
|
|
|
| 8 |
|
| 9 |
+
try:
|
| 10 |
+
from .kalm_reranker_utils import (
|
| 11 |
+
DEFAULT_INSTRUCTION,
|
| 12 |
+
DEFAULT_SYSTEM_INSTRUCTION,
|
| 13 |
+
answer_token_id,
|
| 14 |
+
build_decoder_text,
|
| 15 |
+
cast_floating_parameters,
|
| 16 |
+
extract_yes_no_logits,
|
| 17 |
+
forward_reranker_model,
|
| 18 |
+
get_encoder,
|
| 19 |
+
pool_encoder_chunks,
|
| 20 |
+
validate_text_pairs,
|
| 21 |
+
)
|
| 22 |
+
except ImportError: # Support ``from kalm_reranker import KaLMReranker``.
|
| 23 |
+
from kalm_reranker_utils import (
|
| 24 |
+
DEFAULT_INSTRUCTION,
|
| 25 |
+
DEFAULT_SYSTEM_INSTRUCTION,
|
| 26 |
+
answer_token_id,
|
| 27 |
+
build_decoder_text,
|
| 28 |
+
cast_floating_parameters,
|
| 29 |
+
extract_yes_no_logits,
|
| 30 |
+
forward_reranker_model,
|
| 31 |
+
get_encoder,
|
| 32 |
+
pool_encoder_chunks,
|
| 33 |
+
validate_text_pairs,
|
| 34 |
+
)
|
| 35 |
|
| 36 |
|
| 37 |
class KaLMReranker:
|
|
|
|
| 78 |
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
|
| 79 |
if self.tokenizer.pad_token_id is None:
|
| 80 |
if self.tokenizer.eos_token_id is None:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
"The tokenizer must define a pad token or an EOS token."
|
| 83 |
+
)
|
| 84 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 85 |
+
# Final decoder-token indexing assumes right padding, matching training.
|
| 86 |
self.tokenizer.padding_side = "right"
|
| 87 |
|
| 88 |
self.model = AutoModelForSeq2SeqLM.from_pretrained(
|
|
|
|
| 90 |
dtype=self.dtype,
|
| 91 |
**model_kwargs,
|
| 92 |
)
|
| 93 |
+
cast_floating_parameters(self.model, self.dtype)
|
|
|
|
|
|
|
| 94 |
self.model.to(device=self.device)
|
| 95 |
self.model.eval()
|
| 96 |
|
|
|
|
| 115 |
if isinstance(dtype, torch.dtype):
|
| 116 |
return dtype
|
| 117 |
if not isinstance(dtype, str):
|
| 118 |
+
raise TypeError(
|
| 119 |
+
"dtype must be a torch.dtype or a string such as 'bfloat16'."
|
| 120 |
+
)
|
| 121 |
normalized = dtype.lower().removeprefix("torch.")
|
| 122 |
supported = {
|
| 123 |
"bfloat16": torch.bfloat16,
|
|
|
|
| 132 |
return supported[normalized]
|
| 133 |
|
| 134 |
def _answer_token_id(self, answer: str) -> int:
|
| 135 |
+
return answer_token_id(self.tokenizer, answer)
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
def _get_encoder(self):
|
| 138 |
+
return get_encoder(self.model)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
@staticmethod
|
| 141 |
def _pool_encoder_chunks(
|
|
|
|
| 143 |
attention_mask: torch.Tensor,
|
| 144 |
chunk_size: int,
|
| 145 |
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 146 |
+
return pool_encoder_chunks(hidden_states, attention_mask, chunk_size)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
def _decoder_text(self, query: str, instruction: str) -> str:
|
| 149 |
+
return build_decoder_text(
|
| 150 |
+
self.tokenizer,
|
| 151 |
query,
|
| 152 |
+
instruction,
|
| 153 |
+
self.system_instruction,
|
| 154 |
+
self.query_max_length,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
)
|
| 156 |
|
| 157 |
@staticmethod
|
| 158 |
def _validate_pairs(
|
| 159 |
pairs: Sequence[Tuple[str, str]],
|
| 160 |
) -> List[Tuple[str, str]]:
|
| 161 |
+
return validate_text_pairs(pairs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
@torch.inference_mode()
|
| 164 |
def _predict_batch(
|
|
|
|
| 183 |
return_tensors="pt",
|
| 184 |
).to(self.device)
|
| 185 |
|
| 186 |
+
outputs = forward_reranker_model(
|
| 187 |
+
self.model,
|
| 188 |
+
input_ids=encoder_batch["input_ids"],
|
| 189 |
+
attention_mask=encoder_batch["attention_mask"],
|
| 190 |
+
decoder_input_ids=decoder_batch["input_ids"],
|
| 191 |
+
decoder_attention_mask=decoder_batch["attention_mask"],
|
| 192 |
+
encoder_chunk_size=self.chunk_size,
|
| 193 |
+
)
|
| 194 |
+
yes_no_logits = extract_yes_no_logits(
|
| 195 |
+
outputs.logits,
|
| 196 |
+
decoder_batch["attention_mask"],
|
| 197 |
+
self.yes_token_id,
|
| 198 |
+
self.no_token_id,
|
| 199 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
return torch.softmax(yes_no_logits, dim=-1)[:, 0].cpu().tolist()
|
| 201 |
|
| 202 |
def predict(
|
|
|
|
| 236 |
torch.cuda.empty_cache()
|
| 237 |
tested_batch_size = max(1, tested_batch_size * 3 // 4)
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
if first_batch_scores is None:
|
| 240 |
sorted_scores: List[float] = []
|
| 241 |
loop_start = 0
|
|
|
|
| 254 |
if torch.cuda.is_available():
|
| 255 |
torch.cuda.empty_cache()
|
| 256 |
raise RuntimeError(
|
| 257 |
+
"CUDA ran out of memory during reranking. Retry with a smaller "
|
| 258 |
+
"batch_size or shorter max_length."
|
| 259 |
) from error
|
| 260 |
inverse_indices = np.argsort(length_sorted_indices)
|
| 261 |
return [sorted_scores[index] for index in inverse_indices]
|
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 9 |
+
|
| 10 |
+
DEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."
|
| 11 |
+
DEFAULT_SYSTEM_INSTRUCTION = (
|
| 12 |
+
"Judge whether the Document meets the requirements based on the Query and "
|
| 13 |
+
'the Instruct provided. Note that the answer can only be "yes" or "no".'
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def validate_text_pairs(inputs: Sequence[Sequence[str]]) -> list[tuple[str, str]]:
|
| 18 |
+
"""Validate and normalize a batch of ``(query, document)`` pairs."""
|
| 19 |
+
if isinstance(inputs, (str, bytes)) or not isinstance(inputs, Sequence):
|
| 20 |
+
raise TypeError("inputs must be a sequence of (query, document) pairs.")
|
| 21 |
+
|
| 22 |
+
validated: list[tuple[str, str]] = []
|
| 23 |
+
for index, pair in enumerate(inputs):
|
| 24 |
+
if (
|
| 25 |
+
isinstance(pair, (str, bytes))
|
| 26 |
+
or not isinstance(pair, Sequence)
|
| 27 |
+
or len(pair) != 2
|
| 28 |
+
):
|
| 29 |
+
raise ValueError(f"inputs[{index}] must contain exactly two strings.")
|
| 30 |
+
query, document = pair
|
| 31 |
+
if not isinstance(query, str) or not isinstance(document, str):
|
| 32 |
+
raise TypeError(f"inputs[{index}] must contain exactly two strings.")
|
| 33 |
+
validated.append((query, document))
|
| 34 |
+
return validated
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def answer_token_id(tokenizer: Any, answer: str) -> int:
|
| 38 |
+
"""Return the single vocabulary token used to score an answer."""
|
| 39 |
+
token_ids = tokenizer(answer, add_special_tokens=False)["input_ids"]
|
| 40 |
+
if len(token_ids) != 1:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
f"The answer {answer!r} must tokenize to exactly one token, "
|
| 43 |
+
f"got {token_ids!r}."
|
| 44 |
+
)
|
| 45 |
+
return token_ids[0]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def build_decoder_text(
|
| 49 |
+
tokenizer: Any,
|
| 50 |
+
query: str,
|
| 51 |
+
instruction: str,
|
| 52 |
+
system_instruction: str,
|
| 53 |
+
query_max_length: int,
|
| 54 |
+
) -> str:
|
| 55 |
+
"""Build the decoder-side instruction/query prompt used during training."""
|
| 56 |
+
query_ids = tokenizer(
|
| 57 |
+
query,
|
| 58 |
+
add_special_tokens=False,
|
| 59 |
+
truncation=True,
|
| 60 |
+
max_length=query_max_length,
|
| 61 |
+
)["input_ids"]
|
| 62 |
+
truncated_query = tokenizer.decode(
|
| 63 |
+
query_ids,
|
| 64 |
+
skip_special_tokens=False,
|
| 65 |
+
clean_up_tokenization_spaces=False,
|
| 66 |
+
)
|
| 67 |
+
return (
|
| 68 |
+
"<bos><start_of_turn>user\n"
|
| 69 |
+
f"{system_instruction}\n\n"
|
| 70 |
+
f"<Instruct>: {instruction}\n"
|
| 71 |
+
f"<Query>: {truncated_query}<end_of_turn>\n"
|
| 72 |
+
"<start_of_turn>model\n\n\n\n"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_encoder(model: torch.nn.Module) -> torch.nn.Module:
|
| 77 |
+
if hasattr(model, "get_encoder"):
|
| 78 |
+
return model.get_encoder()
|
| 79 |
+
if hasattr(model, "encoder"):
|
| 80 |
+
return model.encoder
|
| 81 |
+
raise AttributeError(f"Cannot find the encoder on {type(model).__name__}.")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def pool_encoder_chunks(
|
| 85 |
+
hidden_states: torch.Tensor,
|
| 86 |
+
attention_mask: torch.Tensor,
|
| 87 |
+
chunk_size: int,
|
| 88 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 89 |
+
"""Mean-pool consecutive encoder tokens while respecting padding."""
|
| 90 |
+
if chunk_size <= 0:
|
| 91 |
+
raise ValueError("chunk_size must be positive.")
|
| 92 |
+
|
| 93 |
+
batch_size, sequence_length, hidden_size = hidden_states.shape
|
| 94 |
+
num_chunks = (sequence_length + chunk_size - 1) // chunk_size
|
| 95 |
+
padded_length = num_chunks * chunk_size
|
| 96 |
+
pad_length = padded_length - sequence_length
|
| 97 |
+
|
| 98 |
+
if pad_length:
|
| 99 |
+
hidden_states = F.pad(hidden_states, (0, 0, 0, pad_length))
|
| 100 |
+
attention_mask = F.pad(attention_mask, (0, pad_length))
|
| 101 |
+
|
| 102 |
+
hidden_states = hidden_states.view(batch_size, num_chunks, chunk_size, hidden_size)
|
| 103 |
+
chunk_mask = attention_mask.view(batch_size, num_chunks, chunk_size)
|
| 104 |
+
expanded_mask = chunk_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 105 |
+
pooled_hidden = (hidden_states * expanded_mask).sum(dim=2)
|
| 106 |
+
pooled_hidden = pooled_hidden / chunk_mask.sum(dim=2).clamp(min=1).unsqueeze(-1)
|
| 107 |
+
pooled_mask = (chunk_mask.sum(dim=2) > 0).to(attention_mask.dtype)
|
| 108 |
+
return pooled_hidden, pooled_mask
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def forward_reranker_model(
|
| 112 |
+
model: torch.nn.Module,
|
| 113 |
+
*,
|
| 114 |
+
input_ids: torch.Tensor,
|
| 115 |
+
attention_mask: torch.Tensor,
|
| 116 |
+
decoder_input_ids: torch.Tensor,
|
| 117 |
+
decoder_attention_mask: torch.Tensor,
|
| 118 |
+
encoder_chunk_size: int | None,
|
| 119 |
+
):
|
| 120 |
+
"""Run the encoder-decoder model with optional encoder token compression."""
|
| 121 |
+
if encoder_chunk_size is None:
|
| 122 |
+
return model(
|
| 123 |
+
input_ids=input_ids,
|
| 124 |
+
attention_mask=attention_mask,
|
| 125 |
+
decoder_input_ids=decoder_input_ids,
|
| 126 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 127 |
+
return_dict=True,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
encoder_outputs = get_encoder(model)(
|
| 131 |
+
input_ids=input_ids,
|
| 132 |
+
attention_mask=attention_mask,
|
| 133 |
+
return_dict=True,
|
| 134 |
+
)
|
| 135 |
+
pooled_hidden, pooled_mask = pool_encoder_chunks(
|
| 136 |
+
encoder_outputs.last_hidden_state,
|
| 137 |
+
attention_mask,
|
| 138 |
+
encoder_chunk_size,
|
| 139 |
+
)
|
| 140 |
+
return model(
|
| 141 |
+
encoder_outputs=BaseModelOutput(last_hidden_state=pooled_hidden),
|
| 142 |
+
attention_mask=pooled_mask,
|
| 143 |
+
decoder_input_ids=decoder_input_ids,
|
| 144 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 145 |
+
return_dict=True,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def extract_yes_no_logits(
|
| 150 |
+
logits: torch.Tensor,
|
| 151 |
+
decoder_attention_mask: torch.Tensor,
|
| 152 |
+
yes_token_id: int,
|
| 153 |
+
no_token_id: int,
|
| 154 |
+
) -> torch.Tensor:
|
| 155 |
+
"""Extract float32 yes/no logits at each sample's final non-padding token."""
|
| 156 |
+
if decoder_attention_mask.ndim != 2:
|
| 157 |
+
raise ValueError("decoder_attention_mask must have shape [batch, sequence].")
|
| 158 |
+
sequence_lengths = decoder_attention_mask.sum(dim=1) - 1
|
| 159 |
+
if (sequence_lengths < 0).any():
|
| 160 |
+
raise ValueError(
|
| 161 |
+
"Every decoder input must contain at least one non-padding token."
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
batch_indices = torch.arange(logits.shape[0], device=logits.device)
|
| 165 |
+
last_logits = logits[batch_indices, sequence_lengths]
|
| 166 |
+
yes_no_logits = torch.stack(
|
| 167 |
+
(last_logits[:, yes_token_id], last_logits[:, no_token_id]), dim=-1
|
| 168 |
+
).float()
|
| 169 |
+
if not torch.isfinite(yes_no_logits).all():
|
| 170 |
+
bad_count = (~torch.isfinite(yes_no_logits).all(dim=-1)).sum().item()
|
| 171 |
+
raise RuntimeError(
|
| 172 |
+
f"The model produced non-finite yes/no logits for {bad_count} input(s). "
|
| 173 |
+
"Use bfloat16 or float32 instead of float16."
|
| 174 |
+
)
|
| 175 |
+
return yes_no_logits
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def normalize_requested_dtype(dtype: Any) -> torch.dtype | None:
|
| 179 |
+
"""Normalize a caller-provided dtype without changing the ``auto`` behavior."""
|
| 180 |
+
if dtype is None or dtype == "auto":
|
| 181 |
+
return None
|
| 182 |
+
if isinstance(dtype, torch.dtype):
|
| 183 |
+
return dtype
|
| 184 |
+
if not isinstance(dtype, str):
|
| 185 |
+
return None
|
| 186 |
+
normalized = dtype.lower().removeprefix("torch.")
|
| 187 |
+
return {
|
| 188 |
+
"bfloat16": torch.bfloat16,
|
| 189 |
+
"bf16": torch.bfloat16,
|
| 190 |
+
"float16": torch.float16,
|
| 191 |
+
"fp16": torch.float16,
|
| 192 |
+
"float32": torch.float32,
|
| 193 |
+
"fp32": torch.float32,
|
| 194 |
+
}.get(normalized)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def cast_floating_parameters(model: torch.nn.Module, dtype: torch.dtype | None) -> None:
|
| 198 |
+
"""Cast model parameters while preserving checkpoint buffer dtypes."""
|
| 199 |
+
if dtype is None:
|
| 200 |
+
return
|
| 201 |
+
for parameter in model.parameters():
|
| 202 |
+
if parameter.is_floating_point() and parameter.dtype != dtype:
|
| 203 |
+
parameter.data = parameter.data.to(dtype=dtype)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
__all__ = [
|
| 207 |
+
"DEFAULT_INSTRUCTION",
|
| 208 |
+
"DEFAULT_SYSTEM_INSTRUCTION",
|
| 209 |
+
"answer_token_id",
|
| 210 |
+
"build_decoder_text",
|
| 211 |
+
"cast_floating_parameters",
|
| 212 |
+
"extract_yes_no_logits",
|
| 213 |
+
"forward_reranker_model",
|
| 214 |
+
"get_encoder",
|
| 215 |
+
"normalize_requested_dtype",
|
| 216 |
+
"pool_encoder_chunks",
|
| 217 |
+
"validate_text_pairs",
|
| 218 |
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"idx": 0,
|
| 4 |
+
"name": "0",
|
| 5 |
+
"path": "",
|
| 6 |
+
"type": "kalm_cross_encoder.KaLMCrossEncoderModule"
|
| 7 |
+
}
|
| 8 |
+
]
|