QuiddityML

By · 7 November 2026 · 7 min read

Natural language inference (NLI) explained

What entailment, contradiction and neutral mean, why counting shared words fails and how to build an NLI classifier in PyTorch.

Natural language inference (NLI) reads two texts and decides whether the first one supports the second, contradicts it or leaves it open. A compliance analyst can use it to check that a policy paragraph backs a claim, and a chatbot team can use it to check that a generated answer follows from the source it quotes. NLI is the task for questions of the form "does this text support that claim?".

Language models work with tokens, which are whole words or pieces of words. This post says "word" in a few places to keep the examples simple.

Premise and hypothesis

The first text is called the premise and the second is the hypothesis. The premise is the source, such as a policy paragraph or a retrieved document. The hypothesis is the claim being checked against it. The output is one label from a fixed list, so NLI is a form of text classification where the input is a pair of texts instead of one.

Two inputs, a premise and a hypothesis, go into one pair encoder, which returns one of three labels: entailment, where the hypothesis is supported, contradiction, where it is contradicted, and neutral, where there is not enough information or the texts are unrelated.

Sentiment, topic and intent classification read one text and return one label. NLI reads two texts and returns one label that describes how they relate.

Sentiment, topic and intent classification take one text, such as the battery died fast, and a classifier returns one label. Natural language inference takes a pair, the premise the store closes at 9pm and the hypothesis the store is open all night, and returns one label, contradiction.

The three NLI labels

The standard label set has three labels:

"A child is riding a bicycle" entails "A person is on a bike", because a child is a person and a bicycle is a bike. "The room is empty" contradicts "Two people are sitting in the room". "The chef chopped onions" is neutral toward "The chef made soup", since the onions could have gone into soup or into anything else.

Three example pairs. Entailment: A child is riding a bicycle, so A person is on a bike must be true. Contradiction: The room is empty, so Two people are sitting in the room must be false. Neutral: The chef chopped onions does not decide whether The chef made soup.

The labels describe what follows from the premise, not whether the hypothesis is true in the world. If the premise says "The refund period is 30 days", the hypothesis "Customers can request a refund within one month" is entailment even if the real company changed its policy yesterday.

Why shared words are not enough

A tempting shortcut is to count how many words the two texts share and call high overlap entailment. Two pairs show why that fails:

1import re
2 
3def words(text):
4    return set(re.findall(r"[a-z]+", text.lower()))
5 
6def overlap(premise, hypothesis):
7    p, h = words(premise), words(hypothesis)
8    return len(p & h) / len(p | h)
9 
10pairs = [
11    ("The account can be closed after the invoice is paid.",
12     "The account can be closed before the invoice is paid.", "contradiction"),
13    ("The trial lasts fourteen days.",
14     "The trial lasts two weeks.", "entailment"),
15]
16for premise, hypothesis, label in pairs:
17    print(f"{label:13s} overlap {overlap(premise, hypothesis):.2f}")
1contradiction overlap 0.80
2entailment    overlap 0.43

overlap is the number of distinct words the two texts share divided by the number of distinct words in either one. The first pair shares 8 of its 10 distinct words and is a contradiction, because "after" became "before". The second pair shares only "the", "trial" and "lasts" and is entailment, because fourteen days and two weeks are the same length of time. A rule based on overlap would get both pairs wrong.

High word overlap with contradiction: The account can be closed after the invoice is paid versus before the invoice is paid. Low word overlap with entailment: The trial lasts fourteen days versus The trial lasts two weeks.

This is what makes NLI useful as a task: it asks the model to work out what the sentences mean instead of matching words.

How a classifier reads a pair

A trained NLI classifier turns the pair into one sequence. The premise tokens come first, then a separator token such as [SEP], then the hypothesis tokens. The separator tells the model where one text ends and the other begins.

From there the model is the same as any text classifier. An embedding layer maps each token id to a vector. An encoder, such as a recurrent network (RNN) that reads one token at a time, returns one vector $h$ for the whole pair. A linear layer then maps $h$ to three scores, one per label:

$$z = Wh + b$$

$W$ is a weight matrix with one row per label and $b$ is a bias vector. The three scores in $z$ are called logits. Softmax turns them into probabilities that are positive and sum to 1:

