/ Модель

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

Контекст
512 токенов
Параметры
137 млн
Лицензия
Apache 2.0
Архитектура
bert · dense
Библиотека
sentence-transformers
Опубликована
2 мар 2022

msmarco-bert-co-condensor

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

Плотная BERT-модель Sentence-Transformers создаёт эмбеддинги предложений и абзацев для семантического поиска и извлечения релевантных документов.

348скачиваний за 30 дней4лайкавеса обновлены6 мар 2025

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

msmarco-bert-co-condensor — модель Sentence-Transformers, созданная как перенос Luyu/co-condenser-marco-retriever в формат Sentence-Transformers. Это плотная BERT-модель с 136,7 млн параметров, которая преобразует предложения и абзацы в векторы размерностью 768 для семантического поиска и извлечения релевантных фрагментов. Она основана на работе «Unsupervised Corpus Aware Language Model Pre-training for Dense Passage Retrieval» и ориентирована на поиск по коллекциям текстов, включая сценарии на основе MS MARCO.

Модель принимает текст и выдаёт эмбеддинги; для сравнения запросов и документов обычно используют близость их векторов. Максимальная длина контекста — 512 токенов. Репозиторий включает варианты PyTorch, Safetensors, ONNX и OpenVINO. По приведённым в карточке оценкам, качество зависит от набора данных; автор README также указывает на возможную утечку информации и изменение протокола оценки в некоторых результатах исходной статьи, поэтому сравнивать показатели следует с учётом этих оговорок. Лицензия — Apache-2.0.

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

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

Ограничения

Контекст ограничен 512 токенами. README предупреждает, что часть опубликованных оценок могла быть завышена из-за утечки информации и изменения протокола MS MARCO; качество также различается между наборами данных.

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

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

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

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

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

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

Открыть на Hugging Face

sentence-transformers/msmarco-bert-co-condensor

This is a port of the Luyu/co-condenser-marco-retriever model to sentence-transformers model: It maps sentences & paragraphs to a 768 dimensional dense vector space and is optimized for the task of semantic search.

It is based on the paper: Unsupervised Corpus Aware Language Model Pre-training for Dense Passage Retrieval

Evaluation

ModelMS MARCO Dev (MRR@10)TREC DL 2019TREC DL 2020FiQA (NDCG@10)TREC COVID (NDCG@10)TREC News (NDCG@10)TREC Robust04 (NDCG@10)
msmarco-roberta-base-ance-firstp33.0167.8466.0429.567.1238.239.2
msmarco-bert-co-condensor35.5168.1669.1326.0466.8928.5430.71
msmarco-distilbert-base-tas-b34.4371.0469.7830.0265.3937.7042.70
msmarco-distilbert-dot-v537.2570.1471.0828.6171.9637.8838.29
msmarco-bert-base-dot-v538.0870.5173.4532.2974.8138.8142.67

For more details on the comparison, see: SBERT.net - MSMARCO Models

In the paper, Gao & Callan claim a MS MARCO-Dev score of 38.2 (MRR@10). This is achieved by changing the benchmark: The orginal MS MARCO dataset just provides queries and text passages, from which you must retrieve the relevant passages for a given query.

In their code, they combine the passages with the document titles from MS MARCO document task, i.e. they train and evaluate their model with additional information from a different benchmark. In the above table, the score of 35.41 (MRR@10) is on the MS MARCO Passages benchmark as it is proposed, without having the document titles.

They further trained their model with the document titles, which creates an information leackage: The document titles were re-constructed by the MS MARCO organizers at a later stage for the MS MARCO document benchmark. It was not possible to reconstruct all document titles for all passages. However, the distribution of having a title is not equal for relevant and non-relevant passages: 71.9% of the relevant passages have a document title, while only 64.4% of the non-relevant passages have a title. Hence, the model can learn that, as soon as there is a document title, the probability is higher that this passage is annotated as relevant. It will not make the decision based on the passage content, but by the artifact if there is a title or not.

The information leackage and the change of the benchmark likely leads to the inflated scores reported in the paper.

Usage (Sentence-Transformers)

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

pip install -U sentence-transformers

Then you can use the model like this:

from sentence_transformers import SentenceTransformer, util

query = "How many people live in London?"
docs = ["Around 9 Million people live in London", "London is known for its financial district"]

#Load the model
model = SentenceTransformer('sentence-transformers/msmarco-bert-co-condensor')

#Encode query and documents
query_emb = model.encode(query)
doc_emb = model.encode(docs)

#Compute dot score between query and all document embeddings
scores = util.dot_score(query_emb, doc_emb)[0].cpu().tolist()

#Combine docs & scores
doc_score_pairs = list(zip(docs, scores))

#Sort by decreasing score
doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)

#Output passages & scores
for doc, score in doc_score_pairs:
    print(score, doc)

Usage (HuggingFace Transformers)

Without sentence-transformers, you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.

from transformers import AutoTokenizer, AutoModel
import torch

#CLS Pooling - Take output from first token
def cls_pooling(model_output):
    return model_output.last_hidden_state[:,0]

#Encode text
def encode(texts):
    # Tokenize sentences
    encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')

    # Compute token embeddings
    with torch.no_grad():
        model_output = model(**encoded_input, return_dict=True)

    # Perform pooling
    embeddings = cls_pooling(model_output)

    return embeddings


# Sentences we want sentence embeddings for
query = "How many people live in London?"
docs = ["Around 9 Million people live in London", "London is known for its financial district"]

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/msmarco-bert-co-condensor")
model = AutoModel.from_pretrained("sentence-transformers/msmarco-bert-co-condensor")

#Encode query and docs
query_emb = encode(query)
doc_emb = encode(docs)

#Compute dot score between query and all document embeddings
scores = torch.mm(query_emb, doc_emb.transpose(0, 1))[0].cpu().tolist()

#Combine docs & scores
doc_score_pairs = list(zip(docs, scores))

#Sort by decreasing score
doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)

#Output passages & scores
for doc, score in doc_score_pairs:
    print(score, doc)

Full Model Architecture

SentenceTransformer(
  (0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: DistilBertModel 
  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
)

Citing & Authors

Have a look at: Unsupervised Corpus Aware Language Model Pre-training for Dense Passage Retrieval

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей