Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Question answering and textual entailment

Study notes on Question Answering (QA) and Textual Entailment (Natural Language Inference) covering definitions, architectures, evaluation, formulas and exam-style worked answers.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers use Question Answering (QA) systems to build search assistants, chatbots, and customer-support automation that return concise answers from documents or the web. Textual Entailment (also called Natural Language Inference, NLI) is used to check if one sentence logically follows from another — useful in fact-checking, summarisation, and pipeline verification inside QA systems.

Key ideas

  • Open-domain QA — the knowledge source S is a large collection (often the whole web); system must first retrieve relevant documents.

  • Closed-domain (or domain-specific) QA — S is limited to a specific domain (medical, legal), so retrieval is constrained. Not to be confused with closed-book QA (no external retrieval at inference).

  • Retrieval-based QA (IR-based) — pipeline: retrieve top-k documents, then extract answer. Draw: boxes left-to-right labelled "Question -> Document Retriever -> Ranker -> Reader (Answer Extractor) -> Answer". Label arrows and show top-k results between Retriever and Reader.

  • Reading-comprehension (Machine Reading Comprehension, MRC) — given a passage P and question Q, produce an answer usually by extracting a span from P (extractive) or generating text (abstractive).

  • Extractive QA — answer is a continuous text span from passage P. Common in SQuAD-style tasks.

  • Abstractive QA — answer may be newly generated, not a verbatim span.

  • Passage ranking / Retrieval — first stage in open-domain QA: convert Q and passages to vector representations (TF-IDF, BM25, or dense embeddings) and score passages. Typical scoring: BM25 for classical IR; dot-product or cosine for dense vectors. Assume top-k selected for reader.

  • Reader models — given (Q, P), predict answer span or generate answer. Modern readers use neural encoders:

    • Bi-directional RNN + attention (earlier: BiDAF) for span prediction.
    • Transformer-based encoders (BERT, RoBERTa) fine-tuned for span start/end classification.
    • For generative QA, encoder–decoder models (e.g., T5, BART) or decoder-only LMs can be fine-tuned to generate answers.
  • Span prediction formulation — model outputs probability distributions for start and end token positions over passage tokens. Assume passage tokens p1..pn. At inference, enforce start <= end (often with a maximum span length) and score spans by combining start/end probabilities or logits (e.g., sum of logits or product of probabilities).

  • Evaluation metrics for QA —

    • Exact Match (EM): 1 if predicted answer string matches gold answer exactly after normalization, else 0.
    • F1 (token-level): harmonic mean of token-level precision and recall between predicted and gold answer. Overlap is computed on unigram tokens with multiplicity (bag-of-words; use the minimum count per token). When multiple gold answers exist (e.g., SQuAD), compute EM/F1 against each reference and take the maximum per example.
    • For generative answers, BLEU/ROUGE can be used but have limitations.
  • Textual Entailment / NLI — given a premise P and a hypothesis H, decide one of: Entailment (P implies H), Contradiction (P implies not H), Neutral (neither). Formal definition (logic): P entails H iff every model/world where P is true, H is true. Standard evaluation metric is classification accuracy; macro-F1 may also be reported for imbalanced datasets.

  • Datasets and benchmarks — SQuAD (extractive QA), SQuAD 2.0 (includes unanswerable questions), Natural Questions, TriviaQA, HotpotQA (multi-hop) for QA; SNLI, MultiNLI, RTE (GLUE), ANLI for NLI/RTE. (Students: these are examples you may be asked to name.)

  • Typical architectures for NLI — sentence-encoding (Siamese) models, attention-based aligners (Decomposable Attention, ESIM), and Transformer-based fine-tuned models (BERT) that concatenate P and H with a special token and classify.

  • Loss and training — classification uses cross-entropy loss; span prediction uses sum of negative log-likelihoods for start and end positions.

  • Important assumptions and limits — extractive QA assumes answer is contained verbatim in passage; retrieval-based QA assumes top-k retrieval contains answer; NLI datasets use crowd annotations and can contain annotation artifacts (biases). SQuAD 2.0-style setups require handling unanswerable questions via a null span and a decision threshold.

Formulas

precision = TP / (TP + FP)

  • TP = true positives, FP = false positives. Dimensionless. Use when computing overlap of predicted tokens with gold tokens.

recall = TP / (TP + FN)

  • FN = false negatives. Dimensionless. Use with precision to compute F1.

F1 = 2 * precision * recall / (precision + recall)

  • Harmonic mean of precision and recall. Dimensionless. In QA, compute on token overlap between predicted and gold answer.

EM = 1 if normalize(predicted) == normalize(gold) else 0

  • Exact Match score for one example. Dimensionless. Normalization removes punctuation, casing, articles per dataset protocol.

