Skip to content
SDB
Natural Language Processing

Chapter 11 · advanced · 32 min

Question Answering & Summarization

Extractive and abstractive QA, reading comprehension, RAG, and neural summarization

Subhendu Datta BhowmikAI Tutorials

Question Answering

Question Answering (QA) systems automatically produce answers to natural language questions. QA is one of the most demanding NLP tasks, requiring understanding, reasoning, and knowledge retrieval.

QA Taxonomy

TypeQuestionAnswer SourceExample System
Extractive QAAnyPassage (span)BERT on SQuAD
Abstractive QAAnyGenerated textGPT-4, T5
Open-domain QAAnyLarge corpus (retrieval)DPR + FiD, RAG
Knowledge-based QAFactoidKnowledge graphWikidata SPARQL
Visual QAAbout imageImage + captionCLIP, Flamingo
Conversational QAMulti-turnDialogue historyCoQA, QuAC

Reading Comprehension: Extractive QA

Given a context passage and a question, find the answer as a contiguous span in the passage:

Context: "The Eiffel Tower was built by Gustave Eiffel and completed in 1889.
          It stands 330 metres tall in Paris, France."

Question: "Who built the Eiffel Tower?"
Answer:   "Gustave Eiffel" (span from context)

BERT for Span Extraction adds two linear heads on top of BERT token embeddings:

  • Pstart(i)=softmax(wstartThi)P_{\text{start}}(i) = \text{softmax}(\mathbf{w}_{\text{start}}^T h_i): probability that token ii is the answer start
  • Pend(i)=softmax(wendThi)P_{\text{end}}(i) = \text{softmax}(\mathbf{w}_{\text{end}}^T h_i): probability that token ii is the answer end

Answer span: (i,j)(i^*, j^*) where iji^* \leq j^* and Pstart(i)Pend(j)P_{\text{start}}(i^*) \cdot P_{\text{end}}(j^*) is maximized.

SQuAD benchmarks (Stanford Question Answering Dataset):

  • SQuAD 1.1: all questions have answers in the passage
  • SQuAD 2.0: includes 50k unanswerable questions → model must also detect when no answer exists
  • Human performance: ~91% F1; BERT-large: ~88% F1; ALBERT-xxlarge: ~92% F1

Open-Domain QA and RAG

Dense Passage Retrieval (DPR)

Traditional open-domain QA used TF-IDF (BM25) retrieval. DPR (Karpukhin et al., 2020) trains dual BERT encoders:

sim(q,p)=EQ(q)TEP(p)\text{sim}(q, p) = E_Q(q)^T E_P(p)

  • EQE_Q: question encoder (BERT fine-tuned)
  • EPE_P: passage encoder (separate BERT fine-tuned)
  • Trained with in-batch negatives: correct passage should have higher similarity than other passages in the batch

At inference: all passages are pre-encoded and indexed in a FAISS vector index for approximate nearest-neighbor search (millisecond retrieval over millions of passages).

RAG Architecture

Question: "What is the capital of the country that won the 2014 FIFA World Cup?"
  │
  ├─ Retriever (DPR / BM25)
  │     → fetches top-5 passages from Wikipedia about 2014 World Cup
  │
  ├─ Reader / Generator (T5, GPT, LLaMA)
  │     → input: [question] + [passage 1] + ... + [passage k]
  │     → output: "Berlin" (Germany won → capital is Berlin)
  │
  └─ Answer: "Berlin"

RAG vs Pure LLM Generation:

PropertyPure LLMRAG
Knowledge freshnessStatic (training cutoff)Real-time (live retrieval)
Hallucination riskHigherLower (grounded in evidence)
CitabilityNoneCan cite retrieved sources
CostHigh (large model)Moderate (small reader + retriever)
LatencyLowerHigher (retrieval step)

Multi-Hop QA

Some questions require multi-step reasoning across multiple documents:

  • "Where was the CEO of the company that made the iPhone born?"
    1. iPhone → Apple
    2. Apple CEO → Tim Cook
    3. Tim Cook → born in Robertsdale, Alabama

