Logo

开始

  • 安装
    • 使用 pip 安装
    • 使用 Conda 安装
    • 从源代码安装
    • 可编辑安装
    • 安装支持 CUDA 的 PyTorch
  • 快速开始
    • Sentence Transformer
    • Cross Encoder
    • Sparse Encoder
    • 后续步骤
  • 迁移指南
    • 从 v4.x 迁移到 v5.x
      • model.encode 的迁移
      • 从 Asym 到 Router 的迁移
      • 高级用法的迁移
    • 从 v3.x 迁移到 v4.x
      • CrossEncoder 初始化和方法参数的迁移
      • CrossEncoder.fit 特定参数的迁移
      • CrossEncoder 评估器的迁移
    • 从 v2.x 迁移到 v3.x
      • SentenceTransformer.fit 特定参数的迁移
      • SentenceTransformer.fit 中使用的自定义 Dataset 和 DataLoader 的迁移

Sentence Transformer

  • 用法
    • 计算嵌入
      • 初始化 Sentence Transformer 模型
      • 计算嵌入
      • 提示模板
      • 输入序列长度
      • 多进程/多 GPU 编码
    • 语义文本相似度
      • 相似度计算
    • 语义搜索
      • 背景
      • 对称语义搜索 vs. 非对称语义搜索
      • 手动实现
      • 优化实现
      • 速度优化
      • Elasticsearch
      • OpenSearch
      • 近似最近邻
      • 检索与重排序
      • 示例
    • 检索与重排序
      • 检索与重排序流程
      • 检索:双编码器
      • 重排序器:交叉编码器
      • 示例脚本
      • 预训练双编码器(检索)
      • 预训练交叉编码器(重排序器)
    • 聚类
      • k-均值
      • 层次聚类
      • 快速聚类
      • 主题建模
    • 释义挖掘
      • paraphrase_mining()
    • 翻译句子挖掘
      • 基于裕度的挖掘
      • 示例
    • 图像搜索
      • 安装
      • 用法
      • 示例
    • 嵌入量化
      • 二进制量化
      • 标量(int8)量化
      • 额外扩展
      • 演示
      • 亲自尝试
    • 创建自定义模型
      • Sentence Transformer 模型的结构
      • 从 Transformers 模型构建 Sentence Transformer 模型
      • 高级:自定义模块
    • 加速推理
      • PyTorch
      • ONNX
      • OpenVINO
      • 基准测试
  • 预训练模型
    • 原始模型
    • 语义搜索模型
      • 多问答模型
      • MSMARCO 段落模型
    • 多语言模型
      • 语义相似度模型
      • 双语文本挖掘
    • 图像与文本模型
    • INSTRUCTOR 模型
    • 科学相似度模型
  • 训练概述
    • 为什么要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器
      • 回调
    • 多数据集训练
    • 已弃用的训练
    • 最佳基础嵌入模型
    • 与 CrossEncoder 训练的比较
  • 数据集概述
    • Hugging Face Hub 上的数据集
    • 现有数据集
  • 损失概述
    • 损失表
    • 损失修正器
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 语义文本相似度
      • 训练数据
      • 损失函数
    • 自然语言推理
      • 数据
      • SoftmaxLoss
      • MultipleNegativesRankingLoss
    • 释义数据
      • 预训练模型
    • Quora 重复问题
      • 训练
      • MultipleNegativesRankingLoss
      • 预训练模型
    • MS MARCO
      • 双编码器
    • 俄罗斯套娃嵌入
      • 用例
      • 结果
      • 训练
      • 推理
      • 代码示例
    • 自适应层
      • 用例
      • 结果
      • 训练
      • 推理
      • 代码示例
    • 多语言模型
      • 扩展您自己的模型
      • 训练
      • 数据集
      • 训练数据来源
      • 评估
      • 可用预训练模型
      • 用法
      • 性能
      • 引用
    • 模型蒸馏
      • 知识蒸馏
      • 速度-性能权衡
      • 降维
      • 量化
    • 增强型 SBERT
      • 动机
      • 扩展到您自己的数据集
      • 方法论
      • 场景 1:有限或小型标注数据集(少量标注句子对)
      • 场景 2:无标注数据集(仅有未标注句子对)
      • 训练
      • 引用
    • 使用提示进行训练
      • 什么是提示?
      • 为什么要使用提示进行训练?
      • 如何使用提示进行训练?
    • 使用 PEFT 适配器进行训练
      • 兼容性方法
      • 添加新适配器
      • 加载预训练适配器
      • 训练脚本
    • 无监督学习
      • TSDAE
      • SimCSE
      • CT
      • CT(批内负采样)
      • 掩码语言模型 (MLM)
      • GenQ
      • GPL
      • 性能比较
    • 领域适应
      • 领域适应 vs. 无监督学习
      • 自适应预训练
      • GPL: 生成式伪标签
    • 超参数优化
      • HPO 组件
      • 整合所有组件
      • 示例脚本
    • 分布式训练
      • 比较
      • FSDP

