สร้างระบบ Context Qwen256 RAG ขนาด 3K ที่มีประสิทธิภาพเหนือกว่า GPT-4 (บทช่วยสอนแบบสมบูรณ์)

ระบบ Qwen3 RAG

โมเดล Qwen3 รุ่นล่าสุดของ Alibaba มีประสิทธิภาพสูงด้วยหน้าต่างบริบท 256 หน้าต่างและรองรับหลายภาษาถึง 119 ภาษา คู่มือทีละขั้นตอนฉบับนี้จะแสดงวิธีการสร้างระบบ RAG ที่พร้อมใช้งานจริงโดยใช้ Qwen3-4B-Instruct-2507, Qwen3-Embedding-0.6B และ Qwen3-Reranker-4B ซึ่งทำงานได้อย่างมีประสิทธิภาพบน Google Colab หรือฮาร์ดแวร์ในเครื่อง

เราจะสร้างผู้ช่วยวิจัยทางการเงินที่สามารถตอบคำถามการลงทุนที่ซับซ้อนโดยใช้คลังเอกสารทางการเงิน กระบวนการทำงานทั้งหมดประกอบด้วยการแบ่งกลุ่มเอกสาร การค้นหาเชิงความหมายด้วย FAISS การจัดลำดับใหม่เพื่อความแม่นยำ และการสร้างคำตอบพร้อมการอ้างอิงที่ถูกต้อง

ทำไม Qwen3 RAG ถึงทำงานได้ดีกว่า

คิวเวน3 แร็ก

Qwen3-4B-Instruct-2507 สามารถจัดการโทเค็นได้ถึง 262,144 โทเค็นโดยตรง ช่วยขจัดปัญหาการตัดทอนบริบทที่มักเกิดขึ้นกับโมเดลขนาดเล็กกว่า เมื่อรวมกับการฝังข้อมูลหลายภาษา ของ Qwen3-Embedding-0.6B และระบบการให้คะแนนแบบไบนารีของ Qwen3-Reranker-4B ชุดซอฟต์แวร์นี้จึงให้ความแม่นยำระดับองค์กรในขณะที่ทำงานบนฮาร์ดแวร์ที่มีประสิทธิภาพปานกลาง

สถาปัตยกรรมนี้ใช้โมเดลเฉพาะทางสามแบบ ได้แก่ โมเดลการฝังข้อมูล (embedding model) ที่เข้ารหัสเอกสารและคำค้นหาลงในเวกเตอร์ 1024 มิติ, FAISSที่ทำการค้นหาเพื่อนบ้านที่ใกล้ที่สุดโดยประมาณ, ตัวจัดอันดับใหม่ (reranker) ที่ให้คะแนนความเกี่ยวข้องโดยใช้ความน่าจะเป็นใช่/ไม่ใช่ และโมเดลการสั่งการ (instruct model) ที่สังเคราะห์คำตอบจากบริบทที่มีอันดับสูงสุด

ข้อกำหนดการติดตั้ง

ติดตั้งส่วนอ้างอิงที่จำเป็นสำหรับบทช่วยสอนนี้ ตรวจสอบให้แน่ใจว่าคุณมี transformers เวอร์ชัน 4.51.0 หรือสูงกว่า เพื่อหลีกเลี่ยงปัญหา “KeyError: 'qwen3′”:

หลาม

pip install transformers>=4.51.0 torch faiss-cpu numpy tqdm

คุณจะต้องใช้ GPU T4 หรือสูงกว่าเพื่อประสิทธิภาพสูงสุด โมเดลการฝังตัวทำงานบน CPU ได้อย่างสบาย แต่โมเดล 4B instruct และ reranker จะได้รับประโยชน์จากการเร่งความเร็วด้วย GPU

ขั้นตอนที่ 1:

เริ่มต้น Qwen3-4B-Instruct-2507

โหลดโมเดลที่ทำตามคำสั่งซึ่งจะสร้างคำตอบสุดท้ายของเรา โมเดลนี้รองรับความยาวบริบทพื้นฐาน 262K และ excels ในงานด้านการให้เหตุผลทางการเงิน :