softmax(z_i) = exp(z_i) / sum_j exp(z_j)

  • z_i are logits (real numbers). Produces a probability distribution over classes or token positions. Dimensionless. Used in classification and span start/end prediction.

CrossEntropy = - sum_i y_i * log(p_i)

  • y_i are one-hot true labels, p_i are predicted softmax probabilities. Measured in nats (if using natural logarithms) or bits (if using base-2 logarithms). Used as training loss for classification.

attention_score(q, k) = q · k (dot product)

  • q and k are query and key vectors. Units: dimensionless. In scaled dot-product attention, divide by sqrt(d_k) where d_k is key dimension.

scaled_attention = softmax( (Q K^T) / sqrt(d_k) ) V

  • Q, K, V are matrices of queries, keys, values; d_k is key size. Produces attended vectors. Used in Transformer readers.

EM_over_dataset = (1/N) * sum_i EM_i and F1_over_dataset = (1/N) * sum_i F1_i

  • Averages across N examples for reporting.

Worked examples

  1. Compute EM and token-level F1 for one QA example (numerical steps):

    • Gold answer: "prime minister of India"
    • Predicted answer: "the Prime Minister of India"
    • Normalise by lowercasing and removing articles and punctuation -> gold tokens: ["prime","minister","of","india"]; pred tokens: ["prime","minister","of","india"].
    • EM formula: EM = 1 if normalized strings equal. They match, so EM = 1.
    • Token-level precision = TP/(TP+FP) = 4/(4+0) = 1.0. Recall = 4/(4+0) = 1.0. F1 = 1.0.
    • Final reported: EM = 1.0, F1 = 1.0.
  2. Small failure case (token overlap):

    • Gold: "1971 Indo-Pak war"
    • Predicted: "Indo-Pak war"
    • Gold tokens (after normalization): ["1971","indopak","war"]; Pred tokens: ["indopak","war"].
    • TP = 2 ("indo-pak","war"), FP = 0, FN = 1 ("1971"). Precision = 2/(2+0) = 1.0. Recall = 2/(2+1) = 0.6667. F1 = 21.00.6667/(1.6667) = 0.8 (80%). EM = 0 because strings differ. Report EM = 0, F1 = 0.8.
  3. Model answer style (design question): "Design an extractive QA system for a domain of medical articles"

    • Step 1: Preprocess documents: sentence-split, tokenise, retain medical terms (don't aggressively stem). Use domain-specific tokenizer and medical vocabulary expansion (UMLS lookups).
    • Step 2: Retrieval: index documents with BM25 and dense embeddings (dual-encoder) to get high recall; use top-100 for reranking.
    • Step 3: Reranker: fine-tune a cross-encoder (BERT) on domain QA pairs to score passage relevance and select top-5 passages.
    • Step 4: Reader: fine-tune a BERT model for span prediction on domain-labeled data; if no large labelled set, use transfer learning from SQuAD then further fine-tune on small in-domain labels.
    • Step 5: Postprocess: apply medical answer normalization, confidence thresholds, and a fallback to a curated knowledge base for high-risk answers.
    • Evaluation: use EM and token F1; add human-in-the-loop verification for critical answers. Explain choices: BM25 + dense improves recall; cross-encoder provides precision for reader; fine-tuning adapts language patterns.

Common mistakes

  • Forgetting to normalise strings (lowercase, remove punctuation/articles) before computing EM.
  • Assuming retrieval always contains answer — always state top-k and recall requirement.
  • In NLI, equating semantic relatedness with entailment — two sentences can be related but not entail each other.
  • Not handling multiple valid gold answers (SQuAD has multiple references) when computing EM/F1.

For your exam

Kinds of questions:

  • Definitions and short notes: define QA, MRC, extractive vs abstractive, entailment/NLI.
  • Diagrams and pipelines: draw retrieval-reader pipeline, label top-k retrieval and reranker.
  • Derivations/explanations: show how span prediction probabilities are computed and how cross-entropy loss is applied.
  • Numerical: compute EM and F1 for given predictions and gold answers (tokenise and normalise first).
  • Design/analytical: propose an architecture for open-domain QA, justify retrieval and reader choices, discuss evaluation.

What full-marks answers include:

  • Precise definitions (bold technical terms), correct diagram with labelled boxes and arrows, clear assumptions (e.g., extractive assumption), exact formulas used, step-by-step computations for numerical parts, and discussion of limitations and alternatives.

Quick check

  1. What are the three NLI labels used in RTE tasks?
  2. For extractive QA, what two numbers does a span-predicting model output for each token?
  3. Which two metrics are standard for SQuAD-style evaluation?

Answers: 1) Entailment, Contradiction, Neutral. 2) Start and end scores/logits (softmaxed to probabilities over tokens). 3) Exact Match (EM) and token-level F1.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?