$$p_i = \frac{\exp(z_i)}{\sum_j \exp(z_j)}$$

The code below builds the pair and runs it through an untrained model to check the shapes. It then applies softmax to the logits 2.30, 0.30 and 0.90:

1import torch
2import torch.nn as nn
3 
4torch.manual_seed(0)
5 
6class NLIClassifier(nn.Module):
7    def __init__(self, vocab_size, emb_dim, hidden_size, num_labels=3):
8        super().__init__()
9        self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
10        self.rnn = nn.RNN(emb_dim, hidden_size, batch_first=True)
11        self.head = nn.Linear(hidden_size, num_labels)
12 
13    def forward(self, input_ids):
14        output, hn = self.rnn(self.emb(input_ids))
15        return self.head(hn[-1])       # (batch, num_labels)
16 
17vocab = {"<pad>": 0, "[SEP]": 1, "the": 2, "customer": 3, "paid": 4,
18         "order": 5, "purchased": 6}
19labels = ["entailment", "contradiction", "neutral"]
20 
21premise = ["the", "customer", "paid"]
22hypothesis = ["order", "purchased"]
23pair = premise + ["[SEP]"] + hypothesis
24input_ids = torch.tensor([[vocab[w] for w in pair]])
25print(pair)
26print(input_ids.shape)
27 
28model = NLIClassifier(len(vocab), emb_dim=16, hidden_size=32)
29print(model(input_ids).shape)
30 
31z = torch.tensor([2.30, 0.30, 0.90])   # entailment, contradiction, neutral
32probs = z.softmax(dim=-1)
33print({name: round(p, 2) for name, p in zip(labels, probs.tolist())})
34print(labels[probs.argmax().item()])
1['the', 'customer', 'paid', '[SEP]', 'order', 'purchased']
2torch.Size([1, 6])
3torch.Size([1, 3])
4{'entailment': 0.72, 'contradiction': 0.1, 'neutral': 0.18}
5entailment

One pair of six tokens goes in and one row of three logits comes out. Softmax gives entailment 0.72. Taking the label with the highest probability, called the argmax, returns entailment.

The tokens the, customer, paid, [SEP], order, purchased go into an RNN encoder that returns a vector h, then nn.Linear(hidden_size, 3) gives logits 2.30, 0.30 and 0.90 for entailment, contradiction and neutral. Softmax turns them into 0.72, 0.10 and 0.18, and argmax picks entailment.

Training uses labeled pairs, each stored with the index of its label, such as y = 0 for entailment. The loss is cross-entropy, the negative log of the probability the model gave the correct label, which is the same loss used for other single-label classifiers. If the model puts 0.72 on the correct label, the loss is $-\log 0.72 = 0.33$.

Asking a language model instead

A large language model can also do NLI without training for it. The prompt gives both texts and the allowed labels:

1Return exactly one label: entailment, contradiction, or neutral.
2Premise: The refund period is 30 days.
3Hypothesis: Customers can request a refund within one month.

The model generates the answer one token at a time. The system then checks that the answer is one of the three allowed labels and needs a rule for answers that are not, such as mostly entailment.

Evaluating an NLI model

Whichever way the model is built, it is judged on labeled pairs it never saw during training. Accuracy is the share of pairs labeled correctly. Per-label precision and recall show whether one label is the weak spot: precision for contradiction is the share of pairs predicted as contradiction that really are, and recall is the share of real contradictions the model found. A confusion matrix with true labels as rows and predicted labels as columns shows which labels the model mixes up, for example neutral pairs called entailment.

The pairs in the test set should look like the real inputs. A model tested on short everyday sentences says little about how it handles contract clauses or long policy pages.

Where NLI is used

Common mistakes

NLI is a kind of text classification, the task that sorts a whole text into a label such as negative or billing. Token classification labels every token instead of the whole input. The encoder used above is an RNN, and softmax turns its scores into probabilities. NLP tasks explained covers how to tell which task a request needs.

QuiddityML teaches NLI as its own concept in the NLP tasks unit of its NLP track, and its questions ask learners to label premise and hypothesis pairs such as the fourteen-day trial and to explain why one changed word can flip the label (QuiddityML).