Natural language inference: what follows, what conflicts, and what remains open
自然语言推断
Distinguish entailment, contradiction and neutrality with explicit finite models, then test why word overlap cannot establish a sentence-pair relation.
natural-language-inferenceThe same words can describe a different event
Take the invented premise “Ada follows Bo” and hypothesis “Bo follows Ada.” They contain the same words. The first statement does not tell us whether the second is true: perhaps they follow one another, or perhaps only Ada follows Bo. Swapping the arguments changes the relation even though a bag of words does not change.
Natural language inference, or NLI, assigns a relation to a premise–hypothesis pair. Under the task’s interpretation, entailment means the hypothesis follows from the premise; contradiction means it conflicts with the premise; neutral means the premise leaves its truth open. Neutral does not mean false, and it is not a fourth name for low classifier confidence. A confident model can correctly classify a pair as neutral.
SNLI provides a three-way natural language task, with annotation choices about entities, events and their intended correspondence. Those conventions matter when interpreting a pair. Formal implication alone cannot determine what a pronoun refers to or which event a sentence describes. Task examples and entity/event discussion
We will first make the meanings explicit and inspect all possible small worlds. This removes language parsing from the experiment so we can see precisely why a conclusion follows. We then compare that result with a word-overlap shortcut. The program is a finite logic evaluator, not a learned NLI classifier or an automatic translator from sentences to logic.
Three labels require a consistent premise and a defined interpretation
Fix a finite nonempty domain D, a predicate vocabulary and interpretations of named constants. A world assigns true or false to each ground atom: a predicate applied to particular domain members. For premises P, keep the worlds in which all premises hold:
The subscript D matters. These are models over this specific finite domain, not over every domain size. When the set is nonempty, classify hypothesis H by its truth across the retained worlds:
If no world satisfies the premises, the program returns inconsistent separately. In classical semantics, an empty set of premise models vacuously entails both H and its negation. Silently selecting one ordinary NLI label would hide that problem. The separate status is an implementation choice for inspecting malformed or contradictory inputs, not a fourth SNLI annotation label.
Our default domain contains Ada and Bo. Predicates dog and animal each take one argument, while follows takes two. For predicate arities r, the number of ground atoms A and worlds is:
No fact about dogs being animals is built into the predicate names. Supply that rule explicitly, along with Ada being a dog:
For each individual, the implication permits three dog/animal assignments: neither, animal only, or both. Ada’s dog premise fixes her pair to both; Bo has three choices. Four unrelated follows atoms have sixteen assignments. There are therefore 1×3×16=48 premise worlds, and every one makes Ada an animal.
Reverse the membership premise: Ada is an animal, and ask whether Ada is a dog. Now Ada has two allowed assignments, Bo still has three, and the relation still has sixteen. Of 96 premise worlds, 48 make Ada a dog and 48 do not. The conclusion is neutral. An inclusion rule does not supply its converse.
The universal rule also does not assert that any dogs exist. It has 3×3×16=144 worlds. In 2×2×16=64 worlds, neither individual is a dog; 80 worlds contain at least one dog. The existential hypothesis is thus neutral under these premises:
This is the lack of existential import for the universal implication in the stated logic. It does not decide how every natural language speaker uses a generic sentence. Any assumption that dogs exist must be made explicit in this formal experiment.
For the relation reversal, the premise fixes follows(Ada,Bo) true but leaves follows(Bo,Ada) free. Exactly 64 of its 128 worlds support the hypothesis and 64 refute it. A subset-of-words shortcut sees only lexical overlap:
That rule misses argument order, negation and scope. HANS specifically diagnoses lexical-overlap, subsequence and constituent heuristics using controlled examples. Its lesson is to test the condition under which a shortcut fails, rather than infer robust reasoning from a convenient overall score. Heuristics, Table 1 and §2
Enumerate worlds and keep a witness for each outcome
The complete original program runs with Python 3.12 and the standard library. Its tuple-based input language supports atoms, negation, binary conjunction/disjunction/implication and bounded universal or existential quantification. Logical forms are supplied by the author; the program never parses the English example into them.
"""Original finite-model semantics for inspecting NLI labels and shortcuts.
Inputs are explicit logical forms, not parsed unrestricted natural language.
The finite domain is fixed and nonempty. Dataset annotator assumptions may differ.
"""
import itertools
import json
import re
def setup(domain=('Ada','Bo'),predicates=None):
if isinstance(domain,str):raise ValueError('Domain must be a sequence of names')
domain=tuple(domain);predicates={'dog':1,'animal':1,'follows':2} if predicates is None else dict(predicates)
if not 1<=len(domain)<=3 or len(set(domain))!=len(domain) or any(not isinstance(x,str) or not re.fullmatch('[A-Za-z]+',x) for x in domain):raise ValueError('Use1..3 unique named entities')
if not 1<=len(predicates)<=4 or any(not isinstance(k,str) or not re.fullmatch('[a-z]+',k) or isinstance(v,bool) or not isinstance(v,int) or v not in (1,2) for k,v in predicates.items()):raise ValueError('Use1..4 unary/binary predicates')
atoms=[(name,*args) for name,arity in predicates.items() for args in itertools.product(domain,repeat=arity)]
if len(atoms)>12:raise ValueError('At most12 grounded atoms for exhaustive semantics')
return domain,predicates,{atom:i for i,atom in enumerate(atoms)}
def validate(form,domain,predicates):
count=0;quantifiers=0
def visit(node,bound,depth):
nonlocal count,quantifiers
count+=1
if count>128 or depth>12 or not isinstance(node,(list,tuple)) or not node:raise ValueError('Logical form is malformed or too large')
op=node[0]
if op=='atom':
if len(node)<3 or not isinstance(node[1],str) or node[1] not in predicates or len(node)!=predicates[node[1]]+2:raise ValueError('Invalid atom')
for arg in node[2:]:
if not isinstance(arg,str) or (arg not in domain and not (arg.startswith('$') and arg[1:] in bound)):raise ValueError('Unknown entity or unbound variable')
elif op=='not':
if len(node)!=2:raise ValueError('not takes one formula')
visit(node[1],bound,depth+1)
elif op in ('and','or','implies'):
if len(node)!=3:raise ValueError('Binary connective takes two formulas')
visit(node[1],bound,depth+1);visit(node[2],bound,depth+1)
elif op in ('all','exists'):
quantifiers+=1
if quantifiers>2 or len(node)!=3 or node[1] not in ('x','y') or node[1] in bound:raise ValueError('At most two non-shadowed x/y quantifiers')
visit(node[2],bound|{node[1]},depth+1)
else:raise ValueError('Unknown connective')
visit(form,set(),0)
def evaluate(form,world,domain,indices,env=None):
env={} if env is None else env;op=form[0]
if op=='atom':
args=tuple(env[x[1:]] if x.startswith('$') else x for x in form[2:])
return bool(world & (1<<indices[(form[1],*args)]))
if op=='not':return not evaluate(form[1],world,domain,indices,env)
if op=='and':return evaluate(form[1],world,domain,indices,env) and evaluate(form[2],world,domain,indices,env)
if op=='or':return evaluate(form[1],world,domain,indices,env) or evaluate(form[2],world,domain,indices,env)
if op=='implies':return not evaluate(form[1],world,domain,indices,env) or evaluate(form[2],world,domain,indices,env)
values=[evaluate(form[2],world,domain,indices,{**env,form[1]:x}) for x in domain]
return all(values) if op=='all' else any(values)
def infer(premises,hypothesis,domain=('Ada','Bo'),predicates=None):
domain,predicates,indices=setup(domain,predicates);premises=list(premises)
if len(premises)>8:raise ValueError('At most8 premise formulas')
for form in premises+[hypothesis]:validate(form,domain,predicates)
supports=[];refutes=[]
for world in range(1<<len(indices)):
if all(evaluate(p,world,domain,indices) for p in premises):
(supports if evaluate(hypothesis,world,domain,indices) else refutes).append(world)
label='inconsistent' if not supports and not refutes else 'entailment' if not refutes else 'contradiction' if not supports else 'neutral'
return dict(label=label,total_worlds=1<<len(indices),premise_worlds=len(supports)+len(refutes),
supporting_worlds=len(supports),refuting_worlds=len(refutes),
support_witness=supports[0] if supports else None,refutation_witness=refutes[0] if refutes else None)
def overlap_shortcut(premise,hypothesis):
"""Deliberately fallible lexical-subset rule, not an NLI semantic parser."""
words=lambda s:set(re.findall('[a-z]+',s.lower()))
return 'entailment' if words(hypothesis)<=words(premise) else 'neutral'
def demo():
dog=('atom','dog','Ada');animal=('atom','animal','Ada')
rule=('all','x',('implies',('atom','dog','$x'),('atom','animal','$x')))
cases=[('rule_and_fact',[rule,dog],animal),('converse',[rule,animal],dog),
('explicit_negation',[dog],('not',dog)),('role_reversal',[('atom','follows','Ada','Bo')],('atom','follows','Bo','Ada')),
('no_existential_import',[rule],('exists','x',('atom','dog','$x'))),
('inconsistent_premise',[dog,('not',dog)],animal)]
results={name:infer(p,h) for name,p,h in cases}
return dict(domain=['Ada','Bo'],cases=results,
role_reversal_text=dict(premise='Ada follows Bo',hypothesis='Bo follows Ada',shortcut=overlap_shortcut('Ada follows Bo','Bo follows Ada')),
conditions='Explicit finite logical forms; no automatic language parsing, real corpus accuracy or universal-domain proof')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The demo returns 48 supporting worlds for dog-to-animal, 48 supporting and 48 refuting worlds for the converse, and a contradiction when dog(Ada) is paired with not dog(Ada) as the hypothesis. Relation reversal gives 64 worlds on each side. The universal-to-existence example gives 80 supporting and 64 refuting worlds. Explicitly contradictory premises produce no worlds and the separate inconsistent status.
Witness IDs encode complete truth assignments. A neutral result includes evidence that the hypothesis can be true and evidence that it can be false under the premises. These are countermodels inside the declared finite domain, not real observations about Ada and Bo. Renaming or reordering domain and predicate declarations can change IDs without changing the logical result or counts.
Independent tests calculate Boolean truth-table counts, the dog/animal cases and a nested quantifier example: over two individuals, every individual following at least one individual admits nine of sixteen relation assignments. Tests also check argument order, witness truth, inconsistent premises and invariance under declaration order.
Enumeration takes O(2^A K D^Q) time for A ground atoms, total formula size K, domain size D and maximum nested quantifier depth Q. Saving supporting and refuting world IDs costs O(2^A) memory. This version does not optimize memory down to counts and two witnesses. Caps are three domain members, four predicates of arity one or two, twelve ground atoms, eight premises and two quantifiers per formula. Each formula has at most 128 nodes and depth 12. These limits bound the demonstration; exhaustive enumeration becomes expensive as the number of atoms grows.
Formal certainty does not remove language ambiguity
A finite countermodel shows that a conclusion need not follow in this declared setting. Conversely, success over one domain size is not a proof for arbitrary domains. To reason about unrestricted first-order logic, the proof task and method must change. The input grammar also omits many constructions needed for natural language, including a general account of time, modality and reference.
Dataset labels additionally depend on annotation conventions and available background assumptions. If a premise says someone stopped doing something, interpreting what it presupposes involves more than swapping an atom into a truth table. Document such assumptions instead of allowing common sense to enter some examples silently and disappear from others.
A trained NLI model can use lexical features, sequence encoders or other sentence-pair representations to predict labels. That prediction is not the same operation as our exhaustive semantic check. Evaluate targeted groups for negation, role reversal, quantifier scope and lexical substitution; inspect both successes and failures. HANS organizes such heuristic diagnostics, but passing a finite set still does not prove universal reasoning ability. Controlled heuristic tests
Do not mix label spaces when reporting scores. SNLI is three-way; the official HANS evaluation maps contradiction and neutral predictions to non-entailment and evaluates entailment versus non-entailment. A neutral result in our role-reversal example would belong to the latter class, not to contradiction. The referenced HANS repository is pinned to a specific commit; only its README and MIT license were examined here, and no dataset or upstream program is copied or executed. Official evaluation instructions
Find a supporting world and a countermodel
-
Every dog is an animal, and Ada is an animal. Why is “Ada is a dog” neutral rather than entailed?
Answer: Ada can be an animal without being a dog, or she can be both. Both assignments satisfy the premises. In this two-person vocabulary there are 48 worlds of each kind. The rule gives inclusion, not equality of the categories.
-
Does “Every dog is an animal” force at least one dog to exist?
Answer: No. Set both dog atoms false; the implication holds for both individuals regardless of their animal values. Those 64 worlds refute existence, while another 80 support it. The existential hypothesis remains neutral without an existence premise.
-
Ada follows Bo. Add “No one follows Ada.” What happens to the hypothesis that Bo follows Ada?
Answer: It becomes a contradiction: the added universal negative forces follows(Bo,Ada) false. The premises are still consistent because Ada can follow Bo while no one follows Ada. Without that extra premise the reversed relation was neutral.
-
An NLI classifier returns neutral for a HANS item. Should an evaluator turn it into contradiction?
Answer: No. The official binary mapping turns both neutral and contradiction into non-entailment. It does not identify the two semantic relations. Keep the original three-way prediction if later analysis needs that distinction.
Use task conventions and controlled failures together
Read SNLI’s examples and entity/event assumptions to understand the natural language annotation task. Then read HANS’s heuristic definitions and its official evaluation mapping. One defines a broad sentence-pair learning task; the other probes particular ways a model can exploit a shortcut. Their label spaces and evidence should not be treated as interchangeable. SNLI HANS paper Pinned evaluation README
The exhaustive program supplies a separate teaching instrument: meanings are explicit, all finite worlds can be checked and a neutral label has witnesses on both sides. Use it to test a logical claim before asking how a language model should learn the claim’s wording. Bridging those two problems requires an account of interpretation, data and generalization as well as a correct truth table.
Make a prediction, then check
Ada follows Bo. With no additional assumptions, what is the relation to “Bo follows Ada”?
Learning objectives
- Distinguish entailment, contradiction, neutrality and inconsistent premises.
- Count finite models and exhibit supporting/refuting witnesses.
- Explain role reversal and missing existential import.
- Keep SNLI three-way labels separate from HANS binary evaluation.
Prerequisites & connections
Explore related knowledge →References
- A large annotated corpus for learning natural language inference
Samuel R. Bowman, Gabor Angeli, Christopher Potts, Christopher D. Manning · 2015 - Right for the Wrong Reasons: Diagnosing Syntactic Heuristics in Natural Language Inference
R. Thomas McCoy, Ellie Pavlick, Tal Linzen · 2019 - HANS official repository: pinned evaluation README and MIT license
R. Thomas McCoy / HANS contributors · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked scoped SNLI interpretation, HANS heuristic definitions and official binary label mapping. Six paired equations and four explained exercises verified by finite truth counts and witnesses: inclusion versus converse, missing existential import, role reversal, negation and inconsistent premises. Explicit logical forms over a fixed bounded domain are not automatic natural language parsing or arbitrary-domain proofs.
- Single AI author checked scoped SNLI interpretation, HANS heuristic definitions and official binary label mapping. Six paired equations and four explained exercises verified by finite truth counts and witnesses: inclusion versus converse, missing existential import, role reversal, negation and inconsistent premises. Explicit logical forms over a fixed bounded domain are not automatic natural language parsing or arbitrary-domain proofs.
- 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:
- A large annotated corpus for learning natural language inference · Abstract, Table1 and beginning of section2, layout56–93: three labels and entity/event interpretation. Finite formal semantics is not natural language annotation reproduction; no dataset-size or agreement claims.
- Right for the Wrong Reasons: Diagnosing Syntactic Heuristics in Natural Language Inference · PDF page2 Table1 and section2 visually read: lexical-overlap, subsequence and constituent heuristics. Borrow diagnostic organization only; examples/program are original, no model performance reproduced.
- HANS official repository: pinned evaluation README and MIT license · README lines1–34 and MIT license read: map neutral and contradiction to non-entailment for binary evaluation. No data or code copied/run. Commit7299f6f657089ce06a0f98e7e81f8d0f5b7741ce dated2021-01-27.
Related topics