多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型
想要玩轉(zhuǎn)人工智能,特別是多模態(tài)數(shù)據(jù)處理,Qwen2-VL-7B-Instruct模型絕對(duì)是個(gè)得力助手。今天帶你詳細(xì)了解這個(gè)模型,并教你如何將其用在多模態(tài)RAG系統(tǒng)里,讓信息檢索和生成變得更加高效、準(zhǔn)確。
1 Qwen2-VL-7B-Instruct:多模態(tài)AI的新高度
Qwen2-VL-7B-Instruct是一款先進(jìn)的多模態(tài)AI模型,它在圖像和視頻的視覺(jué)理解與交互方面實(shí)現(xiàn)了重大突破。基于前代模型的優(yōu)化,Qwen2-VL-7B-Instruct增添了多項(xiàng)強(qiáng)大功能,使其能夠適應(yīng)多變環(huán)境,執(zhí)行復(fù)雜任務(wù)。
核心優(yōu)勢(shì):
- 視覺(jué)理解:在MathVista、DocVQA和RealWorldQA等視覺(jué)理解測(cè)試中表現(xiàn)出色,能準(zhǔn)確處理各種分辨率和比例的圖像。
- 視頻處理:擅長(zhǎng)處理長(zhǎng)視頻,推動(dòng)了視頻問(wèn)答等領(lǐng)域的發(fā)展。
- 設(shè)備兼容:與多種設(shè)備如手機(jī)、機(jī)器人等無(wú)縫集成,提供高級(jí)視覺(jué)和文本處理能力。
- 多語(yǔ)言識(shí)別:不僅支持英語(yǔ)和中文,還能識(shí)別圖像中的歐洲語(yǔ)言、日語(yǔ)、韓語(yǔ)、阿拉伯語(yǔ)和越南語(yǔ)。
在架構(gòu)上,Qwen2-VL-7B-Instruct進(jìn)行了以下優(yōu)化:
模型架構(gòu)優(yōu)化:
- 動(dòng)態(tài)分辨率處理:能夠動(dòng)態(tài)地將圖像映射到視覺(jué)標(biāo)記,處理不同分辨率的圖像,模擬人類(lèi)的處理方式。
- 多模態(tài)旋轉(zhuǎn)位置嵌入(M-ROPE):通過(guò)將位置嵌入分解為1D、2D和3D格式,分別代表文本、視覺(jué)和視頻數(shù)據(jù),優(yōu)化了多模態(tài)數(shù)據(jù)處理。
快速上手Qwen2-VL-7B-Instruct:
使用Qwen2-VL-7B-Instruct模型,首先需要安裝必要的庫(kù),然后通過(guò)Hugging Face Transformers庫(kù)加載模型:
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
該模型支持圖像、視頻等視覺(jué)數(shù)據(jù)以及文本查詢的輸入,并便于同時(shí)處理多個(gè)輸入,提高工作效率。
2 多模態(tài)RAG的逐步實(shí)施:
步驟1:設(shè)置你的環(huán)境
開(kāi)始構(gòu)建多模態(tài)RAG系統(tǒng)之前,需要通過(guò)Conda或Python虛擬環(huán)境配置開(kāi)發(fā)環(huán)境:
- streamlit
- torch
- transformers
- byaldi
- accelerate
- flash-attn
- qwen_vl_utils
- pdf2image
- python-magic-bin
- extra-streamlit-components
- streamlit-option-menu
步驟2:導(dǎo)入庫(kù)并配置應(yīng)用
導(dǎo)入所需的庫(kù),并配置你的Streamlit應(yīng)用:
import streamlit as st
import os
from byaldi import RAGMultiModalModel
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from pdf2image import convert_from_path
from streamlit_option_menu import option_menu
from datetime import datetime
# 設(shè)置頁(yè)面配置
st.set_page_config(page_title="多模態(tài)RAG系統(tǒng)", layout="wide")
這段代碼初始化了你的Streamlit應(yīng)用程序,設(shè)置了寬布局,并設(shè)置了標(biāo)題。
步驟3:創(chuàng)建目錄和加載模型
接下來(lái),創(chuàng)建上傳PDF的目錄并加載處理查詢所需的模型:
# 創(chuàng)建必要的目錄
UPLOAD_DIR = "uploaded_pdfs"
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
@st.cache_resource
def load_models():
with st.spinner("正在加載模型... 這可能需要幾分鐘。"):
rag_engine = RAGMultiModalModel.from_pretrained("vidore/colpali")
model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", torch_dtype=torch.float16, device_map="cuda")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", trust_remote_code=True)
return rag_engine, model, processor
這一節(jié)設(shè)置了PDF文件的上傳目錄,并加載了處理查詢所需的模型。
步驟4:文件上傳功能
用戶可以上傳PDF文件,系統(tǒng)將對(duì)這些文件進(jìn)行索引,以便后續(xù)檢索:
def save_uploaded_file(uploaded_file):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{timestamp}_{uploaded_file.name}"
file_path = os.path.join(UPLOAD_DIR, filename)
with open(file_path, "wb") as f:
f.write(uploaded_file.getvalue())
return file_path
def main():
if 'indexed_files' not in st.session_state:
st.session_state.indexed_files = set()
selected = option_menu(menu_title=None, optinotallow=["上傳PDF", "查詢文檔"], icnotallow=["cloud-upload", "search"], default_index=0)
rag_engine, model, processor = load_models()
if selected == "上傳PDF":
st.title("PDF文檔上傳")
uploaded_files = st.file_uploader("上傳你的PDF文檔", type=['pdf'], accept_multiple_files=True)
if uploaded_files:
for uploaded_file in uploaded_files:
if uploaded_file.name not in [os.path.basename(f) for f in st.session_state.indexed_files]:
with st.spinner(f"正在處理{uploaded_file.name}..."):
file_path = save_uploaded_file(uploaded_file)
try:
rag_engine.index(input_path=file_path, index_name=os.path.basename(file_path), store_collection_with_index=True, overwrite=True)
st.session_state.indexed_files.add(file_path)
st.success(f"成功處理{uploaded_file.name}")
except Exception as e:
st.error(f"處理{uploaded_file.name}時(shí)出錯(cuò):{str(e)}")
這段代碼允許用戶同時(shí)上傳多個(gè)PDF文件。每個(gè)文件都被處理并索引以供檢索。
步驟5:查詢文檔
PDF被上傳和索引后,用戶就可以查詢:
elif selected == "查詢文檔":
st.title("查詢文檔")
if not st.session_state.indexed_files:
st.warning("請(qǐng)先上傳并索引一些文檔!")
return
query = st.text_input("輸入你的查詢:", placeholder="你想知道什么?")
if query:
with st.spinner("正在處理查詢..."):
all_results = []
for file_path in st.session_state.indexed_files:
results = rag_engine.search(query, k=3, index_name=os.path.basename(file_path))
all_results.extend([(file_path, r) for r in results])
all_results.sort(key=lambda x: x[1].get('score', 0), reverse=True)
if all_results:
top_file, top_result = all_results[0]
images = convert_from_path(top_file)
image_index = top_result["page_num"] - 1
# 在標(biāo)簽頁(yè)中顯示結(jié)果
tab1, tab2 = st.tabs(["結(jié)果", "上下文"])
with tab1:
col1, col2 = st.columns([1, 1])
with col1:
st.image(images[image_index], captinotallow=f"來(lái)自{os.path.basename(top_file)}的第{image_index + 1}頁(yè)", use_column_width=True)
with col2:
messages = [{"role": "user", "content": [{"type": "image", "image": images[image_index]}, {"type": "text", "text": query}]}]
text = processor.apply_chat_template(messages)
inputs = processor(text=[text], images=[images[image_index]], padding=True, return_tensors="pt").to("cuda")
generated_ids = model.generate(**inputs, max_new_tokens=50)
output_text = processor.batch_decode(generated_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
st.markdown("### 模型響應(yīng)")
st.write(output_text[0])
with tab2:
for file_path, result in all_results[:5]:
with st.expander(f"來(lái)自:{os.path.basename(file_path)} - 第{result['page_num']}頁(yè)"):
st.write(result["content"])
st.caption(f"相關(guān)性得分:{result.get('score', 0):.2f}")
這一部分通過(guò)在索引文檔中搜索來(lái)處理用戶查詢。結(jié)果與從文檔中提取的相關(guān)內(nèi)容一起以視覺(jué)方式顯示。
3 結(jié)語(yǔ)
打造一個(gè)多模態(tài)RAG系統(tǒng),就是把先進(jìn)的AI技術(shù)應(yīng)用到簡(jiǎn)化文檔檢索中。通過(guò)將Byaldi和Qwen模型等工具集成到易用的Streamlit應(yīng)用里,我們能更高效地在海量信息中找到所需。在這個(gè)數(shù)據(jù)爆炸的時(shí)代,這樣的系統(tǒng)變得不可或缺,它助力我們個(gè)人和組織更好地理解和利用信息。不管你是深入研究的學(xué)者,還是需要迅速獲取報(bào)告的職場(chǎng)人,這個(gè)系統(tǒng)都能幫你輕松應(yīng)對(duì)。
按照這個(gè)指南,搭建起你自己的多模態(tài)RAG系統(tǒng),讓檢索信息變得既快速又準(zhǔn)確,徹底改變你與數(shù)字內(nèi)容的互動(dòng)方式。讓我們一起邁入更智能、更高效的信息檢索新時(shí)代!
本文轉(zhuǎn)載自 ??AI科技論談??,作者: AI科技論談
