Skip to main content

Re-ranking in RAG Pipelines: Cross-Encoders and Two-Stage Retrieval

Two-stage retrieval for perfect relevance: bi-encoder for fast retrieval, cross-encoder for intelligent re-ranking of top-k.

What do you think about this article?

Re-ranking in RAG Pipelines: Cross-Encoders and Two-Stage Retrieval
RAG EngineeringPhotos:RDNE Stock projectPexels

At a Glance

Two-stage retrieval for perfect relevance: bi-encoder for fast retrieval, cross-encoder for intelligent re-ranking of top-k.

Two-stage retrieval is the secret behind enterprise-grade RAG pipelines. The bi-encoder (fast embedding, e.g. all-MiniLM-L6-v2 dim 384) retrieves the top-k candidates from a vast corpus via RediSearch HNSW in ~50ms. The cross-encoder (model rerank-multilingual-v2p5, dim 2048) then re-ranks these k results based on deep semantic relevance, in another ~30ms. The result: recall@100 of 95%, nDCG@10 of 0.88, total latency <100ms. This article documents the architecture, metrics, latency-quality trade-offs, and real-world implementation with sentence-transformers + RediSearch on local Ollama for final generation.

Introduction: The Problem with Single-Stage Retrieval

As long as you can index 10k documents, a single bi-encoder suffices: load the query vector, compute cosine similarity against all embeddings, rank by score. Simple, effective. But with 1 million documents, the computation becomes prohibitive (1M cosine similarities = real-time latency). Worse: bi-encoders are optimized for retrieval speed, not deep semantic quality. If you search "best practices for re-ranking in RAG", the bi-encoder might confuse it with "ranking vs re-ranking" and return articles about ranking history.

The two-stage pipeline solves this: Stage 1 does fast retrieval (top-100, scalable to millions via HNSW), Stage 2 does intelligent re-ranking of candidates with a more expressive cross-encoder model. Computational cost drops 100x because the cross-encoder works on 100 documents, not 1 million.

Two-Stage Retrieval Architecture

The typical pipeline looks like this:


Query (e.g. "How to optimize Italian embeddings?")
  │
  ├─→ Stage 1: Bi-encoder [all-MiniLM-L6-v2, dim 384]
  │   ├─ Tokenize query → max 512 tokens
  │   ├─ Compute query embedding (384-dim vector)
  │   ├─ Run HNSW search on RediSearch
  │   └─ Return top-100 documents + similarity score (50ms)
  │
  ├─→ Stage 2: Cross-encoder [ms-marco-MiniLM-L-12-v2, dim 2048]
  │   ├─ For each top-100:
  │   │   ├─ Concatenate [query, SEP, document]
  │   │   ├─ Compute relevance score (0-1)
  │   └─ Re-rank by score descending (30ms)
  │
  └─→ Final output: top-10 re-ranked documents
  

When to Use Re-ranking

Always use re-ranking if: corpus > 10k documents, semantic quality > latency, GPU budget available. Skip re-ranking if: latency SLA < 50ms total, corpus < 1k small documents, task is exact-match (SQL filter + retrieval).

Stage 1: Bi-encoder for Fast Retrieval

The bi-encoder (e.g. all-MiniLM-L6-v2) is trained to maximize cosine similarity between query and relevant document. It is fast because it represents query and document independently, enabling pre-computing all document embeddings offline (once and for all).

Key characteristics

  • Embedding dimensionality: 384 (compact, fast)
  • Training objective: Contrastive loss (Siamese network)
  • Query latency: ~20-30ms on CPU
  • Storage per document: 384 float32 = 1.5 KB
  • HNSW index: ~100-200MB for 1M documents (compressible)

Code: Load and compute bi-encoder embeddings


from sentence_transformers import SentenceTransformer
import numpy as np

# Load bi-encoder model (onnx optimized, ~80MB)
biencoder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

# Compute query embedding
query = "How to optimize Italian embeddings in RAG?"
query_embedding = biencoder.encode(query, convert_to_numpy=True)
print(f"Query embedding shape: {query_embedding.shape}")  # (384,)
print(f"L2 norm: {np.linalg.norm(query_embedding):.4f}")  # ~1.0 (normalized)

# Pre-compute corpus embeddings (once, offline)
corpus = [
    "RediSearch HNSW is the best vector index for production",
    "Italian models have bias towards Romance languages",
    "Embedding multilingual vs monolingual: trade-off discussed in SentenceBERT paper",
    "FAISS is obsolete, use native Vector Search in RediSearch"
]
corpus_embeddings = biencoder.encode(corpus, convert_to_numpy=True, show_progress_bar=False)
print(f"Corpus embeddings shape: {corpus_embeddings.shape}")  # (4, 384)
  

Stage 2: Cross-encoder for Re-ranking

The cross-encoder (e.g. cross-encoder/ms-marco-MiniLM-L-12-v2) is a transformer model that takes [query, SEP, document] as input and returns a relevance score (0-1). It is more expressive than bi-encoder because it can model deep interactions between query and document, but it is slower (O(k) where k is the number of candidates to re-rank, not O(1) like bi-encoder).

