Sub topic 5
Running the zero-shot pipeline
This chapter assumes you can run Python with transformers and torch installed (pip install transformers torch). It also assumes you know the premise and hypothesis setup from the earlier chapters on natural language inference (NLI) and on turning classification into entailment. Here you will run the Hugging Face zero-shot-classification pipeline, read its output correctly, and learn what it does at each step so you can predict its cost and behavior.
What the pipeline does
The pipeline wraps three steps: building premise-hypothesis pairs, running an NLI model, and turning the logits into one score per label.
- It takes your text as the premise.
- For each candidate label, it fills a hypothesis template such as
This example is {}.with the label. Three labels produce three hypotheses. - It runs the NLI model once per (premise, hypothesis) pair.
- It converts the entailment evidence for each pair into a score, then sorts the labels from highest to lowest.
Your first classification
The model facebook/bart-large-mnli was fine-tuned on the MultiNLI dataset. It is the standard choice for this pipeline. The first run downloads roughly 1.6 GB of weights, so expect a delay.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "I was charged twice for my subscription this month."
labels = ["billing", "technical support", "sales"]
result = classifier(text, candidate_labels=labels)
print(result["labels"][0], result["scores"][0])The call returns a dictionary with three keys:
| Key | Content |
|---|---|
| `sequence` | The input text, unchanged |
| `labels` | The candidate labels, sorted by score, highest first |
| `scores` | The scores, in the same order as `labels` |
Because of the sorting, result["labels"] is not in the order you passed. Always read labels and scores together by position. Never assume scores[0] belongs to your first label.
For this example the top label should be billing with a score close to 1. The exact number depends on the model version and library version.
Reading the scores
By default the scores are normalized across labels. The pipeline takes the entailment logit of each pair and applies a softmax across all labels. The scores therefore sum to 1, and a high score means "more entailed than the other labels". It does not mean "confidently true".
This has an important consequence. If you pass labels that are all wrong for the text, one of them still receives a high score, because the probability mass has to go somewhere. A score of 0.9 in this mode is a relative judgment, not an absolute one.
The next chapter covers multi-label scoring, where each label is scored independently. The two modes behave differently, so keep them separate in your mind:
- Default (
multi_label=False): softmax over the entailment logits of all labels. Scores sum to 1. Use it when exactly one label is correct. multi_label=True: for each label separately, softmax over the contradiction and entailment logits, ignoring neutral. Scores do not sum to 1. Use it when several labels can apply.
If you pass only one candidate label, the pipeline switches to the independent mode automatically. A softmax over a single value would always give 1.0, which would be meaningless.
Passing labels and texts in different forms
You can pass candidate labels as a list or as a comma-separated string. The list form is safer, because a label that itself contains a comma would be split in two.
classifier(text, candidate_labels="billing, technical support, sales") # works
classifier(text, candidate_labels=["billing", "technical support", "sales"]) # preferredYou can also pass a list of texts. The pipeline then returns a list of result dictionaries, one per text, in the same order as the inputs.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
labels = ["billing", "technical support", "sales"]
texts = [
"I was charged twice for my subscription this month.",
"The app freezes every time I open the settings page.",
"Do you offer a discount for annual plans?",
]
results = classifier(texts, candidate_labels=labels)
for r in results:
print(f"{r['labels'][0]:<18} {r['scores'][0]:.3f} <- {r['sequence']}")Cost: one forward pass per label
The pipeline does not run the model once per text. It runs it once per (text, label) pair. Classifying 1,000 texts against 5 labels needs 5,000 forward passes of a large model. Adding labels increases cost linearly.
This differs from a normal supervised classifier, which scores all labels in a single pass. Compare the options:
| Approach | Forward passes for T texts and L labels |
|---|---|
| Fine-tuned classifier | T |
| NLI zero-shot pipeline | T × L |
| Bi-encoder similarity (later chapter) | T plus L, with label vectors computed once |
You have three practical ways to reduce the cost:
- Use a GPU. Pass
device=0topipeline(...)to place the model on the first CUDA GPU. On CPU,bart-large-mnliis slow for more than a few hundred pairs. - Batch the pairs. Pass
batch_sizeto the pipeline constructor or the call, for examplebatch_size=16. This batches the pairs the pipeline generates. Larger values use more memory and mostly help on a GPU. - Use a smaller NLI model. Distilled and smaller NLI models are available on the Hugging Face Hub. Any model fine-tuned on NLI with an entailment label can work. Check accuracy on your own data before you switch.
import torch
from transformers import pipeline
device = 0 if torch.cuda.is_available() else -1 # -1 means CPU
classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli",
device=device,
batch_size=8,
)
result = classifier(
"Do you offer a discount for annual plans?",
candidate_labels=["billing", "technical support", "sales"],
)
print(result["labels"][0], round(result["scores"][0], 3))Inspecting what the pipeline does by hand
The pipeline finds the entailment label by looking in the model's config.id2label for a name that starts with "entail". This is why a model must expose its labels correctly to work with the pipeline. You can check the mapping yourself:
from transformers import AutoConfig
config = AutoConfig.from_pretrained("facebook/bart-large-mnli")
print(config.id2label)For BART-MNLI the labels are contradiction, neutral and entailment. If a model's labels are named LABEL_0, LABEL_1 and LABEL_2, the pipeline cannot find an entailment index. It then logs a warning and falls back to the last label, which may be wrong. Treat that warning as a real problem. Before you trust the scores, check the model card to confirm which output index means entailment.
Long texts and truncation
NLI models have a maximum input length, 1,024 tokens for BART. The pipeline truncates the premise (your text) when the pair is too long, and the hypothesis stays intact. A long document therefore loses its tail. If the relevant evidence sits near the end, the classifier can miss it. For long documents, split the text into chunks, classify each chunk, and combine the scores. Taking the maximum score per label is a common way to combine them. You can also classify only the part of the text that matters, such as the title and first paragraph.
Common errors
- Reading labels in the wrong order. The
labelslist is reordered by score. Usedict(zip(result["labels"], result["scores"]))to map each label to its score. - Treating default scores as absolute confidence. They sum to 1 across your labels. Off-topic text still gets a "winner".
- Expecting multi-label output by default. Without
multi_label=True, labels compete with each other. - Re-creating the pipeline inside a loop. Loading the model takes seconds. Create the pipeline once and call it many times.
- Passing a single string where you meant a list of labels. A string is split on commas. A label such as
"refund, return"becomes two labels. - Benchmarking on CPU and assuming that speed is the model's limit. Measure on the hardware you will deploy to.
Turning the result into a clean dictionary
In real applications, you usually want a mapping from label to score and a predicted label. This helper keeps that logic in one place.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
def classify(text, labels):
result = classifier(text, candidate_labels=labels)
scores = dict(zip(result["labels"], result["scores"]))
top = result["labels"][0]
return top, scores
top, scores = classify(
"I was charged twice for my subscription this month.",
["billing", "technical support", "sales"],
)
print("prediction:", top)
for label in ["billing", "technical support", "sales"]:
print(f" {label}: {scores[label]:.3f}")Printing in the original label order, as the loop does, makes outputs from different texts easy to compare.
Exercise
You run classifier(text, candidate_labels=["billing", "sales"]) on a text about a broken mobile app. The result is {"labels": ["sales", "billing"], "scores": [0.62, 0.38]}. A teammate concludes that the text is 62% likely to be a sales message. Explain what is wrong with this reading, and say how many forward passes the call needed.
Show answer
In the default mode, scores are a softmax across the labels you supplied, so they sum to 1 and only say which label is more entailed relative to the others. Neither label fits a broken-app message, but the probability mass still has to be split, so "sales" wins by a small margin. The 0.62 is not a calibrated probability that the message is about sales. A fix is to add a label that fits, such as "technical support", or to use multi_label=True and apply a threshold. The call needed two forward passes, one per (text, label) pair.
Exercise
You need to classify 20,000 support tickets against 8 labels with bart-large-mnli. How many model forward passes does that take, and name two changes that would reduce wall-clock time without changing the model.
Show answer
20,000 × 8 = 160,000 forward passes. Run the pipeline on a GPU with device=0, and set a batch_size such as 16 so that the pairs are processed in batches. Creating the pipeline once and reusing it also avoids repeated loading costs.