首页 > 教程攻略 > ai资讯 >开源!我用Qwen2VL实现了一个多模态RAG

开源!我用Qwen2VL实现了一个多模态RAG

来源:互联网 时间:2026-08-27 14:01:07

,未强制添加模板化小标题。 ---

ColPali 本质上是一个“看一眼就懂”的多模态检索器——它直接对图像进行处理,完全跳过 OCR 这一步。这意味着什么?意味着你不再需要费劲地把 PDF 里的文字先识别出来,再去建索引;整页 PDF 就是一张图,ColPali 端到端地理解它。

开源!我用Qwen2VL实现了一个多模态RAG

有了索引之后,生成部分就交给 Qwen2-VL-7B 来搞定。整个过程就像搭积木——检索器负责定位“哪一页有答案”,视觉语言模型负责把答案读出来。

先看看如何把 PDF 转成图片。这一步很关键,因为后面要用图像去匹配和检索。

from pdf2image import convert_from_path

images = convert_from_path("/content/climate_youth_magazine.pdf")
images[5]

byaldi 是 answer.ai 开源的封装工具,有了它,ColPali 用起来就顺手多了。

from byaldi import RAGMultiModalModel

RAG = RAGMultiModalModel.from_pretrained("vidore/colpali")

接下来建立索引,只需要指定 PDF 路径和索引名称即可。

RAG.index(
    input_path="/content/climate_youth_magazine.pdf",
    index_name="image_index", # index will be sa ved at index_root/index_name/
    store_collection_with_index=False,
    overwrite=True
)

索引建好之后,就可以直接搜索了。比如问一句:“全球气温到底变了多少?”

text_query = "How much did the world temperature change so far?"
results = RAG.search(text_query, k=1)
results

返回的结果直接定位到第6页——正是上面展示的那张 PDF 页面。

[{'doc_id': 0, 'page_num': 6, 'score': 17.25, 'metadata': {}, 'base64': None}]

现在把 Qwen2-VL-7B 模型接进来,搭起完整的 RAG 管道。

from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch

model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-2B-Instruct",
                                                        trust_remote_code=True, torch_dtype=torch.bfloat16).cuda().eval()
                                                        
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)

image_index = results[0]["page_num"] - 1
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": images[image_index],
            },
            {"type": "text", "text": text_query},
        ],
    }
]

text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")
generated_ids = model.generate(**inputs, max_new_tokens=50)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)

最后输出答案——模型准确地给出了温度变化数值。

print(output_text)

["The Earth's a verage global temperature has increased by around 1.1°C since the late 19th century, according to the information provided in the image."]答案正确!

整个流程跑下来,你会发现多模态 RAG 并没有想象中那么复杂。核心就两步:用 ColPali 找到包含答案的页面,再用视觉语言模型把答案“读”出来。这种方式对包含图表、复杂排版的文档尤其友好——毕竟,有些信息用 OCR 根本抓不住。

说到底,能直接“看图说话”的检索,才是真正意义上的多模态 RAG。