Bge Code V1
BGE-Code-v1是一个基于LLM的代码嵌入模型,支持代码检索、文本检索和多语言检索,在代码检索和文本检索任务中表现出色。
下载量 103
发布时间 : 5/15/2025
模型简介
BGE-Code-v1是一个多功能代码嵌入模型,主要用于代码检索、文本检索和多语言检索任务。它支持中英文自然语言查询和20种编程语言,在多个基准测试中达到了最先进的性能。
模型特点
卓越的代码检索性能
支持中英文自然语言查询和20种编程语言,在代码检索任务中表现优异
强大的文本检索能力
保持与同类规模文本嵌入模型相当的强大文本检索能力
广泛的多语言支持
在英语、中文、日语、法语等多种语言上表现优异
高效推理
支持FP16加速计算,提高推理效率
模型能力
代码检索
文本检索
多语言检索
SQL查询生成
代码文档生成
代码相似性比较
使用案例
代码开发
代码搜索
根据自然语言描述搜索相关代码片段
在CoIR基准测试中达到98.08%的准确率
SQL查询生成
根据文本问题生成相应的SQL查询
在Text2SQL任务中达到64.35%的准确率
文档生成
代码文档生成
根据代码片段生成相应的文档字符串
在CSN任务中达到89.53%的准确率
🚀 FlagEmbedding
FlagEmbedding 是一个强大的代码嵌入模型,支持代码检索、文本检索和多语言检索。它能够处理多种自然语言查询和不同编程语言的代码,为开发者提供高效的代码匹配和检索功能。
🚀 快速开始
克隆仓库并安装依赖
git clone https://github.com/FlagOpen/FlagEmbedding.git
cd FlagEmbedding
pip install -e .
使用示例
基础用法
from FlagEmbedding import FlagLLMModel
queries = [
"Delete the record with ID 4 from the 'Staff' table.",
'Delete all records in the "Livestock" table where age is greater than 5'
]
documents = [
"DELETE FROM Staff WHERE StaffID = 4;",
"DELETE FROM Livestock WHERE age > 5;"
]
model = FlagLLMModel('BAAI/bge-code-v1',
query_instruction_format="<instruct>{}\n<query>{}",
query_instruction_for_retrieval="Given a question in text, retrieve SQL queries that are appropriate responses to the question.",
trust_remote_code=True,
use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation
embeddings_1 = model.encode_queries(queries)
embeddings_2 = model.encode_corpus(documents)
similarity = embeddings_1 @ embeddings_2.T
print(similarity)
注意:默认情况下,FlagLLMModel
在编码时将使用所有可用的 GPU。你可以设置 os.environ["CUDA_VISIBLE_DEVICES"]
来选择特定的 GPU,也可以设置 os.environ["CUDA_VISIBLE_DEVICES"]=""
使所有 GPU 不可用。
高级用法
使用 Sentence Transformers
from sentence_transformers import SentenceTransformer
import torch
# Load the model, optionally in float16 precision for faster inference
model = SentenceTransformer(
"BAAI/bge-code-v1",
trust_remote_code=True,
model_kwargs={"torch_dtype": torch.float16},
)
# Prepare a prompt given an instruction
instruction = 'Given a question in text, retrieve SQL queries that are appropriate responses to the question.'
prompt = f'<instruct>{instruction}\n<query>'
# Prepare queries and documents
queries = [
"Delete the record with ID 4 from the 'Staff' table.",
'Delete all records in the "Livestock" table where age is greater than 5'
]
documents = [
"DELETE FROM Staff WHERE StaffID = 4;",
"DELETE FROM Livestock WHERE age > 5;"
]
# Compute the query and document embeddings
query_embeddings = model.encode(queries, prompt=prompt)
document_embeddings = model.encode(documents)
# Compute the cosine similarity between the query and document embeddings
similarities = model.similarity(query_embeddings, document_embeddings)
print(similarities)
使用 HuggingFace Transformers
import torch
import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
def last_token_pool(last_hidden_states: Tensor,
attention_mask: Tensor) -> Tensor:
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
if left_padding:
return last_hidden_states[:, -1]
else:
sequence_lengths = attention_mask.sum(dim=1) - 1
batch_size = last_hidden_states.shape[0]
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
def get_detailed_instruct(task_description: str, query: str) -> str:
return f'<instruct>{task_description}\n<query>{query}'
instruction = 'Given a question in text, retrieve SQL queries that are appropriate responses to the question.'
queries = [
"Delete the record with ID 4 from the 'Staff' table.",
'Delete all records in the "Livestock" table where age is greater than 5'
]
documents = [
"DELETE FROM Staff WHERE StaffID = 4;",
"DELETE FROM Livestock WHERE age > 5;"
]
input_texts = queries + documents
tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-code-v1', trust_remote_code=True)
model = AutoModel.from_pretrained('BAAI/bge-code-v1', trust_remote_code=True)
model.eval()
max_length = 4096
# Tokenize the input texts
batch_dict = tokenizer(input_texts, max_length=max_length, padding=True, truncation=True, return_tensors='pt', pad_to_multiple_of=8)
with torch.no_grad():
outputs = model(**batch_dict)
embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
# normalize embeddings
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T) * 100
print(scores.tolist())
✨ 主要特性
- 卓越的代码检索性能:该模型具备出色的代码检索能力,支持英语和中文的自然语言查询,以及 20 种编程语言。
- 强大的文本检索能力:与同规模的文本嵌入模型相比,该模型保持了较强的文本检索能力。
- 广泛的多语言支持:
BGE-Code-v1
提供全面的多语言检索功能,在英语、中文、日语、法语等多种语言中表现出色。
📚 详细文档
评估
BGE-Code-v1 在 CoIR 和 CodeRAG 基准测试中均达到了最先进的性能。
CoIR 评估结果
CodeXEmbed-2B | CodeXEmbed-7B | Voyage-Code-002 | Voyage-Code-003 | BGE-Code-v1 | |
---|---|---|---|---|---|
Apps | 76.86 | 85.38 | 26.52 | 93.62 | 98.08 |
CosQA | 40.47 | 42.47 | 29.79 | 34.45 | 46.72 |
Text2SQL | 78.42 | 78.94 | 69.26 | 62.87 | 64.35 |
CSN | 87.87 | 89.67 | 81.79 | 89.35 | 89.53 |
CSN-CCR | 97.66 | 97.95 | 73.45 | 90.05 | 98.30 |
CodeTrans-Contest | 90.30 | 94.45 | 72.77 | 94.96 | 94.38 |
CodeTrans-DL | 38.57 | 40.46 | 27.48 | 38.57 | 46.13 |
StackOverFlow-QA | 94.47 | 96.33 | 67.68 | 97.17 | 95.35 |
CodeFeedBack-ST | 86.36 | 87.53 | 65.35 | 90.67 | 90.56 |
CodeFeedBack-MT | 65.51 | 68.83 | 28.74 | 93.58 | 94.38 |
AVG | 75.65 | 78.20 | 56.26 | 78.53 | 81.77 |
CodedRAG 评估结果
HummanEval | MBPP | DS-1000 | ODEX | RepoEval | SWE-bench-Lite | AVG | |
---|---|---|---|---|---|---|---|
SFR | 100.0 | 99.0 | 19.3 | 37.1 | 83.8 | 62.7 | 67.0 |
Jina-v2-code | 100.0 | 97.7 | 26.2 | 19.9 | 90.5 | 58.3 | 65.4 |
CodeXEmbed-2B | 100.0 | 97.4 | 25.4 | 23.9 | 88.7 | 52.4 | 64.6 |
Voyage-Code-002 | 100.0 | 99.0 | 33.1 | 26.6 | 94.3 | 29.1 | 63.7 |
BGE-Code-v1 | 100.0 | 99.2 | 40.9 | 36.1 | 93.1 | 67.4 | 72.8 |
评估说明
{
"Apps": "Given a code contest problem description, retrieve relevant code that can help solve the problem.",
"CosQA": "Given a web search query, retrieve relevant code that can help answer the query.",
"Text2SQL": "Given a question in text, retrieve SQL queries that are appropriate responses to the question.",
"CSN": "Given a piece of code, retrieve the document string that summarizes the code.",
"CSN-CCR": "Given a piece of code segment, retrieve the code segment that is the latter part of the code.",
"CodeTrans-DL": "Given a piece of code, retrieve code that is semantically equivalent to the input code.",
"CodeTrans-Contest": "Given a piece of Python code, retrieve C++ code that is semantically equivalent to the input code.",
"StackOverFlow-QA": "Given a question that consists of a mix of text and code snippets, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"CodeFeedBack-ST": "Given a question that consists of a mix of text and code snippets, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"CodeFeedBack-MT": "Given a multi-turn conversation history that consists of a mix of text and code snippets, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"HummanEval": "Given a question that consists of a mix of text and code snippets, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"MBPP": "Given a textual explanation of code functionality, retrieve the corresponding code implementation.",
"DS-1000": "Given a question that consists of a mix of text and code snippets, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"ODEX": "Given a question, retrieve relevant answers that also consist of a mix of text and code snippets, and can help answer the question.",
"RepoEval": "Given a piece of code segment, retrieve the code segment that is the latter part of the code.",
"SWE-bench-Lite": "Given a code snippet containing a bug and a natural language description of the bug or error, retrieve code snippets that demonstrate solutions or fixes for similar bugs or errors (the desired documents)."
}
引用
如果你觉得这个仓库有用,请考虑给它加星 :star: 并引用以下文献:
@article{bge-llm,
title={Making text embedders few-shot learners},
author={Li, Chaofan and Qin, MingHao and Xiao, Shitao and Chen, Jianlyu and Luo, Kun and Shao, Yingxia and Lian, Defu and Liu, Zheng},
journal={arXiv preprint arXiv:2409.15700},
year={2024}
}
@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}
}
📄 许可证
本项目采用 apache-2.0
许可证。
Jina Embeddings V3
Jina Embeddings V3 是一个多语言句子嵌入模型,支持超过100种语言,专注于句子相似度和特征提取任务。
文本嵌入
Transformers 支持多种语言

