Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion fastembed/rerank/cross_encoder/onnx_text_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ def onnx_embed_pairs(self, pairs: list[tuple[str, str]], **kwargs: Any) -> OnnxO
onnx_input = self._preprocess_onnx_input(inputs, **kwargs)
outputs = self._run_model_with_shrinkage(self.ONNX_OUTPUT_NAMES, onnx_input)
relevant_output = outputs[0]
scores: NumpyArray = relevant_output[:, 0]
scores: NumpyArray = (
relevant_output if relevant_output.ndim == 1 else relevant_output[:, 0]
)
return OnnxOutputContext(model_output=scores)

def _rerank_documents(
Expand Down
Binary file added tests/misc/reranker_scores_column.onnx
Binary file not shown.
Binary file added tests/misc/reranker_scores_vector.onnx
Binary file not shown.
47 changes: 47 additions & 0 deletions tests/test_custom_models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import itertools
import json
import os
import shutil
from pathlib import Path

import numpy as np
import pytest
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace

from fastembed.common.model_description import (
BaseModelDescription,
Expand All @@ -16,6 +22,7 @@
from fastembed.rerank.cross_encoder.custom_text_cross_encoder import CustomTextCrossEncoder
from fastembed.text.custom_text_embedding import CustomTextEmbedding, PostprocessingConfig
from fastembed.text.text_embedding import TextEmbedding
from tests.config import TEST_MISC_DIR
from tests.utils import delete_model_cache


Expand Down Expand Up @@ -197,6 +204,46 @@ def test_cross_encoder_custom_model_parallel_processing():
delete_model_cache(model.model._model_dir)


@pytest.mark.parametrize("score_shape", ["vector", "column"])
@pytest.mark.parametrize("entry_point", ["rerank", "rerank_pairs", "parallel"])
def test_custom_cross_encoder_score_shape(
tmp_path: Path, score_shape: str, entry_point: str
) -> None:
tokenizer = Tokenizer(WordLevel({"[PAD]": 0, "query": 1, "a": 2, "b": 3}))
tokenizer.pre_tokenizer = Whitespace()
tokenizer.save(str(tmp_path / "tokenizer.json"))
(tmp_path / "tokenizer_config.json").write_text(
json.dumps({"model_max_length": 16, "pad_token": "[PAD]"}), encoding="utf-8"
)

# The ONNX graphs both cast the sum of token IDs on the sequence axis to float.
# ReduceSum uses keepdims=0 for the vector and keepdims=1 for the column.
shutil.copyfile(TEST_MISC_DIR / f"reranker_scores_{score_shape}.onnx", tmp_path / "model.onnx")

model_name = "test/pair-scores"
TextCrossEncoder.add_custom_model(
model_name, sources=ModelSource(hf=model_name), model_file="model.onnx"
)
model = TextCrossEncoder(
model_name,
cache_dir=str(tmp_path / "cache"),
specific_model_path=str(tmp_path),
providers=["CPUExecutionProvider"],
threads=1,
)
documents = ["a", "b b", "b"]
if entry_point == "rerank":
scores = model.rerank("query", documents, batch_size=2)
else:
scores = model.rerank_pairs(
[("query", document) for document in documents],
batch_size=2,
parallel=2 if entry_point == "parallel" else None,
)

assert list(scores) == [3.0, 7.0, 4.0]


def test_mock_add_custom_models():
dim = 5
size_in_gb = 0.1
Expand Down