/ Модель

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

Контекст
512 токенов
Параметры
40 млн
Лицензия
MIT
Архитектура
bert · dense
Библиотека
sentence-transformers
Опубликована
25 авг 2023

bge-small-en

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

Компактная англоязычная модель BGE преобразует текст в векторы для семантического поиска, извлечения релевантных документов и анализа сходства.

105скачиваний за 30 дней0лайковвеса обновлены28 авг 2023

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

vectoriseai/bge-small-en — англоязычная модель эмбеддингов из семейства BGE (BAAI General Embedding), представленная в проекте FlagEmbedding. Она преобразует текст в плотные векторы размером 384 для поиска и сравнения по смыслу; в карточке указаны архитектура BERT и около 40 млн параметров. Модель принимает текстовые последовательности длиной до 512 токенов и предназначена для английского языка.

Модель подходит для семантического поиска, извлечения релевантных фрагментов для RAG, классификации и кластеризации текста. Для поиска длинных документов по короткому запросу README рекомендует добавлять к запросу инструкцию «Represent this sentence for searching relevant passages:»; к самим документам инструкцию добавлять не нужно. Репозиторий содержит веса PyTorch и Safetensors, а также формат ONNX; лицензия — MIT.

Компактный размер упрощает развёртывание по сравнению с крупными вариантами BGE, сохраняя пригодность для типовых задач текстового поиска. Контекст ограничен 512 токенами, поэтому длинные тексты следует обрабатывать частями. Метаданные классифицируют модель как sentence similarity, а каталог также указывает извлечение признаков.

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

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

Ограничения

Контекст ограничен 512 токенами; для поиска длинных фрагментов по короткому запросу README рекомендует добавлять специальную инструкцию к запросу. Модель ориентирована на английский язык.

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

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

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

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

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

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

Открыть на Hugging Face

More details please refer to our Github: FlagEmbedding.

English | 中文

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 database for LLMs.

************* 🌟Updates🌟 *************

  • 08/09/2023: BGE Models are integrated into Langchain, you can use it like this; C-MTEB leaderboard is avaliable.
  • 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!
  • 08/01/2023: We release the Chinese Massive Text Embedding Benchmark (C-MTEB), consisting of 31 test dataset.

Model List

bge is short for BAAI general embedding.

ModelLanguageDescriptionquery instruction for retrieval*
BAAI/bge-large-enEnglishrank 1st in MTEB leaderboardRepresent this sentence for searching relevant passages:
BAAI/bge-base-enEnglishrank 2nd in MTEB leaderboardRepresent this sentence for searching relevant passages:
BAAI/bge-small-enEnglisha small-scale model but with competitive performanceRepresent this sentence for searching relevant passages:
BAAI/bge-large-zhChineserank 1st in C-MTEB benchmark为这个句子生成表示以用于检索相关文章:
BAAI/bge-large-zh-noinstructChineseThis model is trained without instruction, and rank 2nd in C-MTEB benchmark
BAAI/bge-base-zhChinesea base-scale model but has similar ability with bge-large-zh为这个句子生成表示以用于检索相关文章:
BAAI/bge-small-zhChinesea small-scale model but with competitive performance为这个句子生成表示以用于检索相关文章:

*: If you need to search the long relevant passages to a short query (s2p retrieval task), you need to add the instruction to the query; in other cases, no instruction is needed, just use the original query directly. In all cases, no instruction need to be added to passages.

Usage

Here are some examples to use bge models with FlagEmbedding, Sentence-Transformers, Langchain, or Huggingface Transformers.

Using FlagEmbedding

pip install -U FlagEmbedding

If it doesn't work for you, you can see FlagEmbedding for more methods to install FlagEmbedding.

