/ Модель

Характеристики

Контекст
32 768 токенов
Параметры
1,5 млрд
Размер весов
6,2 ГБ
Лицензия
Apache 2.0
Архитектура
qwen2 · dense
Библиотека
sentence-transformers
Опубликована
15 мая 2025

bge-code-v1

ЭмбеддингиТекст → embedding11 профессий

Модель BGE-Code-v1 создаёт эмбеддинги кода и текста для поиска по коду, документам и мультиязычным запросам.

3 755скачиваний за 30 дней54лайкавеса обновлены20 мая 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Эмбеддинги» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

BGE-Code-v1 — модель для создания векторных представлений кода и текста, разработанная командой BAAI и опубликованная в проекте FlagEmbedding. Она предназначена для поиска кода по запросам на естественном языке, поиска текстовых документов и мультиязычного семантического поиска.

Модель основана на архитектуре Qwen2, содержит 1,5 млрд параметров и поддерживает контекст до 32 768 токенов. Она рассчитана на запросы на английском и китайском языках, охватывает 20 языков программирования и также поддерживает поиск на других естественных языках, включая японский и французский. README сообщает о высоких результатах на бенчмарках CoIR и CodeRAG.

Модель выдаёт эмбеддинги для последующего поиска и сравнения сходства; метаданные также указывают поддержку чат-возможностей и интерфейса вызова инструментов. Для работы нужны совместимые библиотеки, а примеры использования ориентированы на FlagEmbedding, Sentence Transformers и Transformers. Репозиторий распространяется под лицензией Apache-2.0.

Сценарии применения

  • поиск фрагментов кода по запросу на естественном языке
  • поиск похожих функций и классов в репозитории
  • подбор документации и текстов по смыслу
  • мультиязычный поиск по коду и документам
  • извлечение контекста из кодовой базы для Code RAG

Ограничения

Показатели в README приведены на отдельных бенчмарках и не гарантируют аналогичное качество на произвольных данных. Для эффективного кодирования FlagEmbedding по умолчанию использует доступные GPU, поэтому ресурсоёмкость может быть существенной.

Для каких профессий подходит11

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

For more details please refer to our Github: FlagEmbedding.

BGE-Code-v1 is an LLM-based code embedding model that supports code retrieval, text retrieval, and multilingual retrieval. It primarily demonstrates the following capabilities:

  • Superior Code Retrieval Performance: The model demonstrates exceptional code retrieval capabilities, supporting natural language queries in both English and Chinese, as well as 20 programming languages.
  • Robust Text Retrieval Capabilities: The model maintains strong text retrieval capabilities comparable to text embedding models of similar scale.
  • Extensive Multilingual Support: BGE-Code-v1 offers comprehensive multilingual retrieval capabilities, excelling in languages such as English, Chinese, Japanese, French, and more.

Usage

Using 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)

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

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)

Using 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())

Evaluation

BGE-Code-v1 achieves state-of-the-art performance on both the CoIR and CodeRAG benchmarks.

  • CoIR
CodeXEmbed-2BCodeXEmbed-7BVoyage-Code-002Voyage-Code-003BGE-Code-v1
Apps76.8685.3826.5293.6298.08
CosQA40.4742.4729.7934.4546.72
Text2SQL78.4278.9469.2662.8764.35
CSN87.8789.6781.7989.3589.53
CSN-CCR97.6697.9573.4590.0598.30
CodeTrans-Contest90.3094.4572.7794.9694.38
CodeTrans-DL38.5740.4627.4838.5746.13
StackOverFlow-QA94.4796.3367.6897.1795.35
CodeFeedBack-ST86.3687.5365.3590.6790.56
CodeFeedBack-MT65.5168.8328.7493.5894.38
AVG75.6578.2056.2678.5381.77
  • CodedRAG
HummanEvalMBPPDS-1000ODEXRepoEvalSWE-bench-LiteAVG
SFR100.099.019.337.183.862.767.0
Jina-v2-code100.097.726.219.990.558.365.4
CodeXEmbed-2B100.097.425.423.988.752.464.6
Voyage-Code-002100.099.033.126.694.329.163.7
BGE-Code-v1100.099.240.936.193.167.472.8

Instructions for Evaluation

{
    "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)."
}

Citation

If you find this repository useful, please consider giving a star :star: and citation

@misc{bge_code,
    title={Towards A Generalist Code Embedding Model Based On Massive Data Synthesis}, 
    author={Chaofan Li and Jianlyu Chen and Yingxia Shao and Defu Lian and Zheng Liu},
    year={2025},
    eprint={2505.12697},
    archivePrefix={arXiv},
    primaryClass={cs.IR},
    url={https://arxiv.org/abs/2505.12697}, 
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · sentence-transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2Model
Ревизия весов
bd67852

0 моделей