/ Модель

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

Контекст
512 токенов
Лицензия
Apache 2.0
Архитектура
distilbert · dense
Библиотека
sentence-transformers
Опубликована
28 мар 2025

opensearch-neural-sparse-encoding-doc-v3-distill

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

Разреженная модель OpenSearch кодирует документы и запросы в векторы для эффективного поиска по текстовой коллекции.

46 279скачиваний за 30 дней10лайковвеса обновлены30 июн 2025

Бенчмарки

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

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

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

  • NFCorpus

    main_score

    Результат

    0,3447

    MTEB

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

  • ToolBench

    main_score

    Результат

    0,5075

    MTEB

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

  • MemGovern

    main_score

    Результат

    0,9326

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

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

  • TMD

    main_score

    Результат

    0,5945

    MTEB

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

  • LongMemEval

    main_score

    Результат

    0,911

    MTEB

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

  • NovelQA

    main_score

    Результат

    0,5125

    MTEB

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

  • KnowMeBench

    main_score

    Результат

    0,4491

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

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

  • EPBench

    main_score

    Результат

    0,8774

    Общий результат 1Общий результат 1Общий результат 1
    MTEB

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

  • FEVER

    main_score

    Результат

    0,8449

    MTEB

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

  • LoCoMo

    main_score

    Результат

    0,3063

    MTEB

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

  • Gorilla

    main_score

    Результат

    0,299

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

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

  • MemBench

    main_score

    Результат

    0,8861

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

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

  • CQADupstackAndroidRetrieval

    main_score

    Результат

    0,4546

    MTEB

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

  • Touche2020

    main_score

    Результат

    0,293

    MTEB

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

  • ReMe

    main_score

    Результат

    0,5077

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

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

  • LooGLE

    main_score

    Результат

    0,7968

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

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

  • REALTALK

    main_score

    Результат

    0,269

    MTEB

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

  • DBPedia

    main_score

    Результат

    0,4235

    MTEB

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

  • DeepPlanning

    main_score

    Результат

    0,6074

    MTEB

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

  • CQADupstackGisRetrieval

    main_score

    Результат

    0,3588

    MTEB

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

  • CovidQA

    main_score

    Результат

    0,8015

    MTEB

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

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

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

opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill — модель разреженного поиска OpenSearch Contributors. Она преобразует документы в разреженные векторы размерности 30 522, где индексы соответствуют токенам словаря, а веса отражают их важность. Для запросов используются токенизатор и таблица весов; релевантность оценивается скалярным произведением векторов. Модель предназначена для поиска документов, включая работу с инвертированным индексом OpenSearch.

Модель основана на DistilBERT и распространяется в формате safetensors; её можно использовать через Sentence Transformers или в кластере OpenSearch. Контекст ограничен 512 токенами. Карточка описывает обучение на наборах данных для поиска и ранжирования, а также сравнение серии v3 с предыдущими версиями на подмножестве BEIR. Репозиторий содержит Apache-2.0 лицензию.

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

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

Ограничения

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

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

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

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

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

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

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

Открыть на Hugging Face

opensearch-neural-sparse-encoding-doc-v3-distill

Select the model

The model should be selected considering search relevance, model inference and retrieval efficiency(FLOPS). We benchmark models' performance on a subset of BEIR benchmark: TrecCovid,NFCorpus,NQ,HotpotQA,FiQA,ArguAna,Touche,DBPedia,SCIDOCS,FEVER,Climate FEVER,SciFact,Quora.

Overall, the v3 series of models have better search relevance, efficiency and inference speed than the v1 and v2 series. The specific advantages and disadvantages may vary across different datasets.

ModelInference-free for RetrievalModel ParametersAVG NDCG@10AVG FLOPS
opensearch-neural-sparse-encoding-v1133M0.52411.4
opensearch-neural-sparse-encoding-v2-distill67M0.5288.3
opensearch-neural-sparse-encoding-doc-v1✔️133M0.4902.3
opensearch-neural-sparse-encoding-doc-v2-distill✔️67M0.5041.8
opensearch-neural-sparse-encoding-doc-v2-mini✔️23M0.4971.7
opensearch-neural-sparse-encoding-doc-v3-distill✔️67M0.5171.8
opensearch-neural-sparse-encoding-doc-v3-gte✔️133M0.5461.7

