Question answering: finding a relevant page is not yet finding the answer
问答系统
Build a small retrieve-then-read pipeline, return exact supporting text, and measure retrieval, answer quality and abstention separately.
question-answeringA page can repeat the question’s words and never answer it
Suppose someone asks, “Where is River Hall?” An invented archive page repeats “River Hall” many times but contains no current location. A much shorter page states, “River Hall is in Cedar.” The archive may look highly relevant to a search system while the short sentence contains the needed evidence.
Question answering must connect the question to an appropriate answer under a defined knowledge boundary. Is the system answering from a supplied paragraph, an indexed document collection, structured records, or information stored in model parameters? Does the task ask for a short fact, a list, a calculation or an explanation? Those choices determine what counts as evidence and what the evaluation should accept.
For a small service directory, an exact lookup in approved records is a useful non-learning baseline. It can return a known location and its record ID, while unsupported questions go to another workflow. A retrieval-based system becomes useful when the information is scattered across prose and exact lookup has poor coverage. Its test set should include absent answers, stale statements and conflicting records, not only easy matches.
DrQA explicitly separates document retrieval from reading passages to extract answers in an open-domain factoid setting. That separation is the engineering lesson used here. The original system combines hashed bigram TF-IDF retrieval with a recurrent reader; our program uses ordinary unigram vectors and a deliberately narrow rule reader. Retriever and reader, §§3.1–3.2
Retrieval, reading and evidence make different commitments
A system that treats one passage d as the latent support for an answer a can use a mixture model:
Here q is the question and C is the collection. The formula assumes that the chosen passage and question suffice for the reader, rather than requiring several passages jointly. It is a model choice, not a universal description of question answering. The cosine scores below are not normalized passage probabilities and must not be inserted into this formula as if they were.
The prototype’s vocabulary comes from the document collection. It lowercases English alphabetic tokens and removes a small declared stop list. For D documents, document frequency df-w and raw count tf-dw, its smoothed weights are:
Apply the same vocabulary and IDF to a question, then compare L2-normalized vectors:
A zero query vector produces no results. Scores rank positive-overlap documents, with document IDs breaking ties. Repetition, vocabulary mismatch and irrelevant context can change that ranking without changing whether a passage actually supports the answer. The toy corpus deliberately contains such a distractor.
The reader accepts only questions of the form Where is NAME? and complete source sentences NAME is in PLACE. It rejects other subjects, past tense, negation and conditionals because they do not match that explicit grammar. This is a bounded fact-reading contract, not general language understanding. It returns the exact source sentence and character interval, so a consumer can verify what was read.
If no matching support is found, return “no supported answer in these retrieved documents,” not “no answer exists anywhere.” If matching evidence supplies different locations, report a conflict rather than silently selecting one. Unanswerable reading tasks are designed to include plausible-looking answer candidates that are not actually supported by the passage. Task construction
For an evaluation set of answerable questions Q-plus, with annotated support documents E-q and top-k retrieval R-k(q), support recall is:
This metric evaluates supplied support annotations. If the annotations omit a valid supporting document, retrieving that document can look like failure. Under complete support annotation and a rule that a correct answer must use retrieved support, answerable grounded accuracy has the ceiling:
The assumptions matter. A system allowed to guess from other knowledge can produce the right answer string without retrieving the annotated evidence; that does not demonstrate this pipeline’s grounding. Report answer correctness and evidence validity separately.
Abstention also changes the denominator. With M test questions and A answered questions:
The second value is undefined when A=0. Support recall is undefined when there are no answerable questions. Overall exact correctness can separately credit an appropriate abstention on an annotated unanswerable case, but an unsupported question format is still a limitation of the reader, not proof about the world’s facts.
Keep the evidence attached to the answer
Run the complete original program with Python 3.12 and NumPy 1.26.4. All four documents and three test questions are invented. The code copies the input documents into the index, returns evidence offsets as Python Unicode character positions, and preserves conflicting evidence instead of hiding it.
"""Original tiny retrieve-then-read QA pipeline with auditable evidence.
The reader accepts only 'Where is NAME?' and 'NAME is in PLACE.' facts.
TF-IDF cosine scores are retrieval scores, not answer confidence probabilities.
No real Wikipedia corpus, neural reader or DrQA benchmark is reproduced.
"""
from collections import Counter
import json
import math
import re
import numpy as np
STOP={'where','is','in','the','a','an'}
def tokens(s):
if not isinstance(s,str) or len(s)>20000:raise ValueError('Use a bounded English teaching string')
return [x for x in re.findall('[a-z]+',s.lower()) if x not in STOP]
def index(documents):
docs=[dict(d) for d in documents]
if not 1<=len(docs)<=64:raise ValueError('Use1..64 documents')
if any(set(d)!={'id','text'} or not isinstance(d['id'],str) or not d['id'] for d in docs):raise ValueError('Documents need a nonempty ID and text')
if len({d['id'] for d in docs})!=len(docs):raise ValueError('Document IDs must be unique')
counts=[Counter(tokens(d['text'])) for d in docs];vocabulary=sorted(set().union(*(set(c) for c in counts)))
if len(vocabulary)>2048:raise ValueError('Teaching vocabulary cap is2048')
df=np.array([sum(word in c for c in counts) for word in vocabulary])
idf=np.log((len(docs)+1)/(df+1))+1
vectors=np.array([[c[word] for word in vocabulary] for c in counts],dtype=float)*idf
lengths=np.linalg.norm(vectors,axis=1,keepdims=True)
vectors=np.divide(vectors,lengths,out=np.zeros_like(vectors),where=lengths>0)
return dict(documents=docs,vocabulary=vocabulary,idf=idf,vectors=vectors)
def retrieve(store,question,k=2):
if isinstance(k,bool) or not isinstance(k,int) or not 1<=k<=64:raise ValueError('Use retrieval depth1..64')
counts=Counter(tokens(question));q=np.array([counts[w] for w in store['vocabulary']],float)*store['idf']
norm=np.linalg.norm(q)
if norm==0:return []
scores=store['vectors']@(q/norm)
order=sorted(range(len(scores)),key=lambda i:(-float(scores[i]),store['documents'][i]['id']))
return [dict(document=store['documents'][i],score=float(scores[i])) for i in order[:k] if scores[i]>0]
def read_fact(document,entity):
results=[];text=document['text']
for segment in re.finditer(r'[^.!?]+[.!?]?',text):
raw=segment.group();sentence=raw.strip()
match=re.fullmatch(r'([A-Za-z]+(?: [A-Za-z]+)*) is in ([A-Za-z]+(?: [A-Za-z]+)*)\.',sentence)
if match and match[1].lower()==entity.lower():
start=segment.start()+len(raw)-len(raw.lstrip());end=start+len(sentence)
results.append(dict(answer=match[2],document_id=document['id'],start=start,end=end,quote=text[start:end]))
return results
def answer(store,question,k=2):
tokens(question)
parsed=re.fullmatch(r'Where is ([A-Za-z]+(?: [A-Za-z]+)*)\?',question)
if not parsed:return dict(answer=None,status='unsupported_question',retrieved=[],evidence=[])
hits=retrieve(store,question,k);evidence=[e for hit in hits for e in read_fact(hit['document'],parsed[1])]
values={e['answer'].lower() for e in evidence}
if not values:status='no_supported_answer';value=None
elif len(values)>1:status='conflicting_evidence';value=None
else:status='answered';value=evidence[0]['answer']
return dict(answer=value,status=status,retrieved=[dict(id=h['document']['id'],score=h['score']) for h in hits],evidence=evidence)
def evaluate(store,examples,k):
examples=list(examples)
if not examples:raise ValueError('Need at least one evaluation example')
rows=[];answerable=0;retrieved_support=0;answered=0;correct=0;answerable_correct=0
for ex in examples:
prediction=answer(store,ex['question'],k);pred=prediction['answer']
gold=ex['answers'];has_answer=bool(gold);answerable+=has_answer
ids={d['id'] for d in prediction['retrieved']};support=bool(ids&set(ex['support_ids']))
retrieved_support+=has_answer and support
ok=pred.lower() in {s.lower() for s in gold} if pred is not None else not has_answer
answered+=pred is not None;correct+=ok;answerable_correct+=has_answer and ok
rows.append(dict(question=ex['question'],prediction=prediction,correct=ok,support_retrieved=support))
return dict(rows=rows,total=len(rows),answerable=answerable,answered=answered,correct=correct,
accuracy=correct/len(rows),coverage=answered/len(rows),
accuracy_when_answered=sum(r['correct'] and r['prediction']['answer'] is not None for r in rows)/answered if answered else None,
support_recall= retrieved_support/answerable if answerable else None,
answerable_accuracy=answerable_correct/answerable if answerable else None)
def demo():
docs=[dict(id='river-no-answer',text=('River Hall '*20)+'has historical notes but no current location.'),
dict(id='river-current',text='River Hall is in Cedar.'),
dict(id='museum-current',text='Cedar Museum is in Aspen.'),
dict(id='river-past',text='River Hall was in Birch.')]
store=index(docs)
examples=[dict(question='Where is River Hall?',answers=['Cedar'],support_ids=['river-current']),
dict(question='Where is Cedar Museum?',answers=['Aspen'],support_ids=['museum-current']),
dict(question='Where is Stone Lab?',answers=[],support_ids=[])]
return dict(documents=docs,vocabulary=store['vocabulary'],idf=store['idf'].tolist(),
depth1=evaluate(store,examples,1),depth2=evaluate(store,examples,2),
conditions='Invented documents and explicit fact grammar; support recall concerns supplied annotations; no calibrated answer probability')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
At k=1, the River Hall distractor ranks first and the reader finds no supported location. The other answerable question succeeds, and the unknown location receives no answer. Support recall is 1/2, overall correctness is 2/3 and answer coverage is 1/3. At k=2, both supported locations are found: support recall is 1, overall correctness is 1 and coverage is 2/3. All answered cases are correct at both depths, so answered-only accuracy by itself would hide the missed question.
Tests calculate a small TF-IDF/cosine case by hand, verify stable ties and source offsets, and exercise no vocabulary match, unsupported syntax, past/negative/conditional statements and contradictory locations. This proves behavior under the explicit grammar. It does not show that the reader recognizes every paraphrase or knows whether an old record remains valid today.
With D documents and vocabulary V, this dense implementation builds vectors in O(DV plus tokenization work), stores O(DV) numeric values plus original text, and retrieves in O(DV+D log D). An inverted index is a scaling alternative, not an implemented feature here. Caps are 64 documents, 2,048 vocabulary entries and 20,000 characters per teaching string. Reader cost is proportional to the retrieved text it scans.
Use a protocol that exposes the failing component
Freeze the collection snapshot and split evaluation questions so near-duplicate records or questions do not leak into tuning. State whether evaluation accepts answer aliases, several valid passages, multiple answers or abstention. An answer can have the right spelling for the wrong reason, and a correct source can still be quoted incompletely. Check both the returned string and its evidence in context.
Increasing k gives the reader more candidates and can add reading work or introduce conflicting or distracting evidence. The toy retriever computes and sorts all document scores at both depths; k changes the returned subset. It does not guarantee a better final answer. A production system needs a declared policy for provenance, freshness, conflict handling and unsupported question types. Measure latency and work per query alongside retrieval and answer metrics under the same collection and decoding budget.
A learned reader replaces the narrow grammar with a question-conditioned model, while a generative answerer may synthesize several sources. Both expand the behavior that needs validation. A retrieval similarity or a normalized model output is not automatically a calibrated probability of factual correctness. The prototype deliberately makes no such confidence claim.
The official DrQA repository’s separation of retriever, reader and pipeline is a useful implementation reference. The cited snapshot is fixed; its README and software license were inspected, but no upstream code, data or weights are copied or executed here. Official implementation structure
Find the stage that lost the answer
- The top document contains many mentions of River Hall but no location. Is high retrieval similarity enough to return an answer?
Answer: No. Similarity identifies a candidate, not a supported location. The reader must find applicable evidence or abstain within the retrieved set.
- At k=1, one of two answerable questions has retrieved support, and the third question is correctly unanswered. What are support recall and overall correctness in the example?
Answer: Support recall is 1/2. With the supported answer correct, overall correctness is 2/3. These use different denominators and include different tasks.
- Two retrieved records say that River Hall is in different places. What does the program do, and why?
Answer: It returns conflicting_evidence, no selected answer and both evidence records. The grammar supplies no rule for deciding which location is current; selecting the first would hide an unresolved conflict.
- A system answers only one easy question out of ten and gets it right. Can its answered-only accuracy of 1 establish good question-answering performance?
Answer: No. Coverage is only 1/10. Report both values, and distinguish appropriate abstentions from missed answerable questions. If it answers none, answered-only accuracy is undefined rather than perfect.
Compare the task boundary before comparing systems
DrQA studies retrieving and reading at collection scale; the unanswerable-SQuAD paper shows why a plausible span may still be an invalid answer. Their settings clarify two different failure points. The official implementation is a structural reference, while this article’s unigram index, grammar, corpus and measurements are original and deliberately small. No published benchmark score is reproduced.
Make a prediction, then check
At k=1 answered-only accuracy is1 but support recall is1/2. What is missing?
Learning objectives
- Separate retrieval relevance from answer support.
- Return exact evidence and preserve conflicting statements.
- Calculate support recall, coverage and answered-only accuracy.
- State the grammar and knowledge boundary of a rule reader.
Prerequisites & connections
Explore related knowledge →References
- Reading Wikipedia to Answer Open-Domain Questions
Danqi Chen, Adam Fisch, Jason Weston, Antoine Bordes · 2017 - Know What You Don’t Know: Unanswerable Questions for SQuAD
Pranav Rajpurkar, Robin Jia, Percy Liang · 2018 - DrQA official repository: pinned README and software license
Facebook Research / DrQA contributors · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked knowledge boundaries, non-learning lookup baseline, retrieval/reading split and scoped DrQA/unanswerable-task evidence. Six paired equations and four explained exercises verified, including mixture assumptions, TF-IDF hand case, conditional support-recall ceiling, denominator/coverage distinctions, exact source intervals and conflict abstention. The strict location grammar is original and does not reproduce DrQA or calibrated confidence.
- Single AI author checked knowledge boundaries, non-learning lookup baseline, retrieval/reading split and scoped DrQA/unanswerable-task evidence. Six paired equations and four explained exercises verified, including mixture assumptions, TF-IDF hand case, conditional support-recall ceiling, denominator/coverage distinctions, exact source intervals and conflict abstention. The strict location grammar is original and does not reproduce DrQA or calibrated confidence.
- Four computed SVGs bind exact bilingual MDX. The four-topic group passed eight numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Reading Wikipedia to Answer Open-Domain Questions · Abstract, section3.1 and start of3.2, layout178–231: hashed bigram TF-IDF retriever and recurrent reader. Our unigram/rule program is not DrQA reproduction; no benchmark claims.
- Know What You Don’t Know: Unanswerable Questions for SQuAD · Abstract and layout47–67: relevant questions with plausible answer-type distractors but no supported answer. No complete threshold-tuning or experimental reproduction; NULL layer here is original.
- DrQA official repository: pinned README and software license · README opening and software LICENSE read; BSD with non-endorsement clause. No inference about datasets/weights license, no code copied or run. Commit6d7c1b7087b86cfe9bdf84a279adb58dceada3cd dated2021-05-18.
Related topics