HotpotQA and 2WikiMultihopQA benchmark multi-hop reasoning. Solutions include: chain-of-thought prompting, iterative retrieval, and graph-based reasoning over entity chains.

Summarization

Automatic summarization condenses text while preserving key information. Two paradigms:

Extractive Summarization

Selects and concatenates the most important sentences/phrases from the source:

  • No new words are generated
  • Grammatically guaranteed to be correct
  • Lacks cohesion (selected sentences may be disjointed)

Classic algorithms: TextRank (graph-based sentence ranking), LSA (latent semantic analysis), SumBasic (word frequency).

Abstractive Summarization

Generates new text that may not appear verbatim in the source:

  • More fluent and coherent
  • Can synthesize information from multiple sentences
  • Risk of hallucination — generating facts not in the source

Modern abstractive summarization uses seq2seq Transformer models:

  • BART (Lewis et al., 2020): denoising pre-training (random masking, deletion, permutation)
  • T5 (Raffel et al., 2020): text-to-text framing "summarize: {article}"
  • Pegasus (Zhang et al., 2020): pre-trained with Gap Sentence Generation (predict removed sentences)
  • LED (Longformer Encoder-Decoder): handles documents up to 16,384 tokens

Summarization Evaluation: ROUGE

ROUGE (Recall-Oriented Understudy for Gisting Evaluation) measures n-gram overlap between hypothesis and reference summaries:

ROUGE-N=srefsn-gramscountmatch(n-gram)srefsn-gramscount(n-gram)\text{ROUGE-N} = \frac{\sum_{s \in \text{refs}} \sum_{\text{n-gram} \in s} \text{count}_{\text{match}}(\text{n-gram})}{\sum_{s \in \text{refs}} \sum_{\text{n-gram} \in s} \text{count}(\text{n-gram})}

  • ROUGE-1: unigram recall
  • ROUGE-2: bigram recall
  • ROUGE-L: longest common subsequence

BERTScore: measures semantic similarity using BERT token embeddings — better correlation with human judgments than ROUGE.

Typical CNN/DailyMail scores: ROUGE-1 ≈ 44, ROUGE-2 ≈ 21, ROUGE-L ≈ 41 for strong abstractive systems.

QA with BERT, RAG Pipeline, and Abstractive Summarizationpython
# ─── 1. Extractive QA with BERT (HuggingFace) ────────────────
from transformers import pipeline

qa_pipeline = pipeline("question-answering",
                       model="deepset/roberta-base-squad2")

context = """
The Large Hadron Collider (LHC) is the world's largest and most powerful
particle accelerator. It lies in a tunnel 27 kilometres in circumference
and as deep as 175 metres beneath the France-Switzerland border near Geneva.
The LHC was built by CERN between 1998 and 2008 with the aim of allowing
physicists to test the predictions of different theories of particle physics.
It was first started up on 10 September 2008.
"""

questions = [
    "Where is the LHC located?",
    "How long is the tunnel?",
    "When was the LHC first started?",
    "Who built the LHC?",
]

print("Extractive QA (RoBERTa-SQuAD2):")
for q in questions:
    result = qa_pipeline(question=q, context=context)
    print(f"  Q: {q}")
    print(f"  A: {result['answer']} (score={result['score']:.3f})\n")

# ─── 2. RAG with LangChain + FAISS ───────────────────────────
# pip install langchain langchain-community faiss-cpu sentence-transformers
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
from langchain.chains import RetrievalQA

# Prepare documents
documents = [
    "The Python programming language was created by Guido van Rossum and first released in 1991.",
    "Python emphasizes code readability and uses significant indentation.",
    "Python supports multiple programming paradigms: procedural, object-oriented, and functional.",
    "The name Python comes from the BBC show Monty Python's Flying Circus.",
    "Python 3.0 was released in 2008 and is not fully backward compatible with Python 2.",
    "NumPy and Pandas are popular Python libraries for data science.",
    "TensorFlow and PyTorch are the leading Python frameworks for deep learning.",
]