J
jinaai
3.7M
911
Ms Marco MiniLM L6 V2
Apache-2.0
基于MS Marco段落排序任务训练的交叉编码器模型,用于信息检索中的查询-段落相关性评分
文本嵌入 英语
M
cross-encoder
2.5M
86
Opensearch Neural Sparse Encoding Doc V2 Distill
Apache-2.0
基于蒸馏技术的稀疏检索模型,专为OpenSearch优化,支持免推理文档编码,在搜索相关性和效率上优于V1版本
文本嵌入
Transformers 英语

O
opensearch-project
1.8M
7
Sapbert From PubMedBERT Fulltext
Apache-2.0
基于PubMedBERT的生物医学实体表征模型,通过自对齐预训练优化语义关系捕捉
文本嵌入 英语
S
cambridgeltl
1.7M
49
Gte Large
MIT
GTE-Large 是一个强大的句子转换器模型,专注于句子相似度和文本嵌入任务,在多个基准测试中表现出色。
文本嵌入 英语
G
thenlper
1.5M
278
Gte Base En V1.5
Apache-2.0
GTE-base-en-v1.5 是一个英文句子转换器模型,专注于句子相似度任务,在多个文本嵌入基准测试中表现优异。
文本嵌入
Transformers 支持多种语言

G
Alibaba-NLP
1.5M
63
Gte Multilingual Base
Apache-2.0
GTE Multilingual Base 是一个多语言的句子嵌入模型,支持超过50种语言,适用于句子相似度计算等任务。
文本嵌入
Transformers 支持多种语言