from FlagEmbedding import FlagModel
sentences = ["样例数据-1", "样例数据-2"]
model = FlagModel('BAAI/bge-large-zh', query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:")
embeddings_1 = model.encode(sentences)
embeddings_2 = model.encode(sentences)
similarity = embeddings_1 @ embeddings_2.T
print(similarity)

# for s2p(short query to long passage) retrieval task, please use encode_queries() which will automatically add the instruction to each query
# corpus in retrieval task can still use encode() or encode_corpus(), since they don't need instruction
queries = ['query_1', 'query_2']
passages = ["样例文档-1", "样例文档-2"]
q_embeddings = model.encode_queries(queries)
p_embeddings = model.encode(passages)
scores = 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.

Using Sentence-Transformers

Using this model also is easy when you have sentence-transformers installed:

pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer
sentences = ["样例数据-1", "样例数据-2"]
model = SentenceTransformer('BAAI/bge-large-zh')
embeddings_1 = model.encode(sentences, normalize_embeddings=True)
embeddings_2 = model.encode(sentences, normalize_embeddings=True)
similarity = embeddings_1 @ embeddings_2.T
print(similarity)

For s2p(short query to long passage) retrieval task, each short query should start with an instruction (instructions see Model List). But the instruction is not needed for passages.

from sentence_transformers import SentenceTransformer
queries = ['query_1', 'query_2']
passages = ["样例文档-1", "样例文档-2"]
instruction = "为这个句子生成表示以用于检索相关文章:"

model = SentenceTransformer('BAAI/bge-large-zh')
q_embeddings = model.encode([instruction+q for q in queries], normalize_embeddings=True)
p_embeddings = model.encode(passages, normalize_embeddings=True)
scores = q_embeddings @ p_embeddings.T

Using Langchain

You can use bge in langchain like this:

from langchain.embeddings import HuggingFaceBgeEmbeddings
model_name = "BAAI/bge-small-en"
model_kwargs = {'device': 'cuda'}
encode_kwargs = {'normalize_embeddings': True} # set True to compute cosine similarity
model_norm = HuggingFaceBgeEmbeddings(
    model_name=model_name,
    model_kwargs=model_kwargs,
    encode_kwargs=encode_kwargs
)

Using HuggingFace Transformers

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.

from transformers import AutoTokenizer, AutoModel
import torch
# Sentences we want sentence embeddings for
sentences = ["样例数据-1", "样例数据-2"]

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-large-zh')
model = AutoModel.from_pretrained('BAAI/bge-large-zh')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)
# encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)
    # Perform pooling. In this case, cls pooling.
    sentence_embeddings = model_output[0][:, 0]
# normalize embeddings
sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:", sentence_embeddings)

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.

  • MTEB:
Model NameDimensionSequence LengthAverage (56)Retrieval (15)Clustering (11)Pair Classification (3)Reranking (4)STS (10)Summarization (1)Classification (12)
bge-large-en102451263.9853.946.9885.859.4881.5632.0676.21
bge-base-en76851263.3653.046.3285.8658.781.8429.2775.27
gte-large102451263.1352.2246.8485.0059.1383.3531.6673.33
gte-base76851262.3951.1446.284.5758.6182.331.1773.01
e5-large-v2102451262.2550.5644.4986.0356.6182.0530.1975.24
bge-small-en38451262.1151.8244.3183.7857.9780.7230.5374.37
instructor-xl76851261.7949.2644.7486.6257.2983.0632.3261.79
e5-base-v276851261.550.2943.8085.7355.9181.0530.2873.84
gte-small38451261.3649.4644.8983.5457.782.0730.4272.31
text-embedding-ada-0021536819260.9949.2545.984.8956.3280.9730.870.93
e5-small-v238451259.9349.0439.9284.6754.3280.3931.1672.94
sentence-t5-xxl76851259.5142.2443.7285.0656.4282.6330.0873.42
all-mpnet-base-v276851457.7843.8143.6983.0459.3680.2827.4965.07
sgpt-bloom-7b1-msmarco4096204857.5948.2238.9381.955.6577.7433.666.19
all-MiniLM-L12-v238451256.5342.6941.8182.4158.4479.827.963.21
all-MiniLM-L6-v238451256.2641.9542.3582.3758.0478.930.8163.05
contriever-base-msmarco76851256.0041.8841.182.5453.1476.5130.3666.68
sentence-t5-base76851255.2733.6340.2185.1853.0981.1431.3969.81
  • 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.
ModelEmbedding dimensionAvgRetrievalSTSPairClassificationClassificationRerankingClustering
bge-large-zh102464.2071.5353.2378.9472.2665.1148.39
bge-large-zh-noinstruct102463.5370.5550.9876.7772.4964.9150.01
BAAI/bge-base-zh76862.9669.5352.0577.570.9864.9147.63
BAAI/bge-small-zh51258.2763.0746.8770.3567.7861.4845.09
m3e-base76857.1056.9148.1563.9970.2859.3447.68
m3e-large102457.0554.7548.6464.371.2259.6648.88
text-embedding-ada-002(OpenAI)153653.0252.040.6169.5667.3854.2845.68
luotuo102449.3744.439.4166.6265.2949.2544.39
text2vec76847.6338.7941.7167.4165.1849.4537.66
text2vec-large102447.3641.9441.9870.8663.4249.1630.02

Train

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, 0.5 respectively. We used the AdamW optimizer and the learning rate is 2e-5.

Pre-training data:

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.

Besides, we add instruction to the query for s2p(short query to long passage) retrieval task in the training (add nothing to passages). 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 queries in retrieval task, not be added for other tasks. Noted that the instruction is not needed for passages.

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.

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей