FlagEmbedding can map any text to a low-dimensional dense vector which can be used for tasks like retrieval, classification, clustering, or semantic search.
And it also can be used in vector database for LLMs.
************* 🌟Updates🌟 *************
08/09/2023: BGE Models are integrated into Langchain, you can use it like this; C-MTEB leaderboard is avaliable.
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!
a small-scale model but with competitive performance
为这个句子生成表示以用于检索相关文章:
*: If you need to search the long relevant passages to a short query (s2p retrieval task), you need 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 need to be added to passages.
If it doesn't work for you, you can see FlagEmbedding for more methods to install FlagEmbedding.
python
1from FlagEmbedding import FlagModel
2sentences =["样例数据-1","样例数据-2"]3model = FlagModel('BAAI/bge-large-zh', query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:")4embeddings_1 = model.encode(sentences)5embeddings_2 = model.encode(sentences)6similarity = embeddings_1 @ embeddings_2.T
7print(similarity)89# for s2p(short query to long passage) retrieval task, please use encode_queries() which will automatically add the instruction to each query10# corpus in retrieval task can still use encode() or encode_corpus(), since they don't need instruction11queries =['query_1','query_2']12passages =["样例文档-1","样例文档-2"]13q_embeddings = model.encode_queries(queries)14p_embeddings = model.encode(passages)15scores = q_embeddings @ p_embeddings.T
The value of argument query_instruction_for_retrieval see Model List.
FlagModel will use all available GPUs when encoding, please set os.environ["CUDA_VISIBLE_DEVICES"] to choose GPU.
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.
1from langchain.embeddings import HuggingFaceBgeEmbeddings
2model_name ="BAAI/bge-small-en"3model_kwargs ={'device':'cuda'}4encode_kwargs ={'normalize_embeddings':True}# set True to compute cosine similarity5model_norm = HuggingFaceBgeEmbeddings(6 model_name=model_name,7 model_kwargs=model_kwargs,8 encode_kwargs=encode_kwargs
9)
Using HuggingFace Transformers
With 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 first token (i.e., [CLS]) as the sentence embedding.
python
1from transformers import AutoTokenizer, AutoModel
2import torch
3# Sentences we want sentence embeddings for4sentences =["样例数据-1","样例数据-2"]56# Load model from HuggingFace Hub7tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-large-zh')8model = AutoModel.from_pretrained('BAAI/bge-large-zh')910# Tokenize sentences11encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')12# for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)13# encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')1415# Compute token embeddings16with torch.no_grad():17 model_output = model(**encoded_input)18# Perform pooling. In this case, cls pooling.19 sentence_embeddings = model_output[0][:,0]20# normalize embeddings21sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)22print("Sentence embeddings:", sentence_embeddings)
Evaluation
baai-general-embedding models achieve state-of-the-art performance on both MTEB and C-MTEB leaderboard!
More details and evaluation tools see our scripts.
C-MTEB:
We create a benchmark C-MTEB for chinese text embedding which consists of 31 datasets from 6 tasks.
Please refer to C_MTEB for a detailed introduction.
This section will introduce the way we used to train the general embedding.
The training scripts are in FlagEmbedding,
and we provide some examples to do pre-train and fine-tune.
1. RetroMAE Pre-train
We pre-train the model following the method retromae,
which shows promising improvement in retrieval task (paper).
The pre-training was conducted on 24 A100(40G) GPUs with a batch size of 720.
In retromae, the mask ratio of encoder and decoder are 0.3, 0.5 respectively.
We used the AdamW optimizer and the learning rate is 2e-5.
2. Finetune
We fine-tune the model using a contrastive objective.
The format of input data is a triple(query, positive, negative).
Besides the negative in the triple, we also adopt in-batch negatives strategy.
We employ the cross-device negatives sharing method to share negatives among different GPUs,
which can dramatically increase the number of negatives.
We trained our model on 48 A100(40G) GPUs with a large batch size of 32,768 (so there are 65,535 negatives for each query in a batch).
We used the AdamW optimizer and the learning rate is 1e-5.
The temperature for contrastive loss is 0.01.
Besides, we add instruction to the query for s2p(short query to long passage) retrieval task in the training (add nothing to passages).
For English, the instruction is Represent this sentence for searching relevant passages: ;
For Chinese, the instruction is 为这个句子生成表示以用于检索相关文章:.
In the evaluation, the instruction should be added for queries in retrieval task, not be added for other tasks.
Noted that the instruction is not needed for passages.
The finetune script is accessible in this repository: FlagEmbedding.
You can easily finetune your model with it.
Training data:
For English, we collect 230M text pairs from wikipedia, cc-net, and so on.
For chinese, we collect 120M text pairs from wudao, simclue and so on.
The data collection is to be released in the future.
We will continually update the embedding models and training codes,
hoping to promote the development of the embedding model community.
License
FlagEmbedding is licensed under MIT License. The released models can be used for commercial purposes free of charge.