用ColPali实现多模态文档的视觉检索
介绍如何用ColPali模型对含图表和表格的文档图像建立索引,并以文本查询检索最相关文档,涵盖模型加载、嵌入生成与批量检索流程,适用于多模态RAG场景。
Copyright 2025 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 ⚠️ 注意此文件在 Markdown 中, 但包含我们doc- builder(类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 # 视觉文档检索 文档如果除文本外还包括图表,表格和视觉,可以包含多模式数据. 从这些文件中检索信息具有挑战性,因为仅文本检索模型无法处理视觉数据,图像检索模型缺乏颗粒性和文档处理能力. 视觉文档检索可以帮助从各类文档中检索信息,包括多模式检索增强生成(RAG). 这些模型接受文档(作为图像)和文本,并计算它们之间的相似性分数. 本指南演示了如何使用 [ColPali](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/model_doc/colpali>). > [!TIP] > 对于大规模使用的情况,您可能想要用矢量数据库索引和检索文档。 确保安装了Transformers和数据集. ```bash pip install -q datasets transformers ``` 我们将索引一个与UFO目击有关的文件数据集。我们将过滤我们感兴趣的列缺失的示例。它包含若干列,我们对列感兴趣。 `specific_detail_query` 其中载有文件的简短摘要, `image` 包含我们文档的列。 ```python from datasets import load_dataset dataset = load_dataset("davanstrien/ufo-ColPali") dataset = dataset["train"] dataset = dataset.filter(lambda example: example["specific_detail_query"] is not None) print(dataset) ``` ```text Dataset({ features: ['image', 'raw_queries', 'broad_topical_query', 'broad_topical_explanation', 'specific_detail_query', 'specific_detail_explanation', 'visual_element_query', 'visual_element_explanation', 'parsed_into_json'], num_rows: 2172 }) ``` 让我们装上模型和装饰剂。 ```python import torch from transformers import ColPaliForRetrieval, ColPaliProcessor from accelerate import Accelerator device = Accelerator().device model_name = "vidore/colpali-v1.2-hf" processor = ColPaliProcessor.from_pretrained(model_name) model = ColPaliForRetrieval.from_pretrained( model_name, dtype=torch.bfloat16, device_map="auto", ).eval() ``` 将文本查询传递给处理器并返回模型中嵌入的索引文本。对于 image-to-text 搜索,请替换 `text` 参数在 [`ColPaliProcessor`] 与 `images` 要通过图像的参数。 ```python inputs = processor(text="a document about Mars expedition").to(model.device) with torch.no_grad(): text_embeds = model(**inputs, return_tensors="pt").embeddings ``` 索引图像离线,并在推断时返回查询文本嵌入,以获得其最接近的图像嵌入. 通过将图像和图像嵌入输入到数据集来存储图像和图像 [`~datasets.Dataset.map`] 添加一个 `embeddings` 包含索引嵌入物的列。ColPali嵌入物占用了大量的存储,因此从加速器中去掉,并存储在CPU中,作为NumPy向量。 ```python ds_with_embeddings = dataset.map(lambda example: {'embeddings': model(**processor(images=example["image"]).to(device), return_tensors="pt").embeddings.to(torch.float32).detach().cpu().numpy()}) ``` 对于在线推论, 请创建一个功能来搜索分批嵌入的图像并检索最相关的 K 图像。 下面的函数返回数据集中的索引及其在给定索引数据集中的分数、 文本嵌入、 顶级结果的数量、 以及分批大小 。 ```python def find_top_k_indices_batched(dataset, text_embedding, processor, k=10, batch_size=4): scores_and_indices = [] for start_idx in range(0, len(dataset), batch_size): end_idx = min(start_idx + batch_size, len(dataset)) batch = dataset[start_idx:end_idx] batch_embeddings = [torch.tensor(emb[0], dtype=torch.float32) for emb in batch["embeddings"]] scores = processor.score_retrieval(text_embedding.to("cpu").to(torch.float32), batch_embeddings) if hasattr(scores, "tolist"): scores = scores.tolist()[0] for i, score in enumerate(scores): scores_and_indices.append((score, start_idx + i)) sorted_results = sorted(scores_and_indices, key=lambda x: -x[0]) topk = sorted_results[:k] indices = [idx for _, idx in topk] scores = [score for score, _ in topk] return indices, scores ``` 生成文本嵌入并传递到上面的函数,以返回数据集索引和分数. ```python with torch.no_grad(): text_embeds = model(**processor(text="a document about Mars expedition").to(model.device), return_tensors="pt").embeddings indices, scores = find_top_k_indices_batched(ds_with_embeddings, text_embeds, processor, k=3, batch_size=4) print(indices, scores) ``` ```text ([440, 442, 443], [14.370786666870117, 13.675487518310547, 12.9899320602417]) ``` 显示图像以查看火星相关文档 。 ```python for i in indices: display(dataset[i]["image"]) ``` https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/doc_1.png" 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基百科中相关的原始文献: 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维度 备选=“文件1” 样式=“高:200px;对象配位:包含;边右:10px;” https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/doc_2.png" 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基百科中相关的原始文献: 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维度 备选=“文件2” 样式=“高:200px;对象配位:包含;”> https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/doc_3.png" 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基百科中相关的原始文献: 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维基月球在线解说- 维度 备选=“文件3” 样式=“高:200px;对象配位:包含;”>
查看原始来源