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

Update document scores based on ranker node #2048

Merged
merged 13 commits into from
Jun 27, 2022
18 changes: 15 additions & 3 deletions haystack/nodes/ranker/sentence_transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ def __init__(
revision=model_version)
self.transformer_model.eval()

# activation functions to normalize scores after prediction
self.single_label_activation = torch.nn.Sigmoid()
self.multi_label_activation = torch.nn.Identity()

if len(self.devices) > 1:
self.model = DataParallel(self.transformer_model, device_ids=self.devices)

Expand Down Expand Up @@ -119,6 +123,14 @@ def predict(self, query: str, documents: List[Document], top_k: Optional[int] =
similarity_document_tuple[0][-1] if logits_dim >= 2 else similarity_document_tuple[0],
reverse=True)

# rank documents according to scores
sorted_documents = [doc for _, doc in sorted_scores_and_documents]
return sorted_documents[:top_k]
# add normalized scores to documents
sorted_documents = []
for raw_score, doc in sorted_scores_and_documents[:top_k]:
if logits_dim >= 2:
score = self.multi_label_activation(raw_score)[-1]
else:
score = self.single_label_activation(raw_score)[0]
doc.score = score.detach().cpu().numpy().tolist()
sorted_documents.append(doc)

return sorted_documents