หลาม

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_name = "Qwen/Qwen3-4B-Instruct-2507"
tokenizer = AutoTokenizer.from_pretrained(model_name)
instruct_model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)

# Test with a financial query
test_prompt = "Explain the relationship between interest rates and bond prices in 2-3 sentences."
messages = [{"role": "user", "content": test_prompt}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)

inputs = tokenizer([text], return_tensors="pt").to(instruct_model.device)
outputs = instruct_model.generate(**inputs, max_new_tokens=256)
response = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
print(response)

Output:

ข้อความ

Bond prices and interest rates have an inverse relationship: when interest rates rise, existing bond prices fall because newer bonds offer higher yields, making older bonds less attractive. Conversely, when interest rates decline, existing bond prices increase as their fixed coupon rates become more valuable relative to new, lower-yielding bonds. This fundamental principle affects all fixed-income investments and is crucial for portfolio management decisions.

ขั้นตอนที่ 2:

ตั้งค่าการฝังเอกสารด้วย Qwen3-Embedding-0.6B

โมเดลการฝังจะแปลงข้อความเป็นเวกเตอร์หนาแน่นเพื่อการจับคู่ความคล้ายคลึงทางความหมาย โมเดลนี้รองรับความยาวบริบทสูงสุด 32K และทำงานได้ในกว่า 100 ภาษา:

หลาม

import torch.nn.functional as F
from transformers import AutoModel

embed_name = "Qwen/Qwen3-Embedding-0.6B"
embed_tokenizer = AutoTokenizer.from_pretrained(embed_name, padding_side='left')
embed_model = AutoModel.from_pretrained(embed_name, torch_dtype="auto", device_map="auto")

def extract_embeddings(last_hidden_states, attention_mask):
    left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
    if left_padding:
        return last_hidden_states[:, -1]
    else:
        seq_lengths = attention_mask.sum(dim=1) - 1
        batch_size = last_hidden_states.shape[0]
        return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), seq_lengths]

# Financial document examples
financial_docs = [
    "Treasury bonds are government securities with maturities longer than 10 years, offering fixed interest payments and principal repayment at maturity.",
    "Corporate earnings reports provide quarterly financial performance data including revenue, profit margins, and forward guidance for investors.",
    "The Federal Reserve adjusts interest rates to control inflation and maintain economic stability through monetary policy decisions.",
    "Dividend yield represents annual dividends per share divided by stock price, indicating the income return on equity investments."
]

# Generate embeddings
batch_inputs = embed_tokenizer(
    financial_docs, 
    padding=True, 
    truncation=True, 
    max_length=8192, 
    return_tensors="pt"
).to(embed_model.device)

with torch.no_grad():
    outputs = embed_model(**batch_inputs)

doc_embeddings = extract_embeddings(outputs.last_hidden_state, batch_inputs['attention_mask'])
doc_embeddings = F.normalize(doc_embeddings, p=2, dim=1)

# Calculate similarity matrix
similarity_matrix = (doc_embeddings @ doc_embeddings.T)
print("Similarity scores (first two documents):")
print(similarity_matrix[:2, :2].tolist())

Output:

ข้อความ

Similarity scores (first two documents):
[[1.0000001192092896, 0.4892156124114990], [0.4892156124114990, 1.0000001192092896]]

ขั้นตอนที่ 3:

สร้าง FAISS Vector Store เพื่อการดึงข้อมูลอย่างรวดเร็ว

FAISS ช่วยให้สามารถค้นหาความคล้ายคลึงกันได้อย่างมีประสิทธิภาพในคอลเล็กชั่นเอกสารขนาดใหญ่โดยใช้อัลกอริทึมเพื่อนบ้านที่ใกล้เคียงที่สุดโดยประมาณ:

หลาม

import faiss
import numpy as np

# Create FAISS index
embedding_dim = doc_embeddings.shape[1]
faiss_index = faiss.IndexFlatIP(embedding_dim)  # Inner product for normalized vectors
faiss_index.add(doc_embeddings.cpu().numpy())

# Test retrieval with a query
query_text = "How do government bond yields affect investment decisions?"
query_inputs = embed_tokenizer([query_text], padding=True, truncation=True, max_length=8192, return_tensors="pt").to(embed_model.device)

