Ollama를 사용하여 Qwen 3 Embedding 및 Reranker 활용하는 방법 (2026)
RAG 파이프라인을 위한 Qwen 3 임베딩 모델 로컬 환경에 구축하기
Hypereal로 구축 시작하기
단일 API를 통해 Kling, Flux, Sora, Veo 등에 액세스하세요. 무료 크레딧으로 시작하고 수백만으로 확장하세요.
신용카드 불필요 • 10만 명 이상의 개발자 • 엔터프라이즈 지원
Ollama를 활용한 Qwen 3 Embedding 및 Reranker 사용 가이드 (2026)
Qwen 3 Embedding과 Qwen 3 Reranker는 Alibaba에서 검색 증강 생성(RAG) 파이프라인을 위해 특수 제작한 최신 오픈 소스 모델입니다. 이 모델들은 Ollama를 통해 일반 사용자용 하드웨어에서도 효율적으로 실행되면서, embedding 벤치마크에서 최첨단 성능을 제공합니다.
이 가이드는 두 모델을 로컬에 설정하고, RAG 파이프라인에 통합하며, 프로덕션 환경에 맞게 성능을 최적화하는 과정을 안내합니다.
Embedding 및 Reranker 모델이란 무엇인가요?
설정에 들어가기에 앞서, RAG 파이프라인에서 각 모델이 수행하는 역할을 명확히 파악해 보겠습니다.
| 모델 | 역할 | 기능 |
|---|---|---|
| Embedding model | 검색(Retrieval) | 시맨틱 검색을 위해 텍스트를 수치 벡터로 변환 |
| Reranker model | 정제(Refinement) | 검색된 문서가 쿼리와 얼마나 관련 있는지 점수를 재계산 |
| LLM | 생성(Generation) | 검색된 컨텍스트를 사용하여 최종 답변 생성 |
전형적인 RAG 파이프라인은 다음과 같이 작동합니다:
쿼리 → Embedding Model → 벡터 검색 → Top-K 결과
→ Reranker → 재정렬된 Top-N → LLM → 답변
Embedding 모델이 후보군을 빠르게 찾으면, Reranker가 정밀하게 필터링합니다. 두 모델을 함께 사용하면 embedding만 사용할 때보다 답변 품질이 비약적으로 향상됩니다.
Qwen 3 Embedding: 모델 변체
Qwen 3는 다양한 크기의 embedding 모델을 제공합니다.
| 모델 | 파라미터 | 차원(Dimensions) | 최대 토큰 | MTEB 점수 | 필요 VRAM |
|---|---|---|---|---|---|
| qwen3-embedding-0.6b | 0.6B | 1024 | 8,192 | 68.2 | ~1.5 GB |
| qwen3-embedding-1.5b | 1.5B | 1536 | 8,192 | 71.8 | ~3 GB |
| qwen3-embedding-4b | 4B | 2560 | 32,768 | 74.1 | ~6 GB |
| qwen3-embedding-8b | 8B | 4096 | 32,768 | 76.3 | ~10 GB |
대부분의 사례에서 4B 모델이 품질과 성능 사이의 최적의 균형점(Sweet Spot)을 제공합니다.
1단계: Ollama 설치
Ollama가 설치되어 있지 않다면 다음 명령어를 사용하세요:
# macOS
brew install ollama
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows
# https://ollama.com/download 에서 다운로드
Ollama 서버를 시작합니다:
ollama serve
2단계: Qwen 3 Embedding 모델 가져오기(Pull)
# 권장되는 4B 모델 가져오기
ollama pull qwen3-embedding:4b
# VRAM이 낮은 시스템을 위한 작은 모델
ollama pull qwen3-embedding:1.5b
# 최대 품질을 위한 가장 큰 모델
ollama pull qwen3-embedding:8b
모델이 사용 가능한지 확인합니다:
ollama list
3단계: Embedding 생성
Ollama API 사용하기
REST API를 통해 embedding을 생성합니다:
curl http://localhost:11434/api/embed -d '{
"model": "qwen3-embedding:4b",
"input": "How does retrieval-augmented generation work?"
}'
응답 데이터:
{
"model": "qwen3-embedding:4b",
"embeddings": [
[0.0123, -0.0456, 0.0789, ...]
]
}
Python 사용하기
import ollama
# 단일 텍스트 embedding
response = ollama.embed(
model="qwen3-embedding:4b",
input="How does retrieval-augmented generation work?"
)
embedding = response["embeddings"][0]
print(f"Dimensions: {len(embedding)}") # 4B 모델의 경우 2560
# 배치 embedding
documents = [
"RAG combines retrieval with generation for accurate answers.",
"Vector databases store embeddings for fast similarity search.",
"Rerankers improve retrieval precision by re-scoring candidates.",
]
response = ollama.embed(
model="qwen3-embedding:4b",
input=documents
)
embeddings = response["embeddings"]
print(f"Generated {len(embeddings)} embeddings")
4단계: Qwen 3 Reranker 설정
Reranker 모델을 가져옵니다:
ollama pull qwen3-reranker:4b
Reranker는 embedding 모델과 다르게 작동합니다. 벡터를 생성하는 대신, '쿼리-문서' 쌍을 입력받아 관련성 점수를 반환합니다.
Reranker 사용하기
import ollama
import json
def rerank(query: str, documents: list[str], model: str = "qwen3-reranker:4b") -> list[dict]:
"""쿼리 관련성에 따라 문서를 재정렬합니다."""
scored = []
for doc in documents:
# Reranker는 특정 프롬프트 형식을 기대합니다
prompt = f"Query: {query}\nDocument: {doc}\nRelevance:"
response = ollama.generate(
model=model,
prompt=prompt,
options={"temperature": 0}
)
# 응답에서 관련성 점수 파싱
try:
score = float(response["response"].strip())
except ValueError:
score = 0.0
scored.append({"document": doc, "score": score})
# 점수 내림차순 정렬
scored.sort(key=lambda x: x["score"], reverse=True)
return scored
# 예시 사용법
query = "What are the benefits of RAG?"
documents = [
"RAG reduces hallucinations by grounding responses in retrieved data.",
"The weather in Tokyo is currently 22 degrees celsius.",
"Retrieval-augmented generation improves factual accuracy of LLM outputs.",
"Python is a popular programming language for data science.",
]
results = rerank(query, documents)
for r in results:
print(f"Score: {r['score']:.3f} | {r['document'][:60]}")
5단계: 완전한 RAG 파이프라인 구축
다음은 검색을 위해 Qwen 3 Embedding을 사용하고, 정제를 위해 Qwen 3 Reranker를 사용하는 전체 예시입니다:
import ollama
import numpy as np
from typing import Optional
class SimpleRAG:
def __init__(
self,
embed_model: str = "qwen3-embedding:4b",
rerank_model: str = "qwen3-reranker:4b",
llm_model: str = "qwen3:8b",
):
self.embed_model = embed_model
self.rerank_model = rerank_model
self.llm_model = llm_model
self.documents: list[str] = []
self.embeddings: list[list[float]] = []
def add_documents(self, documents: list[str]):
"""지식 기반에 문서를 추가합니다."""
self.documents.extend(documents)
response = ollama.embed(model=self.embed_model, input=documents)
self.embeddings.extend(response["embeddings"])
print(f"Added {len(documents)} documents. Total: {len(self.documents)}")
def _cosine_similarity(self, a: list[float], b: list[float]) -> float:
a, b = np.array(a), np.array(b)
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def retrieve(self, query: str, top_k: int = 10) -> list[dict]:
"""embedding 유사도에 따라 상위 k개 문서를 검색합니다."""
query_embedding = ollama.embed(
model=self.embed_model, input=query
)["embeddings"][0]
scored = []
for i, doc_embedding in enumerate(self.embeddings):
score = self._cosine_similarity(query_embedding, doc_embedding)
scored.append({"index": i, "document": self.documents[i], "score": score})
scored.sort(key=lambda x: x["score"], reverse=True)
return scored[:top_k]
def rerank(self, query: str, candidates: list[dict], top_n: int = 3) -> list[dict]:
"""reranker 모델을 사용하여 후보군을 재정렬합니다."""
for candidate in candidates:
prompt = f"Query: {query}\nDocument: {candidate['document']}\nRelevance:"
response = ollama.generate(
model=self.rerank_model,
prompt=prompt,
options={"temperature": 0}
)
try:
candidate["rerank_score"] = float(response["response"].strip())
except ValueError:
candidate["rerank_score"] = 0.0
candidates.sort(key=lambda x: x["rerank_score"], reverse=True)
return candidates[:top_n]
def query(self, question: str, top_k: int = 10, top_n: int = 3) -> str:
"""전체 RAG 파이프라인: 검색, 재정렬, 생성."""
# 1단계: 검색
candidates = self.retrieve(question, top_k=top_k)
# 2단계: 재정렬
reranked = self.rerank(question, candidates, top_n=top_n)
# 3단계: 생성
context = "\n\n".join([r["document"] for r in reranked])
prompt = f"""Answer the question based on the provided context.
Context:
{context}
Question: {question}
Answer:"""
response = ollama.generate(model=self.llm_model, prompt=prompt)
return response["response"]
# 실행
rag = SimpleRAG()
# 지식 기반 데이터 추가
rag.add_documents([
"Qwen 3 Embedding produces high-quality vector representations.",
"Ollama lets you run models locally on consumer hardware.",
"Rerankers improve precision by re-scoring retrieved documents.",
"RAG pipelines combine retrieval and generation for better answers.",
"Vector databases like ChromaDB and Qdrant store embeddings efficiently.",
])
# 질문하기
answer = rag.query("How do rerankers improve RAG pipelines?")
print(answer)
6단계: LangChain 또는 LlamaIndex와 사용하기
LangChain 통합
from langchain_ollama import OllamaEmbeddings
from langchain_community.vectorstores import Chroma
# embeddings 인스턴스 생성
embeddings = OllamaEmbeddings(
model="qwen3-embedding:4b",
base_url="http://localhost:11434",
)
# ChromaDB와 사용
vectorstore = Chroma.from_texts(
texts=["doc1", "doc2", "doc3"],
embedding=embeddings,
collection_name="my_collection",
)
# 검색
results = vectorstore.similarity_search("my query", k=5)
LlamaIndex 통합
from llama_index.embeddings.ollama import OllamaEmbedding
embed_model = OllamaEmbedding(
model_name="qwen3-embedding:4b",
base_url="http://localhost:11434",
)
# LlamaIndex 파이프라인에서 사용
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
documents = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(
documents,
embed_model=embed_model,
)
성능 튜닝
배치 크기 최적화
대규모 문서 세트의 경우, 속도와 메모리의 균형을 맞추기 위해 배치 크기를 조정하십시오:
# 문서를 배치 단위로 처리
batch_size = 32
for i in range(0, len(documents), batch_size):
batch = documents[i:i + batch_size]
embeddings = ollama.embed(model="qwen3-embedding:4b", input=batch)
하드웨어 권장 사항
| VRAM | 권장 설정 |
|---|---|
| 4 GB | Embedding: 0.6B, Reranker: 없음, LLM: 1.5B |
| 8 GB | Embedding: 1.5B, Reranker: 1.5B, LLM: 4B |
| 16 GB | Embedding: 4B, Reranker: 4B, LLM: 8B |
| 24 GB | Embedding: 8B, Reranker: 4B, LLM: 14B |
양자화(Quantization)
Ollama 모델은 일반적으로 양자화된 형식으로 제공됩니다. embedding 모델의 경우 더 높은 정밀도가 중요합니다:
# embedding 모델에는 Q8 양자화 사용 (더 나은 품질)
ollama pull qwen3-embedding:4b-q8_0
# reranker와 LLM에는 Q4도 충분함
ollama pull qwen3-reranker:4b-q4_K_M
문제 해결(Troubleshooting)
| 문제 | 해결책 |
|---|---|
| "Model not found" | ollama pull qwen3-embedding:4b 실행 |
| 메모리 부족 (Out of memory) | 더 작은 모델 변체를 사용하거나 스왑 메모리 증설 |
| 느린 embedding 속도 | 배치 크기를 줄이거나 GPU 가속 사용 확인 |
| 낮은 검색 품질 | 8B embedding 모델로 업그레이드 |
| 일관성 없는 reranker 점수 | temperature가 0으로 설정되었는지 확인 |
결론
Ollama와 결합된 Qwen 3 Embedding 및 Reranker 모델은 클라우드 기반 솔루션에 필적하는 완전 로컬 및 프라이버시 보호 RAG 파이프라인을 구축하게 해줍니다. 4B 변체는 품질과 성능의 탁월한 균형을 제공하며, 대규모 8B 모델은 최첨단 성능을 보여줍니다.
만약 여러분의 RAG 파이프라인이 검색된 정보를 바탕으로 이미지, 비디오, 오디오와 같은 미디어 콘텐츠 생성을 포함한다면, Hypereal AI는 빠르고 저렴한 AI 미디어 생성용 API를 제공합니다. 로컬 검색과 클라우드 기반 생성을 결합하여 강력한 엔드 투 엔드 AI 파이프라인을 구축해 보세요.
