/ Модель

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

Контекст
32 768 токенов
Параметры
7,1 млрд
Размер весов
28,4 ГБ
Лицензия
Apache 2.0
Архитектура
mistral · dense
Опубликована
25 июл 2024

bge-en-icl

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

Англоязычная модель BAAI на базе Mistral, создающая текстовые эмбеддинги и использующая примеры в запросе для адаптации к новым задачам поиска.

1 665скачиваний за 30 дней137лайковвеса обновлены15 янв 2025

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

  • QuoraRetrieval

    main_score

    Результат

    0,9095

    MTEB

    Публичная таблицаревизия не подтверждена

  • SciFact

    main_score

    Результат

    0,7909

    MTEB

    Публичная таблицаревизия не подтверждена

  • ProceduralMemBench

    main_score

    Результат

    0,4135

    MTEB

    Публичная таблицаревизия не подтверждена

  • DeepPlanning

    main_score

    Результат

    0,5222

    Общий результат 0,4983
    MTEB

    Публичная таблицаревизия не подтверждена

  • MemBench

    main_score

    Результат

    0,9054

    MTEB

    Публичная таблицаревизия не подтверждена

  • NovelQA

    main_score

    Результат

    0,0827

    Общий результат 0,3449Общий результат 0,2188
    MTEB

    Публичная таблицаревизия не подтверждена

  • Gorilla

    main_score

    Результат

    0,3326

    Общий результат 0,5216
    MTEB

    Публичная таблицаревизия не подтверждена

  • MemGovern

    main_score

    Результат

    0,708

    Общий результат 0,9277Общий результат 0,8095Общий результат 0,7917
    MTEB

    Публичная таблицаревизия не подтверждена

  • EPBench

    main_score

    Результат

    0,4771

    Общий результат 0,8555Общий результат 0,7909Общий результат 0,7176
    MTEB

    Публичная таблицаревизия не подтверждена

  • BIOSSES

    main_score

    Результат

    0,8647

    MTEB

    Публичная таблицаревизия не подтверждена

  • KnowMeBench

    main_score

    Результат

    0,5427

    Общий результат 0,4395
    MTEB

    Публичная таблицаревизия не подтверждена

  • TweetSentimentExtractionClassification

    main_score

    Результат

    0,7993

    MTEB

    Публичная таблицаревизия не подтверждена

  • TMD

    main_score

    Результат

    0,3612

    MTEB

    Публичная таблицаревизия не подтверждена

  • BiorxivClusteringS2S

    main_score

    Результат

    0,4838

    MTEB

    Публичная таблицаревизия не подтверждена

  • ReMe

    main_score

    Результат

    0,731

    MTEB

    Публичная таблицаревизия не подтверждена

  • STS15

    main_score

    Результат

    0,8777

    MTEB

    Публичная таблицаревизия не подтверждена

  • MTOPIntentClassification

    main_score

    Результат

    0,94

    MTEB

    Публичная таблицаревизия не подтверждена

  • MindSmallReranking

    main_score

    Результат

    0,306

    MTEB

    Публичная таблицаревизия не подтверждена

  • TwitterURLCorpus

    main_score

    Результат

    0,8786

    MTEB

    Публичная таблицаревизия не подтверждена

  • StackExchangeClusteringP2P

    main_score

    Результат

    0,4605

    MTEB

    Публичная таблицаревизия не подтверждена

  • ESGReports

    main_score

    Результат

    0,4412

    MTEB

    Публичная таблицаревизия не подтверждена

  • CQADupstackRetrieval

    main_score

    Результат

    0,4731

    MTEB

    Публичная таблицаревизия не подтверждена

  • ConvoMem

    main_score

    Результат

    0,4574

    MTEB

    Публичная таблицаревизия не подтверждена

  • LooGLE

    main_score

    Результат

    0,5537

    MTEB

    Публичная таблицаревизия не подтверждена

  • MedrxivClusteringP2P

    main_score

    Результат

    0,4586

    MTEB

    Публичная таблицаревизия не подтверждена

  • RedditClusteringP2P

    main_score

    Результат

    0,7272

    MTEB

    Публичная таблицаревизия не подтверждена

  • MassiveIntentClassification

    main_score

    Результат

    0,8293

    MTEB

    Публичная таблицаревизия не подтверждена

  • STS14

    main_score

    Результат

    0,8283

    MTEB

    Публичная таблицаревизия не подтверждена

  • AmazonPolarityClassification

    main_score

    Результат

    0,9698

    MTEB

    Публичная таблицаревизия не подтверждена

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

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

