Hiring:
We're seeking experienced NLP researchers and intern students focusing on dense retrieval and retrieval-augmented LLMs. If you're interested, please feel free to reach out to us via email at
[email protected]
.
FlagEmbedding can map any text to a low-dimensional dense vector, which can be used for tasks like retrieval, classification, clustering, and semantic search.
And it can also be used in vector databases for LLMs.
************* 🌟
Updates
🌟 *************
10/12/2023: Release
LLM-Embedder
, a unified embedding model to support diverse retrieval augmentation needs for LLMs.
Paper
:fire:
New reranker model
: release cross-encoder models
BAAI/bge-reranker-base
and
BAAI/bge-reranker-large
, which are more powerful than embedding model. We recommend to use/fine-tune them to re-rank top-k documents returned by embedding models.
update embedding model
: release
bge-*-v1.5
embedding model to alleviate the issue of the similarity distribution, and enhance its retrieval ability without instruction.
More
09/07/2023: Update
fine-tune code
: Add script to mine hard negatives and support adding instruction during fine-tuning.
08/09/2023: BGE Models are integrated into
Langchain
, you can use it like
this
; C-MTEB
leaderboard
is
available
.
08/05/2023: Release base-scale and small-scale models,
best performance among the models of the same size 🤗
08/02/2023: Release
bge-large-*
(short for BAAI General Embedding) Models,
rank 1st on MTEB and C-MTEB benchmark!
:tada: :tada:
a small-scale model but with competitive performance
为这个句子生成表示以用于检索相关文章:
[1]: If you need to search the relevant passages in a query, we suggest to add the instruction to the query; in other cases, no instruction is needed, just use the original query directly. In all cases,
no instruction
needs to be added to passages.
[2]: Different from the embedding model, reranker uses question and document as input and directly output similarity instead of embedding. To balance the accuracy and time cost, cross-encoder is widely used to re-rank top-k documents retrieved by other simple models.
For example, use bge embedding model to retrieve top 100 relevant documents, and then use bge reranker to re-rank the top 100 documents to get the final top-3 results.
Following this
example
to prepare data and fine-tune your model.
Some suggestions:
Mine hard negatives following this
example
, which can improve the retrieval performance.
In general, larger hyper-parameter
per_device_train_batch_size
brings better performance. You can expand it by enabling
--fp16
,
--deepspeed df_config.json
(df_config.json can refer to
ds_config.json
,
--gradient_checkpointing
, etc.
If you pre-train bge on your data, the pre-trained model cannot be directly used to calculate similarity, and it must be fine-tuned with contrastive learning before computing similarity.
If the accuracy of the fine-tuned model is still not high, it is recommended to use/fine-tune the cross-encoder model (bge-reranker) to re-rank top-k results. Hard negatives also are needed to fine-tune reranker.
2. The similarity score between two dissimilar sentences is higher than 0.5
Suggest to use bge v1.5, which alleviates the issue of the similarity distribution.
Since we finetune the models by contrastive learning with a temperature of 0.01,
the similarity distribution of the current BGE model is about in the interval [0.6, 1].
So a similarity score greater than 0.5 does not indicate that the two sentences are similar.
For downstream tasks, such as passage retrieval or semantic similarity,
what matters is the relative order of the scores, not the absolute value.
If you need to filter similar sentences based on a similarity threshold,
please select an appropriate similarity threshold based on the similarity distribution on your data (such as 0.8, 0.85, or even 0.9).
3. When does the query instruction need to be used
For the
bge-*-v1.5
, we improve its retrieval ability when not using instruction.
No instruction only has a slight degradation in retrieval performance compared with using instruction.
So you can generate embedding without instruction in all cases for convenience.
For a retrieval task that uses short queries to find long related documents,
it is recommended to add instructions for these short queries.
The best method to decide whether to add instructions for queries is choosing the setting that achieves better performance on your task.
In all cases, the documents/passages do not need to add the instruction.
If it doesn't work for you, you can see
FlagEmbedding
for more methods to install FlagEmbedding.
from FlagEmbedding import FlagModel
sentences_1 = ["样例数据-1", "样例数据-2"]
sentences_2 = ["样例数据-3", "样例数据-4"]
model = FlagModel('BAAI/bge-large-zh-v1.5',
query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation
embeddings_1 = model.encode(sentences_1)
embeddings_2 = model.encode(sentences_2)
similarity = embeddings_1 @ embeddings_2.T
print(similarity)
# for s2p(short query to long passage) retrieval task, suggest to use encode_queries() which will automatically add the instruction to each query# corpus in retrieval task can still use encode() or encode_corpus(), since they don't need instruction
queries = ['query_1', 'query_2']
passages = ["样例文档-1", "样例文档-2"]
q_embeddings = model.encode_queries(queries)
p_embeddings = model.encode(passages)
scores = q_embeddings @ p_embeddings.T
For the value of the argument
query_instruction_for_retrieval
, see
Model List
.
By default, FlagModel will use all available GPUs when encoding. Please set
os.environ["CUDA_VISIBLE_DEVICES"]
to select specific GPUs.
You also can set
os.environ["CUDA_VISIBLE_DEVICES"]=""
to make all GPUs unavailable.
For s2p(short query to long passage) retrieval task,
each short query should start with an instruction (instructions see
Model List
).
But the instruction is not needed for passages.
from sentence_transformers import SentenceTransformer
queries = ['query_1', 'query_2']
passages = ["样例文档-1", "样例文档-2"]
instruction = "为这个句子生成表示以用于检索相关文章:"
model = SentenceTransformer('BAAI/bge-large-zh-v1.5')
q_embeddings = model.encode([instruction+q for q in queries], normalize_embeddings=True)
p_embeddings = model.encode(passages, normalize_embeddings=True)
scores = q_embeddings @ p_embeddings.T
Using Langchain
You can use
bge
in langchain like this:
from langchain.embeddings import HuggingFaceBgeEmbeddings
model_name = "BAAI/bge-large-en-v1.5"
model_kwargs = {'device': 'cuda'}
encode_kwargs = {'normalize_embeddings': True} # set True to compute cosine similarity
model = HuggingFaceBgeEmbeddings(
model_name=model_name,
model_kwargs=model_kwargs,
encode_kwargs=encode_kwargs,
query_instruction="为这个句子生成表示以用于检索相关文章:"
)
model.query_instruction = "为这个句子生成表示以用于检索相关文章:"
Using HuggingFace Transformers
With the transformers package, you can use the model like this: First, you pass your input through the transformer model, then you select the last hidden state of the first token (i.e., [CLS]) as the sentence embedding.
from transformers import AutoTokenizer, AutoModel
import torch
# Sentences we want sentence embeddings for
sentences = ["样例数据-1", "样例数据-2"]
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-large-zh-v1.5')
model = AutoModel.from_pretrained('BAAI/bge-large-zh-v1.5')
model.eval()
# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)# encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')# Compute token embeddingswith torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling. In this case, cls pooling.
sentence_embeddings = model_output[0][:, 0]
# normalize embeddings
sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:", sentence_embeddings)
Usage for Reranker
Different from embedding model, reranker uses question and document as input and directly output similarity instead of embedding.
You can get a relevance score by inputting query and passage to the reranker.
The reranker is optimized based cross-entropy loss, so the relevance score is not bounded to a specific range.
Using FlagEmbedding
pip install -U FlagEmbedding
Get relevance scores (higher scores indicate more relevance):
from FlagEmbedding import FlagReranker
reranker = FlagReranker('BAAI/bge-reranker-large', use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation
score = reranker.compute_score(['query', 'passage'])
print(score)
scores = reranker.compute_score([['what is panda?', 'hi'], ['what is panda?', 'The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.']])
print(scores)
Using Huggingface transformers
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-reranker-large')
model = AutoModelForSequenceClassification.from_pretrained('BAAI/bge-reranker-large')
model.eval()
pairs = [['what is panda?', 'hi'], ['what is panda?', 'The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.']]
with torch.no_grad():
inputs = tokenizer(pairs, padding=True, truncation=True, return_tensors='pt', max_length=512)
scores = model(**inputs, return_dict=True).logits.view(-1, ).float()
print(scores)
Evaluation
baai-general-embedding
models achieve
state-of-the-art performance on both MTEB and C-MTEB leaderboard!
For more details and evaluation tools see our
scripts
.
C-MTEB
:
We create the benchmark C-MTEB for Chinese text embedding which consists of 31 datasets from 6 tasks.
Please refer to
C_MTEB
for a detailed introduction.
* : T2RerankingZh2En and T2RerankingEn2Zh are cross-language retrieval tasks
Train
BAAI Embedding
We pre-train the models using
retromae
and train them on large-scale pair data using contrastive learning.
You can fine-tune the embedding model on your data following our
examples
.
We also provide a
pre-train example
.
Note that the goal of pre-training is to reconstruct the text, and the pre-trained model cannot be used for similarity calculation directly, it needs to be fine-tuned.
For more training details for bge see
baai_general_embedding
.
BGE Reranker
Cross-encoder will perform full-attention over the input pair,
which is more accurate than embedding model (i.e., bi-encoder) but more time-consuming than embedding model.
Therefore, it can be used to re-rank the top-k documents returned by embedding model.
We train the cross-encoder on a multilingual pair data,
The data format is the same as embedding model, so you can fine-tune it easily following our
example
.
For more details please refer to
./FlagEmbedding/reranker/README.md
Our Contributors:
Contact
If you have any question or suggestion related to this project, feel free to open an issue or pull request.
You also can email Shitao Xiao(
[email protected]
) and Zheng Liu(
[email protected]
).
Citation
If you find this repository useful, please consider giving a star :star: and citation
@misc{bge_embedding,
title={C-Pack: Packaged Resources To Advance General Chinese Embedding},
author={Shitao Xiao and Zheng Liu and Peitian Zhang and Niklas Muennighoff},
year={2023},
eprint={2309.07597},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
@misc{llm_embedder,
title={Retrieve Anything To Augment Large Language Models},
author={Peitian Zhang and Shitao Xiao and Zheng Liu and Zhicheng Dou and Jian-Yun Nie},
year={2023},
eprint={2310.07554},
archivePrefix={arXiv},
primaryClass={cs.IR}
}
License
FlagEmbedding is licensed under the
MIT License
. The released models can be used for commercial purposes free of charge.
Runs of BAAI llm-embedder on huggingface.co
220.4K
Total runs
11.4K
24-hour runs
25.8K
3-day runs
75.6K
7-day runs
-234.0K
30-day runs
More Information About llm-embedder huggingface.co Model
llm-embedder huggingface.co is an AI model on huggingface.co that provides llm-embedder's model effect (), which can be used instantly with this BAAI llm-embedder model. huggingface.co supports a free trial of the llm-embedder model, and also provides paid use of the llm-embedder. Support call llm-embedder model through api, including Node.js, Python, http.
llm-embedder huggingface.co is an online trial and call api platform, which integrates llm-embedder's modeling effects, including api services, and provides a free online trial of llm-embedder, you can try llm-embedder online for free by clicking the link below.
BAAI llm-embedder online free url in huggingface.co:
llm-embedder is an open source model from GitHub that offers a free installation service, and any user can find llm-embedder on GitHub to install. At the same time, huggingface.co provides the effect of llm-embedder install, users can directly use llm-embedder installed effect in huggingface.co for debugging and trial. It also supports api for free installation.