Cross Encoder

  • 用法
    • 交叉编码器 vs. 双编码器
      • 交叉编码器 vs. 双编码器
      • 何时使用交叉编码器/双编码器?
      • 交叉编码器用法
      • 结合双编码器和交叉编码器
      • 训练交叉编码器
    • 检索与重排序
      • 检索与重排序流程
      • 检索:双编码器
      • 重排序器:交叉编码器
      • 示例脚本
      • 预训练双编码器(检索)
      • 预训练交叉编码器(重排序器)
    • 加速推理
      • PyTorch
      • ONNX
      • OpenVINO
      • 基准测试
  • 预训练模型
    • MS MARCO
    • SQuAD (QNLI)
    • STSbenchmark
    • Quora 重复问题
    • NLI
    • 社区模型
  • 训练概述
    • 为什么要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
      • 难负例挖掘
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器
      • 回调
    • 多数据集训练
    • 训练技巧
    • 已弃用的训练
    • 与 SentenceTransformer 训练的比较
  • 损失概述
    • 损失表
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 语义文本相似度
      • 训练数据
      • 损失函数
      • 推理
    • 自然语言推理
      • 数据
      • CrossEntropyLoss
      • 推理
    • Quora 重复问题
      • 训练
      • 推理
    • MS MARCO
      • Cross Encoder
      • 训练脚本
      • 推理
    • 重排序器
      • BinaryCrossEntropyLoss
      • CachedMultipleNegativesRankingLoss
      • 推理
    • 模型蒸馏
      • 交叉编码器知识蒸馏
      • 推理
    • 分布式训练
      • 比较
      • FSDP

Sparse Encoder

  • 用法
    • 计算稀疏嵌入
      • 初始化稀疏编码器模型
      • 计算嵌入
      • 输入序列长度
      • 控制稀疏度
      • SPLADE 模型的解释性
      • 多进程/多 GPU 编码
    • 语义文本相似度
      • 相似度计算
    • 语义搜索
      • 手动搜索
      • 向量数据库搜索
      • Qdrant 集成
      • OpenSearch 集成
      • Seismic 集成
      • Elasticsearch 集成
    • 检索与重排序
      • 概述
      • 交互式演示:简单维基百科搜索
      • 全面评估:混合搜索流程
      • 预训练模型
    • 稀疏编码器评估
      • 检索评估示例
  • 预训练模型
    • 核心 SPLADE 模型
    • 无推理 SPLADE 模型
    • 模型集合
  • 训练概述
    • 为什么要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器
      • 回调
    • 多数据集训练
    • 训练技巧
  • 数据集概述
    • Hugging Face Hub 上的数据集
    • 现有数据集
  • 损失概述
    • 稀疏专用损失函数
      • SPLADE 损失
      • CSR 损失
    • 损失表
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 模型蒸馏
      • MarginMSE
    • MS MARCO
      • SparseMultipleNegativesRankingLoss
    • 语义文本相似度
      • 训练数据
      • 损失函数
    • 自然语言推理
      • 数据
      • SpladeLoss
    • Quora 重复问题
      • 训练
    • 信息检索
      • SparseMultipleNegativesRankingLoss (MNRL)
      • 推理与评估
    • 分布式训练
      • 比较
      • FSDP

