Reading comprehension: choose an answer that the passage can support
机器阅读理解
Derive a legal-span distribution, learn from alternative answer spans, and distinguish a best-span decision from calibrated answerability.
reading-comprehensionThe answer is in the passage, but which mention answers the question?
Consider the invented passage “Ada moved from Pine to Cedar.” For “Where did Ada move to?”, both Pine and Cedar look like place names. Selecting any place is insufficient: the reader must distinguish the origin from the destination. For “When did Ada move?”, the passage supplies no date. A plausible date would still be an unsupported answer.
Machine reading comprehension evaluates answering under a supplied context. Its output can be a selected span, a choice among options or a generated answer, depending on the task definition. This article studies extractive reading: return a contiguous passage span or explicitly abstain. That narrow output contract lets us inspect answer boundaries and training signals precisely. It does not cover every kind of comprehension.
The original SQuAD task asks questions about supplied passages and annotates answer spans. Retrieval of a relevant document is therefore outside that particular input contract. SQuAD’s later unanswerable extension adds questions with plausible answer candidates but no supported answer, exposing the weakness of always selecting a span. Original task Unanswerable task construction
A useful baseline returns a matching named entity of the requested type. It will fail when several entities have different roles, and it needs an abstention policy when none is supported. Start evaluation with paired questions such as “from where?” and “to where?” rather than allowing a high aggregate score to hide that distinction.
Normalize over answers that can actually be returned
Let a passage have N tokens. A question-conditioned encoder would produce start scores a, end scores b and a no-answer score c. Our program begins with these scores already supplied; it implements the output layer, loss and decoder, not an encoder that understands the question. With maximum answer length L, the candidate set is:
A span’s token endpoints are inclusive. NULL denotes abstention, not a token in the text. Assign a span the sum of its endpoint scores, then normalize over the legal candidates:
Compute log Z with a maximum-score subtraction to avoid unnecessary exponential overflow. This is a joint distribution restricted to legal spans. Independently normalizing start and end positions defines a different distribution: it can place probability on an end before the start or an overlong answer. Taking the two separate maxima can even return an invalid interval.
For a hand calculation, use a=log[1,4,1], b=log[4,1,1], c=log 2 and L=2. In order NULL, (0,0), (0,1), (1,1), (1,2), (2,2), the unnormalized masses are [2,4,1,4,4,1], so Z=16. The independent maxima are start 1 and end 0, which is illegal. Of the independent endpoint distribution’s mass, 11/18 lies outside our legal span set. A gold answer (1,1) instead receives probability 4/16 under the restricted distribution and loss log 4.
Sometimes several annotated spans are acceptable alternatives, for example two occurrences of the same supported name. If G is the set of accepted candidates, the objective used here is:
This rewards total probability on any accepted candidate. Averaging separate negative log probabilities would instead require probability for each annotation individually. Those are different supervision assumptions. Deduplicate G so repeated annotations do not multiply a candidate’s mass. This implementation accepts NULL alone as an unanswerable label and rejects a mixture of NULL and answer spans; ambiguous labeling needs its own explicit protocol.
Differentiating the two log-sum-exp terms gives a simple gradient. Define q by renormalizing only over accepted candidates:
The start and end scores are shared by several candidate spans. Their gradients sum the contributions of all those spans:
These equations define our teaching output layer; they are not presented as a reproduction of SQuAD’s original baseline training objective. A learned encoder could receive these gradients through its score computations, but that additional model and training data are absent here.
At prediction time, the decoder compares the best single span to NULL using a chosen margin threshold t:
Ties abstain. This rule compares one span with NULL. Summing the probabilities of all spans and comparing that total with NULL answers a different decision question. With many weak candidates, the total can be large even though no single span beats NULL. Neither decision becomes calibrated merely because the scores pass through a softmax.
Run the output layer and inspect the returned characters
The complete original program runs with Python 3.12 and NumPy 1.26.4. Tokenization uses the declared Unicode regular expression. Character evidence uses Python string positions with a half-open interval, while token answers use inclusive endpoints. These positions are not UTF-8 byte offsets or JavaScript UTF-16 code-unit offsets.
"""Original joint span/NULL decoder and marginal-label loss with exact gradients.
Endpoint logits are supplied teaching values, not predictions of a trained
language encoder. Offsets count Python Unicode characters, not UTF-8 bytes.
"""
import json
import math
import re
import numpy as np
def tokenize(passage):
if not isinstance(passage,str) or len(passage)>10000:raise ValueError('Use a short passage')
return [dict(token=m.group(),start=m.start(),end=m.end()) for m in re.finditer(r'\w+|[^\w\s]',passage)]
def distribution(start,end,null_score=0.,max_length=8):
a=np.asarray(start,dtype=float);b=np.asarray(end,dtype=float)
if a.ndim!=1 or b.shape!=a.shape or len(a)>64 or not np.isfinite(a).all() or not np.isfinite(b).all() or (abs(a)>100).any() or (abs(b)>100).any():raise ValueError('Use matching endpoint vectors, length0..64, finite logits within100')
if isinstance(null_score,bool) or not np.isscalar(null_score) or not np.isfinite(null_score) or abs(null_score)>100:raise ValueError('NULL score must be finite and within100')
if isinstance(max_length,bool) or not isinstance(max_length,int) or not 1<=max_length<=16:raise ValueError('Maximum span length must be1..16')
spans=[None]+[(i,j) for i in range(len(a)) for j in range(i,min(len(a),i+max_length))]
scores=np.array([float(null_score)]+[a[i]+b[j] for i,j in spans[1:]])
shifted=scores-scores.max();log_z=float(scores.max()+np.log(np.exp(shifted).sum()));log_p=scores-log_z
return dict(spans=spans,scores=scores,probabilities=np.exp(log_p),log_probabilities=log_p,log_partition=log_z)
def loss_grad(start,end,null_score,gold,max_length=8):
d=distribution(start,end,null_score,max_length);accepted=[]
for item in gold:
if item is not None:
if not isinstance(item,(tuple,list)) or len(item)!=2 or any(isinstance(v,bool) or not isinstance(v,(int,np.integer)) for v in item):raise ValueError('Gold spans must be integer pairs or NULL')
item=tuple(item)
if item not in d['spans']:raise ValueError('Gold span violates order, passage or length constraint')
if item not in accepted:accepted.append(item)
if not accepted or (None in accepted and len(accepted)>1):raise ValueError('Supply at least one alternative span, or NULL alone')
ids=[d['spans'].index(item) for item in accepted];lp=d['log_probabilities'][ids]
log_gold=float(lp.max()+np.log(np.exp(lp-lp.max()).sum()))
ds=d['probabilities'].copy();ds[ids]-=np.exp(lp-log_gold)
ga=np.zeros(len(start));gb=np.zeros(len(end))
for value,span in zip(ds[1:],d['spans'][1:]):ga[span[0]]+=value;gb[span[1]]+=value
return dict(loss=-log_gold,start_gradient=ga,end_gradient=gb,null_gradient=float(ds[0]))
def decode(passage,start,end,null_score=0.,max_length=8,threshold=0.):
tok=tokenize(passage)
if len(tok)!=len(start):raise ValueError('One endpoint logit per token is required')
if isinstance(threshold,bool) or not np.isscalar(threshold) or not np.isfinite(threshold) or abs(threshold)>100:raise ValueError('Use a finite threshold within100')
d=distribution(start,end,null_score,max_length)
if len(d['spans'])==1:return dict(answer=None,token_span=None,character_span=None,status='empty_passage',null_probability=1.)
best=1+int(np.argmax(d['scores'][1:]));span=d['spans'][best]
# Equal scores abstain. The margin is a policy setting, not calibration.
if d['scores'][best]<=null_score+threshold:
return dict(answer=None,token_span=None,character_span=None,status='abstained',null_probability=float(d['probabilities'][0]))
left=tok[span[0]]['start'];right=tok[span[1]]['end']
return dict(answer=passage[left:right],token_span=list(span),character_span=[left,right],status='answered',null_probability=float(d['probabilities'][0]),span_probability=float(d['probabilities'][best]))
def demo():
a=np.log([1.,4.,1.]);b=np.log([4.,1.,1.]);d=distribution(a,b,math.log(2),max_length=2)
independent=np.outer(np.exp(a)/np.exp(a).sum(),np.exp(b)/np.exp(b).sum())
legal=sum(independent[i,j] for i,j in d['spans'][1:])
loss=loss_grad(a,b,math.log(2),[(1,1)],max_length=2)
passage='Ada moved from Pine to Cedar.';tok=tokenize(passage)
sa=np.zeros(len(tok));sb=sa.copy();sa[5]=sb[5]=3.
answer=decode(passage,sa,sb,max_length=3)
null=decode(passage,np.zeros(len(tok)),np.zeros(len(tok)),null_score=5.,max_length=3)
return dict(hand=dict(start=a.tolist(),end=b.tolist(),spans=d['spans'],probabilities=d['probabilities'].tolist(),
partition=math.exp(d['log_partition']),independent_argmax=[int(np.argmax(a)),int(np.argmax(b))],
independent_illegal_mass=float(1-legal),gold_loss=loss['loss'],
start_gradient=loss['start_gradient'].tolist(),end_gradient=loss['end_gradient'].tolist(),null_gradient=loss['null_gradient']),
passage=passage,tokens=tok,answer=answer,null_case=null,
conditions='Manually supplied endpoint scores; exact legal-span/NULL normalization and character evidence; no learned language-comprehension accuracy')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
In the invented passage, hand-assigned start and end scores of 3 at token index 5 (counting from zero) favor Cedar. The decoder returns token interval [5,5], character interval [23,28], span probability about 0.842785 and NULL probability about 0.002089. With all endpoint scores zero and NULL score 5, it abstains; NULL probability is about 0.891835. These outputs demonstrate the decoder’s behavior under supplied scores, not the ability to infer scores from the question.
The independent checks enumerate the hand example, differentiate every start, end and NULL parameter numerically under single-span, alternative-span and NULL supervision, and verify duplicate-label handling. They also check a non-ASCII passage, exact text offsets, ties, empty passages, length restrictions, score bounds and invariance when every candidate score receives the same shift. An empty passage returns an explicit empty-passage result.
There are O(NL) legal spans, so constructing and storing this output distribution costs O(NL). The current implementation finds accepted candidates by scanning the candidate list, adding O(|G|NL) work for multiple labels. It caps N at 64, L at 16 and score magnitudes at 100. These are teaching limits, not a claim about a production reader’s context length. Changing the maximum length changes the normalized candidate set and can also exclude a gold answer.
A span score measures only one part of comprehension
Extractive output cannot directly express an answer absent from the passage, a required calculation or a synthesis of disconnected spans. Those tasks require a different output contract and evaluation. Even a verbatim span may refer to the wrong time, person or event. Returning offsets makes such mistakes inspectable; it does not prevent them.
The original SQuAD evaluation uses exact match and token-overlap F1, taking the best match among available reference answers for each question before averaging over questions. State the normalization protocol when implementing those metrics; tokenization and treatment of punctuation or articles affect the result. Our program does not implement the complete official evaluator. Evaluation, §6.1
Separate answerable and unanswerable cases when evaluating abstention. Tune any margin threshold on held-out data, then report the tradeoff between answer coverage and errors without retuning on the test set. A softmax probability from manual scores has no demonstrated frequency interpretation. Repeated answer strings also require care: string matching can accept the right words from an unsupported mention.
Test the answer contract
-
In the three-token hand example, why is multiplying two independent softmax distributions not the same as our span distribution?
Answer: The independent product assigns mass to all nine endpoint pairs, including end-before-start and overlong pairs. Their total illegal mass is 11/18. Our distribution excludes those pairs and adds NULL before normalization, giving total mass 16 and probability 1/4 to (1,1).
-
Two acceptable spans each have probability 0.2. What is their alternative-label loss? What would averaging their individual losses produce?
Answer: The marginal loss is −log 0.4. The average is −log 0.2. Marginal supervision accepts either span; the average separately pressures both probabilities. Repeating one annotation must not turn its probability 0.2 into 0.4.
-
NULL has score 1 and three legal spans each have score 0. At threshold zero, does this decoder answer? Does the combined span mass exceed NULL mass?
Answer: It abstains because the best span score 0 does not exceed 1. Combined span mass is 3, larger than exp(1), so an aggregate answerability rule would answer. The two rules optimize different decisions.
-
A decoder returns the substring Pine for “Where did Ada move to?” Can perfect character offsets establish correctness?
Answer: No. The offsets establish which text was returned. Pine names the origin, whereas the question asks for the destination Cedar. Evaluate the question–passage relation as well as the integrity of the extracted interval.
From a supplied passage to an explicit no-answer decision
SQuAD gives a concrete passage-and-span task and an evaluation protocol. Its unanswerable extension tests whether a reader can reject a tempting but unsupported candidate. Read the task definitions before comparing model scores: adding no-answer cases changes what the system must decide. SQuAD task and evaluation Unsupported but plausible candidates
This article’s legal-span distribution, alternative-label loss and small decoder are original teaching choices. They isolate constraints, gradient flow and abstention so those mechanisms can be checked without downloading a language model. A next experiment can supply learned question-conditioned scores while preserving the same evidence and evaluation contract.
Make a prediction, then check
NULL scores1 and each of three spans scores0. At zero threshold, what does the best-span decoder do?
Learning objectives
- Normalize over legal spans and a no-answer candidate.
- Derive marginal loss and endpoint gradients for alternative labels.
- Distinguish a best-span margin from aggregate answerability.
- Verify character evidence without mistaking manual scores for comprehension.
Prerequisites & connections
Explore related knowledge →References
- SQuAD: 100,000+ Questions for Machine Comprehension of Text
Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, Percy Liang · 2016 - Know What You Don’t Know: Unanswerable Questions for SQuAD
Pranav Rajpurkar, Robin Jia, Percy Liang · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked scoped SQuAD task/evaluation and plausible unsupported candidates, separately from the original legal-span/NULL output layer. Six paired equations and four explained exercises verified: partition16, independent illegal mass11/18, alternative-label marginal loss, every endpoint/NULL gradient by central differences, exact Unicode character evidence and best-span versus aggregate decision. Scores are manually supplied; no trained language encoder or dataset score claimed.
- Single AI author checked scoped SQuAD task/evaluation and plausible unsupported candidates, separately from the original legal-span/NULL output layer. Six paired equations and four explained exercises verified: partition16, independent illegal mass11/18, alternative-label marginal loss, every endpoint/NULL gradient by central differences, exact Unicode character evidence and best-span versus aggregate decision. Scores are manually supplied; no trained language encoder or dataset score claimed.
- 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:
- SQuAD: 100,000+ Questions for Machine Comprehension of Text · Abstract passage/span task and section6.1 layout388–408: EM/token F1, best reference per question then average. Joint legal-span marginal loss is our teaching choice, not the paper baseline; no benchmark reproduction.
- 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.
Related topics