/ Модель

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

Контекст
514 токенов
Параметры
138 млн
Лицензия
MIT
Архитектура
camembert · dense
Базовая модель
camembert-base
Библиотека
sentence-transformers
Опубликована
22 мая 2023

biencoder-camembert-base-mmarcoFR

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

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

3 231скачиваний за 30 дней9лайковвеса обновлены26 мар 2024

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Модель antoinelouis/biencoder-camembert-base-mmarcoFR — плотный биэнкодер для семантического поиска на французском языке, разработанный Antoine Louis. Она кодирует запросы и фрагменты текста в отдельные векторы размерностью 768 и оценивает их релевантность по косинусному сходству. Модель построена на CamemBERT-base и дообучена на французской части mMARCO, включая сложные отрицательные примеры, полученные от плотных поисковых систем.

Модель предназначена для поиска passage по запросу, ранжирования найденных фрагментов и построения семантического поиска по французским коллекциям документов. В README указаны максимальная длина последовательностей 128 токенов при обучении, а метаданные задают контекст модели в 514 токенов; для вычисления эмбеддингов предлагаются Sentence-Transformers, FlagEmbedding и Transformers. Лицензия — MIT.

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

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

Ограничения

Модель рассчитана на французский язык; при обучении максимальная длина запросов и фрагментов составляла 128 токенов. README приводит оценку на dev-выборке mMARCO-fr, поэтому качество на других языках и типах данных из этих сведений не следует.

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

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

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

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

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

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

Открыть на Hugging Face

biencoder-camembert-base-mmarcoFR

This is a dense single-vector bi-encoder model for French that can be used for semantic search. The model maps queries and passages to 768-dimensional dense vectors which are used to compute relevance through cosine similarity.

Usage

Here are some examples for using the model with Sentence-Transformers, FlagEmbedding, or Huggingface Transformers.

Using Sentence-Transformers

Start by installing the library: pip install -U sentence-transformers. Then, you can use the model like this:

from sentence_transformers import SentenceTransformer

queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]

model = SentenceTransformer('antoinelouis/biencoder-camembert-base-mmarcoFR')
q_embeddings = model.encode(queries, normalize_embeddings=True)
p_embeddings = model.encode(passages, normalize_embeddings=True)

similarity = q_embeddings @ p_embeddings.T
print(similarity)

Using FlagEmbedding

Start by installing the library: pip install -U FlagEmbedding. Then, you can use the model like this:

from FlagEmbedding import FlagModel

queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]

model = FlagModel('antoinelouis/biencoder-camembert-base-mmarcoFR')
q_embeddings = model.encode(queries, normalize_embeddings=True)
p_embeddings = model.encode(passages, normalize_embeddings=True)

similarity = q_embeddings @ p_embeddings.T
print(similarity)

Using Transformers

Start by installing the library: pip install -U transformers. Then, you can use the model like this:

from transformers import AutoTokenizer, AutoModel
from torch.nn.functional import normalize

def mean_pooling(model_output, attention_mask):
    """ Perform mean pooling on-top of the contextualized word embeddings, while ignoring mask tokens in the mean computation."""
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]

tokenizer = AutoTokenizer.from_pretrained('antoinelouis/biencoder-camembert-base-mmarcoFR')
model = AutoModel.from_pretrained('antoinelouis/biencoder-camembert-base-mmarcoFR')

q_input = tokenizer(queries, padding=True, truncation=True, return_tensors='pt')
p_input = tokenizer(passages, padding=True, truncation=True, return_tensors='pt')
with torch.no_grad():
    q_output = model(**encoded_queries)
    p_output = model(**encoded_passages)
q_embeddings = mean_pooling(q_output, q_input['attention_mask'])
q_embedddings = normalize(q_embeddings, p=2, dim=1)
p_embeddings = mean_pooling(p_output, p_input['attention_mask'])
p_embedddings = normalize(p_embeddings, p=2, dim=1)

similarity = q_embeddings @ p_embeddings.T
print(similarity)

Evaluation

The model is evaluated on the smaller development set of mMARCO-fr, which consists of 6,980 queries for a corpus of 8.8M candidate passages. We report the mean reciprocal rank (MRR), normalized discounted cumulative gainand (NDCG), mean average precision (MAP), and recall at various cut-offs (R@k). To see how it compares to other neural retrievers in French, check out the DécouvrIR leaderboard.

Training

Data

We use the French training samples from the mMARCO dataset, a multilingual machine-translated version of MS MARCO that contains 8.8M passages and 539K training queries. We do not employ the BM25 netaives provided by the official dataset but instead sample harder negatives mined from 12 distinct dense retrievers, using the msmarco-hard-negatives distillation dataset.

Implementation

The model is initialized from the camembert-base checkpoint and optimized via the cross-entropy loss (as in DPR) with a temperature of 0.05. It is fine-tuned on one 32GB NVIDIA V100 GPU for 20 epochs (i.e., 65.7k steps) using the AdamW optimizer with a batch size of 152, a peak learning rate of 2e-5 with warm up along the first 500 steps and linear scheduling. We set the maximum sequence lengths for both the questions and passages to 128 tokens. We use the cosine similarity to compute relevance scores.

Citation

@online{louis2024decouvrir,
	author    = 'Antoine Louis',
	title     = 'DécouvrIR: A Benchmark for Evaluating the Robustness of Information Retrieval Models in French',
	publisher = 'Hugging Face',
	month     = 'mar',
	year      = '2024',
	url       = 'https://huggingface.co/spaces/antoinelouis/decouvrir',
}

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
CamembertModel
Ревизия весов
485566a

0 моделей