包引用

  • Sentence Transformer
    • SentenceTransformer
      • SentenceTransformer
      • SentenceTransformerModelCardData
      • SimilarityFunction
    • 训练器
      • SentenceTransformerTrainer
    • 训练参数
      • SentenceTransformerTrainingArguments
    • 损失
      • BatchAllTripletLoss
      • BatchHardSoftMarginTripletLoss
      • BatchHardTripletLoss
      • BatchSemiHardTripletLoss
      • ContrastiveLoss
      • OnlineContrastiveLoss
      • ContrastiveTensionLoss
      • ContrastiveTensionLossInBatchNegatives
      • CoSENTLoss
      • AnglELoss
      • CosineSimilarityLoss
      • DenoisingAutoEncoderLoss
      • GISTEmbedLoss
      • CachedGISTEmbedLoss
      • MSELoss
      • MarginMSELoss
      • MatryoshkaLoss
      • Matryoshka2dLoss
      • AdaptiveLayerLoss
      • MegaBatchMarginLoss
      • MultipleNegativesRankingLoss
      • CachedMultipleNegativesRankingLoss
      • MultipleNegativesSymmetricRankingLoss
      • CachedMultipleNegativesSymmetricRankingLoss
      • SoftmaxLoss
      • TripletLoss
      • DistillKLDivLoss
    • 采样器
      • 批量采样器
      • 多数据集批量采样器
    • 评估
      • 二分类评估器
      • 嵌入相似度评估器
      • 信息检索评估器
      • NanoBEIREvaluator
      • MSEEvaluator
      • 释义挖掘评估器
      • 重排序评估器
      • 句子评估器
      • 序列评估器
      • 翻译评估器
      • 三元组评估器
    • 数据集
      • 并行句子数据集
      • 句子标签数据集
      • 去噪自编码器数据集
      • 无重复数据加载器
    • 模块
      • 主要模块
      • 其他模块
      • 基础模块
    • 量化
      • quantize_embeddings()
      • semantic_search_faiss()
      • semantic_search_usearch()
  • Cross Encoder
    • CrossEncoder
      • CrossEncoder
      • CrossEncoderModelCardData
    • 训练器
      • CrossEncoderTrainer
    • 训练参数
      • CrossEncoderTrainingArguments
    • 损失
      • BinaryCrossEntropyLoss
      • CrossEntropyLoss
      • LambdaLoss
      • ListMLELoss
      • PListMLELoss
      • ListNetLoss
      • MultipleNegativesRankingLoss
      • CachedMultipleNegativesRankingLoss
      • MSELoss
      • MarginMSELoss
      • RankNetLoss
    • 评估
      • CrossEncoderRerankingEvaluator
      • CrossEncoderNanoBEIREvaluator
      • CrossEncoderClassificationEvaluator
      • CrossEncoderCorrelationEvaluator
  • Sparse Encoder
    • SparseEncoder
      • SparseEncoder
      • SparseEncoderModelCardData
      • SimilarityFunction
    • 训练器
      • SparseEncoderTrainer
    • 训练参数
      • SparseEncoderTrainingArguments
    • 损失
      • SpladeLoss
      • FlopsLoss
      • CSRLoss
      • CSRReconstructionLoss
      • SparseMultipleNegativesRankingLoss
      • SparseMarginMSELoss
      • SparseDistillKLDivLoss
      • SparseTripletLoss
      • SparseCosineSimilarityLoss
      • SparseCoSENTLoss
      • SparseAnglELoss
      • SparseMSELoss
    • 采样器
      • 批量采样器
      • 多数据集批量采样器
    • 评估
      • 稀疏信息检索评估器
      • SparseNanoBEIREvaluator
      • 稀疏嵌入相似度评估器
      • 稀疏二分类评估器
      • 稀疏三元组评估器
      • 稀疏重排序评估器
      • 稀疏翻译评估器
      • 稀疏 MSE 评估器
      • 倒数排序融合评估器
    • 模块
      • SPLADE 池化
      • MLM Transformer
      • 稀疏自编码器
      • 稀疏静态嵌入
    • 回调
      • SpladeRegularizerWeightSchedulerCallback
    • 搜索引擎
      • semantic_search_elasticsearch()
      • semantic_search_opensearch()
      • semantic_search_qdrant()
      • semantic_search_seismic()
  • 工具 (util)
    • 辅助函数
      • community_detection()
      • http_get()
      • is_training_available()
      • mine_hard_negatives()
      • normalize_embeddings()
      • paraphrase_mining()
      • semantic_search()
      • truncate_embeddings()
    • 模型优化
      • export_dynamic_quantized_onnx_model()
      • export_optimized_onnx_model()
      • export_static_quantized_openvino_model()
    • 相似度指标
      • cos_sim()
      • dot_score()
      • euclidean_sim()
      • manhattan_sim()
      • pairwise_cos_sim()
      • pairwise_dot_score()
      • pairwise_euclidean_sim()
      • pairwise_manhattan_sim()
