AI Hints
Home›RAG Tutorial›Better Questions
RAG · Lesson 58 of 120

Cross-Encoders

Scoring each pair.

⏱ 2 min read▶ Video at 57:31🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Our embedding model is a bi encoder. It embeds the question and the chunk separately, then compares them. A cross encoder reads the question and the chunk together, so it sees how they relate. That's why it ranks better.

Cross-Encoders
From the video: Cross-Encoders
  • Bi-encoder: separately
  • Cross-encoder: together
  • Better ranking

Two kinds of model

A bi encoder is fast, because chunks are embedded once, ahead of time. A cross encoder must read every pair at question time, so it's slow. That's why we search with one, and rerank with the other.

Bi-encoder

  • Embeds separatelyFast, precomputedFor search

Cross-encoder

  • Reads the pairSlow, per questionFor reranking

Comparing the scores

We score one question against three short texts, with both models. The bi encoder compares two vectors. The cross encoder reads each pair, and gives one score. Run it. The bi encoder's scores are close together. The cross encoder clearly picks the E03 text.

cross_encoder.pypython
from sentence_transformers import CrossEncoder
from rag_kit import embed

q = "What does E03 mean?"
texts = ["E03: the speed sensor is not reading.",
         "E05: the motor is overheating.",
         "These codes appear on the display of the Volt e-bikes."]

cross = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device="cpu")
bi_scores = embed(texts) @ embed([q])[0]
cross_scores = cross.predict([(q, t) for t in texts])
for t, b, c in zip(texts, bi_scores, cross_scores):
    print(f"bi {b:.2f}   cross {c:5.2f} | {t[:30]}")
Output
bi 0.46   cross  8.65 | E03: the speed sensor is not r
bi 0.40   cross -0.82 | E05: the motor is overheating.
bi 0.44   cross -4.69 | These codes appear on the disp

Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Summary

A cross encoder reads question and chunk together, so it ranks far better, but it's too slow for search. Next, rewriting the question.

Key takeaways
  • Reads the pair
  • Clear scores
  • Rerank only
Next up: Query Rewriting — a clearer question