BAAI/bge-en-icl — англоязычная модель эмбеддингов компании Beijing Academy of Artificial Intelligence (BAAI), представленная в проекте FlagEmbedding. Она преобразует текст в векторы для поиска и сопоставления предложений, а также поддерживает обучение в контексте: запрос можно дополнить несколькими примерами, чтобы адаптировать модель к новой задаче. Архитектура — плотная модель семейства Mistral на 7,1 млрд параметров с контекстом до 32 768 токенов.

Модель предназначена для семантического поиска, ранжирования и задач retrieval-augmented generation. В карточке заявлены высокие результаты на бенчмарках BEIR, MTEB и AIR-Bench, включая поиск по длинным документам. Распространяется под лицензией Apache-2.0. Она рассчитана на английский язык; для эффективного кодирования может использовать доступные GPU, а ресурсоёмкость определяется её размером.

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

  • семантический поиск по англоязычным документам
  • поиск ответов в корпусе для RAG-системы
  • ранжирование документов по релевантности запросу
  • поиск по длинным документам
  • сопоставление предложений по смыслу

Ограничения

Модель ориентирована на английский язык и требует значительных вычислительных ресурсов из-за размера 7,1 млрд параметров. Заявленные результаты зависят от задачи и настройки запросов с примерами.

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

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

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

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

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

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

Открыть на Hugging Face

For more details please refer to our Github: FlagEmbedding.

BGE-EN-ICL primarily demonstrates the following capabilities:

  • In-context learning ability: By providing few-shot examples in the query, it can significantly enhance the model's ability to handle new tasks.
  • Outstanding performance: The model has achieved state-of-the-art (SOTA) performance on both BEIR and AIR-Bench.

📑 Open-source Plan

  • Checkpoint
  • Training Data
  • Technical Report
  • Evaluation Pipeline

The technical report for BGE-EN-ICL can be found in Making Text Embedders Few-Shot Learners

Data List

DataIntroduction
public-dataPublic data identical to e5-mistral
full-dataThe full dataset we used for training

Usage

Using FlagEmbedding

git clone https://github.com/FlagOpen/FlagEmbedding.git
cd FlagEmbedding
pip install -e .
from FlagEmbedding import FlagICLModel
queries = ["how much protein should a female eat", "summit define"]
documents = [
    "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.",
    "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."
]
examples = [
  {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
   'query': 'what is a virtual interface',
   'response': "A virtual interface is a software-defined abstraction that mimics the behavior and characteristics of a physical network interface. It allows multiple logical network connections to share the same physical network interface, enabling efficient utilization of network resources. Virtual interfaces are commonly used in virtualization technologies such as virtual machines and containers to provide network connectivity without requiring dedicated hardware. They facilitate flexible network configurations and help in isolating network traffic for security and management purposes."},
  {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
   'query': 'causes of back pain in female for a week',
   'response': "Back pain in females lasting a week can stem from various factors. Common causes include muscle strain due to lifting heavy objects or improper posture, spinal issues like herniated discs or osteoporosis, menstrual cramps causing referred pain, urinary tract infections, or pelvic inflammatory disease. Pregnancy-related changes can also contribute. Stress and lack of physical activity may exacerbate symptoms. Proper diagnosis by a healthcare professional is crucial for effective treatment and management."}
]
model = FlagICLModel('BAAI/bge-en-icl', 
                     query_instruction_for_retrieval="Given a web search query, retrieve relevant passages that answer the query.",
                     examples_for_task=examples,  # set `examples_for_task=None` to use model without examples
                     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, FlagICLModel 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 HuggingFace Transformers

With the 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 the first token (i.e., [CLS]) as the sentence embedding.

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}'

def get_detailed_example(task_description: str, query: str, response: str) -> str:
    return f'<instruct>{task_description}\n<query>{query}\n<response>{response}'