# Create embeddings and vector store
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = FAISS.from_texts(documents, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

# Test retrieval
query = "Who created Python and when?"
retrieved = retriever.get_relevant_documents(query)
print("Retrieved documents:")
for i, doc in enumerate(retrieved, 1):
    print(f"  [{i}] {doc.page_content[:80]}")

# ─── 3. Simple RAG Reader ─────────────────────────────────────
def rag_answer(question, retriever, reader_pipeline):
    """Minimal RAG: retrieve then read."""
    docs = retriever.get_relevant_documents(question)
    context = " ".join([d.page_content for d in docs])
    result = reader_pipeline(question=question, context=context)
    return result['answer'], result['score'], docs

reader = pipeline("question-answering", model="deepset/roberta-base-squad2")
answer, score, sources = rag_answer("Who created Python?", retriever, reader)
print(f"\nRAG Answer: {answer} (confidence: {score:.3f})")
print(f"Source: {sources[0].page_content[:100]}")

# ─── 4. Abstractive Summarization ────────────────────────────
from transformers import pipeline as hf_pipeline

summarizer = hf_pipeline("summarization", model="facebook/bart-large-cnn")

long_text = """
Artificial intelligence (AI) has transformed numerous industries over the past decade.
In healthcare, AI algorithms now assist doctors in diagnosing diseases from medical images
with accuracy that rivals experienced specialists. In finance, machine learning models
detect fraudulent transactions in milliseconds, saving billions of dollars annually.
The transportation sector is being revolutionized by self-driving vehicles that use
computer vision and deep learning to navigate complex environments.

Natural language processing, a branch of AI, has enabled voice assistants like Siri,
Alexa, and Google Assistant to understand and respond to human speech. Large language
models such as GPT-4 and Claude can write essays, answer complex questions, and even
generate code. These advances have sparked debates about the future of work, with some
economists predicting significant job displacement while others argue AI will create
more jobs than it eliminates.

Despite these achievements, significant challenges remain. AI systems can perpetuate
and amplify biases present in training data. The environmental cost of training large
models is substantial. Ensuring the safety and alignment of increasingly powerful AI
systems is a major research priority for the field.
"""

summary = summarizer(long_text, max_length=120, min_length=40, do_sample=False)
print("\nAbstractive Summary (BART-CNN):")
print(summary[0]['summary_text'])

# ─── 5. ROUGE Evaluation ─────────────────────────────────────
# pip install rouge-score
from rouge_score import rouge_scorer

scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)

reference = "Artificial intelligence has transformed healthcare, finance, and transportation. Despite achievements, challenges remain including bias and environmental costs."
hypothesis = summary[0]['summary_text']

scores = scorer.score(reference, hypothesis)
print("\nROUGE Scores:")
for metric, score in scores.items():
    print(f"  {metric}: P={score.precision:.3f} R={score.recall:.3f} F={score.fmeasure:.3f}")

Knowledge check

What is the key advantage of RAG (Retrieval-Augmented Generation) over a pure large language model for question answering?

Summary

  • Extractive QA finds answer spans in context passages; BERT/RoBERTa fine-tuned on SQuAD achieves ~92% F1
  • Open-domain QA retrieves relevant passages with DPR/BM25, then uses a reader model — RAG architecture
  • RAG combines retrieval with generation: reduces hallucination, enables citations, supports fresh knowledge
  • Abstractive summarization generates novel text with BART/T5/Pegasus; evaluated with ROUGE and BERTScore
  • Multi-hop QA requires reasoning across multiple documents — chain-of-thought and iterative retrieval help
  • Hallucination remains a key challenge in abstractive generation — retrieval grounding and faithfulness metrics help

Next: NLP Models — from N-grams to Transformers — understanding the model architectures that power modern NLP.

Natural Language Processing