Sentence Transformers
  • 用法
  • 语义搜索
  • 在 GitHub 上编辑

语义搜索

语义搜索是指超越传统基于关键词搜索的技术。语义搜索不再仅仅依赖关键词的精确匹配,而是旨在理解查询和被搜索文档的含义和上下文。这使得即使关键词不完全匹配,也能获得更相关和准确的搜索结果。

稀疏嵌入是一种表示形式,其中大多数值均为零,只有少数维度包含非零(也称为活跃)值。这与密集嵌入形成对比,密集嵌入中所有维度通常都具有非零值。传统的稀疏嵌入解决方案通常基于词汇,这意味着它们依赖于术语或短语的精确匹配。然而,SPLADE 等现代稀疏编码器模型能够生成在捕获语义含义的同时保持稀疏性的嵌入。

只要搜索解决方案充分利用稀疏嵌入维度绝大多数为 0 的事实,这些嵌入就能实现极其高效的语义搜索。本页展示了一个示例,演示如何手动执行语义搜索,以及如何将 SparseEncoder 模型与流行的向量数据库/搜索系统集成。

如果您不熟悉语义搜索,请参阅Sentence Transformers > 语义搜索,以获取使用密集嵌入模型的更广泛解释。

手动搜索

使用稀疏编码器手动执行语义搜索非常简单,只需几个步骤:

  1. 加载 SparseEncoder 模型:从 Hugging Face Hub 或本地目录加载预训练的稀疏编码器模型。

  2. 编码语料库:使用模型将文档集(语料库)编码为稀疏嵌入。

  3. 编码查询:使用相同的模型将用户查询编码为稀疏嵌入。

  4. 计算相似度:使用合适的相似度函数(例如,余弦相似度、点积)计算查询嵌入与语料库嵌入之间的相似度。

  5. 检索结果:根据相似度分数对结果进行排序,并返回最相关的文档。

  6. 分析结果:可选地,分析结果以了解哪些标记对相似度分数贡献最大。

文档

  1. SparseEncoder

  2. SparseEncoder.encode_query

  3. SparseEncoder.encode_document

  4. util.semantic_search

  5. SparseEncoder.similarity

  6. naver/splade-cocondenser-ensembledistil

from sentence_transformers import SparseEncoder, util

# 1. Load a pretrained SparseEncoder model
model = SparseEncoder("naver/splade-cocondenser-ensembledistil")

# 2. Encode a corpus of texts using the SparseEncoder model
corpus = [
    "Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed.",
    "Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning.",
    "Neural networks are computing systems vaguely inspired by the biological neural networks that constitute animal brains.",
    "Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments.",
    "The James Webb Space Telescope is the largest optical telescope in space, designed to conduct infrared astronomy.",
    "SpaceX's Starship is designed to be a fully reusable transportation system capable of carrying humans to Mars and beyond.",
    "Global warming is the long-term heating of Earth's climate system observed since the pre-industrial period due to human activities.",
    "Renewable energy sources include solar, wind, hydro, and geothermal power that naturally replenish over time.",
    "Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground.",
]

# Use "convert_to_tensor=True" to keep the tensors on GPU (if available)
corpus_embeddings = model.encode_document(corpus, convert_to_tensor=True)

# 3. Encode the user queries using the same SparseEncoder model
queries = [
    "How do artificial neural networks work?",
    "What technology is used for modern space exploration?",
    "How can we address climate change challenges?",
]
query_embeddings = model.encode_query(queries, convert_to_tensor=True)

# 4. Use the similarity function to compute the similarity scores between the query and corpus embeddings
top_k = min(5, len(corpus))  # Find at most 5 sentences of the corpus for each query sentence
results = util.semantic_search(query_embeddings, corpus_embeddings, top_k=top_k, score_function=model.similarity)

# 5. Sort the results and print the top 5 most similar sentences for each query
for query_id, query in enumerate(queries):
    pointwise_scores = model.intersection(query_embeddings[query_id], corpus_embeddings)

    print(f"Query: {query}")
    for res in results[query_id]:
        corpus_id, score = res.values()
        sentence = corpus[corpus_id]

        pointwise_score = model.decode(pointwise_scores[corpus_id], top_k=10)

        token_scores = ", ".join([f'("{token.strip()}", {value:.2f})' for token, value in pointwise_score])

        print(f"Score: {score:.4f} - Sentence: {sentence} - Top influential tokens: {token_scores}")
    print("")
