TAI BUI
Back to curriculum
LearnPython

Natural Language Inference: Textual Entailment

"t entails h" means a human reading t would conclude h is true. NLI is the task of predicting entailment, contradiction, or neutral. Boring on the surface, load-bearing in production.

TIME: ~60 minutesPREREQUISITES: Phase 5 · 05 (Sentiment Analysis), Phase 5 · 13 (Question Answering)

Learning Objectives

  • Define NLI's three-way classification (entailment, contradiction, neutral) and distinguish it from strict logical entailment.
  • Explain how the premise/hypothesis framing turns NLI into a hallucination check for summarization and RAG, and into a zero-shot text classifier.
  • Run a pretrained NLI model (facebook/bart-large-mnli, microsoft/deberta-v3-large-mnli) for entailment scoring and zero-shot classification, and build a RAGAS-style faithfulness check from it.
  • Recognize NLI's known failure modes -- hypothesis-only shortcuts, the lexical-overlap heuristic, document-length degradation, template sensitivity, domain mismatch -- and pick the right checkpoint for a production use case.

The Problem

You built a summarizer. It produced a summary. How do you know the summary does not contain a hallucination?

You built a chatbot. It answered "yes." How do you know the answer is supported by the retrieved passage?

You need to classify 10,000 news articles by topic. You have no training labels. Can you reuse a model?

All three problems reduce to Natural Language Inference. NLI asks: given a premise t and a hypothesis h, is h entailed by t, contradicted, or neutral (unrelated)?

  • Hallucination check: t = source document, h = summary claim. Not entailment = hallucination.
  • Grounded QA: t = retrieved passage, h = generated answer. Not entailment = fabrication.
  • Zero-shot classification: t = document, h = verbalized label ("This is about sports"). Entailment = predicted label.

One task, three production uses. This is why every RAG (retrieval-augmented generation, where the model looks up relevant text before answering) evaluation framework ships an NLI model under the hood.

Warm-up0/3
1. Someone tells you: 'It rained heavily in the city all day.' Using ordinary reasoning, would you say that statement supports, contradicts, or says nothing about the claim 'The streets are completely dry'?Warm-up
2. In the sentiment classifier from an earlier lesson, the model never sees the word 'positive' in the input text. How does it decide 'positive' is the right label to output?Warm-up
3. A classifier ends in a softmax layer over three classes. What do its three output numbers represent?Warm-up
Check: The Problem0/3
1. What is Natural Language Inference (NLI)?Define
2. In the RAG setting, what is faithfulness?Define
3. Why is NLI a faithfulness check for RAG outputs?Explain

The Concept

NLI: three-way classification, premise vs hypothesis

The three labels.

  • Entailment. t → h. "The cat is on the mat" entails "There is a cat."
  • Contradiction. t → ¬h. "The cat is on the mat" contradicts "There is no cat."
  • Neutral. No inference either way. "The cat is on the mat" is neutral to "The cat is hungry."

Not logical entailment. NLI is natural language inference: what a typical human reader would infer, not strict logic. "John walked his dog" entails "John has a dog" under NLI, but strict first-order logic only admits it once you've axiomatized possession.

Datasets.

  • SNLI (2015). 570k human-annotated pairs, image captions as premises. Narrow domain.
  • MultiNLI (2017). 433k pairs across 10 genres. The standard training corpus in 2026.
  • ANLI (2019). Adversarial NLI. Humans wrote examples specifically designed to break existing models. Harder.
  • DocNLI, ConTRoL (2020–21). Document-length premises. Tests multi-hop and long-range inference.

The architecture. A transformer encoder (BERT, RoBERTa, DeBERTa) reads [CLS] premise [SEP] hypothesis [SEP]. The [CLS] representation feeds a 3-way softmax. Train on MNLI, evaluate on held-out benchmarks, get 90%+ accuracy on in-distribution pairs.

Zero-shot via NLI. Given a document and candidate labels, turn each label into a hypothesis ("This text is about sports"). Compute entailment probability for each. Pick the max. This is the mechanism behind Hugging Face's zero-shot-classification pipeline.

