Massive Text Embedding Benchmark
Project description
Massive Text Embedding Benchmark
Installation | Usage | Leaderboard | Documentation | Citing
Installation
pip install mteb
Example Usage
- Using a Python script:
import mteb
from sentence_transformers import SentenceTransformer
# Define the sentence-transformers model name
model_name = "average_word_embeddings_komninos"
# or directly from huggingface:
# model_name = "sentence-transformers/all-MiniLM-L6-v2"
model = SentenceTransformer(model_name)
tasks = mteb.get_tasks(tasks=["Banking77Classification"])
evaluation = mteb.MTEB(tasks=tasks)
results = evaluation.run(model, output_folder=f"results/{model_name}")
Running SentenceTransformer model with prompts
Prompts can be passed to the SentenceTransformer model using the prompts
parameter. The following code shows how to use prompts with SentenceTransformer:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("average_word_embeddings_komninos", prompts={"query": "Query:", "passage": "Passage:"})
evaluation = mteb.MTEB(tasks=tasks)
In prompts the key can be:
- Prompt types (
passage
,query
) - they will be used in reranking and retrieval tasks - Task type - these prompts will be used in all tasks of the given type
BitextMining
Classification
MultilabelClassification
Clustering
PairClassification
Reranking
Retrieval
STS
Summarization
InstructionRetrieval
- Pair of task type and prompt type like
Retrival-query
- these prompts will be used in all classification tasks - Task name - these prompts will be used in the specific task
- Pair of task name and prompt type like
NFCorpus-query
- these prompts will be used in the specific task
- Using CLI
mteb available_tasks
mteb run -m sentence-transformers/all-MiniLM-L6-v2 \
-t Banking77Classification \
--verbosity 3
# if nothing is specified default to saving the results in the results/{model_name} folder
- Using multiple GPUs in parallel can be done by just having a custom encode function that distributes the inputs to multiple GPUs like e.g. here or here.
Usage Documentation
Click on each section below to see the details.
Task selection
Task selection
Tasks can be selected by providing the list of datasets, but also
- by their task (e.g. "Clustering" or "Classification")
tasks = mteb.get_tasks(task_types=["Clustering", "Retrieval"]) # Only select clustering and retrieval tasks
- by their categories e.g. "s2s" (sentence to sentence) or "p2p" (paragraph to paragraph)
tasks = mteb.get_tasks(categories=["s2s", "p2p"]) # Only select sentence2sentence and paragraph2paragraph datasets
- by their languages
tasks = mteb.get_tasks(languages=["eng", "deu"]) # Only select datasets which contain "eng" or "deu" (iso 639-3 codes)
You can also specify which languages to load for multilingual/cross-lingual tasks like below:
import mteb
tasks = [
mteb.get_task("AmazonReviewsClassification", languages = ["eng", "fra"]),
mteb.get_task("BUCCBitextMining", languages = ["deu"]), # all subsets containing "deu"
]
# or you can select specific huggingface subsets like this:
from mteb.tasks import AmazonReviewsClassification, BUCCBitextMining
evaluation = mteb.MTEB(tasks=[
AmazonReviewsClassification(hf_subsets=["en", "fr"]) # Only load "en" and "fr" subsets of Amazon Reviews
BUCCBitextMining(hf_subsets=["de-en"]), # Only load "de-en" subset of BUCC
])
# for an example of a HF subset see "Subset" in the dataset viewer at: https://huggingface.co/datasets/mteb/bucc-bitext-mining
Running a benchmark
Running a Benchmark
mteb
comes with a set of predefined benchmarks. These can be fetched using get_benchmark
and run in a similar fashion to other sets of tasks.
For instance to select the 56 English datasets that form the "Overall MTEB English leaderboard":
import mteb
benchmark = mteb.get_benchmark("MTEB(eng, classic)")
evaluation = mteb.MTEB(tasks=benchmark)
The benchmark specified not only a list of tasks, but also what splits and language to run on. To get an overview of all available benchmarks simply run:
import mteb
benchmarks = mteb.get_benchmarks()
Generally we use the naming scheme for benchmarks MTEB(*)
, where the "*" denotes the target of the benchmark. In the case of a language, we use the three-letter language code. For large groups of languages, we use the group notation, e.g., MTEB(Scandinavian)
for Scandinavian languages. External benchmarks implemented in MTEB like CoIR
use their original name. When using a benchmark from MTEB please cite mteb
along with the citations of the benchmark which you can access using:
benchmark.citation
Passing in `encode` arguments
Passing in encode
arguments
To pass in arguments to the model's encode
function, you can use the encode keyword arguments (encode_kwargs
):
evaluation.run(model, encode_kwargs={"batch_size": 32})
Selecting evaluation split
Selecting evaluation split
You can evaluate only on test
splits of all tasks by doing the following:
evaluation.run(model, eval_splits=["test"])
Note that the public leaderboard uses the test splits for all datasets except MSMARCO, where the "dev" split is used.
Using a custom model
Using a custom model
Models should implement the following interface, implementing an encode
function taking as inputs a list of sentences, and returning a list of embeddings (embeddings can be np.array
, torch.tensor
, etc.). For inspiration, you can look at the mteb/mtebscripts repo used for running diverse models via SLURM scripts for the paper.
from mteb.encoder_interface import PromptType
class CustomModel:
def encode(
self,
sentences: list[str],
task_name: str,
prompt_type: PromptType | None = None,
**kwargs,
) -> np.ndarray:
"""Encodes the given sentences using the encoder.
Args:
sentences: The sentences to encode.
task_name: The name of the task.
prompt_type: The prompt type to use.
**kwargs: Additional arguments to pass to the encoder.
Returns:
The encoded sentences.
"""
pass
model = CustomModel()
tasks = mteb.get_task("Banking77Classification")
evaluation = MTEB(tasks=tasks)
evaluation.run(model)
Evaluating on a custom dataset
Evaluating on a custom dataset
To evaluate on a custom task, you can run the following code on your custom task. See how to add a new task, for how to create a new task in MTEB.
from mteb import MTEB
from mteb.abstasks.AbsTaskReranking import AbsTaskReranking
from sentence_transformers import SentenceTransformer
class MyCustomTask(AbsTaskReranking):
...
model = SentenceTransformer("average_word_embeddings_komninos")
evaluation = MTEB(tasks=[MyCustomTask()])
evaluation.run(model)
Using a cross encoder for reranking
Using a cross encoder for reranking
To use a cross encoder for reranking, you can directly use a CrossEncoder from SentenceTransformers. The following code shows a two-stage run with the second stage reading results saved from the first stage.
from mteb import MTEB
import mteb
from sentence_transformers import CrossEncoder, SentenceTransformer
cross_encoder = CrossEncoder("cross-encoder/ms-marco-TinyBERT-L-2-v2")
dual_encoder = SentenceTransformer("all-MiniLM-L6-v2")
tasks = mteb.get_tasks(tasks=["NFCorpus"], languages=["eng"])
subset = "default" # subset name used in the NFCorpus dataset
eval_splits = ["test"]
evaluation = MTEB(tasks=tasks)
evaluation.run(
dual_encoder,
eval_splits=eval_splits,
save_predictions=True,
output_folder="results/stage1",
)
evaluation.run(
cross_encoder,
eval_splits=eval_splits,
top_k=5,
save_predictions=True,
output_folder="results/stage2",
previous_results=f"results/stage1/NFCorpus_{subset}_predictions.json",
)
Saving retrieval task predictions
Saving retrieval task predictions
To save the predictions from a retrieval task, add the --save_predictions
flag in the CLI or set save_predictions=True
in the run method. The filename will be in the "{task_name}_{subset}_predictions.json" format.
Python:
from mteb import MTEB
import mteb
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
tasks = mteb.get_tasks(tasks=["NFCorpus"], languages=["eng"])
evaluation = MTEB(tasks=tasks)
evaluation.run(
model,
eval_splits=["test"],
save_predictions=True,
output_folder="results",
)
CLI:
mteb run -t NFCorpus -m all-MiniLM-L6-v2 --output_folder results --save_predictions
Fetching result from the results repository
Fetching results from the results repository
Multiple models have already been run on tasks available within MTEB. These results are available results repository.
To make the results more easily accessible, we have designed custom functionality for retrieving from the repository. For instance, if you are selecting the best model for your French and English retrieval task on legal documents you could fetch the relevant tasks and create a dataframe of the results using the following code:
import mteb
from mteb.task_selection import results_to_dataframe
tasks = mteb.get_tasks(
task_types=["Retrieval"], languages=["eng", "fra"], domains=["Legal"]
)
model_names = [
"GritLM/GritLM-7B",
"intfloat/multilingual-e5-small",
"intfloat/multilingual-e5-base",
"intfloat/multilingual-e5-large",
]
models = [mteb.get_model_meta(name) for name in model_names]
results = mteb.load_results(models=models, tasks=tasks)
df = results_to_dataframe(results)
Caching Embeddings To Re-Use Them
Caching Embeddings To Re-Use Them
There are times you may want to cache the embeddings so you can re-use them. This may be true if you have multiple query sets for the same corpus (e.g. Wikipedia) or are doing some optimization over the queries (e.g. prompting, other experiments). You can setup a cache by using a simple wrapper, which will save the cache per task in the cache_embeddings/{task_name}
folder:
# define your task and model above as normal
...
# wrap the model with the cache wrapper
from mteb.models.cache_wrapper import CachedEmbeddingWrapper
model_with_cached_emb = CachedEmbeddingWrapper(model, cache_path='path_to_cache_dir')
# run as normal
evaluation.run(model, ...)
Documentation
Documentation | |
---|---|
📋 Tasks | Overview of available tasks |
📐 Benchmarks | Overview of available benchmarks |
📈 Leaderboard | The interactive leaderboard of the benchmark |
🤖 Adding a model | Information related to how to submit a model to the leaderboard |
👩🔬 Reproducible workflows | Information related to how to reproduce and create reproducible workflows with MTEB |
👩💻 Adding a dataset | How to add a new task/dataset to MTEB |
👩💻 Adding a leaderboard tab | How to add a new leaderboard tab to MTEB |
🤝 Contributing | How to contribute to MTEB and set it up for development |
🌐 MMTEB | An open-source effort to extend MTEB to cover a broad set of languages |
Citing
MTEB was introduced in "MTEB: Massive Text Embedding Benchmark", feel free to cite:
@article{muennighoff2022mteb,
doi = {10.48550/ARXIV.2210.07316},
url = {https://arxiv.org/abs/2210.07316},
author = {Muennighoff, Niklas and Tazi, Nouamane and Magne, Lo{\"\i}c and Reimers, Nils},
title = {MTEB: Massive Text Embedding Benchmark},
publisher = {arXiv},
journal={arXiv preprint arXiv:2210.07316},
year = {2022}
}
You may also want to read and cite the amazing work that has extended MTEB & integrated new datasets:
- Shitao Xiao, Zheng Liu, Peitian Zhang, Niklas Muennighoff. "C-Pack: Packaged Resources To Advance General Chinese Embedding" arXiv 2023
- Michael Günther, Jackmin Ong, Isabelle Mohr, Alaeddine Abdessalem, Tanguy Abel, Mohammad Kalim Akram, Susana Guzman, Georgios Mastrapas, Saba Sturua, Bo Wang, Maximilian Werk, Nan Wang, Han Xiao. "Jina Embeddings 2: 8192-Token General-Purpose Text Embeddings for Long Documents" arXiv 2023
- Silvan Wehrli, Bert Arnrich, Christopher Irrgang. "German Text Embedding Clustering Benchmark" arXiv 2024
- Orion Weller, Benjamin Chang, Sean MacAvaney, Kyle Lo, Arman Cohan, Benjamin Van Durme, Dawn Lawrie, Luca Soldaini. "FollowIR: Evaluating and Teaching Information Retrieval Models to Follow Instructions" arXiv 2024
- Dawei Zhu, Liang Wang, Nan Yang, Yifan Song, Wenhao Wu, Furu Wei, Sujian Li. "LongEmbed: Extending Embedding Models for Long Context Retrieval" arXiv 2024
- Kenneth Enevoldsen, Márton Kardos, Niklas Muennighoff, Kristoffer Laigaard Nielbo. "The Scandinavian Embedding Benchmarks: Comprehensive Assessment of Multilingual and Monolingual Text Embedding" arXiv 2024
For works that have used MTEB for benchmarking, you can find them on the leaderboard.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file mteb-1.19.8.tar.gz
.
File metadata
- Download URL: mteb-1.19.8.tar.gz
- Upload date:
- Size: 770.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2f45831f367e1383a81a108525c71f703b8b2cb8c6b7948d914b68bd240bd48d |
|
MD5 | 5a50773b486038c44bc63217dcad770d |
|
BLAKE2b-256 | c1c21e6da8732a5eb71107ded40cf02405f9707d165514a8189d3e5a614e422e |
Provenance
The following attestation bundles were made for mteb-1.19.8.tar.gz
:
Publisher:
release.yml
on embeddings-benchmark/mteb
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
mteb-1.19.8.tar.gz
- Subject digest:
2f45831f367e1383a81a108525c71f703b8b2cb8c6b7948d914b68bd240bd48d
- Sigstore transparency entry: 149075420
- Sigstore integration time:
- Predicate type:
File details
Details for the file mteb-1.19.8-py3-none-any.whl
.
File metadata
- Download URL: mteb-1.19.8-py3-none-any.whl
- Upload date:
- Size: 1.2 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9a449006f88d931f9271eafb2e23d518f9bf29be2880219a030a4557c1c788bd |
|
MD5 | aa22b23623585f2930313295e4463902 |
|
BLAKE2b-256 | dcd874dd17519d5e9597afb2bd3c719026508bd16a72adc36afdd2ebee9b5182 |
Provenance
The following attestation bundles were made for mteb-1.19.8-py3-none-any.whl
:
Publisher:
release.yml
on embeddings-benchmark/mteb
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
mteb-1.19.8-py3-none-any.whl
- Subject digest:
9a449006f88d931f9271eafb2e23d518f9bf29be2880219a030a4557c1c788bd
- Sigstore transparency entry: 149075422
- Sigstore integration time:
- Predicate type: