sentence-transformers:基于 Sentence Transformer 的文本嵌入与检索框架项目

State-of-the-Art Embeddings, Retrieval, and Reranking

分支57Tags72
文件最后提交记录最后更新时间
8 天前
3 天前
1 天前
1 天前
19 天前
1 天前
5 个月前
3 个月前
3 个月前
4 年前
3 个月前
10 个月前
20 天前
1 个月前
12 天前
4 天前

HF 模型 GitHub - 许可证 PyPI - Python 版本 PyPI - 包版本 文档 - GitHub.io

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-transformers Hugging Face Agent Skill,并让您的智能体使用您的数据微调模型。

该框架支持您微调自己的句子嵌入方法,从而获得面向特定任务的句子嵌入。您可以从多种选项中进行选择,以为您的特定任务获得理想的句子嵌入。

不同训练类型的部分亮点如下:

  • 支持多种 Transformer 网络,包括 BERT、RoBERTa、XLM-R、DistilBERT、Electra、BART 等
  • 多语言与多任务学习
  • 训练过程中进行评估,以寻找最优模型
  • 嵌入模型提供 20 多种损失函数,重排序模型提供 10 多种损失函数,稀疏嵌入模型提供 10 多种损失函数,可让您针对语义搜索、释义挖掘、语义相似度比较、聚类、三元组损失、对比损失等对模型进行专门调优。

配套博客文章

以下 Hugging Face 博客文章以叙述式讲解和完整训练示例,补充本文档:

训练指南:

多模态:

效率优化技术:

应用示例

你可以将此框架用于:

以及更多应用场景。

所有示例请参见 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 开发。我们衷心感谢他们的奠基性工作以及对这一领域的持续贡献。

本仓库包含实验性软件,发布目的仅为提供相关论文的补充背景信息。

项目介绍

多语言句子与图像嵌入技术融合BERT模型【此简介由AI生成】

定制我的领域
15319.08 K2.88 K访问 GitHub