切换以查看结果
"""
Query: How do artificial neural networks work?
Score: 16.9053 - Sentence: Neural networks are computing systems vaguely inspired by the biological neural networks that constitute animal brains. - Top influential tokens: ("neural", 5.71), ("networks", 3.24), ("network", 2.93), ("brain", 2.10), ("computer", 0.50), ("##uron", 0.32), ("artificial", 0.27), ("technology", 0.27), ("communication", 0.27), ("connection", 0.21)
Score: 13.6119 - Sentence: Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning. - Top influential tokens: ("artificial", 3.71), ("neural", 3.15), ("networks", 1.78), ("brain", 1.22), ("network", 1.12), ("ai", 1.07), ("machine", 0.39), ("robot", 0.20), ("technology", 0.20), ("algorithm", 0.18)
Score: 2.7373 - Sentence: Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed. - Top influential tokens: ("machine", 0.78), ("computer", 0.50), ("technology", 0.32), ("artificial", 0.22), ("robot", 0.21), ("ai", 0.20), ("process", 0.16), ("theory", 0.11), ("technique", 0.11), ("fuzzy", 0.06)
Score: 2.1430 - Sentence: Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground. - Top influential tokens: ("technology", 0.42), ("function", 0.41), ("mechanism", 0.21), ("sensor", 0.21), ("device", 0.18), ("process", 0.18), ("generator", 0.13), ("detection", 0.10), ("technique", 0.10), ("tracking", 0.05)
Score: 2.0195 - Sentence: Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments. - Top influential tokens: ("robot", 0.67), ("function", 0.34), ("technology", 0.29), ("device", 0.23), ("experiment", 0.20), ("machine", 0.10), ("artificial", 0.08), ("design", 0.04), ("useful", 0.03), ("they", 0.02)

Query: What technology is used for modern space exploration?
Score: 10.4748 - Sentence: SpaceX's Starship is designed to be a fully reusable transportation system capable of carrying humans to Mars and beyond. - Top influential tokens: ("space", 4.40), ("technology", 1.15), ("nasa", 1.06), ("mars", 0.63), ("exploration", 0.52), ("spacecraft", 0.44), ("robot", 0.32), ("rocket", 0.28), ("astronomy", 0.27), ("travel", 0.26)
Score: 9.3818 - Sentence: The James Webb Space Telescope is the largest optical telescope in space, designed to conduct infrared astronomy. - Top influential tokens: ("space", 3.89), ("nasa", 1.09), ("astronomy", 0.93), ("discovery", 0.48), ("instrument", 0.47), ("technology", 0.35), ("device", 0.26), ("spacecraft", 0.25), ("invented", 0.22), ("equipment", 0.22)
Score: 8.5147 - Sentence: Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments. - Top influential tokens: ("technology", 1.39), ("mars", 0.79), ("exploration", 0.78), ("robot", 0.67), ("used", 0.66), ("nasa", 0.52), ("spacecraft", 0.44), ("device", 0.39), ("explore", 0.38), ("travel", 0.25)
Score: 7.6993 - Sentence: Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground. - Top influential tokens: ("technology", 1.99), ("tech", 1.76), ("technologies", 1.74), ("equipment", 0.32), ("device", 0.31), ("technological", 0.28), ("mining", 0.22), ("sensor", 0.19), ("tool", 0.18), ("software", 0.11)
Score: 2.5526 - Sentence: Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed. - Top influential tokens: ("technology", 1.52), ("machine", 0.27), ("robot", 0.21), ("computer", 0.18), ("engineering", 0.12), ("technique", 0.11), ("science", 0.05), ("technological", 0.05), ("techniques", 0.02), ("innovation", 0.01)

Query: How can we address climate change challenges?
Score: 9.5587 - Sentence: Global warming is the long-term heating of Earth's climate system observed since the pre-industrial period due to human activities. - Top influential tokens: ("climate", 3.21), ("warming", 2.87), ("weather", 1.58), ("change", 0.46), ("global", 0.41), ("environmental", 0.39), ("storm", 0.19), ("pollution", 0.15), ("environment", 0.11), ("adaptation", 0.08)
Score: 1.3191 - Sentence: Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground. - Top influential tokens: ("warming", 0.39), ("pollution", 0.34), ("environmental", 0.15), ("goal", 0.12), ("strategy", 0.07), ("monitoring", 0.07), ("protection", 0.06), ("greenhouse", 0.05), ("safety", 0.02), ("escape", 0.01)
Score: 1.0774 - Sentence: Renewable energy sources include solar, wind, hydro, and geothermal power that naturally replenish over time. - Top influential tokens: ("conservation", 0.39), ("sustainability", 0.18), ("environmental", 0.18), ("sustainable", 0.13), ("agriculture", 0.13), ("alternative", 0.07), ("recycling", 0.00)
Score: 0.2401 - Sentence: Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed. - Top influential tokens: ("strategy", 0.10), ("success", 0.06), ("foster", 0.04), ("engineering", 0.03), ("innovation", 0.00), ("research", 0.00)
Score: 0.1516 - Sentence: Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning. - Top influential tokens: ("strategy", 0.09), ("foster", 0.04), ("research", 0.01), ("approach", 0.01), ("engineering", 0.01)
"""