Check: The Concept0/11
1. What is RTE (Recognizing Textual Entailment) in relation to NLI?Define
2. What does it mean for a premise t to entail a hypothesis h in NLI?Define
3. What does it mean for a premise t to contradict a hypothesis h in NLI?Define
4. What does the neutral label mean in NLI?Define
5. What is zero-shot classification done with NLI?Define
6. Why is NLI called 'natural' language inference rather than logical inference?Explain
7. Why is MultiNLI, rather than SNLI, called the standard NLI training corpus?Explain
8. What was ANLI built to do?Explain
9. How does a transformer NLI model turn a premise and hypothesis into one of three labels?Explain
10. Why does turning a label into a hypothesis let an NLI model classify a document it was never trained to label?Explain
11. Premise: 'The cat is on the mat.' Hypothesis: 'The cat is hungry.' Which label does NLI assign?Apply

Build It

Step 1: run a pretrained NLI model

python
from transformers import pipeline
 
nli = pipeline("text-classification",
               model="facebook/bart-large-mnli",
               top_k=None)  # return all labels; replaces deprecated return_all_scores=True
 
premise = "The cat is sleeping on the couch."
hypothesis = "There is a cat in the room."
 
result = nli({"text": premise, "text_pair": hypothesis})[0]
print(result)
# [{'label': 'entailment', 'score': 0.97},
#  {'label': 'neutral', 'score': 0.02},
#  {'label': 'contradiction', 'score': 0.01}]

For production NLI, facebook/bart-large-mnli and microsoft/deberta-v3-large-mnli are the open defaults. DeBERTa-v3 tops leaderboards.

Step 2: zero-shot classification

python
zs = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
text = "The stock market rallied after the central bank cut interest rates."
labels = ["finance", "sports", "politics", "technology"]
 
result = zs(text, candidate_labels=labels)
print(result)
# {'labels': ['finance', 'politics', 'technology', 'sports'],
#  'scores': [0.92, 0.05, 0.02, 0.01]}

The template is "This example is about {label}." by default. Customize with hypothesis_template. No training data required. No fine-tuning. Works out of the box.

Step 3: faithfulness check for RAG

python
def is_faithful(answer, context, threshold=0.5):
    result = nli({"text": context, "text_pair": answer})[0]
    entail = next(s for s in result if s["label"] == "entailment")
    return entail["score"] > threshold

This is the core of faithfulness scoring in RAGAS, a widely used RAG-evaluation library. Split the generated answer into atomic claims. Check each claim against the retrieved context. Report the fraction that entail.

Step 4: hand-rolled NLI classifier (conceptual)

See code/main.py for a stdlib-only toy: premise and hypothesis are compared via lexical overlap + negation detection. Not competitive with transformer models, but it shows the shape of the task: two texts in, 3-way label out, loss = cross-entropy over {entail, contradict, neutral}.

Check: Build It0/6
1. In Step 1, the pipeline prints entailment 0.97, neutral 0.02 and contradiction 0.01 for 'The cat is sleeping on the couch.' and 'There is a cat in the room.' What does that mean?Apply
2. The Step 2 call zs(text, candidate_labels=['finance','sports','politics','technology']) returns scores [0.92, 0.05, 0.02, 0.01] for the stock-market sentence. What does the pipeline report as the prediction, and why?Apply
3. Step 2 uses the default template. For the text 'The team won the final.' and the label 'sports', which premise and hypothesis pair does the NLI model score?Apply
4. With the Step 3 function, an answer gets an entailment score of 0.55 against its context. What does is_faithful(answer, context) return with the default threshold?Apply
5. A generated answer is split into 4 atomic claims, and 3 of them are entailed by the retrieved context. What faithfulness score does the RAGAS-style procedure report?Apply
6. You build a faithfulness checker for long generated answers. Which design does the lesson's approach support?Design

Pitfalls

  • Hypothesis-only shortcuts. Models can predict the label from the hypothesis alone at ~60% on SNLI because "not", "nobody", "never" correlate with contradiction. Strong baseline for detecting label leakage.
  • Lexical overlap heuristic. The subsequence heuristic ("every subsequence is entailed") passes SNLI but fails HANS (an adversarial diagnostic set built to catch exactly this shortcut) and ANLI. Use adversarial benchmarks.
  • Document-length degradation. Single-sentence NLI models drop 20+ F1 on document-length premises. Use DocNLI-trained models for long context.
  • Zero-shot template sensitivity. "This example is about {label}" vs "{label}" vs "The topic is {label}" can swing accuracy by 10+ points. Tune the template.
  • Domain mismatch. MNLI trains on general English. Legal, medical, and scientific text need domain-specific NLI models (e.g., SciNLI, MedNLI).
