State-of-the-Art Embeddings, Retrieval, and Reranking
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 8 天前 | ||
| 3 天前 | ||
| 1 天前 | ||
| 1 天前 | ||
| 19 天前 | ||
| 1 天前 | ||
| 5 个月前 | ||
| 3 个月前 | ||
| 3 个月前 | ||
| 4 年前 | ||
| 3 个月前 | ||
| 10 个月前 | ||
| 20 天前 | ||
| 1 个月前 | ||
| 12 天前 | ||
| 4 天前 |
Sentence Transformers:嵌入、检索与重排序
本框架提供了一种便捷的方法,用于计算嵌入,以支持访问、使用和训练最先进嵌入模型与重排序器模型。它可以使用 Sentence Transformer 模型计算嵌入(快速入门),使用 Cross-Encoder(又称重排序器)模型计算相似度得分(快速入门),使用 Sparse Encoder 模型生成稀疏嵌入(快速入门),或使用 Multi-Vector Encoder 模型计算 token 级嵌入,以支持 ColBERT 风格的晚期交互检索(快速入门)。这开启了广泛的应用场景,包括 语义搜索、语义文本相似度 和 释义挖掘。
🤗 Hugging Face 上提供了超过 15,000 个预训练 Sentence Transformers 模型,可供广泛选择和立即使用,其中包括 大规模文本嵌入基准(MTEB)排行榜 上的许多最先进模型。此外,使用 Sentence Transformers 可以轻松训练或微调你自己的 嵌入模型、重排序器模型、稀疏编码器模型 或 多向量编码器模型,从而针对特定用例创建自定义模型。
如需查阅完整文档,请访问 www.SBERT.net。
安装
我们推荐 Python 3.10+、PyTorch 2.2+ 以及 transformers v5.0+。
pip install -U sentence-transformers
请参见文档中的 安装,了解 uv、conda、源码安装和可编辑安装、CUDA 配置,以及可选依赖([image]、[audio]、[video]、[train]、[onnx]、[openvino]、[dev])。
快速入门
请参见我们文档中的 快速入门。
嵌入模型
首先下载一个预训练嵌入模型,即 Sentence Transformer 模型。
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
然后,向模型提供一些文本。
sentences = [
"The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium.",
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# => (3, 384)
至此即可。我们现在已经得到了包含嵌入向量的 numpy 数组,每个文本对应一个。我们可以用它们来计算相似度。
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.6660, 0.1046],
# [0.6660, 1.0000, 0.1411],
# [0.1046, 0.1411, 1.0000]])
Reranker 模型
首先下载一个预训练的 Reranker,又称 Cross Encoder 模型。
from sentence_transformers import CrossEncoder
# 1. Load a pretrained CrossEncoder model
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
然后,向模型提供一些文本。
# The texts for which to predict similarity scores
query = "How many people live in Berlin?"
passages = [
"Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.",
"Berlin has a yearly total of about 135 million day visitors, making it one of the most-visited cities in the European Union.",
"In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs.",
]
# 2a. predict scores for pairs of texts
scores = model.predict([(query, passage) for passage in passages])
print(scores)
# => [8.607139 5.506266 6.352977]
一切就绪。你还可以使用 model.rank 来避免手动执行重排序:
# 2b. Rank a list of passages for a query
ranks = model.rank(query, passages, return_documents=True)
print("Query:", query)
for rank in ranks:
print(f"- #{rank['corpus_id']} ({rank['score']:.2f}): {rank['text']}")
"""
Query: How many people live in Berlin?
- #0 (8.61): Berlin had a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.
- #2 (6.35): In 2013 around 600,000 Berliners were registered in one of the more than 2,300 sport and fitness clubs.
- #1 (5.51): Berlin has a yearly total of about 135 million day visitors, making it one of the most-visited cities in the European Union.
"""
Sparse Encoder 模型
首先下载一个预训练的稀疏嵌入模型,也称为 Sparse Encoder 模型。
from sentence_transformers import SparseEncoder
# 1. Load a pretrained SparseEncoder model
model = SparseEncoder("naver/splade-cocondenser-ensembledistil")
# The sentences to encode
sentences = [
"The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium.",
]
# 2. Calculate sparse embeddings by calling model.encode()
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 30522] - sparse representation with vocabulary size dimensions
# 3. Calculate the embedding similarities
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[ 35.629, 9.154, 0.098],
# [ 9.154, 27.478, 0.019],
# [ 0.098, 0.019, 29.553]])
# 4. Check sparsity stats
stats = SparseEncoder.sparsity(embeddings)
print(f"Sparsity: {stats['sparsity_ratio']:.2%}")
# Sparsity: 99.84%
多向量编码器模型
首先,请下载一个预训练的多向量模型,也称为晚期交互(ColBERT 风格)模型。
from sentence_transformers import MultiVectorEncoder
# 1. Load a pretrained MultiVectorEncoder model
model = MultiVectorEncoder("lightonai/GTE-ModernColBERT-v1")
queries = ["What is the capital of France?"]
documents = [
"Paris is the capital of France.",
"Berlin is the capital of Germany.",
]
# 2. Encode queries and documents into sequences of token-level embeddings
query_embeddings = model.encode_query(queries)
document_embeddings = model.encode_document(documents)
print(query_embeddings[0].shape, document_embeddings[0].shape)
# (10, 128) (9, 128) # one 128-dimensional vector per token
# 3. Score them with late interaction (MaxSim)
scores = model.similarity(query_embeddings, document_embeddings)
print(scores)
# tensor([[9.6037, 9.4055]])
预训练模型
我们提供适用于 100 多种语言的大量预训练模型。部分模型为通用模型,其余模型可针对特定使用场景生成嵌入。
训练
提示: 正在使用 AI 编码智能体(Claude Code、Codex、Cursor、Gemini CLI 等)?请通过
hf skills add train-sentence-transformers [--claude] [--global]安装train-sentence-transformersHugging Face Agent Skill,并让您的智能体使用您的数据微调模型。
该框架支持您微调自己的句子嵌入方法,从而获得面向特定任务的句子嵌入。您可以从多种选项中进行选择,以为您的特定任务获得理想的句子嵌入。
- 嵌入模型
- 重排序模型
- 稀疏嵌入模型
- 多向量(晚期交互)模型
不同训练类型的部分亮点如下:
- 支持多种 Transformer 网络,包括 BERT、RoBERTa、XLM-R、DistilBERT、Electra、BART 等
- 多语言与多任务学习
- 训练过程中进行评估,以寻找最优模型
- 嵌入模型提供 20 多种损失函数,重排序模型提供 10 多种损失函数,稀疏嵌入模型提供 10 多种损失函数,可让您针对语义搜索、释义挖掘、语义相似度比较、聚类、三元组损失、对比损失等对模型进行专门调优。
配套博客文章
以下 Hugging Face 博客文章以叙述式讲解和完整训练示例,补充本文档:
训练指南:
- 训练与微调嵌入模型:双编码器嵌入模型的端到端训练。
- 训练与微调重排模型:为检索与重排流水线中的第二阶段训练 Cross Encoder 模型。
- 训练与微调稀疏嵌入模型:训练 SPLADE 及其他稀疏编码器。
多模态:
- 多模态嵌入与重排模型:通过统一 API 使用文本、图像、音频和视频模型。
- 训练与微调多模态嵌入与重排模型:训练多模态模型,并附视觉文档检索实战讲解。
效率优化技术:
- Matryoshka 嵌入模型入门:可变维度嵌入,截断时质量损失极小。
- 训练速度提升 400 倍的静态嵌入模型:无需注意力机制、对 CPU 更友好的嵌入模型。
- 二值与标量嵌入量化,实现更快、更低成本的检索:嵌入向量的训练后压缩。
应用示例
你可以将此框架用于:
-
计算句子嵌入
-
语义文本相似度
-
语义检索
-
检索与重排
以及更多应用场景。
所有示例请参见 examples/sentence_transformer/applications。
开发环境配置
将仓库(或其 fork)克隆到本地后,在虚拟环境中运行:
python -m pip install -e ".[dev]"
pre-commit install
要测试你的更改,请运行:
pytest
引用与作者
如果你发现本仓库对你有帮助,欢迎引用我们的论文 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 = "https://arxiv.org/abs/1908.10084",
}
如果你使用了其中任一多语言模型,欢迎引用我们的论文 Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation:
@inproceedings{reimers-2020-multilingual-sentence-bert,
title = "Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2020",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/2004.09813",
}
请查看 Publications,了解集成到 SentenceTransformers 中的各项论文。
维护者
维护者:Tom Aarsen,🤗 Hugging Face
如果发现有故障(正常情况下不应出现),或你还有其他问题,请随时提交 issue。
该项目最初由 TU Darmstadt 的 Ubiquitous Knowledge Processing (UKP) Lab 开发。我们衷心感谢他们的奠基性工作以及对这一领域的持续贡献。
本仓库包含实验性软件,发布目的仅为提供相关论文的补充背景信息。