Key characteristics

  • Input format: [query, SEP, document] (max 512 tokens)
  • Output: Single logit (relevance score)
  • Training objective: Pointwise ranking (sigmoid loss)
  • Latency per document: ~3-5ms on CPU
  • Trade-off: Slow on k candidates, but high quality

Code: Re-ranking with cross-encoder


from sentence_transformers.cross_encoders import CrossEncoder
import numpy as np

# Load cross-encoder for re-ranking
crossencoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-12-v2", device="cpu")

# Simulate top-100 candidates from Stage 1
candidates = [
    "RediSearch HNSW is the best vector index for production",
    "Italian models have bias towards Romance languages",
    "Embedding multilingual vs monolingual: trade-off discussed in paper",
]

query = "How to optimize Italian embeddings in RAG?"

# Re-ranking: compute score for each [query, SEP, document]
scores = crossencoder.predict(
    [[query, doc] for doc in candidates],
    convert_to_numpy=True
)
print(f"Cross-encoder scores: {scores}")  # e.g., [0.8, 0.3, 0.6]

# Re-rank by score descending
ranked_indices = np.argsort(-scores)
print(f"Rank order: {ranked_indices}")  # e.g., [0, 2, 1]

# Final output
print("\\nRe-ranked results:")
for idx in ranked_indices:
    print(f"  [{scores[idx]:.3f}] {candidates[idx]}")
  

Evaluation Metrics: nDCG, MRR, Recall@k

How do we measure if re-ranking actually improved quality? Three classic metrics:

nDCG (normalized Discounted Cumulative Gain)

Measures ranking quality accounting for position (top documents weigh more than lower ones). Formula:


DCG@k = rel(1) + rel(2)/log2(2) + rel(3)/log2(3) + ... + rel(k)/log2(k)
nDCG@k = DCG@k / IDCG@k  (normalized by ideal ranking)

Where rel(i) = relevance score of document at position i (0 or 1, binary)
Interpretation: nDCG@10 = 0.85 means "ranking is 85% of the ideal ranking"
  

MRR (Mean Reciprocal Rank)

The average of the reciprocal rank of the first relevant document. Useful for "find first match" tasks.


MRR = 1/N * sum(1/rank_i for i in relevant_docs)

Example: if first relevant document is at position 3, MRR@query = 1/3 = 0.333
  

Recall@k

Fraction of relevant documents in top-k. Position-independent, measures coverage.


Recall@100 = (number of relevant docs in top-100) / (total number of relevant docs)

If 95 out of 100 relevant documents appear in top-100, Recall@100 = 0.95
  

Code: Compute evaluation metrics


import numpy as np
from sklearn.metrics import ndcg_score

def evaluate_ranking(ranked_indices, relevance_labels, k=10):
    """
    ranked_indices: array of indices ordered (top-k first)
    relevance_labels: binary array 1/0 for each document
    """

    # nDCG@k
    top_k_relevance = relevance_labels[ranked_indices[:k]]
    idcg = np.sum(1.0 / np.log2(np.arange(2, len(relevance_labels) + 2)))  # ideal
    dcg = np.sum(top_k_relevance / np.log2(np.arange(2, k + 2)))
    ndcg_k = dcg / idcg

    # Recall@k
    recall_k = np.sum(top_k_relevance) / np.sum(relevance_labels)

    # MRR@k
    first_relevant = np.argmax(top_k_relevance)
    mrr_k = 1.0 / (first_relevant + 1) if top_k_relevance[first_relevant] else 0.0

    return {
        "nDCG@k": ndcg_k,
        "Recall@k": recall_k,
        "MRR@k": mrr_k
    }

# Test
relevance = np.array([1, 0, 1, 0, 1, 0, 0, 0, 0, 0])  # 3 relevant documents
ranked = np.array([0, 2, 4, 1, 3, 5, 6, 7, 8, 9])    # perfect ranking
print(evaluate_ranking(ranked, relevance, k=10))
# {'nDCG@k': 1.0, 'Recall@k': 1.0, 'MRR@k': 1.0}
  

Latency vs Quality Trade-off

Increasing k in the bi-encoder (candidates) improves recall, but increases re-ranking time (O(k)). What is the optimal k?

Empirical benchmark

  • k=10: Bi-encoder 20ms + Cross-encoder 40ms (10*4ms) = 60ms total. nDCG@10 ≈ 0.72 (top-10 final is good, but initial rank is mediocre).
  • k=50: Bi-encoder 25ms + Cross-encoder 200ms (50*4ms) = 225ms total. nDCG@10 ≈ 0.88 (much higher probability of relevant document in top-50, so re-ranking ranks it well).
  • k=100: Bi-encoder 30ms + Cross-encoder 400ms = 430ms total. nDCG@10 ≈ 0.90 (marginal improvement).

Practical decision: Use k=30-50 for quality RAG. Use k=10 only if SLA < 100ms. Use k=100+ if quality >> latency (e.g., batch retrieval overnight).

Implementation: Bi-encoder + RediSearch HNSW

RediSearch (Redis Stack 7+) supports HNSW (Hierarchical Navigable Small World) for native vector search. This enables fast retrieval in a single operation, without exporting vectors to memory.

