79 RAG Interview Questions and Answers (2026)

RAG has moved from demo trick to production backbone, and interviewers know it. They no longer stop at "what is retrieval-augmented generation?" They ask why your retrieval missed, how you'd chunk a messy PDF, and how you'd prove recall actually improved. Walk in with surface-level familiarity and it shows in the first follow-up.
This guide gives you 79 questions with concise, interview-ready answers, plus code where it helps. They run Junior → Mid → Senior, so you lock in the fundamentals first, then work up to reranking, ANN indexes, quantization and graph RAG. Work through them in order and you'll walk in ready to answer the follow-ups, not just the opener.
Q1.What specific problems does Retrieval-Augmented Generation solve compared with relying solely on a model's parametric memory?
RAG grounds the model in external documents fetched at query time. This fixes the core limits of parametric memory: knowledge that is frozen, incomplete, unverifiable and expensive to update.
Stale knowledge: Weights stop learning at the training cutoff. RAG pulls current data (today's prices, new policies) without retraining.
Private or domain data the model never saw
Hallucination:
With relevant passages in context, the model copies facts from evidence instead of reconstructing them from fuzzy memory.
It is also easier to make it say "not found" when retrieval returns nothing.
No attribution: Retrieved chunks carry source IDs, so answers can cite documents that users and auditors can check.
Cost and agility of updates: Updating knowledge means re-indexing documents, not fine-tuning. Deleting a document removes the knowledge, which matters for compliance.
Access control: Retrieval can filter by user permissions. Knowledge baked into weights can't be scoped per user.
Long-tail facts: Rare facts are poorly memorized. Retrieval surfaces them exactly.
Caveat: RAG is only as good as its retrieval. Bad chunks still produce wrong answers, and fine-tuning remains better for teaching style or behavior than facts.
Q2.What are the primary stages of the retrieve-then-generate pipeline?
A RAG pipeline has an offline indexing phase that prepares documents and an online query phase. The query phase retrieves relevant chunks and has the LLM generate an answer grounded in them.
Ingestion and parsing: Load sources (PDFs, HTML, databases) and extract clean text plus metadata (title, date, permissions).
Chunking: Split text into retrievable units sized for the embedding model and context window, often with overlap.
Embedding and indexing: Encode chunks into vectors and store them in a vector index (optionally also a BM25 index) along with their metadata.
Query processing: Optionally rewrite, expand or decompose the user query, then embed it.
Retrieval: Run an approximate nearest-neighbor search (and/or hybrid keyword search) with metadata filters to get the top-k candidates.
Reranking and filtering: A cross-encoder reorders the candidates. Keep the best few, dedupe them and fit them to the token budget.
Augmentation (prompt construction): Insert the chunks into a prompt with instructions: answer only from the context, cite sources, admit when the answer isn't there.
Generation and post-processing: The LLM produces the answer. Then attach citations, run guardrails or grounding checks, and log for evaluation.
Q3.How does recursive character chunking differ from fixed-size chunking?
Fixed-size chunking cuts text every N characters or tokens regardless of content. Recursive character chunking tries a hierarchy of natural separators so it splits at the largest meaningful boundary that still fits the size limit.
Fixed-size:
Simple, fast and predictable in size, usually with overlap to soften cut edges.
Often splits mid-sentence or mid-word, so chunks carry broken ideas and noisier embeddings.
Recursive (e.g. LangChain RecursiveCharacterTextSplitter):
Try splitting on the first separator, e.g. "\n\n" (paragraphs).
Any piece still larger than chunk_size is split with the next separator: "\n", then " ", then "".
Small adjacent pieces are merged back up toward chunk_size, with chunk_overlap.
Result:
Chunks mostly align with paragraphs and sentences, giving more coherent semantic units and better retrieval, while still respecting a size cap.
Chunk sizes vary more. Separators can be customized per format (e.g. code or Markdown).
It is still not semantic: it follows formatting, not meaning, but it is the common sensible default.
Q4.What is an inverted index and how does it make lexical retrieval fast?
An inverted index maps each term to a postings list of the documents containing it. A query only reads the postings for its own terms instead of scanning every document, so cost scales with the matching documents rather than with corpus size.
Structure:
Dictionary: term → pointer to its postings.
Postings entries: doc ID, term frequency, and optionally positions (needed for phrase queries).
Side statistics: document lengths and document frequency, which BM25 uses for normalization and IDF.
Why it's fast:
Sparsity: a query touches a handful of lists, and rare terms have short lists.
Postings are sorted by doc ID, which enables linear-time merging for OR/AND queries and skip pointers to jump ahead during intersection.
Compression (delta-encoded doc IDs plus variable-byte or bit-packing) keeps lists in memory or cache.
Dynamic pruning (WAND, MaxScore, Block-Max WAND) uses per-term score upper bounds to skip documents that cannot reach the top-k.
Used by Lucene, Elasticsearch/OpenSearch and Tantivy for BM25, and also for learned sparse models like SPLADE.
Q5.What does the faithfulness metric evaluate in a RAG system?
Faithfulness (groundedness) measures whether the generated answer is supported by the retrieved context. It catches hallucination: claims the model made up or pulled from its parametric memory instead of the provided documents.
How it's typically computed (e.g. RAGAS):
An LLM breaks the answer into atomic claims.
Each claim is checked: can it be inferred from the retrieved context?
Score = supported claims ÷ total claims, giving a value from 0 to 1.
What it does NOT measure:
Correctness: a faithful answer can still be wrong if the retrieved context is wrong.
Relevance: an answer can be fully grounded yet not address the question (that is answer relevancy).
Retrieval quality, which is covered by context precision and context recall.
It needs no ground-truth answer, only the question, the context and the answer, so it can run on production traffic.
Diagnostic use: low faithfulness with good context points to a generation problem. Typical fixes are prompting to answer only from context, citations, or a different model.
Q6.What does Mean Reciprocal Rank measure?
Mean Reciprocal Rank (MRR) measures how high the first relevant result appears, averaged over queries. For each query you take 1/rank of the first relevant item, then average those values.
Calculation:
MRR = (1/|Q|) · Σ 1/rank_i.
First relevant result at rank 1 scores 1.0, at rank 2 scores 0.5, at rank 4 scores 0.25.
If nothing relevant appears in the top k, the query scores 0 (this variant is MRR@k).
What it captures:
Only the first hit counts. Any additional relevant results are ignored.
It is steeply position-sensitive: moving a hit from rank 1 to 2 costs as much as moving it from 2 to infinity.
When to use it:
Good fit when one good answer suffices: QA, known-item search, or checking whether the top chunk is right.
Poor fit when the answer needs several chunks or relevance is graded. Use Recall@k or nDCG in those cases.
Q7.What is the difference between Recall@k and Precision@k in the context of RAG retrieval?
Recall@k and Precision@k in the context of RAG retrieval?Recall@k asks: of all the relevant chunks, what fraction made it into the top k? Precision@k asks: of the top k chunks, what fraction are relevant? Recall measures coverage, and precision measures noise.
Formulas:
Recall@k = relevant in top k ÷ total relevant.
Precision@k = relevant in top k ÷ k.
Example: 3 relevant chunks exist, and 2 of them appear in the top 5. Recall@5 = 0.67 and Precision@5 = 0.4.
Why recall usually matters more in RAG:
If a needed chunk isn't retrieved, the LLM cannot answer correctly, no matter how good it is.
The LLM can often ignore some irrelevant chunks, so missing evidence is the worse failure.
Why precision still matters:
Noisy context wastes tokens and raises cost and latency.
It can distract the model ("lost in the middle") or lead to answers grounded in the wrong passage.
The trade-off with k:
Raising k raises recall and typically lowers precision.
A common pattern is to retrieve a large k for recall, then rerank and keep a small top-n for precision.
Both ignore order within the top k. Use MRR or nDCG when ranking position matters.
Q8.What does nDCG measure in ranked search results?
nDCG (normalized Discounted Cumulative Gain) measures ranking quality with graded relevance. Highly relevant results should appear near the top. The score is normalized against the ideal ordering, so it falls between 0 and 1 and is comparable across queries.
Building blocks:
Gain: each result has a relevance grade (e.g. 0 to 3), not just relevant or irrelevant.
Discount: the gain at position i is divided by log2(i+1), so lower positions count less.
DCG@k: the sum of discounted gains over the top k.
nDCG@k = DCG@k ÷ IDCG@k, where IDCG is the DCG of the perfect ranking.
Why use it over simpler metrics:
Unlike Precision or Recall@k, it is order-aware.
Unlike MRR, it credits all relevant results, not just the first.
It distinguishes "perfect" from "partially relevant" results.
Common variant: gain = 2^rel − 1, which emphasizes highly relevant items.
Cost: it needs graded relevance labels, which are more expensive to collect than binary judgments.
Q9.What does context recall measure in RAG evaluation?
Context recall measures whether the retriever fetched all the information needed to answer the question. It is typically computed as the fraction of facts in a ground-truth reference answer that can be attributed to the retrieved context.
How it's computed (RAGAS-style):
Split the reference answer into claims or sentences.
An LLM judge checks whether each claim is supported by the retrieved chunks.
Score = attributable claims ÷ total claims.
Alternative: with labeled relevant chunk IDs, it reduces to classic retrieval recall (relevant retrieved ÷ total relevant).
Key properties:
It requires ground truth (a reference answer or labels), unlike faithfulness.
It evaluates the retriever, not the generator.
Interpreting it:
Low context recall means missing evidence. Typical fixes: increase k, use hybrid search (add BM25), improve chunking, or apply query rewriting.
Pair it with context precision: recall checks that everything needed was retrieved, and precision checks that what was retrieved is relevant and well ranked.
Q10.How does multi-query retrieval work?
Multi-query retrieval uses an LLM to rewrite one user question into several differently phrased queries. It retrieves for each query and fuses the results. This raises recall, because relevant chunks worded differently from the original question still get found.
Pipeline:
The LLM generates N variants (paraphrases, different angles or sub-questions).
Each variant, usually plus the original, is embedded and searched, often in parallel.
Results are unioned and deduplicated by chunk ID.
The union is ranked by Reciprocal Rank Fusion or a cross-encoder reranker, and the top-k go to the generator.
Why it helps:
A single embedding is one point in vector space. Several queries cover more of it.
It reduces vocabulary mismatch and sensitivity to how the question was phrased.
Costs:
An extra LLM call plus N searches add latency and spend.
Poor variants can drift off-topic and add noise, so reranking matters.
Example: LangChain's MultiQueryRetriever.
Q11.What is Hypothetical Document Embeddings (HyDE)?
HyDE)?HyDE (Gao et al., 2022) is a query-expansion technique. An LLM first writes a hypothetical answer document for the query, and that document's embedding (not the query's) is used to search the corpus. Retrieval then becomes answer-to-answer similarity instead of question-to-answer similarity.
Steps:
Prompt the LLM: "Write a passage that answers: {query}".
Embed the generated passage. Optionally average several samples together with the query embedding.
Run nearest-neighbor search with that vector and return the real documents.
Why it works:
Short questions and long documents sit in different regions of embedding space. A fake answer looks like real answers in style, vocabulary and length.
Hallucinated details mostly don't matter: the dense vector captures the relevance pattern, and only real documents reach the final answer.
It works zero-shot, with no relevance labels.
Limitations:
The extra LLM call adds latency and cost.
If the LLM lacks domain knowledge or misreads the query, it steers retrieval to the wrong topic.
Gains shrink with embedders already trained for asymmetric query-document retrieval.
Q12.What is context compression in retrieval pipelines?
Context compression shrinks retrieved content to only the parts relevant to the query before it reaches the generator. This cuts tokens, cost, and noise while keeping the evidence needed to answer.
Why it's needed:
Retrieved chunks are mostly irrelevant text around a few useful sentences.
Extra tokens raise cost and latency, and they dilute attention ("lost in the middle").
Compression frees budget to include more distinct sources.
Main approaches:
Filtering: drop whole chunks below a relevance threshold, using embedding similarity or reranker scores (e.g. LangChain EmbeddingsFilter).
Extractive: keep only query-relevant sentences or passages (e.g. LLMChainExtractor inside a ContextualCompressionRetriever).
Abstractive: an LLM summarizes chunks with respect to the query.
Token-level: models like LLMLingua prune low-information tokens. Small models trained for this, like RECOMP, are another option.
Risks:
It can drop qualifying context: negations, conditions, dates.
Abstractive summaries can introduce hallucinations and break exact citations.
An extra model call adds latency.
Evaluate it by checking that faithfulness and answer correctness hold while token count drops.
Q13.What is the architectural difference between a bi-encoder and a cross-encoder?
A bi-encoder encodes the query and the document separately into fixed vectors and compares them with a cheap similarity function; a cross-encoder feeds the query and document together through one transformer and outputs a relevance score directly. Bi-encoders scale to retrieval, while cross-encoders are more accurate but too slow to run over a whole corpus.
Bi-encoder: independent encoding:
Query and document each pass through an encoder (often shared weights) and are pooled into a single embedding.
Relevance = cosine or dot product of the two vectors, so document embeddings can be precomputed and stored in an ANN index.
Query cost: one encoder pass plus a fast vector search, which works over millions of documents.
Cross-encoder: joint encoding:
Input is the concatenated pair ([CLS] query [SEP] doc); a classification head outputs one score.
Full self-attention lets every query token attend to every document token, capturing fine-grained interactions (negation, exact matches, word order).
Nothing can be precomputed: each query needs N forward passes for N candidates.
Why the accuracy gap: The bi-encoder compresses a whole document into one vector before seeing the query (an information bottleneck); the cross-encoder conditions on both at once.
Typical pattern: retrieve then rerank:
Bi-encoder (often with BM25) retrieves the top 50 to 200 candidates fast.
Cross-encoder rescores only those candidates to pick the final top-k for the LLM.
Q14.Why is brute-force k-NN search impractical at scale?
Brute-force k-NN compares the query against every stored vector, so each query costs O(N·d): latency and compute grow linearly with corpus size and become unacceptable at millions to billions of vectors.
Compute cost:
1B vectors × 768 dims ≈ 768B multiply-adds per query, before sorting for top-k.
Multiply by query throughput (QPS) and hardware cost explodes.
Memory and bandwidth:
Raw float32 storage: 1B × 768 × 4 bytes ≈ 3 TB, which must be scanned fully each query.
Search becomes memory-bandwidth bound, not just FLOP bound.
No sublinear structure: Exact tree methods (KD-trees) degrade to near-linear in high dimensions (curse of dimensionality), so exact search rarely beats a scan.
The fix: approximate nearest neighbor (ANN): HNSW, IVF, and product quantization trade a small recall loss for orders-of-magnitude speedups and less memory.
When brute force is fine: small corpora (roughly under ~100K vectors), GPU-accelerated flat search, or as ground truth for measuring ANN recall.
Q15.What is iterative retrieval?
Iterative retrieval runs several rounds of retrieve-then-reason instead of one. The output of each round (a partial answer, a reasoning step, or a rewritten query) drives the next retrieval, so the system can gather evidence it could not have known to ask for up front.
Why single-shot retrieval falls short:
Multi-hop questions need a bridge fact first (e.g. "Who directed the film that won Best Picture in 1998?" requires finding the film before the director).
The original query embedding often lacks the vocabulary of the passages that hold the answer.
The basic loop:
Retrieve with the current query.
The LLM reasons or drafts an answer over the results.
Derive a new query from what was learned or what is still missing.
Repeat until a stopping condition is met, then produce the final answer.
Known variants:
IRCoT: interleaves each chain-of-thought step with a retrieval call.
ITER-RETGEN: uses the previous generation as the next query.
FLARE: retrieves only when the model is about to generate low-confidence tokens.
Trade-offs:
Each round adds LLM calls, so latency and cost grow.
Query drift: an early wrong hop compounds over later rounds.
You need explicit stopping rules (max hops, a confidence threshold, or "no new evidence").
Q16.What problem do contextual chunk headers solve during retrieval?
Contextual chunk headers fix the problem of chunks losing their context once cut from a document. A chunk like "Revenue grew 12%" doesn't say which company or year. Prepending document and section context makes the chunk retrievable and interpretable on its own.
The problem:
Chunks often rely on pronouns or implicit subjects ("it", "this policy") and on the surrounding headings.
Their embeddings miss key entities, so queries naming those entities don't match. Similar chunks from different documents also become indistinguishable.
The fix:
Before embedding, prepend a header such as the document title, a section path ("Acme 10-K 2023 > Financials > Revenue") or an LLM-generated one-line summary of the document.
A related variant is contextual retrieval: an LLM writes a chunk-specific context sentence, indexed for both embeddings and BM25.
Benefits:
Higher recall and precision, plus better disambiguation across documents.
The LLM also sees where the text came from at generation time.
Trade-offs:
Extra tokens per chunk, plus indexing cost if headers are LLM-generated.
Keep headers short so they don't dominate the chunk embedding.
Q17.How does semantic chunking decide where to split a document?
Semantic chunking splits where the meaning shifts. It embeds consecutive sentences and cuts where the similarity between neighbors drops sharply, so each chunk covers one coherent topic.
Typical algorithm:
Split the document into sentences.
Embed each sentence, often with a small window of neighboring sentences for stability.
Compute the cosine distance between each pair of adjacent sentences.
Mark breakpoints where the distance exceeds a threshold: a percentile (e.g. 95th), standard deviations above the mean, or an interquartile-range rule.
Group the sentences between breakpoints into chunks. Optionally enforce min and max sizes.
Why it helps: Chunks are topically coherent, so embeddings are focused and retrieval returns complete ideas.
Costs and caveats:
Every sentence must be embedded at index time, which is slower and more expensive.
Results are sensitive to the threshold, and chunk sizes can vary wildly.
Gains over recursive splitting are often modest. Benchmark before adopting it.
Q18.Why does parent-child chunking improve retrieval accuracy compared to flat chunking?
Parent-child chunking separates what you search on from what you give the LLM. Small child chunks are embedded for precise matching. When a child matches, its larger parent chunk is returned for full context. This resolves the precision-versus-context trade-off that a single flat chunk size forces.
The flat chunking dilemma:
Small chunks give sharp embeddings but too little context to answer.
Large chunks give enough context, but the embedding averages several topics, so the match is diluted and recall drops.
How parent-child works:
Split documents into parents (sections or ~1-2k tokens), then split each parent into children (~100-300 tokens) that keep a parent_id.
Index only the child embeddings. Store the parents in a docstore.
At query time, match children, map them to parents, dedupe, and pass the parents to the LLM.
Why accuracy improves:
Focused child embeddings match specific queries better.
Parents supply the surrounding definitions and caveats, so answers are more complete and faithful.
Trade-offs:
Larger contexts cost more tokens, and parents may include irrelevant text.
It adds storage and mapping complexity. Variants include sentence-window retrieval and auto-merging.
Q19.How does structure-aware chunking handle headings, tables and code blocks differently from plain text splitting?
Structure-aware chunking uses the document's own layout (headings, tables, code fences, lists) as split boundaries and metadata. Plain text splitting treats everything as a character stream and cuts wherever the size limit lands.
Headings:
Split at section boundaries (e.g. MarkdownHeaderTextSplitter on #/##, or HTML <h1>-<h3>).
Store the heading path as metadata or prepend it to the chunk, so each chunk knows its context.
Oversized sections are sub-split recursively.
Tables:
Keep a table atomic, or split it by rows while repeating the header row in every piece so the values stay interpretable.
It is often serialized to Markdown, HTML or row-wise "column: value" text, or summarized by an LLM for the embedding while the raw table is stored for generation.
Plain splitting would scatter cells and orphan rows from their headers.
Code blocks:
Never cut inside a fence. Split code at function or class boundaries (language-aware separators or AST parsing).
Keep the explanatory prose and its imports or signature with the code.
Other structure: Lists stay with their lead-in sentence. Figure captions, page numbers and element types are kept as metadata for filtering and citation.
Requirements:
You need a good parser (e.g. layout-aware PDF parsing via unstructured or Docling) to recover the structure first.
Payoff: coherent, self-describing chunks and far fewer broken tables or code snippets in answers.
Q20.What happens when a chunk exceeds the embedding model's maximum input length?
Usually the input is silently truncated: the model embeds only the first N tokens and ignores the rest, so part of the chunk never influences its vector. Some APIs instead reject the request with an error.
What libraries do:
Local models (e.g. sentence-transformers) truncate to max_seq_length (often 256 or 512 tokens) with no warning.
Hosted APIs typically return an error above their token limit, or truncate if a truncation flag is set.
Why silent truncation hurts retrieval:
The full chunk text is still stored and sent to the LLM, but its vector represents only the head. Queries about the tail content won't match it.
It is hard to detect because nothing fails. Recall just quietly drops for content near chunk ends.
Fixes:
Chunk by tokens using the embedding model's own tokenizer, not by characters or words, and stay safely below the limit.
Add a validation step at ingest that counts tokens and re-splits any oversized chunk.
Use a long-context embedding model, keeping in mind that very long chunks dilute the vector's meaning anyway.
Last resort: split into sub-chunks and pool their embeddings (e.g. average them). This works but blurs the signal.
Q21.How does Reciprocal Rank Fusion combine multiple ranked lists?
RRF ignores raw scores. It gives each document 1 / (k + rank) from every list it appears in, sums those contributions, and re-sorts. Documents ranked highly by several retrievers rise to the top.
Formula:
RRF(d) = Σ_i 1 / (k + rank_i(d)), where ranks are 1-based.
A document absent from a list contributes 0 for that list (in practice, lists are truncated to the top N).
The constant k (commonly 60):
It dampens the gap between top ranks: with k=60, rank 1 scores 1/61 and rank 2 scores 1/62. No single list dominates.
A smaller k favors top positions more aggressively.
Behavior:
It rewards consensus: rank 5 in both lists beats rank 1 in only one list.
It needs no training or score normalization and works with any number of lists (BM25, dense, multiple query rewrites).
Weighted variants multiply each list's term by a weight.
Q22.Why is rank-based fusion like RRF often preferred over raw score combination?
Scores from different retrievers live on incomparable, query-dependent scales, so adding them is mostly adding noise. Ranks are directly comparable, which makes RRF robust and calibration-free.
Problems with raw scores:
BM25 is unbounded and varies with query length and term rarity. Cosine similarity sits in a narrow band (e.g. 0.7–0.9 for most candidates).
Distributions shift per query, so a fixed weight such as 0.5*bm25 + 0.5*cos is effectively a different weighting on every query.
Normalization is fragile:
Min-max scaling is sensitive to outliers and to how many candidates you keep. Z-scores assume well-behaved distributions.
Fusion weights need labeled data to tune and break when you swap a model.
Why RRF works well:
It is scale-invariant, needs no training, and has a single forgiving parameter (k).
It rewards documents several retrievers agree on and is a strong, hard-to-beat default.
Trade-offs:
It discards confidence: a huge score gap and a tiny one at adjacent ranks count the same.
With good labeled data, a tuned convex combination of normalized scores, or a cross-encoder reranker after fusion, can outperform RRF.
Q23.What is learned sparse retrieval?
Learned sparse retrieval uses a neural model to produce sparse, vocabulary-sized term-weight vectors for queries and documents. You get BM25-style exact matching and inverted-index efficiency, but with learned term importance and term expansion that adds semantic matching.
How it works:
A transformer (e.g. BERT with its MLM head, as in SPLADE) outputs a weight for each vocabulary term. Most weights are zero.
Re-weighting: important terms get high weights, filler terms get low ones, all learned from relevance data rather than raw TF-IDF.
Expansion: terms absent from the text can still get weight (e.g. "car" → "vehicle"), which reduces vocabulary mismatch.
Score = dot product over shared terms.
Examples: SPLADE, uniCOIL, DeepImpact, and ELSER in Elasticsearch.
Advantages:
It is served from a standard inverted index with WAND-style pruning.
It is interpretable: you can see which terms matched.
It handles exact tokens (IDs, rare names) better than dense vectors and often generalizes well out of domain.
Costs:
Expansion lengthens postings lists. Sparsity regularization (e.g. a FLOPS penalty) controls the speed/quality trade-off.
Documents require model inference at index time. Some variants make the query side inference-free to cut latency.
It is tied to the model's tokenizer vocabulary.
Q24.What does the k1 parameter control in the BM25 scoring formula?
k1 parameter control in the BM25 scoring formula?k1 controls term-frequency saturation: how quickly extra occurrences of a query term stop adding to the score. Low k1 saturates fast and approaches binary matching. High k1 lets frequency keep raising the score almost linearly.
Where it appears:
score = IDF · tf·(k1+1) / (tf + k1·(1 − b + b·dl/avgdl))
As tf → ∞, the term's contribution approaches IDF·(k1+1), so k1 also sets the ceiling.
Extremes:
k1 = 0: frequency is ignored, so only presence or absence (plus IDF) counts.
Large k1: scoring behaves close to raw TF, so keyword-stuffed documents get rewarded.
Typical values are 1.2–2.0 (Lucene and Elasticsearch default to 1.2).
Interaction with b:
b scales length normalization inside the same denominator, so long documents need more occurrences to reach the same saturation.
Tune k1 and b together on a labeled query set, because the defaults are rarely optimal for a specific corpus.
Q25.How does BM25 improve upon classical TF-IDF?
BM25 keeps TF-IDF's core idea (reward query terms that are frequent in a document but rare in the corpus) but fixes its two main weaknesses: unbounded term-frequency growth and no principled handling of document length. It also uses a probabilistically derived IDF.
Term-frequency saturation (k1):
In TF-IDF, 50 occurrences score far higher than 5, so keyword-stuffed documents win.
BM25 uses tf·(k1+1)/(tf+k1·norm), which rises quickly then plateaus. Extra repetitions add diminishing value. k1 (typically 1.2 to 2.0) sets how fast it saturates.
Document length normalization (b):
Long documents naturally contain more term occurrences. BM25 scales TF relative to the corpus average length, so long documents aren't unfairly favored.
The strength of this is tunable rather than fixed.
Probabilistic IDF: It is derived from the Robertson–Spärck Jones probabilistic relevance model: log((N − n + 0.5)/(n + 0.5) + 1). Very common terms contribute near zero.
Practical result: BM25 is a strong, tunable lexical baseline. It is the default in Lucene, Elasticsearch and OpenSearch, and it serves as the sparse half of hybrid RAG retrieval (exact matches on IDs, codes and rare names).
Q26.How do you construct a ground-truth evaluation dataset for a retrieval system?
Build a set of realistic queries, each paired with the documents or chunks that are relevant to it (ideally graded, and optionally with a reference answer). Then use that set as a fixed benchmark to compute Recall@k, MRR and nDCG for every retrieval change.
1. Source the queries:
Best: real user queries from logs, sampled to match production distribution.
Subject-matter experts write questions covering key topics and edge cases.
Synthetic: an LLM generates questions from sampled chunks, which gives a free positive label. Filter out trivial, lexically copied questions and spot-check quality.
2. Label relevance:
Pooling: union the top-k results from several retrievers (BM25, dense, hybrid), then have humans or an LLM judge grade them. This finds relevant docs the original source chunk missed.
Use graded labels (e.g. 0 to 3) if you plan to report nDCG.
Write annotation guidelines, double-label a subset, and measure inter-annotator agreement.
Calibrate any LLM judge against human labels before trusting it.
3. Ensure coverage:
Mix query types: factoid, multi-hop, keyword or ID lookups, paraphrased, and ambiguous.
Include unanswerable queries (no relevant doc) to test abstention.
Include hard negatives that look similar but are wrong.
4. Make it durable:
Label at the document or passage level (or with stable IDs) so re-chunking doesn't invalidate labels.
Version the dataset and keep a held-out split so you don't tune to the test set.
Refresh it as the corpus and user behavior drift. Feed production failures back in as new cases.
Size: a few hundred well-labeled queries usually beat thousands of noisy ones for comparing systems.
Q27.In RAG evaluation, what is the difference between context relevance and faithfulness?
Context relevance evaluates the retriever: did the retrieved chunks actually address the query? Faithfulness evaluates the generator: is every claim in the answer supported by those retrieved chunks? Measuring them separately tells you which stage of the pipeline failed.
Context relevance (query ↔ context):
Asks what fraction of the retrieved content is useful for answering the question, versus noise or off-topic text.
Low scores point to retrieval problems: bad chunking, a weak embedding model, missing hybrid search, or no reranker.
Faithfulness / groundedness (answer ↔ context):
Typically computed by splitting the answer into atomic claims, then using an LLM or NLI model to check whether the context entails each one. The score is supported claims divided by total claims (this is how RAGAS does it).
Low scores mean the generator is hallucinating or mixing in parametric knowledge. Fix it with prompting, citation requirements, or a different model.
Why the two are independent:
Relevant context with an unfaithful answer means the generator ignored good evidence.
Irrelevant context with a faithful answer means the answer is grounded but useless (or wrong), because the evidence itself was wrong.
Faithfulness is not correctness: an answer can be fully faithful to a stale or incorrect document.
These two usually sit alongside answer relevance (does the answer address the question?) and context recall (was all needed information retrieved?).
Q28.How do you compute Discounted Cumulative Gain?
DCG sums the graded relevance of each ranked result, discounting each by the log of its position, so relevant items near the top count more. You usually normalize it by the ideal DCG to get nDCG in [0, 1].
Formula (cutoff k):
Standard form: DCG@k = Σ_{i=1..k} rel_i / log2(i + 1). Position 1 gets a discount of 1, position 2 gets 1/1.585, and so on.
Exponential gain variant: (2^rel_i − 1) / log2(i + 1). This rewards highly relevant items more strongly and is common in web search. State which variant you are using.
Normalization:
Sort the true relevance labels in descending order and compute DCG on that ideal ranking. This gives IDCG.
Compute nDCG@k = DCG@k / IDCG@k. This makes scores comparable across queries that have different numbers of relevant documents.
Worked example: relevances [3, 2, 0, 1] give 3/1 + 2/1.585 + 0/2 + 1/2.322 ≈ 4.69. The ideal order [3, 2, 1, 0] gives ≈ 4.76, so nDCG ≈ 0.985.
Why use it: unlike Recall@k, DCG handles graded relevance and is sensitive to rank order.
Q29.What causes domain shift in retrieval embeddings?
Domain shift happens when the text and relevance patterns in your corpus and queries differ from what the embedding model saw in training (typically web text and MS MARCO-style QA). The vectors then stop separating relevant from irrelevant content in your domain.
Vocabulary and tokenization: Jargon, acronyms, product codes, and IDs are rare or absent in pretraining. They get split into meaningless subwords and end up with poor representations.
Semantic drift of terms: The same word means different things in different fields ("cell" in biology vs. telecom, "consideration" in law). The model applies the general sense.
Format and length mismatch: Tables, code, logs, OCR noise, and very long or very short chunks don't resemble the training passages.
Query distribution: Real users send keyword fragments, internal shorthand, or other languages, unlike the clean natural questions in training data.
Different notion of relevance: General models learn topical similarity. Your domain may need exact matches (statute numbers, drug dosages) or need to distinguish documents that are topically close but contradict each other.
Temporal drift: new entities, products, and events appear after the model was trained.
Symptoms and mitigations:
Symptoms: domain documents cluster tightly with uniformly high cosine scores, and Recall@k is good on public benchmarks but poor on your eval set.
Mitigations: hybrid BM25 plus dense search, a cross-encoder reranker, a domain-pretrained model, or fine-tuning on synthetic in-domain query–chunk pairs with hard negatives.
Q30.Why do retrieval models use asymmetric encoders for queries versus documents?
Queries and documents are different kinds of text playing different roles. A short, underspecified question has to match a long passage that answers it, not a passage that resembles it. Asymmetric encoding lets the model learn that mapping, and also lets you split compute between offline indexing and online querying.
Input asymmetry:
Queries are a few words, often keyword-like, and express an information need. Documents are long and full of facts.
The task is query → answer, not paraphrase detection. A symmetric model tends to retrieve other questions that look like the query.
Ways to implement it:
Separate towers: DPR uses two distinct BERT encoders, one for questions and one for passages.
Shared weights with role markers: E5 uses "query: " and "passage: " prefixes, and BGE and Instructor prepend instructions. This is cheaper and still role-aware.
Both towers must still project into the same vector space so dot product or cosine similarity is meaningful.
Compute asymmetry: Documents are encoded once offline, so a heavy encoder is affordable there. Queries are encoded per request, so a lighter query encoder reduces latency. Learned sparse models push this to the extreme with inference-free query encoding.
Pitfall: forgetting the query or passage prefix at inference silently degrades recall. For symmetric tasks (duplicate detection, clustering), use the same encoding mode on both sides.
Q31.How does contrastive learning train retrieval embedding models?
Contrastive learning trains a bi-encoder so that a query's embedding scores higher with its relevant passage than with non-relevant ones. A softmax loss (InfoNCE) pulls positive pairs together and pushes negatives apart in the vector space.
Training data: Each example is a (query, positive passage) pair plus negatives: in-batch negatives (other queries' positives) and mined hard negatives.
InfoNCE loss:
Compute similarities s(q, d) = cos(E_q(q), E_d(d)) / τ, then apply cross-entropy over the candidates with the positive as the correct class.
Temperature τ (around 0.01–0.05) sharpens the distribution and controls how strongly hard negatives are penalized.
Why batch size matters: With in-batch negatives, a batch of B gives B−1 free negatives per query. Larger batches (or memory banks and gradient caching) give more negatives and a tighter embedding space.
Typical recipe:
Weakly supervised pretraining on huge numbers of noisy pairs (title–body, QA forums, citations).
Fine-tuning on labeled retrieval data (MS MARCO, NQ) with hard negatives, often plus distillation from a cross-encoder teacher's scores.
Q32.What is the role of query rewriting in conversational multi-turn RAG?
In multi-turn chat, follow-up questions depend on earlier context ("what about its pricing?"), but the retriever is stateless. Query rewriting uses the chat history to turn each follow-up into a standalone, self-contained search query, so retrieval finds the right documents.
Problems it solves:
Coreference: "it" or "that plan" is resolved to the actual entity.
Ellipsis: "and for Europe?" becomes "What is the refund policy for Europe?"
Embedding the raw follow-up retrieves vague or irrelevant chunks. Embedding the whole history dilutes the signal.
How it's done:
A "condense question" LLM step takes the recent turns plus the new message and outputs a standalone query (e.g. LangChain create_history_aware_retriever).
It can also decompose compound questions or add keywords for hybrid search.
Side benefits: Standalone queries are cacheable, loggable and easier to evaluate.
Pitfalls:
It adds latency, so use a small, fast model.
The rewriter can carry over stale context after a topic shift, or distort user intent.
Pass only recent turns, and consider retrieving with both the original and the rewritten query.
Q33.How does query rewriting improve retrieval recall?
Query rewriting improves recall by turning the user's raw query into one or more forms that better match how relevant documents are actually written. This closes the vocabulary and intent gap, so the retriever surfaces chunks it would otherwise miss.
The core problem is query/document mismatch:
Users write short, vague, or colloquial queries ("my app keeps crashing"), while docs use precise terms ("OOM error in worker process").
Dense retrieval tolerates synonyms partly. BM25 misses them entirely. Both struggle with underspecified or multi-intent queries.
Common rewriting techniques:
Clarification/normalization: fix typos, expand acronyms, add domain terms.
Conversational rewriting: resolve pronouns and context from chat history ("what about its pricing?" becomes "What is Product X's pricing?").
Expansion: add synonyms or related terms. This mainly helps lexical retrieval.
Multi-query: an LLM generates several paraphrases, retrieves for each, and merges the union (e.g. with Reciprocal Rank Fusion).
HyDE / step-back: embed a hypothetical answer, or a more general version of the question, instead of the literal query.
Why recall goes up:
Each variant probes a different region of the embedding or term space. The union covers more relevant chunks than any single query.
Precision is recovered downstream with a reranker.
Costs and risks:
An extra LLM call adds latency and cost.
Query drift: a rewrite can change the meaning or drop exact identifiers. Keep the original query in the set.
Validate the gain with recall@k on a labeled eval set rather than assuming it.
Q34.When would you use query decomposition instead of simple query rewriting?
Use decomposition when the question needs several distinct pieces of evidence that no single query would retrieve together. Rewriting only rephrases one information need. Decomposition splits a compound or multi-hop question into sub-questions, retrieves for each, then synthesizes the results.
Rewriting is enough when: There is one information need that is just poorly phrased, ambiguous, or dependent on chat context.
Decomposition fits when:
Comparative questions: "Compare the refund policies of Plan A and Plan B" needs one retrieval per entity.
Multi-hop questions: "Who manages the team that owns service X?" requires finding the team first, then its manager.
Aggregations across time or entities: "How did revenue change from 2021 to 2023?"
Compound asks: several unrelated questions in one message.
Two execution styles:
Parallel: the sub-questions are independent (comparisons), so retrieve them concurrently and merge.
Sequential: each answer feeds the next sub-query (multi-hop), as in least-to-most or IRCoT-style iterative retrieval.
Trade-offs:
More LLM and retrieval calls mean higher latency and cost.
Errors compound across hops: a wrong first hop poisons the rest.
Over-decomposing simple queries adds noise. Route with a classifier, or let the LLM decide whether to split.
Q35.How does Maximal Marginal Relevance balance relevance and diversity among retrieved chunks?
MMR selects chunks greedily. At each step it picks the candidate that is most similar to the query but least similar to the chunks already chosen. A weight λ sets the trade-off between relevance and novelty.
The scoring rule:
MMR(d) = λ · sim(d, q) − (1 − λ) · max over selected s of sim(d, s)
The first term rewards relevance to the query. The second penalizes redundancy with the closest already-selected chunk.
The algorithm:
Retrieve a larger candidate pool by similarity (fetch_k, e.g. 20–50).
Pick the most relevant chunk first.
Repeatedly add the candidate with the highest MMR score until k chunks are selected.
Tuning λ:
λ = 1 is pure similarity search. λ = 0 is pure diversity.
Values around 0.5–0.7 are typical.
When it helps:
Corpora with overlapping or near-duplicate chunks.
Broad questions that need several facets covered.
Caveat:
Too much diversity pulls in less relevant chunks.
For narrow factoid queries, plain top-k plus a reranker may be better.
Q36.How do you choose how many top-k chunks to pass to the generator?
Choose k empirically. Raising k improves the chance the evidence is present (recall), but it adds noise, cost, and attention dilution. Tune k on an eval set, and usually retrieve wide, rerank, then pass a small, high-precision set.
The trade-off:
Too small: the needed chunk is missing, so the model answers wrong or says "I don't know".
Too large: distractors cause errors, "lost in the middle" sets in, and latency and token cost rise.
Measure it:
Plot retrieval recall@k to find where gains flatten.
Then sweep k against end-to-end metrics (answer correctness, faithfulness) and pick the knee of the curve.
Two-stage pattern:
Retrieve 20–100 candidates for recall.
A cross-encoder reranks them, and the top 3–10 go to the generator.
Make k adaptive:
Use a relevance-score threshold, or cut off where scores drop sharply, instead of a fixed k.
Vary k by query type: factoid queries need few chunks, while summaries and comparisons need more.
Constraints:
Chunk size times k must fit the context budget, leaving room for instructions and output.
Smaller chunks allow a larger k.
Q37.Why should near-duplicate chunks be removed before assembling the context for generation?
Near-duplicates waste the limited context budget on repeated information. They crowd out distinct evidence and can skew the model toward over-represented content, so deduplication raises the information density of the context.
Where duplicates come from:
Overlapping chunk windows.
The same document stored in multiple versions or formats.
Boilerplate (headers, disclaimers).
Merged results from multi-query or hybrid retrieval.
Why they hurt:
Token waste: they raise cost and latency without adding facts.
Lost coverage: they fill top-k slots that diverse, complementary chunks should occupy.
Bias: repetition acts as false emphasis, and the model may treat a repeated claim as more authoritative.
Version conflicts: slightly different copies (old vs new policy) can produce contradictory answers.
Messy citations: several sources point to the same content.
How to dedupe:
Exact duplicates: hashing.
Near duplicates: MinHash/SimHash, or a cosine-similarity threshold between chunk embeddings (e.g. above 0.95).
Merge adjacent overlapping chunks from the same document.
Prefer the newest or most authoritative version.
Apply MMR for softer redundancy control.
Dedupe at ingestion as well as at query time.
Q38.How do LLM-based rerankers differ from cross-encoder rerankers?
Both score query-document relevance jointly, but a cross-encoder is a small model fine-tuned to output a relevance score per pair, while an LLM reranker prompts a large generative model to judge or order candidates. LLM rerankers offer more reasoning and instruction-following at much higher latency and cost.
Cross-encoder rerankers:
Encoder models (BERT/MiniLM-sized, e.g. ms-marco-MiniLM, bge-reranker) trained on labeled relevance pairs.
Pointwise: one forward pass per (query, doc) pair, producing a calibrated-ish score; batches well on a GPU.
Fast and cheap (milliseconds per pair), but limited by input length and training domain.
LLM-based rerankers:
Decoder LLMs prompted (or fine-tuned, e.g. RankGPT, RankZephyr) to rate or rank documents.
Can be pointwise (score each doc), pairwise (which of two is better), or listwise (output a permutation of many docs, often via sliding windows).
Strengths: world knowledge, multi-step reasoning, custom instructions ("prefer recent policy docs"), strong zero-shot quality in new domains.
Trade-offs of LLM rerankers:
Much higher latency and token cost; listwise output is sequential generation.
Less stable: position bias, sensitivity to prompt wording, occasional malformed output that needs parsing fallbacks.
Context-window limits cap how many candidates fit per call.
Practical choice: cross-encoder as the default reranker; LLM reranking on a small top-k when queries need reasoning or quality outweighs cost (sometimes cascaded after a cross-encoder).
Q39.How does an Inverted File (IVF) index accelerate nearest-neighbor retrieval?
IVF) index accelerate nearest-neighbor retrieval?IVF partitions the vector space into clusters with k-means and stores each vector in the inverted list of its nearest centroid. At query time it scans only the few clusters closest to the query instead of the whole dataset, cutting comparisons dramatically at a small cost in recall.
Build (training) phase:
Run k-means on a sample to get nlist centroids (Voronoi cells).
Assign every vector to its nearest centroid's list.
Query phase:
Compare the query to all centroids (cheap: nlist is small).
Pick the nprobe nearest cells.
Exhaustively scan only vectors in those lists and return the top-k.
Why it's faster: Work drops from N comparisons to roughly nlist + nprobe·(N/nlist).
Where recall is lost: A true neighbor near a cell boundary may sit in an unprobed cell; raising nprobe recovers it.
Common pairing: IVF-PQ (e.g. FAISS IndexIVFPQ) compresses vectors inside lists with product quantization to also save memory.
Q40.What is the core trade-off among latency, memory, and recall in ANN indexes?
ANN indexes let you pick at most two of low latency, low memory, and high recall: improving one usually costs another. Every index type and parameter is a position on this triangle, so tuning means choosing the cheapest point that meets your recall target.
Recall vs latency: Searching more candidates finds more true neighbors but takes longer (HNSW efSearch, IVF nprobe).
Memory vs recall:
Compression (product or scalar quantization, binary) shrinks vectors 4 to 64x but approximates distances, lowering recall.
Re-ranking with full-precision vectors can win recall back at extra cost.
Memory vs latency:
HNSW is fast and accurate but stores full vectors plus graph links (higher M means more memory).
Disk-based indexes (DiskANN) save RAM but add I/O latency.
Hidden fourth axis: build time and updatability: High efConstruction or IVF retraining costs time; some indexes handle inserts and deletes poorly.
How to tune in practice: Compute ground truth with brute force on a sample, plot recall@k vs latency, and pick the cheapest configuration meeting the target under your memory budget.
Q41.What is the difference between efConstruction and efSearch in HNSW?
efConstruction and efSearch in HNSW?Both set the size of the dynamic candidate list in HNSW's greedy graph search, but efConstruction applies at index build time (finding neighbors for each inserted node) while efSearch applies at query time (finding the query's nearest neighbors).
efConstruction (build-time):
When inserting a vector, HNSW searches with this beam width to find candidates, then keeps up to M links.
Higher values give a better-connected graph and higher achievable recall, at the cost of slower indexing.
Fixed once the index is built: changing it requires a rebuild.
efSearch (query-time):
How many candidates the search keeps while traversing the bottom layer; must be at least k.
Higher values mean better recall but more latency per query.
Tunable per query without rebuilding, so it is the main runtime recall/latency knob.
How they interact: efConstruction sets the ceiling of graph quality; efSearch decides how much of that quality each query exploits. A poor graph can't be fully rescued by a huge efSearch.
Typical starting points: M=16, efConstruction=200, then sweep efSearch (50 to 500) against measured recall.
Q42.What is agentic retrieval at a conceptual level?
Agentic retrieval puts an LLM agent in control of the retrieval process. It decides whether to retrieve, what to search for, which source or tool to use, and whether the results are good enough, working in a plan-act-observe loop rather than a fixed retrieve-then-generate pipeline.
Contrast with classic RAG:
Classic RAG always runs one similarity search on the raw query and passes the top-k results to the generator.
Agentic RAG treats retrieval as a tool the model calls dynamically, possibly zero or many times.
Core capabilities:
Query planning: decomposes complex questions into sub-queries and rewrites vague ones.
Routing: chooses among a vector store, SQL, web search, APIs, or a knowledge graph.
Self-evaluation: grades retrieved context and re-queries or switches sources when it is weak.
Synthesis: combines evidence from multiple steps and sources into one answer.
Relation to other patterns:
It generalizes iterative retrieval, Self-RAG, and CRAG: those hard-code one decision policy, while an agent reasons about the policy itself.
It is often implemented with ReAct-style prompting or tool calling (e.g. via LangGraph or LlamaIndex agents).
Trade-offs:
Gains: better accuracy on multi-hop, multi-source, and ambiguous queries.
Costs: higher latency and token cost, non-determinism, and harder debugging and evaluation.
Required guardrails: step budgets and loop limits.
Q43.What is Corrective RAG (CRAG) at a conceptual level?
Corrective RAG (Yan et al., 2024) adds a lightweight retrieval evaluator that grades the retrieved documents before generation. Depending on the confidence score, it keeps and refines the documents, discards them and falls back to web search, or blends both. Bad retrieval is then corrected instead of being passed straight to the LLM.
Retrieval evaluator:
A small fine-tuned model (T5-large in the paper) scores the relevance of each query-document pair.
Thresholds map the scores to one of three actions: Correct, Incorrect, or Ambiguous.
The three actions:
Correct: run knowledge refinement. Documents are split into small "strips", irrelevant strips are filtered out, and the rest are recomposed.
Incorrect: discard the retrieved documents, rewrite the query into search keywords, and use web search results instead.
Ambiguous: combine the refined internal documents with the web results.
Key properties:
Plug-and-play: it wraps any retriever and generator without retraining the LLM (unlike Self-RAG).
It targets the most common RAG failure: confidently generating from irrelevant context.
Caveats:
Quality depends on the evaluator, and thresholds need tuning.
The web fallback adds latency and may be unacceptable for private-data domains.
Q44.How does GraphRAG structure knowledge for retrieval?
GraphRAG uses an LLM to turn unstructured text into a knowledge graph of entities and relationships. It then clusters that graph into a hierarchy of communities and pre-writes a summary for each one. Retrieval can therefore follow explicit connections and use pre-aggregated summaries, not just isolated chunks.
Indexing pipeline (Microsoft GraphRAG):
Chunk the corpus into text units.
The LLM extracts entities, relationships (with descriptions and weights), and optionally claims from each chunk.
Merge duplicate entities and summarize their descriptions to form the graph: nodes are entities, edges are relationships.
Run hierarchical community detection (Leiden) to group densely connected entities at multiple levels.
Generate community reports bottom-up, so higher levels summarize their sub-communities.
What gets stored: The graph itself, entity and relationship descriptions, links back to source text units, community reports, and embeddings for entities and text.
How retrieval uses the structure:
Local search: match query entities, fan out to neighbors, relationships, and source chunks. Good for entity-specific questions.
Global search: map-reduce over community reports. Good for corpus-wide themes.
DRIFT search: starts from community context, then refines with local follow-ups.
Cost: indexing requires many LLM calls, and extraction errors propagate into the graph.
Q45.What are the primary failure points in an end-to-end RAG system?
RAG can fail at every stage, and errors compound. Bad parsing or chunking ruins retrieval, bad retrieval starves generation, and even good context can be ignored or misused by the LLM.
Ingestion and parsing:
Text is garbled when extracted from PDFs, tables and scans. Metadata goes missing and stale documents pile up.
Missing content: the answer simply isn't in the corpus.
Chunking:
Chunks that are too small lose context. Chunks that are too large dilute the embedding.
Splits can cut a table or a definition in half.
Retrieval:
The relevant chunk isn't in the top-k (low recall), often due to vocabulary mismatch, exact IDs or acronyms that dense search misses, or a weak embedding model.
Wrong metadata filters or permission filters can exclude the right document.
Ranking and context assembly:
The right chunk is retrieved but cut off by the token budget or reranked too low.
"Lost in the middle": the model under-attends to passages buried mid-context.
Generation:
The model ignores the context and hallucinates from parametric memory, or fails to extract the answer.
Wrong format, incomplete answers to multi-part questions, or fabricated citations.
Query understanding: Ambiguous or multi-hop questions need rewriting or decomposition. Without it, a single vector lookup fails.
Operational: The index drifts out of sync with the source data, latency or cost blows up, and no evaluation exists to detect regressions.
Debugging tip: evaluate retrieval (recall@k) separately from generation (faithfulness) to localize the failure.
Q46.How does late chunking differ conceptually from traditional pre-embedding chunking?
Traditional chunking splits the document first and embeds each chunk in isolation. Late chunking runs the whole document through the embedding model first, then pools the token embeddings for each chunk span. Every chunk vector is therefore conditioned on the full document context.
Traditional (chunk then embed):
Each chunk sees only its own text. References like "it", "the company" or "this method" lose their antecedents if those sit in another chunk.
The result is chunk vectors missing key entities, which hurts recall.
Late chunking (embed then chunk):
Encode the full document with a long-context model and keep the per-token output embeddings (before pooling).
Map chunk boundaries onto token spans.
Mean-pool the tokens in each span to get one vector per chunk.
Why it works: Attention has already mixed document-wide context into every token, so the chunk vector "knows" what "it" refers to.
Properties and limits:
Index size and query path stay the same: still one vector per chunk.
It needs a long-context embedding model that exposes token-level outputs and uses mean pooling.
Documents longer than the context window must still be split into macro-windows.
It is cheaper than LLM-based "contextual retrieval", which writes a context prefix for each chunk, because no generation step is required.
Q47.How would you empirically tune chunk size and overlap for a new document corpus?
Treat chunking as a hyperparameter search. Build a labeled evaluation set, index the corpus under several size and overlap configurations, and pick the one that maximizes retrieval and answer quality within your token and cost budget.
Build an evaluation set:
Collect 50 to a few hundred realistic queries, each with gold answers or gold source spans. Real user logs are best; LLM-generated queries can bootstrap the set.
Label at the span level, not the chunk level, so labels stay valid when chunk boundaries change.
Define the grid:
Size, measured in tokens: e.g. 128, 256, 512, 1024.
Overlap: e.g. 0%, 10%, 20%.
Splitter type: fixed-length, recursive, or structure-aware (headings, sections).
Measure:
Retrieval metrics: recall@k, MRR, nDCG. A hit means the retrieved chunk contains the gold span.
End-to-end metrics: answer correctness and faithfulness, judged by an LLM or by humans.
Compare at an equal context budget (total retrieved tokens), because larger chunks trivially raise recall@k.
Interpret the trade-offs:
Small chunks give precise vectors but fragment context. Large chunks keep context but dilute the embedding and waste prompt space.
Overlap protects facts that straddle a boundary, at the cost of index size and duplicate results.
Break results down by query type (factoid vs. summary) and by document type. The best setting may differ, which can justify per-source configurations.
Hold out part of the evaluation set to confirm the winner, and re-run the search when the corpus or embedding model changes.
Q48.What does the b parameter control in BM25?
b parameter control in BM25?b controls how strongly BM25 normalizes term frequency by document length. It ranges from 0 (no length normalization) to 1 (full normalization), and the usual default is 0.75.
Where it appears:
The TF denominator becomes tf + k1·(1 − b + b·|d|/avgdl).
If a document is longer than average (|d| > avgdl), its effective TF shrinks. If it is shorter, its TF is boosted.
Extremes:
b = 0: length is ignored, so long documents win simply by containing more words.
b = 1: TF is fully scaled by relative length, which penalizes long documents the most.
Tuning intuition:
Lower b when length reflects genuinely more relevant content (e.g. long, comprehensive docs).
Keep or raise it when length is mostly verbosity or boilerplate.
In RAG, chunks are often similar in size, so b matters less than it does on whole documents.
Contrast with k1: k1 controls TF saturation, while b controls length normalization.
Q49.How can you construct a synthetic evaluation dataset with ground-truth query-chunk pairs without manual labeling?
Reverse the problem: sample chunks from your corpus and have an LLM write questions that each chunk answers. Each (generated question, source chunk ID) pair becomes a labeled example for free, which you can then score with Recall@k, MRR, or nDCG.
Generation pipeline:
Sample chunks, stratified across documents and topics so popular sections don't dominate.
Prompt an LLM to produce 1–3 questions per chunk that are answerable only from that chunk. Optionally also generate a reference answer for end-to-end evaluation.
Store the pair as (query, positive_chunk_id).
Quality filtering:
Use an LLM-judge pass to drop questions that are vague, unanswerable, or that leak context ("according to the passage...").
Ask for paraphrased wording so questions don't just copy phrases from the chunk. Copied phrasing inflates BM25 and lexical scores.
Deduplicate near-identical questions.
Diversity:
Vary question types (factoid, how-to, comparison) and personas, and use few-shot examples from real user logs so the style matches production queries.
Build multi-hop questions by combining two related chunks; both chunks are then the ground truth.
Pitfalls:
False negatives: other chunks may also answer the question. Use an LLM to judge the top retrieved results, or report graded relevance instead of a single gold chunk.
Synthetic questions tend to be easier and cleaner than real ones, so calibrate against a small human-labeled set.
Tooling: the RAGAS testset generator and LlamaIndex generate_question_context_pairs automate this workflow. Cheaper heuristics include using section titles as queries or inverse-cloze sentences.
Q50.Why can MRR drop while Recall@k remains constant after an index change?
Recall@k remains constant after an index change?Recall@k only checks whether a relevant document appears anywhere in the top k, so it ignores order. MRR is 1/rank of the first relevant hit. If an index change pushes relevant documents from rank 1 down to rank 4 but they stay inside k, recall is unchanged while MRR falls.
The math: Recall@10 treats ranks 1 and 9 identically (both count as a hit). MRR treats rank 1 as 1.0 and rank 4 as 0.25.
Index changes that reshuffle order:
ANN settings: a lower ef_search or nprobe, or graph rebuilds, return approximate neighbors in a perturbed order.
Quantization (PQ, scalar, binary): compressed distances keep roughly the right candidate set but blur fine-grained ordering.
Corpus additions: new near-duplicate or boilerplate chunks score higher and crowd above the true answer.
Embedding model or chunking changes, a different distance metric, or missing normalization.
Why it matters for RAG:
If only the top few chunks reach the prompt, a lower rank can drop the answer from the context entirely.
LLMs attend better to early context (the "lost in the middle" effect), so even when the chunk is included, a lower rank can hurt answer quality.
Fixes: always track rank-aware metrics (MRR, nDCG) alongside recall. Re-score candidates with exact distances or a cross-encoder reranker. Tune ANN parameters against MRR, not just recall.
Q51.Why are hard negatives critical when training a dense embedding retriever?
Random and in-batch negatives are usually off-topic and trivially easy to tell apart. The loss quickly hits near zero and the model only learns coarse topic separation. At inference, though, the retriever must rank among passages that are all on-topic but only one of which answers the query. Hard negatives train exactly that fine-grained distinction.
Gradient signal:
Easy negatives get almost zero probability in the softmax, so they contribute almost no gradient.
Hard negatives score close to the positive, so they dominate the loss and force the model to use details like entities, numbers, and negation.
Mining strategies:
BM25 hard negatives: top lexical matches that aren't relevant. Adding these gave DPR a clear boost.
Self-mined (ANCE-style): retrieve with the current model's index and use its high-ranked non-positives, refreshing periodically as the model improves.
Cross-encoder scored: pick candidates a reranker judges as close but not relevant.
Main risk: false negatives:
The "hardest" negatives are often actually relevant but unlabeled. Training on them teaches the model wrong signals.
Mitigations: skip the very top ranks when sampling, filter with a cross-encoder score threshold, or use soft labels via distillation.
Practice: mix one or a few hard negatives per query with in-batch negatives, which balances a stable training signal against discriminative pressure.
Q52.How do in-batch negatives work during contrastive training of embedding models?
In a batch of B (query, positive) pairs, each query treats the other B−1 queries' positives as its negatives. One B×B similarity matrix gives every query one positive and many negatives at almost no extra encoding cost. A softmax cross-entropy (InfoNCE) loss then pushes each query toward its own positive and away from the rest.
Mechanics:
Encode B queries and B positive documents.
Compute the similarity matrix S = Q @ D.T / τ (usually cosine similarity, with temperature τ).
Treat each row as a classification over B documents. The correct label is the diagonal (labels = arange(B)).
Often the loss is made symmetric by adding the document-to-query direction (the transpose).
Why it works so well:
Negatives are free: they reuse embeddings already computed for the batch.
More negatives give a tighter bound and a better gradient signal, so larger batches generally help.
Common ways to scale the batch:
gather embeddings across GPUs so every device sees the global batch,
use GradCache-style gradient caching, or memory banks or queues (MoCo-style).
Weaknesses:
Random in-batch negatives are mostly easy, so the model learns topic separation but not fine-grained relevance.
Fix: append mined hard negatives (e.g. BM25 or previous-model top-k that are not relevant) as extra columns.
False negatives: a batch neighbour may actually be relevant to your query, which penalizes correct behaviour.
Mitigations: deduplicate batches, filter negatives, or soft-label negatives with a cross-encoder.
Temperature τ controls how sharply hard negatives are weighted. Too low is unstable; too high gives a weak signal.
Q53.How does Matryoshka Representation Learning allow embedding truncation without retraining?
MRL applies the training loss to several nested prefixes of the embedding at once (e.g. the first 64, 128, 256 … 768 dims). This forces the most important information into the leading dimensions. Afterwards you can keep the first k dims, renormalize, and still get a good embedding with no retraining. This works only because the model was trained that way.
Training objective:
Total loss = Σ over sizes m ∈ {64, 128, …, d} of w_m · loss(embedding[:m]).
Each prefix must work on its own (e.g. in a contrastive loss).
Gradients therefore push coarse, high-value information early and finer detail later, giving a coarse-to-fine ordering.
Training costs about the same as normal: one forward pass, with extra cheap loss terms.
Why ordinary models can't be truncated:
In a standard embedding, information is spread across all dimensions in no particular order.
Dropping dimensions removes signal arbitrarily, so quality collapses. You would need PCA or retraining instead.
Using it in practice:
Slice, then L2-normalize again before cosine or dot-product search.
Smaller vectors cut storage, memory and ANN latency, with gradual quality loss rather than a cliff.
Funnel or adaptive retrieval: shortlist with short vectors, then re-score candidates with full-length vectors.
Many APIs expose this directly, e.g. a dimensions parameter.
Caveats:
Quality still drops at very small sizes. Validate recall@k at your chosen dimension on your own data.
Queries and documents must be truncated to the same size.
Q54.How does multimodal retrieval align different modalities into a single embedding space?
Each modality gets its own encoder, followed by a projection into a shared vector dimension. The encoders are trained contrastively on paired data (e.g. image–caption pairs), so matching pairs land close together and non-matching pairs land far apart. After training, a text query can be compared directly against image embeddings with cosine similarity.
Architecture (CLIP-style dual encoder):
Image encoder: a ViT or CNN. Text encoder: a transformer.
Linear projection heads map both outputs to the same dimension, followed by L2 normalization.
Each item is encoded independently, so the corpus can be pre-indexed in a normal vector database.
Alignment objective:
A symmetric InfoNCE loss is computed over the batch: image-to-text and text-to-image.
In-batch non-matching pairs serve as negatives.
This requires very large paired datasets (CLIP used about 400M image–text pairs).
Extending to more modalities: ImageBind-style models bind audio, depth and other modalities to a shared anchor (images) using only pairs with that anchor.
Practical caveats:
Modality gap: embeddings from different modalities occupy offset regions of the space.
As a result, cross-modal and same-modal scores are not directly comparable in a mixed index. Normalize or rank per modality.
Generic CLIP is weak on text-heavy images (charts, scanned PDFs) and on fine details.
Alternatives to a single joint space:
Convert to text: caption images, OCR documents, transcribe audio, then use a text embedder.
Visual document retrievers such as ColPali: late interaction over page-image patches.
Multimodal LLM-based embedders that accept interleaved inputs.
Q55.Under what conditions are cosine similarity, dot product, and Euclidean distance functionally equivalent for ranking?
For a fixed query, all three metrics produce the same ranking when every document vector has the same norm. The most common case is L2-normalized (unit) vectors. Then dot product equals cosine, and Euclidean distance is a monotone decreasing function of cosine. The query's own norm never affects the ranking.
The algebra:
q·d = ‖q‖‖d‖ cos θ. The factor ‖q‖ is constant across candidates, so ranking by dot product equals ranking by cosine only if ‖d‖ is constant.
‖q − d‖² = ‖q‖² + ‖d‖² − 2 q·d. If ‖d‖ is constant, smallest distance means largest dot product.
With unit vectors: ‖q − d‖² = 2 − 2 cos θ.
When they diverge:
With unnormalized documents, dot product favours large-norm vectors.
Norm often encodes something like popularity or confidence, sometimes intentionally (e.g. maximum inner product search in recommenders).
Euclidean distance penalizes norm differences, so it differs from both other metrics.
Practical implications:
Use the metric the embedding model was trained with.
If the model outputs normalized vectors, pick whichever metric the index computes fastest (often inner product).
Normalize at both ingest and query time. Mixing normalized and unnormalized vectors silently changes rankings.
Raw score values and thresholds differ across metrics even when rankings match.
Q56.How would you select an embedding model for retrieval over a specialised domain corpus?
Shortlist candidates from public benchmarks, then decide using an evaluation set built from your own domain queries and documents. Weigh retrieval quality against operational constraints: cost, latency, context length and hosting. Public leaderboards rarely reflect specialized vocabulary.
Build a domain eval set first:
Collect real queries from logs or subject-matter experts, labelled with relevant chunks.
Alternatively, generate synthetic queries with an LLM from your chunks, then spot-check them.
Measure recall@k (what feeds the LLM), plus nDCG or MRR, using your actual chunking.
Shortlist candidates:
MTEB retrieval scores are a starting filter, not the final verdict.
Include domain-specific models where they exist (biomedical, legal, code, finance).
Include multilingual models if your corpus or users need them.
Include a BM25 baseline and a hybrid. Jargon, IDs and part numbers often favour lexical matching.
Check operational fit:
Max input tokens must be at least your chunk size, otherwise text is silently truncated.
Dimension and MRL support affect index size and cost. Also consider embedding throughput and query latency.
Hosting: API vs self-hosted (data privacy, licence, vendor lock-in). Switching models later means re-embedding the whole corpus.
Follow model-specific usage, e.g. query and document prefixes or instructions.
If no model is good enough:
Add a reranker, or fine-tune the best candidate on domain pairs with hard negatives.
Re-evaluate on a held-out split to confirm the gain.
Q57.When would you fine-tune the embedding model rather than add or fine-tune a reranker to fix poor retrieval quality?
First diagnose whether the problem is recall or ranking. If relevant documents never reach the candidate set, fine-tune the embedder, because a reranker can only reorder what it is given. If relevant documents are in the top-50 or top-100 but ranked too low, add or tune a reranker. It is cheaper, needs no reindex, and is better at nuanced relevance.
Diagnostic:
Compare recall@100 with recall@5 on a labelled set.
Low recall@100: the retriever is the bottleneck, so work on the embedder (or chunking, or hybrid search).
High recall@100 but low recall@5: an ordering problem, so use a reranker.
Fine-tune the embedding model when:
Domain vocabulary or semantics are foreign to the base model (jargon, acronyms, internal product names).
The latency budget can't absorb a cross-encoder pass, or candidate sets would need to be huge to reach good recall.
You have enough training pairs, ideally with mined hard negatives.
Cost: you must re-embed and reindex the whole corpus and version the index, and you risk regressions on out-of-domain queries.
Add or fine-tune a reranker when:
Errors are about fine distinctions: negation, exact constraints, the question's intent versus mere topical overlap.
Cross-encoders read the query and document jointly, so they capture these interactions that bi-encoders cannot.
You want to iterate quickly: no reindex, easy A/B testing and rollback.
Cost: extra per-query latency and compute that scale with candidate count.
Often you do both: fine-tune the embedder for recall, rerank for precision.
Q58.How does vector index sharding work across multiple nodes?
Sharding splits the vector collection into partitions, each held on a node with its own local ANN index (HNSW, IVF, etc.). A coordinator scatters each query to the relevant shards, each shard returns its local top-k, and the coordinator merges them into the global top-k. Replicas of each shard add throughput and fault tolerance.
Partitioning strategies:
Hash or random by ID
Pros: shards stay balanced and are easy to rebalance.
Cons: every query must hit every shard, since neighbours can live anywhere.
Semantic, cluster-based (IVF-like)
Pros: queries route only to the nearest few clusters' shards, which saves compute.
Cons: risks hotspots and recall loss when true neighbours sit on unprobed shards.
Metadata or tenant-based
Pros: a query for tenant X hits only that tenant's shard, giving good isolation.
Cons: shard sizes can be uneven.
Query execution:
The coordinator routes the query and any filters to the target shards.
Each shard runs its ANN search, often over-fetching k' > k to protect recall after merging.
The coordinator merges results by score (a heap) and returns the global top-k. This assumes scores are comparable across shards.
Operational concerns:
Tail latency is set by the slowest shard. Use replicas, hedged requests and timeouts.
Writes go to the owning shard's segment. Background compaction and index building happen per shard.
Rebalancing when nodes are added means moving data and rebuilding indexes, which is costly for graph indexes.
Sharding scales data size (memory). Replication scales QPS.
Q59.How do vector databases store and index structured metadata alongside vectors?
Vector databases store metadata as a payload attached to each vector ID. Fields used in filters get conventional secondary indexes: inverted indexes, B-trees or range indexes, and bitmaps. At query time the engine combines the filter with ANN search by pre-filtering, post-filtering, or filtering during graph traversal, choosing based on how selective the filter is.
Storage:
Payloads live in a columnar or key-value store keyed by vector ID, e.g. JSON payloads in Qdrant, scalar fields in Milvus, metadata in Pinecone.
Payloads are often kept separate from the ANN structure so vectors stay compact in memory.
Secondary indexes (usually opt-in per field):
Keyword or categorical fields: inverted index or bitmap from value to ID set.
Numeric or date fields: range index (B-tree or sorted structure).
Text, geo and other types use specialised indexes in some engines.
Unindexed fields may still be filterable, but each check is a slow scan.
Combining filters with ANN:
Pre-filter: resolve the filter to an allowed-ID bitmap, then search only those IDs.
For very selective filters, brute-force the small subset. For broad filters, the graph becomes sparse and recall suffers.
Post-filter: run ANN first, then drop non-matching results. This is fast but can return fewer than k results.
Mitigate with over-fetching.
In-filter: HNSW traversal skips non-matching nodes but still uses them for navigation.
Some engines add extra graph links or use ACORN-style traversal to keep filtered graphs connected.
Query planners estimate filter cardinality and switch strategy automatically.
Physical partitioning by metadata: Namespaces, partitions or collections per tenant or category avoid filtering entirely for high-cardinality isolation needs like multi-tenancy.
Q60.How does a vector database handle real-time vector updates without rebuilding the entire graph?
Q61.How does single-stage filtered vector search work?
Q62.Why do vector databases typically rely on soft deletes and background compaction?
Q63.Why can pre-filtering lead to severe performance degradation in graph-based indexes like HNSW?
HNSW?Q64.What causes index drift in mutable approximate nearest neighbor indexes over time?
Q65.Under what circumstances can HyDE degrade retrieval performance?
Q66.How should retrieved documents be ordered within the context window to maximize answer accuracy?
Q67.How does ColBERT's late-interaction mechanism differ from a standard bi-encoder?
ColBERT's late-interaction mechanism differ from a standard bi-encoder?Q68.What does the nprobe parameter control during an IVF search?
nprobe parameter control during an IVF search?Q69.What is the difference between Scalar Quantization and Product Quantization?
Q70.What does the M parameter control in an HNSW index?
M parameter control in an HNSW index?Q71.How does an HNSW graph achieve logarithmic search time?
HNSW graph achieve logarithmic search time?Q72.How does asymmetric distance computation work in product quantization?
Q73.What are the memory trade-offs between HNSW and IVF-Flat indexes?
HNSW and IVF-Flat indexes?Q74.How does HNSW build its multi-layer graph?
HNSW build its multi-layer graph?Q75.How does binary quantisation of embeddings work, and why is it usually paired with oversampling and rescoring?
Q76.How would you choose between a flat index, IVF-PQ and HNSW for a billion-vector corpus under a fixed memory budget?
IVF-PQ and HNSW for a billion-vector corpus under a fixed memory budget?