Sentence Transformers v5.4 多模態嵌入與 Reranker 模型使用指南
Multimodal Embedding & Reranker Models with Sentence Transformers
Sentence Transformers v5.4 的同一 API 現可編碼並比較文字、圖像、音訊和影片,文章示範其多模態嵌入與 reranker 用法。嵌入模型將不同模態映射至共享嵌入空間;預訓練多模態 reranker 目前主要處理文字與圖像配對。示例涵蓋跨模態檢索、混合模態文件重排及先檢索再重排流程,並列出輸入格式、支援模型和安裝依賴。
文章展示 Sentence Transformers v5.4 的跨模態檢索與 reranker 重排流程,並整理支援模型和輸入格式,提供實作參考。
Sentence Transformers 是用於嵌入模型和重排序模型的 Python 函式庫,可應用於檢索增強生成、語義搜尋等用途。v5.4 更新後,你現在可透過同一套熟悉的 API,編碼和比較文字、圖像、音訊及影片。本文會示範如何使用這些全新的多模態功能進行嵌入和重排序。
多模態嵌入模型會把不同模態的輸入映射至共用嵌入空間;多模態重排序模型則為混合模態配對評估相關性分數。這帶來視覺文件檢索、跨模態搜尋和多模態 RAG 流程等用途。
如欲訓練自己的多模態模型,請參閲配套網誌文章:使用 Sentence Transformers 訓練及微調多模態嵌入與重排序模型。
目錄
甚麼是多模態模型?
傳統嵌入模型會把文字轉換成固定大小的向量。多模態嵌入模型則把不同模態(文字、圖像、音訊或影片)的輸入映射至共用嵌入空間。這代表你可以使用熟悉的相似度函數,以文字查詢比對圖像文件,反過來亦然。
同樣地,傳統重排序(Cross Encoder)模型會計算文字配對之間的相關性分數。多模態重排序模型則可為配對評分,其中一項或兩項內容可以是圖像、文字與圖像組合文件或其他模態。
例如,你可以用文字查詢比對圖像文件、尋找符合描述的影片片段,或建立跨模態 RAG 流程。
安裝
多模態模型需要額外相依套件。請安裝所需模態的額外套件(詳情請參閲安裝説明):
# For image support
pip install -U "sentence-transformers[image]"
# For audio support
pip install -U "sentence-transformers[audio]"
# For video support
pip install -U "sentence-transformers[video]"
# Mix and match as needed
pip install -U "sentence-transformers[image,video,train]"
以 VLM 為基礎的模型(例如 Qwen3-VL-2B)需要至少約 8 GB VRAM 的 GPU。8B 版本則預計需要約 20 GB。如果本機沒有 GPU,可考慮使用雲端 GPU 服務或 Google Colab。這些模型在 CPU 上會非常慢;純文字或 CLIP 模型更適合在 CPU 上推論。
多模態嵌入模型
載入模型
載入多模態嵌入模型的方法,與載入純文字模型完全相同:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
目前部分模型整合的合併請求仍在等候處理,因此可能需要提供
revision參數。待合併後,就能像上方一樣載入,不必指定 revision。
模型會自動偵測支援的模態,因此無須額外配置。如欲控制圖像解像度或模型精度等設定,請參閲 Processor 和模型 kwargs。
編碼圖像
載入多模態模型後,model.encode() 可同時接收圖像和文字。圖像可透過 URL、本機檔案路徑或 PIL Image 物件提供(所有接受的格式請參閲支援的輸入類型):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
# Encode images from URLs
img_embeddings = model.encode([
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
])
print(img_embeddings.shape)
# (2, 2048)
跨模態相似度
由於模型會把文字嵌入和圖像嵌入映射至相同空間,因此可以計算兩者的相似度:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
# Encode images
img_embeddings = model.encode([
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
])
# Encode text queries (one matching + one hard negative per image)
text_embeddings = model.encode([
"A green car parked in front of a yellow building",
"A red car driving on a highway",
"A bee on a pink flower",
"A wasp on a wooden table",
])
# Compute cross-modal similarities
similarities = model.similarity(text_embeddings, img_embeddings)
print(similarities)
# tensor([[0.5115, 0.1078],
# [0.1999, 0.1108],
# [0.1255, 0.6749],
# [0.1283, 0.2704]])
結果符合預期:「停在黃色建築物前的綠色汽車」最像汽車圖像(0.51),而「粉紅色花朵上的蜜蜂」最像蜜蜂圖像(0.67)。較難區分的負例(「在公路上行駛的紅色汽車」、「木桌上的黃蜂」)則正確取得較低分數。
你可能留意到,即使最匹配的分數(0.51、0.67)也遠低於 1.0。這是由模態差距造成:不同模態的嵌入往往聚集在空間中不同區域。跨模態相似度通常低於同模態相似度(例如文字對文字),但相對次序會保留,因此檢索仍然有效。
編碼查詢和文件
在檢索任務中,建議使用 encode_query() 和 encode_document()。許多檢索模型會按輸入是查詢還是文件,附加不同指令提示詞,類似聊天模型按目標套用不同系統提示詞。模型作者可在模型配置中指定提示詞,而 encode_query()/encode_document() 會自動載入並套用正確提示詞:
encode_query()會使用模型的"query"提示詞(如有),並設定task="query"。encode_document()會依次使用第一個可用提示詞:"document"、"passage"或"corpus",並設定task="document"。
底層而言,兩者都是 encode() 的簡單封裝,只是代你選擇提示詞。以下是跨模態檢索示例:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
# Encode text queries with the query prompt
query_embeddings = model.encode_query([
"Find me a photo of a vehicle parked near a building",
"Show me an image of a pollinating insect",
])
# Encode document screenshots with the document prompt
doc_embeddings = model.encode_document([
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
])
# Compute similarities
similarities = model.similarity(query_embeddings, doc_embeddings)
print(similarities)
# tensor([[0.3907, 0.1490],
# [0.1235, 0.4872]])
這些方法接受與 encode() 相同的輸入類型(圖像、URL、多模態字典等),亦傳遞相同參數。對沒有專用查詢/文件提示詞的模型而言,其行為與 encode() 完全相同。
多模態重排序模型
多模態重排序(CrossEncoder)模型會為輸入配對評估相關性,每個元素可以是文字、圖像、音訊、影片或其組合。它們的品質往往超越嵌入模型,但由於每次只處理一組配對,速度較慢。目前可用的預訓練多模態重排序模型以文字和圖像輸入為主,但架構支援底層模型能處理的任何模態。
混合模態文件排序
rank() 方法會針對查詢為文件清單評分並排序,支援混合模態:
from sentence_transformers import CrossEncoder
model = CrossEncoder("Qwen/Qwen3-VL-Reranker-2B")
query = "A green car parked in front of a yellow building"
documents = [
# Image documents (URL or local file path)
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
# Text document
"A vintage Volkswagen Beetle painted in bright green sits in a driveway.",
# Combined text + image document
{
"text": "A car in a European city",
"image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
},
]
rankings = model.rank(query, documents)
for rank in rankings:
print(f"{rank['score']:.4f}\t(document {rank['corpus_id']})")
"""
0.9375 (document 0)
0.5000 (document 3)
-1.2500 (document 2)
-2.4375 (document 1)
"""
重排序模型正確地把汽車圖像(文件 0)識別為最相關結果,其次是關於歐洲城市汽車的文字+圖像組合文件(文件 3)。蜜蜂圖像(文件 1)的分數最低。 請留意,模態差距會影響絕對分數:文字-圖像配對分數的範圍,可能與文字-文字或圖像-圖像配對不同。
與嵌入模型一樣,你也可以使用 modalities 和 supports() 檢查重排序模型支援哪些模態:
print(model.modalities)
# ['text', 'image', 'video', 'message']
print(model.supports("image"))
# True
# Check if the model supports a specific pair of modalities
print(model.supports(("image", "text")))
# True
預測配對分數
你亦可使用 predict() 取得指定輸入配對的原始相關性分數:
from sentence_transformers import CrossEncoder
model = CrossEncoder("jinaai/jina-reranker-m0", trust_remote_code=True)
scores = model.predict([
("A green car", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"),
("A bee on a flower", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"),
("A green car", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"),
])
print(scores)
# [0.9389156 0.96922314 0.46063158]
檢索並重排序
常見做法是先使用嵌入模型快速初步檢索,再用重排序模型進一步精煉排名靠前的結果:
from sentence_transformers import SentenceTransformer, CrossEncoder
# Step 1: Retrieve with an embedding model
embedder = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
query = "revenue growth chart"
query_embedding = embedder.encode_query(query)
# Pre-compute corpus embeddings (do this once, then store them)
document_screenshots = [
"path/to/doc1.png",
"path/to/doc2.png",
# ... potentially millions of document screenshots
]
corpus_embeddings = embedder.encode_document(document_screenshots, show_progress_bar=True)
# Simple cosine similarity retrieval, viable as long as embeddings fit in memory
similarities = embedder.similarity(query_embedding, corpus_embeddings)
top_k_indices = similarities.argsort(descending=True)[0][:10]
# Step 2: Rerank the top-k results with a reranker model
reranker = CrossEncoder("nvidia/llama-nemotron-rerank-vl-1b-v2", trust_remote_code=True)
top_k_documents = [document_screenshots[i] for i in top_k_indices]
rankings = reranker.rank(query, top_k_documents)
for rank in rankings:
print(f"{rank['score']:.4f}\t{top_k_documents[rank['corpus_id']]}")
由於語料庫嵌入已預先計算,即使在數百萬份文件中,初步檢索仍然快速。之後重排序模型會在較小的候選集合中提供更準確的評分。
輸入格式與配置
支援的輸入類型
多模態模型接受多種輸入格式。以下簡介可傳入 model.encode() 的資料:
| 模態 | 接受的格式 |
|---|---|
| 文字 | - 字串 |
| 圖像 | - PIL.Image.Image 物件- 檔案路徑(例如 "./photo.jpg")- URL(例如 "https://.../image.jpg")- Numpy 陣列、torch 張量 |
| 音訊 | - 檔案路徑(例如 "./audio.wav")- URL(例如 "https://.../audio.wav")- Numpy/torch 陣列 - 含有 "array" 和 "sampling_rate" 鍵的字典- torchcodec.AudioDecoder 實例 |
| 影片 | - 檔案路徑(例如 "./video.mp4")- URL(例如 "https://.../video.mp4")- Numpy/torch 陣列 - 含有 "array" 和 "video_metadata" 鍵的字典- torchcodec.VideoDecoder 實例 |
| 多模態 | - 把模態名稱映射至數值的字典, 例如 {"text": "a caption", "image": "https://.../image.jpg"}有效鍵: "text"、"image"、"audio"、"video" |
| 訊息 | - 含有 "role" 和 "content" 鍵的訊息字典清單,例如 [{"role": "user", "content": [...]}] |
檢查模態支援
你可使用 modalities 屬性和 supports() 方法,檢查模型支援哪些模態:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Qwen/Qwen3-VL-Embedding-2B")
# List all supported modalities
print(model.modalities)
# ['text', 'image', 'video', 'message']
# Check for a specific modality
print(model.supports("image"))
# True
print(model.supports("audio"))
# False
"message" 模態表示模型接受內容交錯排列的聊天式訊息輸入。實際上,你很少需要直接使用此格式。傳入字串、URL 或多模態字典時,模型會在內部轉換為適當的訊息格式。Sentence Transformers 支援兩種訊息格式:
- 結構化(大部分 VLM,例如 Qwen3-VL):內容是具類型的字典清單,例如
[{"type": "text", "text": "..."}, {"type": "image", "image": ...}] - 扁平(例如 Deepseek-V3):內容是直接值,例如
"some text"
系統會根據模型的聊天範本自動偵測格式。
由於所有輸入在內部都會轉換為相同訊息格式,你可以在同一次 encode() 呼叫中混合不同輸入類型:
embeddings = model.encode([
# A text input
"A green car parked in front of a yellow building",
# An image input (URL)
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
# A combined text + image input
{
"text": "A car in a European city",
"image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
},
])
如需傳入原始訊息輸入,請按此處
如果模型不採用上述任何格式,而你需要完全控制,可直接傳入含有 role 和 content 鍵的原始訊息字典:
embeddings = model.encode([
[
{
"role": "user",
"content": [
{"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"},
{"type": "text", "text": "Describe this vehicle."},
],
}
],
])
這會略過自動格式轉換,直接把訊息傳入處理器的 apply_chat_template()。
Processor 和模型 kwargs
你可能需要控制圖像解像度範圍或模型精度。載入模型時可使用 processor_kwargs 和 model_kwargs:
model = SentenceTransformer(
"Qwen/Qwen3-VL-Embedding-2B",
model_kwargs={"attn_implementation": "flash_attention_2", "torch_dtype": "bfloat16"},
processor_kwargs={"min_pixels": 28 * 28, "max_pixels": 600 * 600},
)
processor_kwargs控制輸入預處理方式(例如圖像解像度範圍)。max_pixels愈大,質素愈高,但需要更多記憶體和運算資源。這些參數會直接傳給AutoProcessor.from_pretrained(...)。model_kwargs控制底層模型載入方式(例如精度、注意力實作)。這些參數會傳給相應的AutoModel.from_pretrained(...)呼叫(例如AutoModel、AutoModelForCausalLM、AutoModelForSequenceClassification等,視乎模型模組配置而定)。
更多 kwargs 詳情請參閲 SentenceTransformer API 參考文件。
Sentence Transformers v5.4 把
tokenizer_kwargs改名為processor_kwargs,以反映多模態模型使用的是 processor,而不只是 tokenizer。舊名稱仍可使用,但已棄用。
支援的模型
以下是 v5.4 支援的多模態模型,亦可在v5.4 整合合集中查閲:
支援的多模態嵌入模型
| 模型 | 參數量 | 模態 | Revision |
|---|---|---|---|
| Qwen/Qwen3-VL-Embedding-2B | 2B | 文字、圖像、影片 | 不需要 revision |
| Qwen/Qwen3-VL-Embedding-8B | 8B | 文字、圖像、影片 | 不需要 revision |
| nvidia/llama-nemotron-embed-vl-1b-v2 | 1.7B | 文字、圖像 | 不需要 revision |
| nvidia/omni-embed-nemotron-3b | 4.7B | 文字、圖像 | 不需要 revision |
| LCO-Embedding/LCO-Embedding-Omni-3B | 5B | 文字、圖像、音訊、影片 | 不需要 revision |
| LCO-Embedding/LCO-Embedding-Omni-7B | 9B | 文字、圖像、音訊、影片 | 不需要 revision |
| BidirLM/BidirLM-Omni-2.5B-Embedding | 2.5B | 文字、圖像、音訊 | 不需要 revision |
| BAAI/BGE-VL-base | 0.1B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-large | 0.4B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-MLLM-S1 | 8B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-MLLM-S2 | 8B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-v1.5-zs | 8B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-v1.5-mmeb | 8B | 文字、圖像 | 不需要 revision |
| BAAI/BGE-VL-Screenshot | 4B | 文字、圖像 | 不需要 revision |
| royokong/e5-v | 8B | 文字、圖像 | 不需要 revision |
| eagerworks/eager-embed-v1 | 4B | 文字、圖像 | revision="refs/pr/2" |
| nomic-ai/nomic-embed-multimodal-3b | 5B | 文字、圖像 | revision="refs/pr/4" |
| nomic-ai/nomic-embed-multimodal-7b | 9B | 文字、圖像 | revision="refs/pr/3" |
| Haon-Chen/e5-omni-3B | 5B | 文字、圖像、音訊、影片 | revision="refs/pr/2" |
| Haon-Chen/e5-omni-7B | 9B | 文字、圖像、音訊、影片 | revision="refs/pr/1" |
支援的多模態重排序模型
| 模型 | 參數量 | 模態 | Revision |
|---|---|---|---|
| Qwen/Qwen3-VL-Reranker-2B | 2B | 文字、圖像、影片 | 不需要 revision |
| Qwen/Qwen3-VL-Reranker-8B | 8B | 文字、圖像、影片 | 不需要 revision |
| nvidia/llama-nemotron-rerank-vl-1b-v2 | 2B | 文字、圖像 | 不需要 revision |
| jinaai/jina-reranker-m0 | 2B | 文字、圖像 | 不需要 revision |
純文字重排序模型(v5.4 新增)
| 模型 | 參數量 | Revision |
|---|---|---|
| Qwen/Qwen3-Reranker-0.6B | 0.6B | 不需要 revision |
| Qwen/Qwen3-Reranker-4B | 4B | 不需要 revision |
| Qwen/Qwen3-Reranker-8B | 8B | 不需要 revision |
| mixedbread-ai/mxbai-rerank-base-v2 | 0.5B | 不需要 revision |
| mixedbread-ai/mxbai-rerank-large-v2 | 2B | 不需要 revision |
| ContextualAI/ctxl-rerank-v2-instruct-multilingual-1b | 1B | revision="refs/pr/2" |
| ContextualAI/ctxl-rerank-v2-instruct-multilingual-2b | 3B | revision="refs/pr/1" |
| ContextualAI/ctxl-rerank-v2-instruct-multilingual-6b | 7B | revision="refs/pr/1" |
按此查看純文字重排序模型使用示例
from sentence_transformers import CrossEncoder
model = CrossEncoder("mixedbread-ai/mxbai-rerank-base-v2")
query = "How do I bake sourdough bread?"
documents = [
"Sourdough bread requires a starter made from flour and water, fermented over several days.",
"The history of bread dates back to ancient Egypt around 8000 BCE.",
"To bake sourdough, mix your starter with flour, water, and salt, then let it rise overnight.",
"Rye bread is a popular alternative to wheat-based breads in Northern Europe.",
]
pairs = [(query, doc) for doc in documents]
scores = model.predict(pairs)
print(scores)
# [ 7.3077507 -2.6217823 8.724761 -2.2488995]
rankings = model.rank(query, documents)
for rank in rankings:
print(f"{rank['score']:.4f}\t{documents[rank['corpus_id']]}")
# 8.7248 To bake sourdough, mix your starter with flour, water, and salt, then let it rise overnight.
# 7.3078 Sourdough bread requires a starter made from flour and water, fermented over several days.
# -2.2489 Rye bread is a popular alternative to wheat-based breads in Northern Europe.
# -2.6218 The history of bread dates back to ancient Egypt around 8000 BCE.
CLIP 模型
較舊的 CLIP 模型仍受支援:
| 模型 | ImageNet 零樣本 Top-1 準確度 | 備註 |
|---|---|---|
| sentence-transformers/clip-ViT-L-14 | 75.4 | |
| sentence-transformers/clip-ViT-B-16 | 68.1 | |
| sentence-transformers/clip-ViT-B-32 | 63.3 | |
| sentence-transformers/clip-ViT-B-32-multilingual-v1 | 不適用 | 支援 50 多種語言的多語言文字編碼器 |
這些簡單的 CLIP 模型在較低規格硬件上仍然表現良好。
按此查看 CLIP 使用示例
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/clip-ViT-L-14")
images = [
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg",
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
"https://huggingface.co/datasets/huggingface/cats-image/resolve/main/cats_image.jpeg"
]
texts = ["A green car", "A bee on a flower", "Some cats on a couch", "One cat sitting in the window"]
image_embeddings = model.encode(images)
text_embeddings = model.encode(texts)
print(image_embeddings.shape, text_embeddings.shape)
# (3, 768) (4, 768)
similarities = model.similarity(image_embeddings, text_embeddings)
print(similarities)
# tensor([[0.2208, 0.1042, 0.0617, 0.0907], First image (car) is most similar to "A green car"
# [0.1205, 0.2303, 0.0632, 0.0917], Second image (bee) is most similar to "A bee on a flower"
# [0.1107, 0.0196, 0.2425, 0.1162]]) Third image (multiple cats) is most similar to "Some cats on a couch"
其他資源
文件
- Sentence Transformer > 使用方法
- Sentence Transformer > 預訓練模型
- Cross Encoder > 使用方法
- Cross Encoder > 預訓練模型
- 安裝
訓練
如欲瞭解如何使用自己的數據微調這些多模態模型,請參閲配套網誌文章:使用 Sentence Transformers 訓練及微調多模態嵌入與重排序模型。
- Sentence Transformer > 訓練概覽
- Sentence Transformer > 訓練示例
- Cross Encoder > 訓練概覽
- Cross Encoder > 訓練示例
- Sparse Encoder > 訓練概覽
- Sparse Encoder > 訓練示例
Hugging Face Hub
配套網誌文章
本文的訓練配套文章及相關 Sentence Transformers 指南:
- 使用 Sentence Transformers 訓練及微調多模態嵌入與重排序模型:本文的直接訓練配套指南,附有視覺文件檢索操作示範。
- 使用 Sentence Transformers 訓練及微調嵌入模型:純文字雙編碼器嵌入模型的一般訓練指南。
- 使用 Sentence Transformers 訓練及微調重排序模型:Cross Encoder(重排序模型)訓練,適用於純文字和多模態重排序模型。
- 訓練及微調稀疏嵌入模型:用於稀疏檢索的 SPLADE 訓練。
- 🪆 Matryoshka 嵌入模型簡介:可變大小嵌入,並於配套訓練文章中應用至多模態模型。
- 使用 Sentence Transformers 快 400 倍訓練靜態嵌入模型:適合 CPU 的文字嵌入模型。
- 二元和純量嵌入量化,令檢索大幅提速並降低成本:嵌入向量的後訓練壓縮。
來源:Hugging Face Blog · huggingface.co