Skip to content

Commit 1540c48

Browse files
authored
Add text-ranking pipeline tag (#1267)
Hello! ## Pull Request overview * Add `text-ranking` pipeline tag * Slightly update the docs for `sentence-similarity` ## Details This PR adds a `text-ranking` pipeline tag for reranker models like: * https://huggingface.co/models?author=cross-encoder * https://huggingface.co/models?search=reranker E.g.: ```python from sentence_transformers import CrossEncoder # 1. Load a pre-trained CrossEncoder model model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") # 2a. Either: predict scores for a pair of sentences scores = model.predict([ ("How many people live in Berlin?", "Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers."), ("How many people live in Berlin?", "Berlin is well known for its museums."), ]) # => array([ 8.607138 , -4.3200774], dtype=float32) # 2b. Or: rank a list of passages for a query query = "How many people live in Berlin?" passages = [ "Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.", "Berlin is well known for its museums.", "In 2014, the city state Berlin had 37,368 live births (+6.6%), a record number since 1991.", "The urban area of Berlin comprised about 4.1 million people in 2014, making it the seventh most populous urban area in the European Union.", "The city of Paris had a population of 2,165,423 people within its administrative city limits as of January 1, 2019", "An estimated 300,000-420,000 Muslims reside in Berlin, making up about 8-11 percent of the population.", "Berlin is subdivided into 12 boroughs or districts (Bezirke).", "In 2015, the total labour force in Berlin was 1.85 million.", "In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs.", "Berlin has a yearly total of about 135 million day visitors, which puts it in third place among the most-visited city destinations in the European Union.", ] ranks = model.rank(query, passages) # Print the scores print("Query:", query) for rank in ranks: print(f"{rank['score']:.2f}\t{passages[rank['corpus_id']]}") """ Query: How many people live in Berlin? 8.92 The urban area of Berlin comprised about 4.1 million people in 2014, making it the seventh most populous urban area in the European Union. 8.61 Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers. 8.24 An estimated 300,000-420,000 Muslims reside in Berlin, making up about 8-11 percent of the population. 7.60 In 2014, the city state Berlin had 37,368 live births (+6.6%), a record number since 1991. 6.35 In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs. 5.42 Berlin has a yearly total of about 135 million day visitors, which puts it in third place among the most-visited city destinations in the European Union. 3.45 In 2015, the total labour force in Berlin was 1.85 million. 0.33 Berlin is subdivided into 12 boroughs or districts (Bezirke). -4.24 The city of Paris had a population of 2,165,423 people within its administrative city limits as of January 1, 2019 -4.32 Berlin is well known for its museums. """ ``` I haven't created a spec for the API here, as I think that's better left to those who've created other specs. I think we might already have a Sentence Ranking API that we might not want to break. This is slightly blocking the next [Sentence Transformers release](https://github.com/UKPLab/sentence-transformers), as I'd like to know whether I can tag CrossEncoder (a.k.a. reranker) models as `text-ranking`. Related to this PR: huggingface-internal/moon-landing#12877 (private repo). - Tom Aarsen
1 parent 0a0960c commit 1540c48

File tree

6 files changed

+176
-4
lines changed

6 files changed

+176
-4
lines changed

packages/tasks/src/pipelines.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,11 @@ export const PIPELINE_DATA = {
550550
color: "blue",
551551
hideInModels: true,
552552
},
553+
"text-ranking": {
554+
name: "Text Ranking",
555+
modality: "nlp",
556+
color: "red",
557+
},
553558
"text-retrieval": {
554559
name: "Text Retrieval",
555560
subtasks: [

packages/tasks/src/tasks/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ export const TASKS_MODEL_LIBRARIES: Record<PipelineType, ModelLibraryKey[]> = {
147147
"tabular-to-text": ["transformers"],
148148
"text-classification": ["adapter-transformers", "setfit", "spacy", "transformers", "transformers.js"],
149149
"text-generation": ["transformers", "transformers.js"],
150+
"text-ranking": ["sentence-transformers", "transformers"],
150151
"text-retrieval": [],
151152
"text-to-image": ["diffusers"],
152153
"text-to-speech": ["espnet", "tensorflowtts", "transformers", "transformers.js"],
@@ -232,6 +233,7 @@ export const TASKS_DATA: Record<PipelineType, TaskData | undefined> = {
232233
"tabular-to-text": undefined,
233234
"text-classification": getData("text-classification", textClassification),
234235
"text-generation": getData("text-generation", textGeneration),
236+
"text-ranking": getData("text-ranking", placeholder),
235237
"text-retrieval": undefined,
236238
"text-to-image": getData("text-to-image", textToImage),
237239
"text-to-speech": getData("text-to-speech", textToSpeech),

packages/tasks/src/tasks/sentence-similarity/about.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ You can extract information from documents using Sentence Similarity models. The
88

99
The [Sentence Transformers](https://www.sbert.net/) library is very powerful for calculating embeddings of sentences, paragraphs, and entire documents. An embedding is just a vector representation of a text and is useful for finding how similar two texts are.
1010

11-
You can find and use [hundreds of Sentence Transformers](https://huggingface.co/models?library=sentence-transformers&sort=downloads) models from the Hub by directly using the library, playing with the widgets in the browser or using Inference Endpoints.
11+
You can find and use [thousands of Sentence Transformers](https://huggingface.co/models?library=sentence-transformers&sort=downloads) models from the Hub by directly using the library, playing with the widgets in the browser or using Inference Endpoints.
1212

1313
## Task Variants
1414

@@ -79,8 +79,8 @@ sentences = ["I'm happy", "I'm full of happiness"]
7979

8080
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
8181

82-
#Compute embedding for both lists
83-
embedding_1= model.encode(sentences[0], convert_to_tensor=True)
82+
# Compute embedding for both lists
83+
embedding_1 = model.encode(sentences[0], convert_to_tensor=True)
8484
embedding_2 = model.encode(sentences[1], convert_to_tensor=True)
8585

8686
util.pytorch_cos_sim(embedding_1, embedding_2)

packages/tasks/src/tasks/sentence-similarity/data.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const taskData: TaskDataCustom = {
44
datasets: [
55
{
66
description: "Bing queries with relevant passages from various web sources.",
7-
id: "ms_marco",
7+
id: "microsoft/ms_marco",
88
},
99
],
1010
demo: {
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
## Use Cases 🔍
2+
3+
### Information Retrieval
4+
5+
You can improve Information Retrieval search stacks by applying a Text Ranking model as a Reranker in the common "[Retrieve and Rerank pipeline](https://sbert.net/examples/applications/retrieve_rerank/README.html)". First, you can use a [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) or [Feature Extraction](https://huggingface.co/tasks/feature-extraction) model as a Retriever to find the (for example) 100 most relevant documents for a query. Afterwards, you can rerank each of these 100 documents with a Text Ranking model to select an updated top 10. Often times, this results in improved retrieval performance than only using a Retriever model.
6+
7+
## The Sentence Transformers library
8+
9+
The [Sentence Transformers](https://www.sbert.net/) library is very powerful for using and training both Sentence Transformer (a.k.a. embedding or retriever) models as well as Cross Encoder (a.k.a. reranker) models.
10+
11+
You can find and use [Sentence Transformers](https://huggingface.co/models?library=sentence-transformers&sort=downloads) models from the Hub by directly using the library, playing with the widgets in the browser or using Inference Endpoints.
12+
13+
## Task Variants
14+
15+
### Passage Ranking
16+
17+
Passage Ranking is the task of ranking documents based on their relevance to a given query. The task is evaluated on Normalized Discounted Cumulative Gain, Mean Reciprocal Rank, or Mean Average Precision. These models take one query and multiple documents and return ranked documents according to the relevancy to the query. 📄
18+
19+
You can use it via the [Sentence Transformers library](https://sbert.net/docs/cross_encoder/usage/usage.html) like so:
20+
21+
```python
22+
from sentence_transformers import CrossEncoder
23+
24+
# 1. Load a pre-trained CrossEncoder model
25+
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
26+
27+
query = "How many people live in Berlin?"
28+
passages = [
29+
"Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.",
30+
"Berlin is well known for its museums.",
31+
"In 2014, the city state Berlin had 37,368 live births (+6.6%), a record number since 1991.",
32+
"The urban area of Berlin comprised about 4.1 million people in 2014, making it the seventh most populous urban area in the European Union.",
33+
"The city of Paris had a population of 2,165,423 people within its administrative city limits as of January 1, 2019",
34+
"An estimated 300,000-420,000 Muslims reside in Berlin, making up about 8-11 percent of the population.",
35+
"Berlin is subdivided into 12 boroughs or districts (Bezirke).",
36+
"In 2015, the total labour force in Berlin was 1.85 million.",
37+
"In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs.",
38+
"Berlin has a yearly total of about 135 million day visitors, which puts it in third place among the most-visited city destinations in the European Union.",
39+
]
40+
41+
# 2a. Either: predict scores for all pairs of sentences involved in the query
42+
scores = model.predict([(query, passage) for passage in passages])
43+
# => [ 8.607138 -4.320077 7.5978117 8.915804 -4.237982 8.2359 0.33119553 3.4510403 6.352979 5.416662 ]
44+
45+
# 2b. Or rank a list of passages for a query
46+
ranks = model.rank(query, passages, return_documents=True)
47+
48+
# Print the reranked passages
49+
print("Query:", query)
50+
for rank in ranks:
51+
print(f"- #{rank['corpus_id']} ({rank['score']:.2f}): {rank['text']}")
52+
"""
53+
Query: How many people live in Berlin?
54+
- #3 (8.92): The urban area of Berlin comprised about 4.1 million people in 2014, making it the seventh most populous urban area in the European Union.
55+
- #0 (8.61): Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.
56+
- #5 (8.24): An estimated 300,000-420,000 Muslims reside in Berlin, making up about 8-11 percent of the population.
57+
- #2 (7.60): In 2014, the city state Berlin had 37,368 live births (+6.6%), a record number since 1991.
58+
- #8 (6.35): In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs.
59+
- #9 (5.42): Berlin has a yearly total of about 135 million day visitors, which puts it in third place among the most-visited city destinations in the European Union.
60+
- #7 (3.45): In 2015, the total labour force in Berlin was 1.85 million.
61+
- #6 (0.33): Berlin is subdivided into 12 boroughs or districts (Bezirke).
62+
- #4 (-4.24): The city of Paris had a population of 2,165,423 people within its administrative city limits as of January 1, 2019
63+
- #1 (-4.32): Berlin is well known for its museums.
64+
"""
65+
```
66+
67+
Rerankers often outperform [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) or [Feature Extraction](https://huggingface.co/tasks/feature-extraction) models, but they're too slow to rank a query against all documents. This is why they're commonly used to perform a final reranking of the top documents from a retriever: you can get the efficiency of a retriever model with the performance of a reranker.
68+
69+
## Useful Resources
70+
71+
Would you like to learn more about Text Ranking? Here is a curated resource that you may find helpful!
72+
73+
- [Sentence Transformers > Cross Encoder Documentation](https://www.sbert.net/docs/cross_encoder/usage/usage.html)
74+
- [Sentence Transformers > Usage > Retrieve & Re-Rank](https://www.sbert.net/examples/applications/retrieve_rerank/README.html)
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import type { TaskDataCustom } from "../index.js";
2+
3+
const taskData: TaskDataCustom = {
4+
datasets: [
5+
{
6+
description: "Bing queries with relevant passages from various web sources.",
7+
id: "microsoft/ms_marco",
8+
},
9+
],
10+
demo: {
11+
inputs: [
12+
{
13+
label: "Source sentence",
14+
content: "Machine learning is so easy.",
15+
type: "text",
16+
},
17+
{
18+
label: "Sentences to compare to",
19+
content: "Deep learning is so straightforward.",
20+
type: "text",
21+
},
22+
{
23+
label: "",
24+
content: "This is so difficult, like rocket science.",
25+
type: "text",
26+
},
27+
{
28+
label: "",
29+
content: "I can't believe how much I struggled with this.",
30+
type: "text",
31+
},
32+
],
33+
outputs: [
34+
{
35+
type: "chart",
36+
data: [
37+
{
38+
label: "Deep learning is so straightforward.",
39+
score: 2.2006407,
40+
},
41+
{
42+
label: "This is so difficult, like rocket science.",
43+
score: -6.2634873,
44+
},
45+
{
46+
label: "I can't believe how much I struggled with this.",
47+
score: -10.251488,
48+
},
49+
],
50+
},
51+
],
52+
},
53+
metrics: [
54+
{
55+
description:
56+
"Discounted Cumulative Gain (DCG) measures the gain, or usefulness, of search results discounted by their position. The normalization is done by dividing the DCG by the ideal DCG, which is the DCG of the perfect ranking.",
57+
id: "Normalized Discounted Cumulative Gain",
58+
},
59+
{
60+
description:
61+
"Reciprocal Rank is a measure used to rank the relevancy of documents given a set of documents. Reciprocal Rank is the reciprocal of the rank of the document retrieved, meaning, if the rank is 3, the Reciprocal Rank is 0.33. If the rank is 1, the Reciprocal Rank is 1",
62+
id: "Mean Reciprocal Rank",
63+
},
64+
{
65+
description:
66+
"Mean Average Precision (mAP) is the overall average of the Average Precision (AP) values, where AP is the Area Under the PR Curve (AUC-PR)",
67+
id: "Mean Average Precision",
68+
},
69+
],
70+
models: [
71+
{
72+
description: "An extremely efficient text ranking model trained on a web search dataset.",
73+
id: "cross-encoder/ms-marco-MiniLM-L6-v2",
74+
},
75+
{
76+
description: "A strong multilingual text reranker model.",
77+
id: "Alibaba-NLP/gte-multilingual-reranker-base",
78+
},
79+
{
80+
description: "An efficient text ranking model that punches above its weight.",
81+
id: "Alibaba-NLP/gte-reranker-modernbert-base",
82+
},
83+
],
84+
spaces: [],
85+
summary:
86+
"Text Ranking is the task of ranking a set of texts based on their relevance to a query. Text ranking models are trained on large datasets of queries and relevant documents to learn how to rank documents based on their relevance to the query. This task is particularly useful for search engines and information retrieval systems.",
87+
widgetModels: ["cross-encoder/ms-marco-MiniLM-L6-v2"],
88+
youtubeId: "",
89+
};
90+
91+
export default taskData;

0 commit comments

Comments
 (0)