自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型 原創(chuàng)

發(fā)布于 2024-12-3 15:03
瀏覽
0收藏

詳解Qwen2-VL-7B-Instruct模型,玩轉(zhuǎn)多模態(tài)RAG。

想要玩轉(zhuǎn)人工智能,特別是多模態(tài)數(shù)據(jù)處理,Qwen2-VL-7B-Instruct模型絕對是個得力助手。今天帶你詳細(xì)了解這個模型,并教你如何將其用在多模態(tài)RAG系統(tǒng)里,讓信息檢索和生成變得更加高效、準(zhǔn)確。

1、Qwen2-VL-7B-Instruct:多模態(tài)AI的新高度

Qwen2-VL-7B-Instruct是一款先進(jìn)的多模態(tài)AI模型,它在圖像和視頻的視覺理解與交互方面實(shí)現(xiàn)了重大突破?;谇按P偷膬?yōu)化,Qwen2-VL-7B-Instruct增添了多項(xiàng)強(qiáng)大功能,使其能夠適應(yīng)多變環(huán)境,執(zhí)行復(fù)雜任務(wù)。

核心優(yōu)勢:

  • 視覺理解:在MathVista、DocVQA和RealWorldQA等視覺理解測試中表現(xiàn)出色,能準(zhǔn)確處理各種分辨率和比例的圖像。
  • 視頻處理:擅長處理長視頻,推動了視頻問答等領(lǐng)域的發(fā)展。
  • 設(shè)備兼容:與多種設(shè)備如手機(jī)、機(jī)器人等無縫集成,提供高級視覺和文本處理能力。
  • 多語言識別:不僅支持英語和中文,還能識別圖像中的歐洲語言、日語、韓語、阿拉伯語和越南語。

在架構(gòu)上,Qwen2-VL-7B-Instruct進(jìn)行了以下優(yōu)化:

模型架構(gòu)優(yōu)化:

  • 動態(tài)分辨率處理:能夠動態(tài)地將圖像映射到視覺標(biāo)記,處理不同分辨率的圖像,模擬人類的處理方式。

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型-AI.x社區(qū)

  • 多模態(tài)旋轉(zhuǎn)位置嵌入(M-ROPE):通過將位置嵌入分解為1D、2D和3D格式,分別代表文本、視覺和視頻數(shù)據(jù),優(yōu)化了多模態(tài)數(shù)據(jù)處理。

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型-AI.x社區(qū)

快速上手Qwen2-VL-7B-Instruct:

使用Qwen2-VL-7B-Instruct模型,首先需要安裝必要的庫,然后通過Hugging Face Transformers庫加載模型:

from transformers import Qwen2VLForConditionalGeneration, AutoProcessor

model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")

該模型支持圖像、視頻等視覺數(shù)據(jù)以及文本查詢的輸入,并便于同時處理多個輸入,提高工作效率。

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型-AI.x社區(qū)

2、多模態(tài)RAG的逐步實(shí)施:

步驟1:設(shè)置你的環(huán)境

開始構(gòu)建多模態(tài)RAG系統(tǒng)之前,需要通過Conda或Python虛擬環(huán)境配置開發(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)入庫并配置應(yīng)用

導(dǎo)入所需的庫,并配置你的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è)置頁面配置
st.set_page_config(page_title="多模態(tài)RAG系統(tǒng)", layout="wide")

這段代碼初始化了你的Streamlit應(yīng)用程序,設(shè)置了寬布局,并設(shè)置了標(biāo)題。

步驟3:創(chuàng)建目錄和加載模型

接下來,創(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)將對這些文件進(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}時出錯:{str(e)}")

這段代碼允許用戶同時上傳多個PDF文件。每個文件都被處理并索引以供檢索。

步驟5:查詢文檔

PDF被上傳和索引后,用戶就可以查詢:

elif selected == "查詢文檔":
    st.title("查詢文檔")

    if not st.session_state.indexed_files:
        st.warning("請先上傳并索引一些文檔!")
        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)簽頁中顯示結(jié)果
                tab1, tab2 = st.tabs(["結(jié)果", "上下文"])

                with tab1:
                    col1, col2 = st.columns([1, 1])
                    with col1:
                        st.image(images[image_index], captinotallow=f"來自{os.path.basename(top_file)}的第{image_index + 1}頁", 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"來自:{os.path.basename(file_path)} - 第{result['page_num']}頁"):
                            st.write(result["content"])
                            st.caption(f"相關(guān)性得分:{result.get('score', 0):.2f}")

這一部分通過在索引文檔中搜索來處理用戶查詢。結(jié)果與從文檔中提取的相關(guān)內(nèi)容一起以視覺方式顯示。

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型-AI.x社區(qū)

  

多模態(tài)RAG利器,帶你跑通Qwen2-VL-7B-Instruct大模型-AI.x社區(qū)

3、結(jié)語

打造一個多模態(tài)RAG系統(tǒng),就是把先進(jìn)的AI技術(shù)應(yīng)用到簡化文檔檢索中。通過將Byaldi和Qwen模型等工具集成到易用的Streamlit應(yīng)用里,我們能更高效地在海量信息中找到所需。在這個數(shù)據(jù)爆炸的時代,這樣的系統(tǒng)變得不可或缺,它助力我們個人和組織更好地理解和利用信息。不管你是深入研究的學(xué)者,還是需要迅速獲取報告的職場人,這個系統(tǒng)都能幫你輕松應(yīng)對。

按照這個指南,搭建起你自己的多模態(tài)RAG系統(tǒng),讓檢索信息變得既快速又準(zhǔn)確,徹底改變你與數(shù)字內(nèi)容的互動方式。讓我們一起邁入更智能、更高效的信息檢索新時代!


本文轉(zhuǎn)載自公眾號AI科技論談

原文鏈接:??https://mp.weixin.qq.com/s/R3SsfZ3yGFloAvkZwtte2g??

?著作權(quán)歸作者所有,如需轉(zhuǎn)載,請注明出處,否則將追究法律責(zé)任
收藏
回復(fù)
舉報
回復(fù)
相關(guān)推薦