For more details please refer to our Github: FlagEmbedding.
BGE-Multilingual-Gemma2 is a LLM-based multilingual embedding model. It is trained on a diverse range of languages and tasks based on google/gemma-2-9b. BGE-Multilingual-Gemma2 primarily demonstrates the following advancements:
Diverse training data: The model's training data spans a broad range of languages, including English, Chinese, Japanese, Korean, French, and more.Additionally, the data covers a variety of task types, such as retrieval, classification, and clustering.
Outstanding performance: The model exhibits state-of-the-art (SOTA) results on multilingual benchmarks like MIRACL, MTEB-pl, and MTEB-fr. It also achieves excellent performance on other major evaluations, including MTEB, C-MTEB and AIR-Bench.
📑 Open-source Plan
Checkpoint
Training Data
The training data of BGE-Multilingual-Gemma2 is available at this link.
Usage
Using FlagEmbedding
git clone https://github.com/FlagOpen/FlagEmbedding.git
cd FlagEmbedding
pip install -e .
python
1from FlagEmbedding import FlagLLMModel
2queries =["how much protein should a female eat","summit define"]3documents =[4"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",5"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."6]7model = FlagLLMModel('BAAI/bge-multilingual-gemma2',8 query_instruction_for_retrieval="Given a web search query, retrieve relevant passages that answer the query.",9 use_fp16=True)# Setting use_fp16 to True speeds up computation with a slight performance degradation10embeddings_1 = model.encode_queries(queries)11embeddings_2 = model.encode_corpus(documents)12similarity = embeddings_1 @ embeddings_2.T
13print(similarity)14# [[ 0.559 0.01654 ]15# [-0.002575 0.4998 ]]
By default, FlagLLMModel 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.
Using Sentence Transformers
python
1from sentence_transformers import SentenceTransformer
2import torch
34# Load the model, optionally in float16 precision for faster inference5model = SentenceTransformer("BAAI/bge-multilingual-gemma2", model_kwargs={"torch_dtype": torch.float16})67# Prepare a prompt given an instruction8instruction ='Given a web search query, retrieve relevant passages that answer the query.'9prompt =f'<instruct>{instruction}\n<query>'10# Prepare queries and documents11queries =[12'how much protein should a female eat',13'summit define',14]15documents =[16"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",17"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."18]1920# Compute the query and document embeddings21query_embeddings = model.encode(queries, prompt=prompt)22document_embeddings = model.encode(documents)2324# Compute the cosine similarity between the query and document embeddings25similarities = model.similarity(query_embeddings, document_embeddings)26print(similarities)27# tensor([[ 0.5591, 0.0164],28# [-0.0026, 0.4993]], dtype=torch.float16)
Using HuggingFace Transformers
python
1import torch
2import torch.nn.functional as F
34from torch import Tensor
5from transformers import AutoTokenizer, AutoModel
678deflast_token_pool(last_hidden_states: Tensor,9 attention_mask: Tensor)-> Tensor:10 left_padding =(attention_mask[:,-1].sum()== attention_mask.shape[0])11if left_padding:12return last_hidden_states[:,-1]13else:14 sequence_lengths = attention_mask.sum(dim=1)-115 batch_size = last_hidden_states.shape[0]16return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]171819defget_detailed_instruct(task_description:str, query:str)->str:20returnf'<instruct>{task_description}\n<query>{query}'212223task ='Given a web search query, retrieve relevant passages that answer the query.'24queries =[25 get_detailed_instruct(task,'how much protein should a female eat'),26 get_detailed_instruct(task,'summit define')27]28# No need to add instructions for documents29documents =[30"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",31"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."32]33input_texts = queries + documents
3435tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-multilingual-gemma2')36model = AutoModel.from_pretrained('BAAI/bge-multilingual-gemma2')37model.eval()3839max_length =409640# Tokenize the input texts41batch_dict = tokenizer(input_texts, max_length=max_length, padding=True, truncation=True, return_tensors='pt', pad_to_multiple_of=8)4243with torch.no_grad():44 outputs = model(**batch_dict)45 embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])4647# normalize embeddings48embeddings = F.normalize(embeddings, p=2, dim=1)49scores =(embeddings[:2] @ embeddings[2:].T)*10050print(scores.tolist())51# [[55.92064666748047, 1.6549524068832397], [-0.2698777914047241, 49.95653533935547]]
Evaluation
bge-multilingual-gemma2 exhibits state-of-the-art (SOTA) results on benchmarks like MIRACL, MTEB-pl, and MTEB-fr. It also achieves excellent performance on other major evaluations, including MTEB, C-MTEB and AIR-Bench.
a small-scale model but with competitive performance
为这个句子生成表示以用于检索相关文章:
Citation
If you find this repository useful, please consider giving a star :star: and citation
@misc{bge-m3,
title={BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation},
author={Jianlv Chen and Shitao Xiao and Peitian Zhang and Kun Luo and Defu Lian and Zheng Liu},
year={2024},
eprint={2402.03216},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
@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}
}