Sub topic 3
Natural Language Inference: Premise, Hypothesis, Entailment
This chapter assumes you know basic Python, understand supervised text classification, and have a general idea of what a pretrained language model is. You should also be able to install and import Python packages. The chapter explains the task that makes zero-shot classification possible. It covers what natural language inference (NLI) asks a model to do, how the data is labeled, what the model outputs, and where it goes wrong. The next chapter uses this task to build a classifier.
What NLI asks
Natural language inference is also called recognizing textual entailment. The model receives two pieces of text:
- The premise is a statement that is taken as given.
- The hypothesis is a second statement whose relationship to the premise must be judged.
The model decides whether the premise supports the hypothesis. It does not decide whether the hypothesis is true in the real world. It only judges what follows from the premise.
NLI datasets use three labels:
| Label | Meaning | Example hypothesis for the premise "A man is playing a guitar on stage." |
|---|---|---|
| entailment | The hypothesis must be true if the premise is true. | "A person is playing an instrument." |
| contradiction | The hypothesis cannot be true if the premise is true. | "Nobody is making music." |
| neutral | The premise neither confirms nor rules out the hypothesis. | "The man is playing a song he wrote." |
The test for entailment is the one a careful reader would apply: if someone read only the premise, would they accept the hypothesis as almost certainly true? The test is not strict logical proof. "A man is playing a guitar" entails "A person is playing an instrument" even though a logician could invent odd scenarios in which it fails. Annotators were asked to use common sense.
Where the training data comes from
Models such as facebook/bart-large-mnli are fine-tuned on MultiNLI (MNLI). MNLI contains about 433,000 sentence pairs. Each pair was written and labeled by crowd workers. The premises come from several genres, including fiction, government documents, telephone speech and travel guides. Workers were given a premise and asked to write one hypothesis for each of the three labels.
This process has two consequences that matter later:
- The model learns from many genres, so it handles varied vocabulary better than a model trained on one domain.
- Hypotheses written by people carry stylistic habits. For example, negation words such as "never" and "nobody" often appear in contradiction hypotheses. A model can partly exploit those habits instead of reasoning about meaning. This is called annotation artifacts, and it is one reason NLI scores can be unreliable on unusual phrasing.
How a transformer reads a premise and hypothesis
A pretrained transformer encoder reads one sequence of tokens. For a pair of texts, the tokenizer joins them with special separator tokens. The model then reads both texts together, so every token in the hypothesis can attend to every token in the premise. This joint reading is a cross-encoder setup. It lets the model compare specific words, such as "charged twice" against "billing".
A classification head sits on top of the encoder. It produces three numbers called logits, one per NLI label. A softmax turns the logits into probabilities that add up to one.
Running an NLI model directly
The following code loads the model and prints the probability of each label for three hypotheses. It reads the label order from the model configuration instead of assuming it.
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
name = "facebook/bart-large-mnli"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name)
model.eval()
premise = "A man is playing a guitar on stage."
hypotheses = [
"A person is playing an instrument.",
"Nobody is making music.",
"The man is playing a song he wrote.",
]
print(model.config.id2label)
for hypothesis in hypotheses:
inputs = tokenizer(premise, hypothesis, return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits[0]
probs = torch.softmax(logits, dim=0)
scores = {model.config.id2label[i]: round(probs[i].item(), 3) for i in range(len(probs))}
print(hypothesis, scores)For this model the label order is {0: 'contradiction', 1: 'neutral', 2: 'entailment'}. Other NLI models use other orders, so always look labels up through model.config.label2id or id2label. Hard-coding index 2 for entailment silently breaks when you swap models.
Expect the first hypothesis to receive a high entailment probability, the second a high contradiction probability, and the third a mostly neutral result. Exact numbers vary by library version, so do not rely on the digits.
Passing the pair correctly
Call the tokenizer with the premise as the first argument and the hypothesis as the second. Do not concatenate the two strings yourself. The tokenizer inserts the separator tokens the model was trained with. A manually joined string lacks them, and the model sees a different input from the one it was fine-tuned on.
Length limits
The combined premise and hypothesis must fit the model's maximum length, which is 1,024 tokens for BART. Long documents need truncation or splitting. If truncation cuts the premise, the model judges a partial text. Pass truncation=True for safety and decide deliberately which part of a long document to keep.
Why neutral matters
Entailment is not the opposite of contradiction. Neutral is the most common outcome for an unrelated hypothesis, and it is the reason NLI can reject wrong labels. Consider the premise "I was charged twice for my subscription this month."
- "This example is billing." is likely entailed.
- "This example is sales." is probably neutral. The text does not say anything about sales.
- "This example is about cooking." is probably neutral too.
Contradiction is rarer in classification use, because most wrong labels are merely unsupported, not impossible. Later chapters make use of this distinction when they decide how to convert the three outputs into one score per label.
Why this task transfers to new labels
The model was never trained on the label "billing". It was trained to judge whether a short statement follows from a passage. If you phrase a category as a statement, such as "This example is billing.", the model can apply the same judgment it learned on MNLI. The category name is just words in the hypothesis. This is the central idea behind the next chapter: any label you can express as a sentence becomes a question the model already knows how to answer.
Gotchas and failure modes
- Direction matters. NLI is asymmetric. "A man is playing a guitar" entails "A person is playing an instrument", but the reverse does not hold. Swapping premise and hypothesis changes the result.
- Entailment is not truth. A premise can be false and still entail a hypothesis. The model checks support, not facts.
- Lexical overlap bias. Models tend to predict entailment when hypothesis words overlap heavily with the premise, even when meaning differs. "The doctor saw the lawyer" and "The lawyer saw the doctor" can be confused.
- Negation shortcuts. A hypothesis with a negation word may be pushed toward contradiction regardless of content.
- Short, vague hypotheses. "This is good." gives the model little to anchor on, and scores become unstable.
- Probabilities are not calibrated. A softmax output of 0.9 does not mean the model is right 90 percent of the time. Treat scores as rankings until you measure them on labeled data, which a later chapter covers.
Checking your understanding by probing
A quick way to learn what a model has absorbed is to write minimal pairs: two hypotheses that differ in one word. Run the code above with these premise and hypothesis pairs and note how the label probabilities move.
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
name = "facebook/bart-large-mnli"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name)
model.eval()
pairs = [
("The package arrived on Monday.", "The package arrived."),
("The package arrived on Monday.", "The package did not arrive."),
("The package arrived on Monday.", "The package arrived on Tuesday."),
("The package arrived on Monday.", "The package was heavy."),
]
for premise, hypothesis in pairs:
inputs = tokenizer(premise, hypothesis, return_tensors="pt", truncation=True)
with torch.no_grad():
probs = torch.softmax(model(**inputs).logits[0], dim=0)
best = int(probs.argmax())
print(f"{hypothesis!r}: {model.config.id2label[best]} ({probs[best].item():.2f})")You should see entailment for the first pair, contradiction for the second and third, and neutral for the last. If a result surprises you, you have found a limit of the model, which is useful information before you build on it.
Summary of the working model
- NLI is a three-way judgment about a premise and a hypothesis: entailment, contradiction or neutral.
- A cross-encoder transformer reads both texts together and outputs three logits.
- Label order differs between models, so read it from the configuration.
- Neutral lets the model say "not supported" without calling a statement false.
- The task transfers to new categories because a label can be written as a hypothesis.
Exercise
You run an NLI model with the premise "The meeting was moved to Friday." and the hypothesis "The meeting was rescheduled." You then swap them and run the premise "The meeting was rescheduled." with the hypothesis "The meeting was moved to Friday." Which direction do you expect to score higher for entailment, and why? Also, why should you not hard-code index 2 as the entailment label?
Show answer
The first direction should score higher. Being moved to Friday implies the meeting was rescheduled. Being rescheduled does not say which day, so the reverse is neutral. NLI is asymmetric. Label order differs between models (for example, some put entailment first), so you should read the index from model.config.label2id["entailment"] to avoid using the wrong output.
Exercise
A colleague says an NLI model gave 0.95 entailment for "The product is excellent." against the review "I would never buy this again." What does this suggest about the model, and what two checks would you run?
Show answer
It suggests a failure such as an annotation artifact or a wrong label mapping, since the review contradicts the hypothesis. First, confirm the label order through model.config.id2label to make sure index 0 or 1 was not read as entailment. Second, run minimal pairs and the premise and hypothesis in the correct argument order, then check whether the same error appears on similar examples to see if it is systematic.