说明文档
msmarco-distilbert-dot-v5
这是一个 sentence-transformers 模型:它将句子和段落映射到 768 维的密集向量空间,专为语义搜索设计。它基于 MS MARCO 数据集 的 50 万个(查询,答案)对进行训练。关于语义搜索的介绍,请查看:SBERT.net - 语义搜索
使用方法(Sentence-Transformers)
使用 sentence-transformers 可以轻松使用此模型:
pip install -U sentence-transformers
然后你可以这样使用模型:
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-distilbert-dot-v5')
#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
print("Query:", query)
for doc, score in doc_score_pairs:
print(score, doc)
使用方法(HuggingFace Transformers)
如果没有 sentence-transformers,你可以这样使用模型:首先将输入通过 transformer 模型,然后需要在上下文词嵌入之上应用正确的池化操作。
from transformers import AutoTokenizer, AutoModel
import torch
#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output.last_hidden_state
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)
#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 = mean_pooling(model_output, encoded_input['attention_mask'])
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-distilbert-dot-v5")
model = AutoModel.from_pretrained("sentence-transformers/msmarco-distilbert-dot-v5")
#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
print("Query:", query)
for doc, score in doc_score_pairs:
print(score, doc)
技术细节
以下是有关此模型使用方式的一些技术细节:
| 设置 | 值 |
|---|---|
| 维度 | 768 |
| 最大序列长度 | 512 |
| 产生归一化嵌入 | 否 |
| 池化方法 | Mean pooling |
| 适用的评分函数 | dot-product(例如 util.dot_score) |
训练
有关使用的训练脚本,请参阅本仓库中的 train_script.py。
该模型使用以下参数进行训练:
DataLoader:
torch.utils.data.dataloader.DataLoader,长度为 7858,参数如下:
{'batch_size': 64, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}
损失函数:
sentence_transformers.losses.MarginMSELoss.MarginMSELoss
fit() 方法的参数:
{
"callback": null,
"epochs": 30,
"evaluation_steps": 0,
"evaluator": "NoneType",
"max_grad_norm": 1,
"optimizer_class": "<class 'transformers.optimization.AdamW'>",
"optimizer_params": {
"lr": 1e-05
},
"scheduler": "WarmupLinear",
"steps_per_epoch": null,
"warmup_steps": 10000,
"weight_decay": 0.01
}
完整模型架构
SentenceTransformer(
(0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: DistilBertModel
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
)
引用与作者
此模型由 sentence-transformers 训练。
如果您觉得此模型有帮助,请引用我们的论文 Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks:
@inproceedings{reimers-2019-sentence-bert,
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2019",
publisher = "Association for Computational Linguistics",
url = "http://arxiv.org/abs/1908.10084",
}
许可证
此模型基于 Apache 2 许可证发布。但请注意,此模型基于 MS MARCO 数据集进行训练,该数据集有自己的许可证限制:MS MARCO - Terms and Conditions。
sentence-transformers/msmarco-distilbert-dot-v5
作者 sentence-transformers
创建时间: 2022-03-02 23:29:05+00:00
更新时间: 2025-03-06 13:21:10+00:00
在 Hugging Face 上查看