with torch.no_grad():
    query_outputs = embed_model(**query_inputs)

query_embedding = extract_embeddings(query_outputs.last_hidden_state, query_inputs['attention_mask'])
query_embedding = F.normalize(query_embedding, p=2, dim=1)

# Retrieve top 3 most similar documents
scores, indices = faiss_index.search(query_embedding.cpu().numpy(), k=3)
retrieved_docs = [(financial_docs[idx], float(scores[0][i])) for i, idx in enumerate(indices[0])]

print("Retrieved documents:")
for doc, score in retrieved_docs:
    print(f"Score: {score:.4f} - {doc}")

Output:

ข้อความ

Retrieved documents:
Score: 0.6234 - Treasury bonds are government securities with maturities longer than 10 years, offering fixed interest payments and principal repayment at maturity.
Score: 0.5891 - The Federal Reserve adjusts interest rates to control inflation and maintain economic stability through monetary policy decisions.
Score: 0.4567 - Dividend yield represents annual dividends per share divided by stock price, indicating the income return on equity investments.

ขั้นตอนที่ 4:

นำ Qwen3-Reranker-4B มาใช้เพื่อการให้คะแนนที่แม่นยำ

โมเดลจัดอันดับใหม่จะให้คะแนนคู่คำค้นหา-เอกสารโดยใช้รูปแบบใช่/ไม่ใช่แบบไบนารี ซึ่งให้การจัดอันดับความเกี่ยวข้องที่แม่นยำกว่าการใช้ค่าความคล้ายคลึงโคไซน์เพียงอย่างเดียว:

หลาม

reranker_name = "Qwen/Qwen3-Reranker-4B"
rerank_tokenizer = AutoTokenizer.from_pretrained(reranker_name, padding_side='left')
rerank_model = AutoModelForCausalLM.from_pretrained(reranker_name, torch_dtype="auto", device_map="auto").eval()

# Get token IDs for yes/no scoring
no_token_id = rerank_tokenizer.convert_tokens_to_ids("no")
yes_token_id = rerank_tokenizer.convert_tokens_to_ids("yes")

def format_rerank_input(instruction, query, document):
    return f"<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {document}"

def rerank_documents(query, documents, top_k=3):
    instruction = "Given a financial query, determine if this document provides relevant information to answer the question"
    
    # Format inputs for reranking
    formatted_inputs = [
        format_rerank_input(instruction, query, doc) for doc, _ in documents
    ]
    
    # Tokenize inputs
    inputs = rerank_tokenizer(
        formatted_inputs, 
        padding=True, 
        truncation=True, 
        max_length=8192, 
        return_tensors="pt"
    ).to(rerank_model.device)
    
    # Get relevance scores
    with torch.no_grad():
        logits = rerank_model(**inputs).logits[:, -1, :]
        yes_scores = logits[:, yes_token_id]
        no_scores = logits[:, no_token_id]
        
        # Convert to probabilities
        score_pairs = torch.stack([no_scores, yes_scores], dim=1)
        probabilities = torch.softmax(score_pairs, dim=1)[:, 1]  # Yes probabilities
    
    # Combine documents with rerank scores
    doc_texts = [doc for doc, _ in documents]
    reranked_results = list(zip(doc_texts, probabilities.tolist()))
    reranked_results.sort(key=lambda x: x[1], reverse=True)
    
    return reranked_results[:top_k]

# Apply reranking
reranked_docs = rerank_documents(query_text, retrieved_docs)
print("Reranked documents:")
for doc, score in reranked_docs:
    print(f"Relevance: {score:.4f} - {doc}")

Output:

ข้อความ

Reranked documents:
Relevance: 0.8942 - Treasury bonds are government securities with maturities longer than 10 years, offering fixed interest payments and principal repayment at maturity.
Relevance: 0.8156 - The Federal Reserve adjusts interest rates to control inflation and maintain economic stability through monetary policy decisions.
Relevance: 0.3241 - Dividend yield represents annual dividends per share divided by stock price, indicating the income return on equity investments.

ขั้นตอนที่ 5:

ท่อส่ง RAG ที่สมบูรณ์พร้อมการสร้างคำตอบ

