/ Модель

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

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

bge-small-en

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

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

161скачиваний за 30 дней1лайквеса обновлены18 мар 2024

Бенчмарки

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

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

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

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

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

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

Supabase/bge-small-en — это англоязычная версия модели встраивания текста BGE, опубликованная Supabase в формате ONNX для работы с Transformers.js. Модель основана на архитектуре BERT, содержит около 40 млн параметров и принимает последовательности длиной до 512 токенов. В карточке указано, что исходная линейка BGE разработана командой BAAI; эта версия представляет собой форк с весами ONNX.

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

Модель рассчитана на английский язык и имеет лицензию MIT. Это компактный вариант BGE, удобный для JavaScript-приложений и сценариев, где важны размер модели и получение эмбеддингов; окно контекста ограничено 512 токенами.

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

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

Ограничения

Модель предназначена для английского языка, а максимальная длина входной последовательности составляет 512 токенов. Для поиска «запрос—фрагмент» рекомендуется добавлять к запросу специальную инструкцию.

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

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

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

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

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

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

Открыть на Hugging Face

Fork of https://huggingface.co/BAAI/bge-small-en with ONNX weights to be compatible with Transformers.js. See JavaScript usage.


For more details please refer to our GitHub repo: 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 databases for LLMs.

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

  • 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! :tada: :tada:
  • 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-enEnglish:trophy: rank 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-small-enChinese:trophy: rank 1st in C-MTEB benchmark为这个句子生成表示以用于检索相关文章:
BAAI/bge-small-en-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为这个句子生成表示以用于检索相关文章:

Usage

This model can be used with both Python and JavaScript.

Python

Use with FlagEmbedding

pip install -U FlagEmbedding

See FlagEmbedding for more methods to install FlagEmbedding.

from FlagEmbedding import FlagModel
sentences = ["样例数据-1", "样例数据-2"]
model = FlagModel('Supabase/bge-small-en', query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:")
embeddings = model.encode(sentences)
print(embeddings)

# for 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()
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.

Use with 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('Supabase/bge-small-en')
embeddings = model.encode(sentences, normalize_embeddings=True)
print(embeddings)

For retrieval task, each query should start with an instruction (instructions see Model List).

from sentence_transformers import SentenceTransformer
queries = ["手机开不了机怎么办?"]
passages = ["样例段落-1", "样例段落-2"]
instruction = "为这个句子生成表示以用于检索相关文章:"

model = SentenceTransformer('Supabase/bge-small-en')
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

Use with Transformers and PyTorch

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('Supabase/bge-small-en')
model = AutoModel.from_pretrained('Supabase/bge-small-en')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# for retrieval task, add an instruction to query
# 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)

JavaScript

This model can be used with JavaScript via Transformers.js.

Use with Deno or Supabase Edge Functions

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { env, pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.5.0'
// Configuration for Deno runtime
env.useBrowserCache = false;
env.allowLocalModels = false;
const pipe = await pipeline(
  'feature-extraction',
  'Supabase/bge-small-en',
);
serve(async (req) => {
  // Extract input string from JSON body
  const { input } = await req.json();
  // Generate the embedding from the user input
  const output = await pipe(input, {
    pooling: 'mean',
    normalize: true,
  });
  // Extract the embedding output
  const embedding = Array.from(output.data);
  // Return the embedding
  return new Response(
    JSON.stringify({ embedding }),
    { headers: { 'Content-Type': 'application/json' } }
  );
});

Use within the browser (JavaScript Modules)

<script type="module">
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.5.0';
const pipe = await pipeline(
  'feature-extraction',
  'Supabase/bge-small-en',
);
// Generate the embedding from text
const output = await pipe('Hello world', {
  pooling: 'mean',
  normalize: true,
});
// Extract the embedding output
const embedding = Array.from(output.data);
console.log(embedding);
</script>

Use within Node.js or a web bundler (Webpack, etc)

import { pipeline } from '@xenova/transformers';
const pipe = await pipeline(
  'feature-extraction',
  'Supabase/bge-small-en',
);
// Generate the embedding from text
const output = await pipe('Hello world', {
  pooling: 'mean',
  normalize: true,
});
// Extract the embedding output
const embedding = Array.from(output.data);
console.log(embedding);

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
bge-small-en38451261.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, and 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.

For the version with *-instrcution, we add instruction to the query for retrieval task in the training. 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 sentence to passages retrieval task, not be added for other tasks.

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

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

Нельзя запустить

Модель выложена для браузера (ONNX / transformers.js).

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

0 моделей