Natural Language Inference: Entailment and Contradiction
What You'll Learn
- 1Formulate natural language inference as three-way classification over a premise and a hypothesis
- 2Compare cross-encoder and bi-encoder inference models with their real computational cost
- 3Compute softmax posteriors and attention weights that produce an inference decision
- 4Diagnose heuristic shortcuts using SNLI, MultiNLI, ANLI, and HANS
Natural language inference decides whether a premise sentence guarantees, contradicts, or says nothing about a hypothesis. It is the most reused supervised task in language understanding, because anything shaped like "does A license B" can be restated as NLI: fact verification, retrieval filtering, claim detection, and open-domain question answering all reduce to it. A search engine that cannot separate a close paraphrase from a contradiction will surface the wrong passage.
Task Formulation
Given a premise and a hypothesis , the model returns one label from a closed set:
Entailment is directional: entails when every world in which is true makes true, so "a woman is playing a violin" entails "a woman is making music" but not the reverse. Contradiction is symmetric and stricter, requiring that no world satisfies both sentences. Neutral covers everything left, which is the largest and least well-defined class and roughly one third of every balanced NLI corpus.
A classifier scores the three labels with a shared encoder and a softmax over the final hidden state:
where is the three-vector of logits produced by the classification head.
Cross-Encoders and Bi-Encoders
Two architectures dominate, and they differ in cost more than in accuracy. A cross-encoder concatenates the pair into one sequence, runs joint self-attention over tokens, and reads the label off the first token, giving strong interaction but one forward pass per candidate pair. A bi-encoder embeds each sentence separately and compares vectors, so premises and hypotheses need only passes plus a similarity search.
Sentence-BERT (Reimers and Gurevych, 2019) made this concrete: finding the most similar pair among one million sentences dropped from 65 hours with a BERT cross-encoder to 5 seconds with a bi-encoder, while retaining the accuracy of the slow path on STS-B.
Decomposable Attention
Parikh et al. (2016) removed joint attention by factoring inference into attend, compare, and aggregate, each a shallow feed-forward network. Every premise token is scored against every hypothesis token , the scores are normalized along one axis, and the weighted average builds an aligned view of the other sentence:
Each token is then replaced by the pair and passed through a deep average network, so the whole model runs in scoring work with small constants and no recurrence.
Benchmarks and Failure Modes
| Dataset | Year | Size | Source text | Why it exists |
|---|---|---|---|---|
| SNLI | 2015 | 570,000 pairs | Flickr30k image captions | First large supervised NLI set |
| MultiNLI | 2018 | 433,000 pairs | 10 written and spoken genres | Tests domain transfer |
| SICK | 2014 | 10,000 pairs | Image captions | Fine-grained relatedness plus labels |
| ANLI | 2020 | 162,865 train | Wikipedia, news, fiction, debates | Adversarial human and model loop |
| HANS | 2019 | 30,000 pairs | Heuristic templates | Exposes lexical overlap shortcuts |
MultiNLI reports matched and mismatched accuracy, where mismatched genres were never seen in training, and the gap between them reads out how brittle a model is. Human agreement sits near 87 percent on MultiNLI while RoBERTa-large passes 90, yet that model falls to chance on the non-entailment cases in HANS, so headline accuracy hides the shortcut.
Worked Examples
Worked Code
from transformers import pipeline
import torch
def nli_predict(premise, hypothesis):
"""Cross-encoder NLI with a released checkpoint."""
clf = pipeline(
"text-classification",
model="cross-encoder/nli-deberta-v3-base",
top_k=None,
)
text = f"{premise} [SEP] {hypothesis}"
scores = clf(text)[0]
best = max(scores, key=lambda s: s["score"])
return {s["label"]: round(s["score"], 4) for s in scores}, best["label"]
probs, label = nli_predict(
"Two dogs race across the grass.",
"Animals are running outdoors.",
)
print(probs, "->", label)
import numpy as np
def softmax(x):
e = np.exp(x - x.max())
return e / e.sum()
def attend(hyp_tokens, prem_tokens):
"""Decomposable attention: e, alpha, beta for one hypothesis token."""
e = prem_tokens @ hyp_tokens.T # (m, n) similarity scores
alpha = np.exp(e - e.max(axis=0, keepdims=True))
alpha /= alpha.sum(axis=0, keepdims=True) # normalize over premise tokens
beta = prem_tokens.T @ alpha # (n, d) aligned premise vectors
return e, alpha, beta
rng = np.random.default_rng(0)
prem = rng.normal(size=(6, 8)) # 6 premise tokens, 8-dim vectors
hyp = rng.normal(size=(4, 8)) # 4 hypothesis tokens
e, alpha, beta = attend(hyp, prem)
print("alpha columns sum to", alpha.sum(axis=0).round(3))
print("beta shape", beta.shape)
print("label posterior", softmax(np.array([2.1, 0.3, -1.4])).round(3))
Real-World Applications
- Retrieval filtering - Cross-encoder NLI rerankers drop contradicting passages from the top 100 hits of a RAG system before generation runs.
- Fact verification - Fever (Thorne et al., 2018) reframes NLI over evidence sentences and spawned the Climate-Fever and SciFact test sets.
- Zero-shot classification - Yin et al. (2019) cast each label as a hypothesis and beat supervised baselines on 10 of 12 classification datasets with an MNLI model.
- Data augmentation - Back-translated premises passed through an NLI filter add clean pairs and routinely lift downstream accuracy by 2 to 5 points.
đĄAccuracy is not understanding
Common Mistakes
Treating entailment as symmetric
Fix: Entailment runs from premise to hypothesis only, so swap the pair and the label usually becomes neutral.
Reporting accuracy on an imbalanced NLI set
Fix: Use macro F1 across the three labels, since neutral and contradiction dominate some corpora.
Comparing cross-encoder and bi-encoder scores directly
Fix: Cross-encoders output calibrated logits while bi-encoders output cosine similarities, so calibrate on a dev set before comparing.
Best Practices
- Evaluate on both a matched and a mismatched genre to measure domain shift
- Add a heuristic probe such as HANS whenever MNLI accuracy moves more than a point
- Use a bi-encoder for retrieval and a cross-encoder only to rerank the top candidates
Key Takeaways
- NLI is three-way classification with a softmax over exactly three logits
- Cross-encoders cost quadratic pair evaluations while bi-encoders cost linear passes plus a search
- SNLI has 570,000 pairs, MultiNLI 433,000, and ANLI 162,865 adversarial training examples
- Decomposable attention normalizes token scores with a softmax and runs in O(n m) work
Frequently Asked Questions
Why is neutral the hardest label?
Neutral has no positive linguistic signature, so it is defined only as the complement of entailment and contradiction. Models learn it as a residual class, which is why confusion between neutral and contradiction accounts for most errors on MultiNLI dev.
Does more NLI data keep helping?
Going from SNLI 570k to SNLI plus MultiNLI 1,003k pairs adds a few in-domain points, but ANLI's 162,865 adversarial examples move out-of-distribution accuracy far more than an equal number of random ones, because they were written to break a specific model.
What is the practical accuracy target?
RoBERTa-large reaches 90.2 percent matched and about 89.9 percent mismatched on MultiNLI while humans reach roughly 87 percent on the same protocol, so leave headroom for annotation noise when you set expectations.
Interview Questions
Q1: Explain when you would use a bi-encoder instead of a cross-encoder for NLI.
Bi-encoders encode each sentence once and search with an index, turning quadratic pair scoring into linear work, which is what cut Sentence-BERT search over one million sentences from 65 hours to 5 seconds.
Q2: How do you detect that an NLI model is relying on lexical overlap?
Run it on HANS, which holds 30,000 heuristically generated pairs; models trained on SNLI and MNLI drop to about 50 percent accuracy on the non-entailment overlap items while humans stay above 90 percent.