Sub topic 7
Single-label and multi-label scoring
This chapter assumes you can run the zero-shot-classification pipeline from the previous chapter. It also assumes you know that the pipeline asks an NLI model whether a text entails a hypothesis built from each candidate label. Here you will learn what the multi_label argument changes in the math, how to read the scores, and which mistakes to avoid.
Two questions the same model can answer
Each candidate label becomes one premise-hypothesis pair. For the text "I was charged twice for my subscription this month" and the label "billing", the model sees the following pair:
- Premise: the text.
- Hypothesis: "This example is billing."
The NLI model returns three logits for each pair: contradiction, neutral, and entailment. A logit is a raw score from the model before it is turned into a probability. The pipeline has to turn those three numbers per label into one score per label. It has two ways to do that, and each way answers a different question.
| Mode | `multi_label` | Question answered | Scores across labels |
|---|---|---|---|
| Single-label | `False` (default) | Which one label fits best? | Sum to 1 |
| Multi-label | `True` | Does each label fit, judged alone? | Independent, each between 0 and 1 |
Single-label scoring
With multi_label=False, the pipeline ignores the neutral and contradiction logits. It collects the entailment logit for every label and applies one softmax across the labels. Softmax rescales a list of numbers so they are positive and add up to 1. The result works like a probability distribution over your labels.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "The app crashes when I try to update my payment method."
labels = ["billing", "technical support", "sales"]
result = classifier(text, candidate_labels=labels)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label}: {score:.3f}")
print("sum:", round(sum(result["scores"]), 3))The labels come back sorted from highest to lowest score, and the sum prints as 1.0. Because the scores compete, a high score for one label forces the others down. This has two consequences:
- The top label always gets a decent-looking score, even if none of the labels truly fits. If you give the model only irrelevant labels, one of them still wins.
- The score depends on the other labels in the list. Adding or removing a label changes every score. A score of 0.62 means "62% of the competition", not "62% sure the text is about this".
Use single-label mode when exactly one label must be chosen and the labels are mutually exclusive, such as routing a ticket to one queue.
Multi-label scoring
With multi_label=True, each label is scored on its own. For each hypothesis, the pipeline discards the neutral logit. It then applies a softmax over only the contradiction and entailment logits and keeps the entailment probability. The score therefore means "entailment against contradiction for this hypothesis", and it does not depend on any other label.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "The app crashes when I try to update my payment method."
labels = ["billing", "technical support", "sales"]
result = classifier(
text,
candidate_labels=labels,
hypothesis_template="This customer message is about {}.",
multi_label=True,
)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label}: {score:.3f}")This message is about a crash and a payment method, so both "technical support" and "billing" can score high. The scores do not sum to 1, and none of them is forced down by the others. The output is still sorted by score, but the order is only a convenience. Each score stands alone.
Reproducing both modes by hand
Computing both modes yourself shows exactly what the pipeline does. The following script scores every label in one batch and computes both versions from the same logits.
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
name = "facebook/bart-large-mnli"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name)
text = "The app crashes when I try to update my payment method."
labels = ["billing", "technical support", "sales"]
template = "This example is {}."
inputs = tokenizer(
[text] * len(labels),
[template.format(label) for label in labels],
return_tensors="pt",
padding=True,
)
with torch.no_grad():
logits = model(**inputs).logits # shape: (num_labels, 3)
entail = model.config.label2id["entailment"]
contra = model.config.label2id["contradiction"]
# Single-label: one softmax across labels, using entailment logits only.
single = torch.softmax(logits[:, entail], dim=0)
# Multi-label: a separate softmax per label over [contradiction, entailment].
multi = torch.softmax(logits[:, [contra, entail]], dim=1)[:, 1]
for label, s, m in zip(labels, single.tolist(), multi.tolist()):
print(f"{label:18s} single={s:.3f} multi={m:.3f}")
print("single sums to", round(single.sum().item(), 3))The single column should match the pipeline's default output, and the multi column should match multi_label=True with the same template. Small differences of about 0.001 can appear from numeric precision. Look up the label ids with model.config.label2id and do not hard-code 0, 1 and 2. Different NLI models order their classes differently.
Reading the scores
The two modes behave differently on the same inputs, which is the main source of confusion. The following table lists common situations.
| Situation | Single-label result | Multi-label result |
|---|---|---|
| Text clearly fits one label | That label near 1.0 | That label high, others low |
| Text fits two labels | The two split the mass, for example 0.55 and 0.40 | Both high, for example 0.93 and 0.88 |
| Text fits no label | One label still wins with a moderate score | All scores low |
| You add a similar label | Existing scores drop | Existing scores do not change |
The third row is why multi-label scoring is useful even when you only want one answer. It exposes the "none of these" case, which a thresholding step can act on. The next chapters cover thresholds and abstaining in detail. For now, remember that single-label scores cannot show it.
Choosing a mode
Choose by the shape of the task, not by which output looks nicer:
- Use single-label mode when every text belongs to exactly one class and you always want a prediction.
- Use multi-label mode when texts can carry several tags, such as topics, intents, or content flags.
- Use multi-label mode with a threshold when some texts may match nothing and you want the system to abstain.
- Use multi-label mode for a yes/no question about one label, such as "is this an urgent request?".
Common errors
- Treating single-label scores as confidence. The scores always sum to 1, so a confident-looking top score can appear for a text that fits no label. Check the margin against the second label as well.
- Using single-label mode for multi-tag data. If a text truly has two labels, the scores split between them and neither looks decisive. A threshold of 0.5 would then reject both.
- Forgetting that the order of labels does not matter, but their number does. In single-label mode, adding ten loosely related labels dilutes every score.
- Mixing up the argument name. The pipeline argument is
multi_label, in the singular. A misspelled keyword such asmulti_labelsraises an error or is ignored, depending on your version of the library, so check the output sums when in doubt. - Overlapping labels in single-label mode. Labels like "billing" and "payments" compete for the same texts, so the winner can flip between near-identical inputs. Label wording is covered in a later chapter.
- Relying on the neutral class. In multi-label mode the neutral logit is discarded. A hypothesis the model thinks is merely unrelated can still receive a score far from zero if its contradiction logit is also low, so test with texts that clearly do not match.
Cost
Both modes run one forward pass per label, so cost grows linearly with the number of labels in either mode. Multi-label scoring does not cost more than single-label scoring. Batching helps, but a taxonomy of 200 labels means 200 model calls for every text. Chapter-level alternatives to this cost appear later in the tutorial.
Exercise
A support ticket reads "Please cancel my plan, and also I want to know why the dashboard shows an error." You classify it against ["billing", "technical support", "sales"] in single-label mode and get scores of 0.52 for "technical support" and 0.41 for "billing". A colleague says the model is unsure. Which mode should you use to check whether the model actually sees both topics, and what would you expect to see?
Show answer
Use multi_label=True. The ticket carries two topics, so single-label mode splits the probability between them and makes both look uncertain. In multi-label mode each label is scored independently, so you would expect both "technical support" and "billing" to score high (for example above 0.8) and "sales" to score low. The scores no longer sum to 1.
Exercise
In the manual implementation, why does single-label scoring use softmax with dim=0 over the entailment logits, while multi-label scoring uses softmax with dim=1 over the contradiction and entailment logits?
Show answer
The logits tensor has one row per label and one column per NLI class. Single-label scoring compares labels with each other, so it takes the entailment column and normalizes down the rows (dim=0), which makes the scores sum to 1. Multi-label scoring judges each label alone, so it takes the contradiction and entailment columns and normalizes across them within each row (dim=1). The entailment probability from each row does not depend on any other row.
Exercise
You call the pipeline with a single candidate label, ["urgent"], and multi_label left at its default. Does the score come from a softmax across labels? What does it mean?
Show answer
No. With one candidate label the pipeline switches to multi-label scoring automatically, because a softmax across one value would always be 1.0. The score is the entailment probability from a softmax over the contradiction and entailment logits for the hypothesis, such as "This example is urgent.", so it can be used for a yes/no check on that label.