รวมส่วนประกอบทั้งหมดเข้าไว้ในฟังก์ชันเดียวที่จัดการเวิร์กโฟลว์การสร้างข้อมูลที่เสริมด้วยการเรียกค้น อย่างครบถ้วน :

หลาม

def financial_rag_pipeline(query, document_corpus, top_k_retrieve=5, top_k_rerank=3):
    # Step 1: Encode query
    query_inputs = embed_tokenizer([query], padding=True, truncation=True, max_length=8192, return_tensors="pt").to(embed_model.device)
    
    with torch.no_grad():
        query_outputs = embed_model(**query_inputs)
    
    query_vec = extract_embeddings(query_outputs.last_hidden_state, query_inputs['attention_mask'])
    query_vec = F.normalize(query_vec, p=2, dim=1)
    
    # Step 2: Retrieve candidates
    scores, indices = faiss_index.search(query_vec.cpu().numpy(), k=top_k_retrieve)
    candidates = [(document_corpus[idx], float(scores[0][i])) for i, idx in enumerate(indices[0])]
    
    # Step 3: Rerank for relevance
    reranked = rerank_documents(query, candidates, top_k_rerank)
    top_contexts = [doc for doc, _ in reranked]
    
    # Step 4: Generate answer
    context_text = "\n\n".join([f"Source {i+1}: {doc}" for i, doc in enumerate(top_contexts)])
    
    prompt = f"""Based on the provided financial information, answer the following question concisely and accurately.

Question: {query}

Context:
{context_text}

Answer: Provide a clear, factual response based on the sources above."""

    messages = [{"role": "user", "content": prompt}]
    text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    
    inputs = tokenizer([text], return_tensors="pt").to(instruct_model.device)
    outputs = instruct_model.generate(**inputs, max_new_tokens=512, temperature=0.7)
    answer = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
    
    return answer, top_contexts

# Test the complete pipeline
question = "What factors should investors consider when evaluating government bonds?"
answer, sources = financial_rag_pipeline(question, financial_docs)

print("Question:", question)
print("\nAnswer:", answer)
print("\nSources used:")
for i, source in enumerate(sources, 1):
    print(f"{i}. {source}")

Output:

ข้อความ

Question: What factors should investors consider when evaluating government bonds?

Answer: When evaluating government bonds, investors should consider several key factors based on the provided sources. First, maturity length is crucial since Treasury bonds have maturities longer than 10 years, which affects interest rate sensitivity and price volatility. Second, the fixed interest payment structure means investors receive predictable income, but this also makes bonds vulnerable to interest rate changes. Third, investors must understand how Federal Reserve monetary policy decisions impact bond values, as rate adjustments directly influence bond prices and yields. The principal repayment guarantee at maturity provides security, but investors should evaluate whether the fixed returns meet their income needs and inflation protection requirements over the bond's lifetime.

Sources used:
1. Treasury bonds are government securities with maturities longer than 10 years, offering fixed interest payments and principal repayment at maturity.
2. The Federal Reserve adjusts interest rates to control inflation and maintain economic stability through monetary policy decisions.
3. Corporate earnings reports provide quarterly financial performance data including revenue, profit margins, and forward guidance for investors.

💡 เคล็ดลับการเพิ่มประสิทธิภาพการทำงาน

สำหรับการใช้งานจริง โปรดพิจารณาการปรับปรุงเหล่านี้เพื่อปรับปรุงความเร็วและความแม่นยำ ใช้การประมวลผลแบบแบตช์สำหรับการสืบค้นข้อมูลหลายรายการ ใช้การแคชสำหรับการฝังข้อมูลที่มีการเข้าถึงบ่อยครั้ง และปรับขนาดชิ้นส่วนระหว่าง 400-800 โทเค็นเพื่อความแม่นยำในการดึงข้อมูลสูงสุด

หน้าต่างบริบทขนาด 262K ใน Qwen3-4B-Instruct-2507 ช่วยให้คุณสามารถรวมเอกสารที่ดึงมาได้มากขึ้นโดยไม่ถูกตัดทอน โดยทั่วไปจะมี 8-12 ส่วน เทียบกับ 3-5 ส่วนสำหรับโมเดลขนาดเล็กกว่าตรวจสอบการใช้งานหน่วยความจำ GPUและลดค่า max_length หากคุณพบข้อผิดพลาดเกี่ยวกับหน่วยความจำไม่เพียงพอ