Overview

This is a learned sparse retrieval model. It encodes the documents to 30522 dimensional sparse vectors. For queries, it just use a tokenizer and a weight look-up table to generate sparse vectors. The non-zero dimension index means the corresponding token in the vocabulary, and the weight means the importance of the token. And the similarity score is the inner product of query/document sparse vectors.

The training datasets includes MS MARCO, eli5_question_answer, squad_pairs, WikiAnswers, yahoo_answers_title_question, gooaq_pairs, stackexchange_duplicate_questions_body_body, wikihow, S2ORC_title_abstract, stackexchange_duplicate_questions_title-body_title-body, yahoo_answers_question_answer, searchQA_top5_snippets, stackexchange_duplicate_questions_title_title, yahoo_answers_title_answer, fever, fiqa, hotpotqa, nfcorpus, scifact.

OpenSearch neural sparse feature supports learned sparse retrieval with lucene inverted index. Link: https://opensearch.org/docs/latest/query-dsl/specialized/neural-sparse/. The indexing and search can be performed with OpenSearch high-level API.

Usage (Sentence Transformers)

First install the Sentence Transformers library:

pip install -U sentence-transformers

Then you can load this model and run inference.

from sentence_transformers.sparse_encoder import SparseEncoder

# Download from the 🤗 Hub
model = SparseEncoder("opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill")

query = "What's the weather in ny now?"
document = "Currently New York is rainy."

query_embed = model.encode_query(query)
document_embed = model.encode_document(document)

sim = model.similarity(query_embed, document_embed)
print(f"Similarity: {sim}")
# Similarity: tensor([[11.1105]])

decoded_query = model.decode(query_embed)
decoded_document = model.decode(document_embed)

for i in range(len(decoded_query)):
    query_token, query_score = decoded_query[i]
    doc_score = next((score for token, score in decoded_document if token == query_token), 0)
    if doc_score != 0:
        print(f"Token: {query_token}, Query score: {query_score:.4f}, Document score: {doc_score:.4f}")

# Token: ny, Query score: 5.7729, Document score: 0.8049
# Token: weather, Query score: 4.5684, Document score: 0.9710
# Token: now, Query score: 3.5895, Document score: 0.4720
# Token: ?, Query score: 3.3313, Document score: 0.0286
# Token: what, Query score: 2.7699, Document score: 0.0787
# Token: in, Query score: 0.4989, Document score: 0.0417

Usage (HuggingFace)

This model is supposed to run inside OpenSearch cluster. But you can also use it outside the cluster, with HuggingFace models API.

import json
import itertools
import torch

from transformers import AutoModelForMaskedLM, AutoTokenizer


# get sparse vector from dense vectors with shape batch_size * seq_len * vocab_size
def get_sparse_vector(feature, output):
    values, _ = torch.max(output*feature["attention_mask"].unsqueeze(-1), dim=1)
    # note we update the activation for v3 model
    values = torch.log(1 + torch.log(1 + torch.relu(values)))
    values[:,special_token_ids] = 0
    return values
    
# transform the sparse vector to a dict of (token, weight)
def transform_sparse_vector_to_dict(sparse_vector):
    sample_indices,token_indices=torch.nonzero(sparse_vector,as_tuple=True)
    non_zero_values = sparse_vector[(sample_indices,token_indices)].tolist()
    number_of_tokens_for_each_sample = torch.bincount(sample_indices).cpu().tolist()
    tokens = [transform_sparse_vector_to_dict.id_to_token[_id] for _id in token_indices.tolist()]

    output = []
    end_idxs = list(itertools.accumulate([0]+number_of_tokens_for_each_sample))
    for i in range(len(end_idxs)-1):
        token_strings = tokens[end_idxs[i]:end_idxs[i+1]]
        weights = non_zero_values[end_idxs[i]:end_idxs[i+1]]
        output.append(dict(zip(token_strings, weights)))
    return output
    
# download the idf file from model hub. idf is used to give weights for query tokens
def get_tokenizer_idf(tokenizer):
    from huggingface_hub import hf_hub_download
    local_cached_path = hf_hub_download(repo_id="opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill", filename="idf.json")
    with open(local_cached_path) as f:
        idf = json.load(f)
    idf_vector = [0]*tokenizer.vocab_size
    for token,weight in idf.items():
        _id = tokenizer._convert_token_to_id_with_added_voc(token)
        idf_vector[_id]=weight
    return torch.tensor(idf_vector)