向量数据库搜索

此外,一些向量数据库和搜索引擎也可用于使用稀疏编码器执行语义搜索。这些系统旨在高效处理大规模向量数据并快速检索相关文档。它们可以利用嵌入的稀疏性来优化存储和搜索操作。

整体结构与手动搜索类似,但向量数据库负责处理文档的索引和检索。步骤大致如下:

  1. 编码语料库:加载您的数据并使用预训练的稀疏编码器对文档进行编码。

  2. 索引:文档及其稀疏嵌入在向量数据库中进行索引。

  3. 编码查询:用户查询使用相同的稀疏编码器进行编码。

  4. 检索:向量数据库执行相似度搜索以查找最相关的文档。

  5. 结果:搜索结果连同其相似度分数和文档内容一并返回。

稀疏向量用于搜索的优点是:

  • 效率:稀疏向量(其中大多数值为零)的存储和搜索效率高于密集向量。

  • 可解释性:稀疏嵌入中的非零维度通常对应于特定标记,使您能够理解哪些标记对相似度分数有贡献。

  • 精确匹配:稀疏向量可以保留在密集嵌入中可能丢失的精确术语匹配信号。

Qdrant 集成

本示例演示如何设置 Qdrant 进行稀疏向量搜索,展示了如何使用稀疏编码器高效编码和索引文档、使用稀疏向量构建搜索查询,并提供交互式查询界面。请参阅 semantic_search_qdrant.py 或以下内容:

先决条件:

  • Qdrant 在本地运行(或可访问),更多详细信息请参阅 Qdrant 快速入门。

  • 已安装 Python Qdrant 客户端

    pip install qdrant-client
    

文档

  1. SparseEncoder

  2. SparseEncoder.encode_query

  3. SparseEncoder.encode_document

  4. semantic_search_qdrant

  5. naver/splade-cocondenser-ensembledistil

  6. sentence-transformers/natural-questions

import time

from datasets import load_dataset
from sentence_transformers import SparseEncoder
from sentence_transformers.sparse_encoder.search_engines import semantic_search_qdrant

# 1. Load the natural-questions dataset with 100K answers
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
num_docs = 10_000
corpus = dataset["answer"][:num_docs]

# 2. Come up with some queries
queries = dataset["query"][:2]

# 3. Load the model
sparse_model = SparseEncoder("naver/splade-cocondenser-ensembledistil")

# 4. Encode the corpus
corpus_embeddings = sparse_model.encode_document(
    corpus, convert_to_sparse_tensor=True, batch_size=16, show_progress_bar=True
)

# Initially, we don't have a qdrant index yet
corpus_index = None
while True:
    # 5. Encode the queries using the full precision
    start_time = time.time()
    query_embeddings = sparse_model.encode_query(queries, convert_to_sparse_tensor=True)
    print(f"Encoding time: {time.time() - start_time:.6f} seconds")

    # 6. Perform semantic search using qdrant
    results, search_time, corpus_index = semantic_search_qdrant(
        query_embeddings,
        corpus_index=corpus_index,
        corpus_embeddings=corpus_embeddings if corpus_index is None else None,
        top_k=5,
        output_index=True,
    )

    # 7. Output the results
    print(f"Search time: {search_time:.6f} seconds")
    for query, result in zip(queries, results):
        print(f"Query: {query}")
        for entry in result:
            print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}, corpus_id: {entry['corpus_id']}")
        print("")

    # 8. Prompt for more queries
    queries = [input("Please enter a question: ")]