def get_new_queries(queries, query_max_len, examples_prefix, tokenizer):
    inputs = tokenizer(
        queries,
        max_length=query_max_len - len(tokenizer('<s>', add_special_tokens=False)['input_ids']) - len(
            tokenizer('\n<response></s>', add_special_tokens=False)['input_ids']),
        return_token_type_ids=False,
        truncation=True,
        return_tensors=None,
        add_special_tokens=False
    )
    prefix_ids = tokenizer(examples_prefix, add_special_tokens=False)['input_ids']
    suffix_ids = tokenizer('\n<response>', add_special_tokens=False)['input_ids']
    new_max_length = (len(prefix_ids) + len(suffix_ids) + query_max_len + 8) // 8 * 8 + 8
    new_queries = tokenizer.batch_decode(inputs['input_ids'])
    for i in range(len(new_queries)):
        new_queries[i] = examples_prefix + new_queries[i] + '\n<response>'
    return new_max_length, new_queries

task = 'Given a web search query, retrieve relevant passages that answer the query.'
examples = [
  {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
   'query': 'what is a virtual interface',
   'response': "A virtual interface is a software-defined abstraction that mimics the behavior and characteristics of a physical network interface. It allows multiple logical network connections to share the same physical network interface, enabling efficient utilization of network resources. Virtual interfaces are commonly used in virtualization technologies such as virtual machines and containers to provide network connectivity without requiring dedicated hardware. They facilitate flexible network configurations and help in isolating network traffic for security and management purposes."},
  {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
   'query': 'causes of back pain in female for a week',
   'response': "Back pain in females lasting a week can stem from various factors. Common causes include muscle strain due to lifting heavy objects or improper posture, spinal issues like herniated discs or osteoporosis, menstrual cramps causing referred pain, urinary tract infections, or pelvic inflammatory disease. Pregnancy-related changes can also contribute. Stress and lack of physical activity may exacerbate symptoms. Proper diagnosis by a healthcare professional is crucial for effective treatment and management."}
]
examples = [get_detailed_example(e['instruct'], e['query'], e['response']) for e in examples]
examples_prefix = '\n\n'.join(examples) + '\n\n' # if there not exists any examples, just set examples_prefix = ''
queries = [
    get_detailed_instruct(task, 'how much protein should a female eat'),
    get_detailed_instruct(task, 'summit define')
]
documents = [
    "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.",
    "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."
]
query_max_len, doc_max_len = 512, 512

tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-en-icl')
model = AutoModel.from_pretrained('BAAI/bge-en-icl')
model.eval()

new_query_max_len, new_queries = get_new_queries(queries, query_max_len, examples_prefix, tokenizer)

query_batch_dict = tokenizer(new_queries, max_length=new_query_max_len, padding=True, truncation=True, return_tensors='pt')
doc_batch_dict = tokenizer(documents, max_length=doc_max_len, padding=True, truncation=True, return_tensors='pt')

with torch.no_grad():
    query_outputs = model(**query_batch_dict)
    query_embeddings = last_token_pool(query_outputs.last_hidden_state, query_batch_dict['attention_mask'])
    doc_outputs = model(**doc_batch_dict)
    doc_embeddings = last_token_pool(doc_outputs.last_hidden_state, doc_batch_dict['attention_mask'])
    
# normalize embeddings
query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
doc_embeddings = F.normalize(doc_embeddings, p=2, dim=1)
scores = (query_embeddings @ doc_embeddings.T) * 100
print(scores.tolist())

Evaluation

bge-en-icl achieve state-of-the-art performance on both MTEB and AIR-Bench leaderboard!

BEIR

BEIR

QA (en, nDCG@10):

AIR-Bench_24.04wikiwebnewshealthcarelawfinancearxivmsmarcoALL (8)
e5-mistral-7b-instruct61.6744.4148.1856.3219.3254.7944.7859.0348.56
SFR-Embedding-Mistral63.4651.2752.2158.7623.2756.9447.7558.9951.58
NV-Embed-v162.8450.4251.4658.5320.6549.8946.1060.2750.02
Linq-Embed-Mistral61.0448.4149.4460.1820.3450.0447.5660.5049.69
gte-Qwen2-7B-instruct63.4651.2054.0754.2022.3158.2040.2758.3950.26
stella_en_1.5B_v561.9950.8853.8758.8123.2257.2644.8161.3851.53
bge-en-icl zero-shot64.6154.4055.1157.2525.1054.8148.4663.7152.93
bge-en-icl few-shot64.9455.1156.0258.8528.2957.1650.0464.5054.36