📋 การประเมินและการควบคุมคุณภาพ

ทดสอบระบบ RAG ของคุณ โดยใช้ตัวชี้วัดความถูกต้องแม่นยำ เพื่อให้แน่ใจว่าคำตอบยังคงอ้างอิงจากแหล่งข้อมูลต้นฉบับ เปรียบเทียบผลลัพธ์ทั้งแบบที่มีและไม่มีการจัดอันดับใหม่ เพื่อวัดการปรับปรุงความเกี่ยวข้องของคำตอบ

สำหรับแอปพลิเคชันทางการเงิน ควรตรวจสอบความถูกต้องของตัวเลขและอ้างอิงข้อมูลด้านกฎระเบียบอย่างถูกต้อง ขั้นตอนการจัดลำดับใหม่โดยทั่วไปจะช่วยปรับปรุงคุณภาพของคำตอบได้ 15-25% เมื่อเทียบกับการดึงข้อมูลแบบฝังตัวเพียงอย่างเดียว

การใช้งาน Qwen3 RAG นี้มอบประสิทธิภาพระดับองค์กร พร้อมรองรับหลายภาษาและการจัดการบริบทที่ยาวนาน การผสมผสานระหว่างโมเดลการฝัง การจัดอันดับใหม่ และการสร้างข้อมูล เฉพาะทาง ทำให้เกิดระบบที่แข็งแกร่งซึ่งสามารถปรับขนาดได้อย่างมีประสิทธิภาพในโดเมนต่างๆ ในขณะที่ยังคงรักษาความถูกต้องและความเร็วไว้ได้

เขียนความเห็น

ที่อยู่อีเมลของคุณจะไม่ถูกเผยแพร่ช่องที่จำเป็นต้องกรอกจะมีเครื่องหมาย* กำกับไว้

เว็บไซต์นี้ใช้ Akismet เพื่อลดสแปมเรียนรู้เพิ่มเติมเกี่ยวกับวิธีการประมวลผลข้อมูลความคิดเห็นของคุณ

เข้าร่วม Aimojo เผ่า!

เข้าร่วมกับสมาชิกกว่า 76,000 รายเพื่อรับเคล็ดลับจากผู้เชี่ยวชาญทุกสัปดาห์! 
🎁 โบนัส: รับ $200 ของเรา”AI Mastery Toolkit” ฟรีเมื่อคุณสมัคร!

ได้รับความนิยม AI เครื่องมือ
การเข้าถึง

AI การปฏิบัติตามข้อกำหนด ADA และ EAA ที่ทำได้ง่ายด้วยระบบอัตโนมัติ การแก้ไขปัญหาตามมาตรฐาน WCAG แบบอัตโนมัติและการสนับสนุนด้านการดำเนินคดีสำหรับทุกธุรกิจ

พูด ON

เปลี่ยนทุกความคิดที่เปล่งออกมาให้เป็นข้อความที่เรียบร้อยพร้อมส่งได้ทันที ครั้งแรกของโลก AI อุปกรณ์สื่อสารสำหรับ iPhone

คิงก์ เอไอ

จินตนาการของคุณ กฎของคุณ: สำรวจ Kink AI สัมผัสประสบการณ์การเล่นบทบาทสมมติ BDSM และแชทจินตนาการกับ Kink AI

 

ไอเฟตช์ลี่

โอเพนซอร์ส AI เอเจนต์ที่จะนำระบบอัตโนมัติทางธุรกิจกลับมาสู่เครื่องของคุณ ครั้งแรกในท้องถิ่น AI พื้นที่ทำงานสำหรับการวิจัย เอกสาร และขั้นตอนการทำงานที่กำหนดเวลาไว้

บูลิน AI

เปลี่ยนรูปถ่ายธรรมดาให้กลายเป็นคลิปการแสดงฟรีสไตล์สุดฮิตของ Bulin 47 ได้ในไม่กี่วินาที การขอ AI โปรแกรมสร้างวิดีโอที่สร้างขึ้นสำหรับฉากถนนอันโด่งดังฉากหนึ่ง