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 databases for LLMs.
************* 🌟Updates🌟 *************
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:
See FlagEmbedding for more methods to install FlagEmbedding.
python
1from FlagEmbedding import FlagModel
2sentences =["样例数据-1","样例数据-2"]3model = FlagModel('Supabase/bge-small-en', query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:")4embeddings = model.encode(sentences)5print(embeddings)67# for retrieval task, please use encode_queries() which will automatically add the instruction to each query8# corpus in retrieval task can still use encode() or encode_corpus()9queries =['query_1','query_2']10passages =["样例段落-1","样例段落-2"]11q_embeddings = model.encode_queries(queries)12p_embeddings = model.encode(passages)13scores = 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.
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('Supabase/bge-small-en')8model = AutoModel.from_pretrained('Supabase/bge-small-en')910# Tokenize sentences11encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')12# for retrieval task, add an instruction to query13# 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)
1import{ pipeline }from'@xenova/transformers';2const pipe =awaitpipeline(3'feature-extraction',4'Supabase/bge-small-en',5);6// Generate the embedding from text7const output =awaitpipe('Hello world',{8pooling:'mean',9normalize:true,10});11// Extract the embedding output12const embedding =Array.from(output.data);13console.log(embedding);
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, and 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.
For the version with *-instrcution, we add instruction to the query for retrieval task in the training.
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 sentence to passages retrieval task, not be added for other tasks.
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.