Long-Doc (en, Recall@10):

AIR-Bench_24.04arxiv (4)book (2)healthcare (5)law (4)ALL (15)
text-embedding-3-large74.5373.1665.8364.4768.77
e5-mistral-7b-instruct72.1472.4468.4462.9268.49
SFR-Embedding-Mistral72.7972.4167.9464.8369.00
NV-Embed-v177.6575.4972.3869.5573.45
Linq-Embed-Mistral75.4673.8171.5868.5872.11
gte-Qwen2-7B-instruct63.9368.5165.5965.2665.45
stella_en_1.5B_v573.1774.3870.0269.3271.25
bge-en-icl zero-shot78.3078.2173.6567.0973.75
bge-en-icl few-shot79.6379.3674.8067.7974.83

Model List

bge is short for BAAI general embedding.

ModelLanguageDescriptionquery instruction for retrieval [1]
BAAI/bge-en-iclEnglish-A LLM-based embedding model with in-context learning capabilities, which can fully leverage the model's potential based on a few shot examplesProvide instructions and few-shot examples freely based on the given task.
BAAI/bge-m3MultilingualInference Fine-tuneMulti-Functionality(dense retrieval, sparse retrieval, multi-vector(colbert)), Multi-Linguality, and Multi-Granularity(8192 tokens)
BAAI/llm-embedderEnglishInference Fine-tunea unified embedding model to support diverse retrieval augmentation needs for LLMsSee README
BAAI/bge-reranker-largeChinese and EnglishInference Fine-tunea cross-encoder model which is more accurate but less efficient [2]
BAAI/bge-reranker-baseChinese and EnglishInference Fine-tunea cross-encoder model which is more accurate but less efficient [2]
BAAI/bge-large-en-v1.5EnglishInference Fine-tuneversion 1.5 with more reasonable similarity distributionRepresent this sentence for searching relevant passages:
BAAI/bge-base-en-v1.5EnglishInference Fine-tuneversion 1.5 with more reasonable similarity distributionRepresent this sentence for searching relevant passages:
BAAI/bge-small-en-v1.5EnglishInference Fine-tuneversion 1.5 with more reasonable similarity distributionRepresent this sentence for searching relevant passages:
BAAI/bge-large-zh-v1.5ChineseInference Fine-tuneversion 1.5 with more reasonable similarity distribution为这个句子生成表示以用于检索相关文章:
BAAI/bge-base-zh-v1.5ChineseInference Fine-tuneversion 1.5 with more reasonable similarity distribution为这个句子生成表示以用于检索相关文章:
BAAI/bge-small-zh-v1.5ChineseInference Fine-tuneversion 1.5 with more reasonable similarity distribution为这个句子生成表示以用于检索相关文章:
BAAI/bge-large-enEnglishInference Fine-tune:trophy: rank 1st in MTEB leaderboardRepresent this sentence for searching relevant passages:
BAAI/bge-base-enEnglishInference Fine-tunea base-scale model but with similar ability to bge-large-enRepresent this sentence for searching relevant passages:
BAAI/bge-small-enEnglishInference Fine-tunea small-scale model but with competitive performanceRepresent this sentence for searching relevant passages:
BAAI/bge-large-zhChineseInference Fine-tune:trophy: rank 1st in C-MTEB benchmark为这个句子生成表示以用于检索相关文章:
BAAI/bge-base-zhChineseInference Fine-tunea base-scale model but with similar ability to bge-large-zh为这个句子生成表示以用于检索相关文章:
BAAI/bge-small-zhChineseInference Fine-tunea small-scale model but with competitive performance为这个句子生成表示以用于检索相关文章:

Citation

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

@misc{li2024makingtextembeddersfewshot,
      title={Making Text Embedders Few-Shot Learners}, 
      author={Chaofan Li and MingHao Qin and Shitao Xiao and Jianlyu Chen and Kun Luo and Yingxia Shao and Defu Lian and Zheng Liu},
      year={2024},
      eprint={2409.15700},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2409.15700}, 
}
@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}
}

License

FlagEmbedding is licensed under the MIT License.

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

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

GPU в ailist

Универсальный рантайм

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

Подбираем GPU…

Класс архитектуры
MistralModel
Ревизия весов
971c7e1

0 моделей