Check: Pitfalls0/5
1. What does the hypothesis-only baseline expose?Explain
2. A single-sentence NLI model scores well on sentence pairs but drops over 20 F1 on document-length premises. Why?Analyze
3. A zero-shot classifier's accuracy moves by 10+ points when the template changes from 'This example is about {label}' to '{label}'. What explains this?Analyze
4. A model passes SNLI but fails HANS, a diagnostic set built to catch exactly one shortcut. Which shortcut does that pattern suggest?Analyze
5. A team applies an MNLI-trained model to medical notes and sees accuracy drop. What is the most likely cause and the fix?Analyze

Use It

The 2026 stack:

Use caseModel
General-purpose NLImicrosoft/deberta-v3-large-mnli
Fast / edgecross-encoder/nli-deberta-v3-base
Zero-shot classification (lightweight)facebook/bart-large-mnli
Document-level NLIMoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli
MultilingualMoritzLaurer/multilingual-MiniLMv2-L6-mnli-xnli
Hallucination detection in RAGNLI layer inside RAGAS / DeepEval

The 2026 meta-pattern: NLI is the duct tape of text understanding. Whenever you need "does A support B?" or "does A contradict B?", reach for NLI before you reach for another LLM call.

Check: Use It0/2
1. You must check claims against 40-page source documents in a production RAG pipeline. Which choice fits best?Design
2. A mobile app needs on-device-friendly NLI with low latency for short pairs. Which listed checkpoint fits?Design

Ship It

Save as outputs/skill-nli-picker.md:

markdown
---
name: nli-picker
description: Pick an NLI model, label template, and evaluation setup for a classification / faithfulness / zero-shot task.
version: 1.0.0
phase: 5
lesson: 21
tags: [nlp, nli, zero-shot]
---
 
Given a use case (faithfulness check, zero-shot classification, document-level inference), output:
 
1. Model. Named NLI checkpoint. Reason tied to domain, length, language.
2. Template (if zero-shot). Verbalization pattern. Example.
3. Threshold. Entailment cutoff for the decision rule. Reason based on calibration.
4. Evaluation. Accuracy on held-out labeled set, hypothesis-only baseline, adversarial subset.
 
Refuse to ship zero-shot classification without a 100-example labeled sanity check. Refuse to use a sentence-level NLI model on document-length premises. Flag any claim that NLI solves hallucination — it reduces it; it does not eliminate it.
Check: Ship It0/2
1. A stakeholder claims that adding an NLI faithfulness check means the chatbot no longer hallucinates. Which response is accurate?Analyze
2. You must tag 10,000 unlabeled news articles by topic, and you plan to use NLI zero-shot classification. What is the best plan?Design
Author's Note

The mistake I've made with NLI faithfulness checks is shipping the default threshold. bart-large-mnli was trained on MNLI's genre mix, not on the specific claim style your summarizer or RAG pipeline actually produces, so a 0.5 cutoff calibrated on someone else's distribution tells you nothing about where your false positives sit. I once watched a faithfulness gate wave a claim through that flatly contradicted its source passage, because the entailment score landed at 0.51 instead of 0.49. Nothing in the pipeline flagged it. The number just happened to land on the wrong side of an arbitrary line.

Calibrate the threshold on your own labeled examples before you trust it in production. Treat the entailment score as a ranking signal you tune, not a constant you borrow from a paper. The hypothesis-only baseline in the pitfalls list deserves the same suspicion: run it against your own data before assuming your fine-tuned model learned the task and not the shortcut.

Exercises

  1. Easy. Run facebook/bart-large-mnli on 20 hand-crafted (premise, hypothesis, label) triples covering all three classes. Measure accuracy. Add adversarial "subsequence heuristic" traps ("I did not eat the cake" vs "I ate the cake") and see if it breaks.
  2. Medium. Compare the zero-shot template "This text is about {label}" against "The topic is {label}" and "{label}" on 100 AG News headlines. Report accuracy swing.
  3. Hard. Build a RAG faithfulness checker: atomic-claim decomposition + NLI per claim. Evaluate on 50 RAG-generated answers with gold context. Measure false-positive and false-negative rates vs hand labels.

Key Terms

TermWhat people sayWhat it actually means
NLINatural Language Inference3-way classification of premise-hypothesis relationship.
RTERecognizing Textual EntailmentOlder name for NLI; same task.
Entailment"t implies h"A typical reader would conclude h is true given t.
Contradiction"t rules out h"A typical reader would conclude h is false given t.
Neutral"undecided"No inference from t to h either way.
Zero-shot classificationNLI as classifierVerbalize labels as hypotheses, pick max entailment.
FaithfulnessIs the answer supported?NLI over (retrieved context, generated answer).

Further Reading

Code

Ships With