Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix sentence transformers reranker import #231

Merged
merged 1 commit into from
Oct 8, 2024
Merged
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
2 changes: 1 addition & 1 deletion redisvl/utils/rerank/cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def _initialize_clients(self, api_config: Optional[Dict]):
from cohere import AsyncClient, Client
except ImportError:
raise ImportError(
"Cohere vectorizer requires the cohere library. \
"Cohere reranker requires the cohere library. \
Please install with `pip install cohere`"
)

Expand Down
31 changes: 25 additions & 6 deletions redisvl/utils/rerank/hf_cross_encoder.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any, Dict, List, Optional, Tuple, Union

from sentence_transformers import CrossEncoder
from pydantic.v1 import PrivateAttr

from redisvl.utils.rerank.base import BaseReranker

Expand Down Expand Up @@ -31,25 +31,44 @@ class HFCrossEncoderReranker(BaseReranker):
)
"""

_client: Any = PrivateAttr()

def __init__(
self,
model_name: str = "cross-encoder/ms-marco-MiniLM-L-6-v2",
model: str = "cross-encoder/ms-marco-MiniLM-L-6-v2",
limit: int = 3,
return_score: bool = True,
**kwargs,
) -> None:
"""
Initialize the HFCrossEncoderReranker with a specified model and ranking criteria.

Parameters:
model_name (str): The name or path of the cross-encoder model to use for reranking.
model (str): The name or path of the cross-encoder model to use for reranking.
Defaults to 'cross-encoder/ms-marco-MiniLM-L-6-v2'.
limit (int): The maximum number of results to return after reranking. Must be a positive integer.
return_score (bool): Whether to return scores alongside the reranked results.
"""
model = model or kwargs.pop("model_name", None)
super().__init__(
model=model_name, rank_by=None, limit=limit, return_score=return_score
model=model, rank_by=None, limit=limit, return_score=return_score
)
self.model: CrossEncoder = CrossEncoder(model_name)
self._initialize_client(**kwargs)

def _initialize_client(self, **kwargs):
"""
Setup the huggingface cross-encoder client using optional kwargs.
"""
# Dynamic import of the sentence-transformers module
try:
from sentence_transformers import CrossEncoder
except ImportError:
raise ImportError(
"HFCrossEncoder reranker requires the sentence-transformers library. \
Please install with `pip install sentence-transformers`"
)

self._client = CrossEncoder(self.model, **kwargs)

def rank(
self, query: str, docs: Union[List[Dict[str, Any]], List[str]], **kwargs
Expand Down Expand Up @@ -97,7 +116,7 @@ def rank(
texts = [str(doc) for doc in docs]
doc_subset = [{"content": doc} for doc in docs]

scores = self.model.predict([(query, text) for text in texts])
scores = self._client.predict([(query, text) for text in texts])
scores = [float(score) for score in scores]
docs_with_scores = list(zip(doc_subset, scores))
docs_with_scores.sort(key=lambda x: x[1], reverse=True)
Expand Down
Loading