# load the model
model = AutoModelForMaskedLM.from_pretrained("opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill")
tokenizer = AutoTokenizer.from_pretrained("opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill")
idf = get_tokenizer_idf(tokenizer)

# set the special tokens and id_to_token transform for post-process
special_token_ids = [tokenizer.vocab[token] for token in tokenizer.special_tokens_map.values()]
get_sparse_vector.special_token_ids = special_token_ids
id_to_token = ["" for i in range(tokenizer.vocab_size)]
for token, _id in tokenizer.vocab.items():
    id_to_token[_id] = token
transform_sparse_vector_to_dict.id_to_token = id_to_token



query = "What's the weather in ny now?"
document = "Currently New York is rainy."

# encode the query
feature_query = tokenizer([query], padding=True, truncation=True, return_tensors='pt', return_token_type_ids=False)
input_ids = feature_query["input_ids"]
batch_size = input_ids.shape[0]
query_vector = torch.zeros(batch_size, tokenizer.vocab_size)
query_vector[torch.arange(batch_size).unsqueeze(-1), input_ids] = 1
query_sparse_vector = query_vector*idf

# encode the document
feature_document = tokenizer([document], padding=True, truncation=True, return_tensors='pt', return_token_type_ids=False)
output = model(**feature_document)[0]
document_sparse_vector = get_sparse_vector(feature_document, output)


# get similarity score
sim_score = torch.matmul(query_sparse_vector[0],document_sparse_vector[0])
print(sim_score)   # tensor(11.1105, grad_fn=<DotBackward0>)


query_token_weight = transform_sparse_vector_to_dict(query_sparse_vector)[0]
document_query_token_weight = transform_sparse_vector_to_dict(document_sparse_vector)[0]
for token in sorted(query_token_weight, key=lambda x:query_token_weight[x], reverse=True):
    if token in document_query_token_weight:
        print("score in query: %.4f, score in document: %.4f, token: %s"%(query_token_weight[token],document_query_token_weight[token],token))
        

        
# result:
# score in query: 5.7729, score in document: 0.8049, token: ny
# score in query: 4.5684, score in document: 0.9710, token: weather
# score in query: 3.5895, score in document: 0.4720, token: now
# score in query: 3.3313, score in document: 0.0286, token: ?
# score in query: 2.7699, score in document: 0.0787, token: what
# score in query: 0.4989, score in document: 0.0417, token: in

The above code sample shows an example of neural sparse search. Although there is no overlap token in original query and document, but this model performs a good match.

Detailed Search Relevance

ModelAverageTrec CovidNFCorpusNQHotpotQAFiQAArguAnaToucheDBPediaSCIDOCSFEVERClimate FEVERSciFactQuora
opensearch-neural-sparse-encoding-v10.5240.7710.3600.5530.6970.3760.5080.2780.4470.1640.8210.2630.7230.856
opensearch-neural-sparse-encoding-v2-distill0.5280.7750.3470.5610.6850.3740.5510.2780.4350.1730.8490.2490.7220.863
opensearch-neural-sparse-encoding-doc-v10.4900.7070.3520.5210.6770.3440.4610.2940.4120.1540.7430.2020.7160.788
opensearch-neural-sparse-encoding-doc-v2-distill0.5040.6900.3430.5280.6750.3570.4960.2870.4180.1660.8180.2240.7150.841
opensearch-neural-sparse-encoding-doc-v2-mini0.4970.7090.3360.5100.6660.3380.4800.2850.4070.1640.8120.2160.6990.837
opensearch-neural-sparse-encoding-doc-v3-distill0.5170.7240.3450.5440.6940.3560.5200.2940.4240.1630.8450.2390.7080.863
opensearch-neural-sparse-encoding-doc-v3-gte0.5460.7340.3600.5820.7160.4070.5200.3890.4550.1670.8600.3120.7250.873

License

This project is licensed under the Apache v2.0 License.

Copyright

Copyright OpenSearch Contributors. See NOTICE for details.

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

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

GPU в ailist

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

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

Первый модуль sentence-transformers (sentence_transformers.models.Router) рантайм не поддерживает.

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

0 моделей