OpenSearch 集成

本示例演示如何设置 OpenSearch 进行稀疏向量搜索,展示了如何使用稀疏编码器高效编码和索引文档、使用稀疏向量构建搜索查询,并提供交互式查询界面。请参阅 semantic_search_opensearch.py 或以下内容:

先决条件:

  • OpenSearch 在本地运行(或可访问),更多详细信息请参阅 本地 OpenSearch。

  • 此外,您需要安装 Python OpenSearch 客户端:https://docs.opensearch.org/docs/latest/clients/python-low-level/,例如:

      pip install opensearch-py
    
  • 此脚本是为 opensearch v2.15.0+ 创建的。

文档

  1. SparseEncoder

  2. SparseEncoder.encode_query

  3. SparseEncoder.encode_document

  4. semantic_search_opensearch

  5. opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill

  6. sentence-transformers/natural-questions

import time

from datasets import load_dataset

from sentence_transformers import SparseEncoder
from sentence_transformers.models import Router
from sentence_transformers.sparse_encoder.models import MLMTransformer, SparseStaticEmbedding, SpladePooling
from sentence_transformers.sparse_encoder.search_engines import semantic_search_opensearch

# 1. Load the natural-questions dataset with 100K answers
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
num_docs = 10_000
corpus = dataset["answer"][:num_docs]
print(f"Finish loading data. Corpus size: {len(corpus)}")

# 2. Come up with some queries
queries = dataset["query"][:2]

# 3. Load the model
model_id = "opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill"
doc_encoder = MLMTransformer(model_id)
router = Router.for_query_document(
    query_modules=[
        SparseStaticEmbedding.from_json(
            model_id,
            tokenizer=doc_encoder.tokenizer,
            frozen=True,
        ),
    ],
    document_modules=[
        doc_encoder,
        SpladePooling("max", activation_function="log1p_relu"),
    ],
)

sparse_model = SparseEncoder(modules=[router], similarity_fn_name="dot")

print("Start encoding corpus...")
start_time = time.time()
# 4. Encode the corpus
corpus_embeddings = sparse_model.encode_document(
    corpus, convert_to_sparse_tensor=True, batch_size=32, show_progress_bar=True
)
corpus_embeddings_decoded = sparse_model.decode(corpus_embeddings)
print(f"Corpus encoding time: {time.time() - start_time:.6f} seconds")

corpus_index = None
while True:
    # 5. Encode the queries using inference-free mode
    start_time = time.time()
    query_embeddings = sparse_model.encode_query(queries, convert_to_sparse_tensor=True)
    query_embeddings_decoded = sparse_model.decode(query_embeddings)
    print(f"Query encoding time: {time.time() - start_time:.6f} seconds")

    # 6. Perform semantic search using OpenSearch
    results, search_time, corpus_index = semantic_search_opensearch(
        query_embeddings_decoded,
        corpus_embeddings_decoded=corpus_embeddings_decoded if corpus_index is None else None,
        corpus_index=corpus_index,
        top_k=5,
        output_index=True,
    )

    # 7. Output the results
    print(f"Search time: {search_time:.6f} seconds")
    for query, result in zip(queries, results):
        print(f"Query: {query}")
        for entry in result:
            print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}, corpus_id: {entry['corpus_id']}")
        print("")

    # 8. Prompt for more queries
    queries = [input("Please enter a question: ")]

Seismic 集成

本示例演示如何使用 Seismic 进行性能极高的稀疏向量搜索。它不需要运行单独的客户端,而是直接在内存中执行搜索。Seismic 库在 Bruch 等人 (2024) 的论文中提出,其中显示其性能比常见的倒排文件(IVF)方法高出一个数量级。有关构建 Seismic 索引的更多信息,请查阅 Seismic 指南。请参阅 semantic_search_seismic.py 或以下内容:

先决条件:

  • 已安装 Seismic Python 包

    pip install pyseismic-lsr
    

文档

  1. SparseEncoder

  2. SparseEncoder.encode_query

  3. SparseEncoder.encode_document

  4. semantic_search_seismic

  5. naver/splade-cocondenser-ensembledistil

  6. sentence-transformers/natural-questions

import time

from datasets import load_dataset

from sentence_transformers import SparseEncoder
from sentence_transformers.sparse_encoder.search_engines import semantic_search_seismic