RediSearch Setup


import redis
from redis.commands.search.field import VectorField, TextField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType

# Connect to Redis (local with RediSearch module)
r = redis.Redis(host="localhost", port=6379, decode_responses=False)

# Define schema with HNSW vector field
schema = [
    TextField("doc_id", sortable=True),
    TextField("content"),
    VectorField(
        "embedding",
        algorithm="HNSW",
        attributes={
            "TYPE": "FLOAT32",
            "DIM": 384,
            "DISTANCE_METRIC": "COSINE",
            "EF_CONSTRUCTION": 200,  # index quality
            "M": 16,  # max connections per node
        }
    )
]

# Create index
definition = IndexDefinition(prefix=["doc:"], index_type=IndexType.HASH)
r.ft("rag_index").create_index(schema, definition=definition)
print("RediSearch index 'rag_index' created")
  

Corpus indexing


# Index 1000 sample documents
documents = [
    {"id": 1, "content": "RediSearch HNSW is very fast"},
    {"id": 2, "content": "Italian embeddings are specific"},
    # ... 998 more
]

biencoder = SentenceTransformer("all-MiniLM-L6-v2")

for doc in documents:
    embedding = biencoder.encode(doc["content"], convert_to_numpy=True)

    # Store in Redis
    doc_key = f"doc:{doc['id']}"
    r.hset(
        doc_key,
        mapping={
            "doc_id": str(doc["id"]),
            "content": doc["content"],
            "embedding": embedding.tobytes()  # binary vector
        }
    )

print(f"Indexed {len(documents)} documents")
  

Integration with Local Ollama (Stage 3)

Once you have the top-10 re-ranked documents, pass them to Ollama (local LLM, e.g. llama3.1:8b) for final answer generation. Ollama runs on-prem in your VPS (zero cloud provider).

Code: Query Ollama


import requests
import json

# Ollama local endpoint (VPS Hetzner, :11434)
OLLAMA_URL = "http://localhost:11434/api/generate"

def generate_rag_response(query, top_documents, model="llama3.1:8b"):
    """
    Generate RAG response using local Ollama
    """

    # Create context from top-10 re-ranked docs
    context = "\\n\\n".join([
        f"[Doc {i+1}] {doc['content']}"
        for i, doc in enumerate(top_documents[:10])
    ])

    prompt = f"""Based on the following context, answer the question in English.

Context:
{context}

Question: {query}

Answer:"""

    # Call Ollama
    response = requests.post(
        OLLAMA_URL,
        json={
            "model": model,
            "prompt": prompt,
            "stream": False,
            "temperature": 0.7
        },
        timeout=30
    )

    if response.status_code == 200:
        result = response.json()
        return result["response"]
    else:
        raise Exception(f"Ollama error: {response.status_code}")

# Test
top_docs = [
    {"content": "RediSearch HNSW is the fastest vector index for production"},
    {"content": "Ollama supports models from 7B to 70B locally"},
]
answer = generate_rag_response("How to configure Ollama?", top_docs)
print(answer)
  

Production Best Practices

1. Bi-encoder result caching

Cache bi-encoder results (top-100) if the query is identical, saving 25ms. Use Redis with TTL=1 hour.

2. Batch cross-encoder

If you receive 10 queries in parallel, batch the 1000 cross-encoding operations into a single call (faster on GPU).

3. Monitor metrics

Track average nDCG@10, p95 latency, cache hit-rate. Use Prometheus + Grafana.

4. Intelligent fallback

If Ollama is down, return the top-10 re-ranked documents as response (graceful degradation, no error).

FAQ

Q: Is cross-encoder always better than bi-encoder?

A: No. For corpus <1k documents, bi-encoder alone is sufficient. Cross-encoder adds latency; only use if quality > speed. For "facts" datasets (e.g. FAQ), bi-encoder is enough.

Q: How much does re-ranking cost on GPU?

A: On NVIDIA A100: ~0.5ms per document. On CPU (MacBook M3): ~4ms per document. RediSearch HNSW on CPU is O(log N), very efficient.

Q: Can I use cloud API embeddings instead of sentence-transformers?

A: Technically yes, but: (1) API cost, (2) network latency, (3) privacy (data to an external service). We use local Ollama to avoid all of this. Sentence-transformers is open-source, local, free.

Q: Does multilingual cross-encoder work well for Italian?

A: Yes, ms-marco-MiniLM-L-12-v2 is trained on 101 languages. Italian recall@100 ≈ English recall@100. But a fine-tuned model on Italian corpus is always better if available.

Q: How to scale to 100M documents?

A: Use RediSearch partitioning (sharding by ID range), or Elasticsearch for massive corpora. Two-stage retrieval scales well up to 50M documents on a single Redis instance.

Conclusion

Two-stage retrieval is the foundation of quality RAG pipelines. Bi-encoder for fast retrieval (Stage 1), cross-encoder for intelligent re-ranking (Stage 2), finally local Ollama for generation. Metrics (nDCG, MRR, Recall@k) guide optimization toward the latency-quality balance ideal for your use case.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects