Sub topic 4
Turning classification into an entailment question
This chapter assumes you know what supervised text classification is, have a general idea of what a pretrained transformer is, and can run Python with torch and transformers installed. The previous chapter introduced natural language inference (NLI): given a premise and a hypothesis, a model decides whether the premise entails the hypothesis, contradicts it, or neither. Here you will see how that task becomes a classifier for labels the model never saw.
The core idea
A supervised classifier learns a fixed mapping from text to a closed set of labels. The label set is baked into the output layer, so a new label means new training data.
An NLI model has no label-specific output layer. Its three outputs are always contradiction, neutral and entailment, whatever the topic. That makes it reusable. You can state a candidate label as a sentence, and the model judges whether the text supports it.
The reformulation has three steps:
- Treat the text you want to classify as the premise.
- For each candidate label, build a hypothesis: a short sentence that claims the label applies.
- Ask the NLI model how strongly the premise entails each hypothesis. The label with the strongest entailment wins.
Take the premise "I was charged twice for my subscription this month." With the labels billing, technical support and sales, you would test these three pairs:
| Premise | Hypothesis |
|---|---|
| I was charged twice for my subscription this month. | This example is billing. |
| I was charged twice for my subscription this month. | This example is technical support. |
| I was charged twice for my subscription this month. | This example is sales. |
A good NLI model should rate the first pair as entailment and the others as neutral or contradiction.
Why this works
A model trained on NLI datasets such as MultiNLI has learned a general skill: judging whether one sentence supports another. The premise and hypothesis can be about any subject. The model does not memorize "billing". It learned that a complaint about duplicate charges supports a statement about billing.
This is a form of transfer. The classification task is rewritten into the format the model was trained on, so no new training is needed. This is the main reason zero-shot classification works with NLI models at all.
The model's knowledge comes from two places. The pretrained encoder or encoder-decoder supplies language understanding. NLI fine-tuning teaches it to compare two sentences. Any label that can be written as a plausible English statement can be tested.
From logits to label scores
The NLI model returns three logits per pair. How you turn them into a score per label depends on whether you treat the labels as mutually exclusive. The Hugging Face pipeline offers both modes.
Single-label mode (default)
The pipeline takes only the entailment logit of each pair. It then applies a softmax across the labels. The scores sum to 1, so the labels compete with each other. Use this when exactly one label is correct.
Multi-label mode (`multi_label=True`)
Each label is scored on its own. For each pair, the pipeline ignores the neutral logit and applies a softmax over the contradiction and entailment logits. The score is the probability of entailment against contradiction. The scores do not sum to 1, so several labels can score high for the same text. The next chapters cover this mode in more detail.
The difference matters because the two scores answer different questions. The single-label score answers "which label fits best?" The multi-label score answers "does this label fit at all?" A single-label softmax gives a confident answer even when every label is a poor fit, because the probabilities must add up to 1.
Reproducing the scoring by hand
This script does the same work as the pipeline and computes both score types. It batches all hypotheses for one premise into a single forward pass.
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 = "The app crashes when I try to update my payment method."
labels = ["billing", "technical support", "sales"]
template = "This example is {}."
hypotheses = [template.format(label) for label in labels]
inputs = tokenizer(
[premise] * len(labels),
hypotheses,
return_tensors="pt",
padding=True,
truncation="only_first",
)
with torch.no_grad():
logits = model(**inputs).logits # shape: (num_labels, 3)
entail = model.config.label2id["entailment"]
contra = model.config.label2id["contradiction"]
# Single-label: softmax over the entailment logits of all labels.
single = torch.softmax(logits[:, entail], dim=0)
# Multi-label: per label, softmax over contradiction vs entailment.
multi = torch.softmax(logits[:, [contra, entail]], dim=1)[:, 1]
print(f"{'label':<20}{'single':>10}{'multi':>10}")
for label, s, m in zip(labels, single, multi):
print(f"{label:<20}{s.item():>10.3f}{m.item():>10.3f}")Run it and compare the two columns. The single column sums to 1. The multi column does not. If you pass the same text, labels and template to the pipeline function with and without multi_label=True, the numbers should match yours up to rounding.
Always read the entailment and contradiction indices from model.config.label2id. Models disagree on the order of the three classes, and hard-coding an index silently gives wrong scores.
Cost: one forward pass per label
This design has a cost. Each label creates a separate premise-hypothesis pair, and each pair needs its own forward pass through the model. With 3 labels and 1,000 texts, the model runs 3,000 times. With 50 labels it runs 50,000 times.
A supervised classifier scores all labels in one pass. This is why zero-shot NLI classification gets slow when the label set is large. It is also why the model reads the premise again for every label. Later chapters compare this with embedding-based approaches, which encode the text once.
The scale of the problem depends on the model. bart-large-mnli has hundreds of millions of parameters, so on a CPU it is slow for large batches. Smaller distilled NLI models trade some accuracy for speed.
Common errors
- Reading single-label scores as confidence. Because the scores sum to 1, the top label can show 0.9 even if no label really fits. Consider whether "none of these" is a possible answer for your data.
- Treating neutral as contradiction. Single-label mode ignores the neutral logit completely. Multi-label mode ignores it too. A pair the model rates as neutral can still get a middling score.
- Labels that are not valid hypotheses. A label with odd grammar, or a long phrase, makes the hypothesis ambiguous. The model is then judging the awkward sentence, not your category.
- Overlapping labels in single-label mode. If two labels both apply to a text, they split the probability mass and neither looks confident. Use multi-label mode when labels can overlap.
- Long premises. The tokenizer truncates the premise (
truncation="only_first") when the pair exceeds the model's limit. For long documents, the end of the text may never be seen.
Where this fits
This chapter explains the mechanism behind the pipeline. The next chapter runs zero-shot-classification directly and shows how its arguments map to the steps above. Hypothesis templates and label wording, covered after that, change the hypothesis text. Since the model scores each hypothesis as a sentence, wording changes can move the scores noticeably.
Exercise
A text is "My invoice shows the wrong amount, and the website also keeps logging me out." You score it against the labels billing and technical support. In single-label mode the scores come out near 0.55 and 0.45. In multi-label mode they come out near 0.97 and 0.95. Explain why the two modes differ, and say which result better reflects the text.
Show answer
In single-label mode, the pipeline applies a softmax across the labels' entailment logits, so the scores must sum to 1 and the labels compete. Both labels apply to this text, so they split the probability and neither gets a high score. In multi-label mode each label is scored on its own, as entailment against contradiction, so both can be high. The multi-label result better reflects the text, because the message contains both a billing problem and a technical problem.
Exercise
You have 200 support emails and 25 candidate labels. How many NLI forward passes does zero-shot classification need, and what could you change to reduce the cost?
Show answer
It needs 200 x 25 = 5,000 forward passes, because each email is paired with each label's hypothesis. To reduce the cost you could use a smaller distilled NLI model, reduce the number of labels (for example, by first narrowing down to a few candidates with a cheaper method), or use an embedding-similarity approach that encodes each text only once.