# 1. Load the natural-questions dataset with 100K answers
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
num_docs = 10_000
corpus = dataset["answer"][:num_docs]

# 2. Come up with some queries
queries = dataset["query"][:2]

# 3. Load the model
sparse_model = SparseEncoder("naver/splade-cocondenser-ensembledistil")

# 4. Encode the corpus
print("Start encoding corpus...")
start_time = time.time()
corpus_embeddings = sparse_model.encode_document(
    corpus, convert_to_sparse_tensor=True, batch_size=16, show_progress_bar=True
)
corpus_embeddings_decoded = sparse_model.decode(corpus_embeddings)
print(f"Corpus encoding time: {time.time() - start_time:.6f} seconds")

corpus_index = None
while True:
    # 5. Encode the queries using the full precision
    start_time = time.time()
    query_embeddings = sparse_model.encode_query(queries, convert_to_sparse_tensor=True)
    query_embeddings_decoded = sparse_model.decode(query_embeddings)
    print(f"Encoding time: {time.time() - start_time:.6f} seconds")

    # 6. Perform semantic search using Seismic
    results, search_time, corpus_index = semantic_search_seismic(
        query_embeddings_decoded,
        corpus_embeddings_decoded=corpus_embeddings_decoded if corpus_index is None else None,
        corpus_index=corpus_index,
        top_k=5,
        output_index=True,
    )

    # 7. Output the results
    print(f"Search time: {search_time:.6f} seconds")
    for query, result in zip(queries, results):
        print(f"Query: {query}")
        for entry in result:
            print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}, corpus_id: {entry['corpus_id']}")
        print("")

    # 8. Prompt for more queries
    queries = [input("Please enter a question: ")]

Elasticsearch 集成

本示例演示如何设置 Elasticsearch 进行稀疏向量搜索,展示了如何使用稀疏编码器高效编码和索引文档、使用稀疏向量构建搜索查询,并提供交互式查询界面。请参阅 semantic_search_elasticsearch.py 或以下内容:

先决条件:

  • Elasticsearch 在本地运行(或可访问),更多详细信息请参阅 本地 Elasticsearch。

  • 已安装 Python Elasticsearch 客户端

    pip install elasticsearch
    

文档

  1. SparseEncoder

  2. SparseEncoder.encode_query

  3. SparseEncoder.encode_document

  4. semantic_search_elasticsearch

  5. naver/splade-cocondenser-ensembledistil

  6. sentence-transformers/natural-questions

import time

from datasets import load_dataset

from sentence_transformers import SparseEncoder
from sentence_transformers.sparse_encoder.search_engines import semantic_search_elasticsearch

# 1. Load the natural-questions dataset with 100K answers
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
num_docs = 10_000
corpus = dataset["answer"][:num_docs]

# 2. Come up with some queries
queries = dataset["query"][:2]

# 3. Load the model
sparse_model = SparseEncoder("naver/splade-cocondenser-ensembledistil")

# 4. Encode the corpus
print("Start encoding corpus...")
start_time = time.time()
corpus_embeddings = sparse_model.encode_document(
    corpus, convert_to_sparse_tensor=True, batch_size=16, show_progress_bar=True
)
corpus_embeddings_decoded = sparse_model.decode(corpus_embeddings)
print(f"Corpus encoding time: {time.time() - start_time:.6f} seconds")

corpus_index = None
while True:
    # 5. Encode the queries using the full precision
    start_time = time.time()
    query_embeddings = sparse_model.encode_query(queries, convert_to_sparse_tensor=True)
    query_embeddings_decoded = sparse_model.decode(query_embeddings)
    print(f"Encoding time: {time.time() - start_time:.6f} seconds")

    # 6. Perform semantic search using Elasticsearch
    results, search_time, corpus_index = semantic_search_elasticsearch(
        query_embeddings_decoded,
        corpus_embeddings_decoded=corpus_embeddings_decoded if corpus_index is None else None,
        corpus_index=corpus_index,
        top_k=5,
        output_index=True,
    )

    # 7. Output the results
    print(f"Search time: {search_time:.6f} seconds")
    for query, result in zip(queries, results):
        print(f"Query: {query}")
        for entry in result:
            print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}, corpus_id: {entry['corpus_id']}")
        print("")

    # 8. Prompt for more queries
    queries = [input("Please enter a question: ")]
上一个 下一个

© 版权所有 2025。

使用 Sphinx 构建,并使用由 Read the Docs 提供的主题。