G
Alibaba-NLP
1.2M
246
Polybert
polyBERT是一个化学语言模型,旨在实现完全由机器驱动的超快聚合物信息学。它将PSMILES字符串映射为600维密集指纹,以数值形式表示聚合物化学结构。
文本嵌入
Transformers

P
kuelumbus
1.0M
5
Bert Base Turkish Cased Mean Nli Stsb Tr
Apache-2.0
基于土耳其语BERT的句子嵌入模型,专为语义相似度任务优化
文本嵌入
Transformers 其他

B
emrecan
1.0M
40
GIST Small Embedding V0
MIT
基于BAAI/bge-small-en-v1.5模型微调的文本嵌入模型,通过MEDI数据集与MTEB分类任务数据集训练,优化了检索任务的查询编码能力。
文本嵌入
Safetensors 英语
G
avsolatorio
945.68k
29
精选推荐AI模型
Llama 3 Typhoon V1.5x 8b Instruct
专为泰语设计的80亿参数指令模型,性能媲美GPT-3.5-turbo,优化了应用场景、检索增强生成、受限生成和推理任务
大型语言模型
Transformers 支持多种语言

L
scb10x
3,269
16
Cadet Tiny
Openrail
Cadet-Tiny是一个基于SODA数据集训练的超小型对话模型,专为边缘设备推理设计,体积仅为Cosmo-3B模型的2%左右。
对话系统
Transformers 英语

C
ToddGoldfarb
2,691
6
Roberta Base Chinese Extractive Qa
基于RoBERTa架构的中文抽取式问答模型,适用于从给定文本中提取答案的任务。
问答系统 中文
R
uer
2,694
98