Sub topic 11
Limitations: Cost per Label, Ambiguity, Domain Shift and Bias
This chapter assumes you can run the zero-shot-classification pipeline, that you know how hypothesis templates and multi_label=True work, and that you can compute accuracy and macro F1 on a small labeled sample. Zero-shot classification with an NLI model avoids labeling data, but it has four weaknesses that you should measure before you ship it: inference cost that grows with the label count, sensitivity to ambiguous label wording, weaker accuracy outside the model's training domain, and inherited bias.
Cost per label
The pipeline does not run one forward pass per text. For each text it builds one premise and hypothesis pair for every candidate label, and the model scores each pair separately. Classifying N texts against K labels takes N × K forward passes through a large cross-encoder. facebook/bart-large-mnli has about 400 million parameters, so this adds up quickly.
A fine-tuned classifier with a softmax head scores all K classes in a single pass. Its cost does not depend on K.
import time
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "I was charged twice for my subscription this month."
all_labels = [
"billing", "technical support", "sales", "shipping",
"account access", "feedback", "legal", "careers",
]
classifier(text, candidate_labels=all_labels[:2]) # warm-up call
for k in (2, 4, 8):
start = time.perf_counter()
classifier(text, candidate_labels=all_labels[:k])
elapsed = time.perf_counter() - start
print(f"{k} labels: {elapsed:.2f}s")Expect the time to grow roughly in proportion to k. The exact numbers depend on your hardware.
Ways to reduce the cost:
- Batch the inputs and run on a GPU. This lowers the cost per pair but not the number of pairs.
- Use a smaller NLI model, such as a distilled one. Check accuracy on your sample first.
- Run a two-stage design. A cheap bi-encoder picks the top 3 labels out of 50, and the NLI model rescores only those.
- Use zero-shot predictions to pseudo-label a corpus, then train a small supervised classifier on it. Inference then costs one pass per text.
Ambiguity in labels and texts
An NLI model judges whether a hypothesis follows from the text. This is a different question from the one a human annotator answers when assigning a category, and the two can disagree in three ways.
Overlapping labels. A message such as "The app crashes when I try to update my payment method" is about both billing and technical support. With single-label scoring the scores are normalized across labels and compete with each other, so the winner can be arbitrary. With multi_label=True both labels can score high, and you need a rule for what to do then (see the chapter on thresholds).
Vague label names. A label such as "other" or "general" gives the model nothing to entail. A hypothesis like "This example is other" is almost never entailed, so the label never wins. It does not work as a catch-all. Handle the catch-all case by abstaining when every real label scores low.
Wording sensitivity. Two labels that mean the same thing to you can produce different predictions. You can measure this by classifying the same texts with two wordings of the label set and checking how often the predictions agree.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
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?",
"My package never arrived and tracking shows no update.",
]
wording_a = {
"billing": "billing",
"tech": "technical support",
"sales": "sales",
"shipping": "shipping",
}
wording_b = {
"billing": "payment problems",
"tech": "software bugs",
"sales": "buying a product",
"shipping": "delivery",
}
def predict(text, wording):
names = list(wording.values())
top = classifier(text, candidate_labels=names)["labels"][0]
return next(key for key, value in wording.items() if value == top)
agree = 0
for t in texts:
a, b = predict(t, wording_a), predict(t, wording_b)
print(f"{a:9s} {b:9s} {t}")
agree += a == b
print("agreement:", agree / len(texts))Low agreement means your labels are poorly specified or the model is unstable on them. Choose wording using a labeled sample, and keep that sample separate from the one you use for the final accuracy number.
Domain shift
NLI models are trained on datasets such as MNLI, which contains fiction, government text, telephone transcripts and similar sources. When your texts differ from that material, zero-shot accuracy usually falls. Common causes:
- Specialized vocabulary. Medical, legal and financial text uses terms that the model may not link to your plain-language labels.
- Informal or noisy text. Abbreviations, emoji, typos and code snippets are rare in the training data.
- Language.
bart-large-mnliis English-only. For other languages, use a multilingual NLI model, and expect lower scores than in English. - Length. Long documents are truncated to the model's maximum input length, so a relevant sentence near the end can be dropped. Split long texts into passages and combine the passage scores.
- Label semantics. Labels that depend on your organization's internal definitions, such as "tier-2 escalation", carry no meaning for a model that has not seen them.
Bias
The model learned from human-written text and from an NLI dataset with known annotation artifacts. Two problems follow.
First, the model can use shortcuts. Annotators writing contradictions often used negation words, so negated text can be pushed toward "contradiction" regardless of meaning.
Second, associations between people and attributes can influence scores. If a label such as "angry" scores differently when only a group word changes, the classifier is treating groups differently. This is a risk when labels describe people, for example sentiment, toxicity or risk.
A minimal probe holds the sentence fixed and swaps one term:
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
template = "The {} customer asked for a refund and was told to wait."
groups = ["young", "elderly", "foreign", "local"]
labels = ["angry", "calm"]
for group in groups:
result = classifier(
template.format(group),
candidate_labels=labels,
multi_label=True,
)
scores = dict(zip(result["labels"], result["scores"]))
print(f"{group:8s} angry={scores['angry']:.3f} calm={scores['calm']:.3f}")Large differences between groups on identical text are evidence of bias. Small differences on a handful of sentences prove little. Use many templates and several terms per group before drawing a conclusion, and treat the probe as a screening step, not a certification.
Summary of failure modes and mitigations
The following diagram links each limitation to the symptom you will see and the usual fix.
| Limitation | How to detect it | First response |
|---|---|---|
| Cost per label | Time per text rises with the label count | Two-stage ranking or a smaller model |
| Ambiguity | Low agreement across label wordings | Rewrite labels, use multi-label, set a threshold |
| Domain shift | Macro F1 on your sample is far below published numbers | Add domain-specific templates, then consider fine-tuning |
| Bias | Different scores when only a group term changes | Counterfactual probes and human review |
Practical checklist before deployment
- Count the pairs: texts per day multiplied by labels. Measure latency on your real hardware.
- Collect at least a few dozen labeled examples per class, more for rare classes, and report macro F1 so small classes are not hidden.
- Run the wording-agreement test and keep the more stable label set.
- Inspect the confusion matrix for label pairs that are always mixed up. Those pairs usually need merging or rewording.
- Run counterfactual probes if any label describes people.
- Decide what happens to texts the model cannot place: an abstain path with human review is safer than a forced guess.
- Monitor accuracy over time on a small, regularly refreshed labeled sample, because the text source can change.
If these checks show that zero-shot accuracy is not good enough, labeling a few hundred examples and fine-tuning is often the better choice. The final chapter covers how to decide.
Exercise
A team classifies 20,000 support tickets per day against 40 candidate labels using the NLI pipeline, and inference is too slow. How many premise and hypothesis pairs does the model score per day, and name two changes that would reduce this number without losing the ability to add new labels later?
Show answer
The model scores 20,000 × 40 = 800,000 pairs per day. Two changes: (1) a two-stage design in which a bi-encoder keeps the top few labels per ticket and the NLI model rescores only those, which cuts the pairs per ticket from 40 to a small number; (2) a hierarchy of coarse groups followed by labels within the winning group. Both keep the label set editable because no model is retrained when a label is added.
Exercise
You run the same four texts with two wordings of the same label set and the predictions agree on only two of the four. What does this tell you, and what should you do next?
Show answer
It shows the predictions depend on label wording, so the labels are underspecified or the model is unstable on them. Do not pick a wording by looking at the final test results. Instead, compare the two wordings on a separate labeled development sample using macro F1, inspect the texts where they disagree to find overlapping or vague labels, rewrite those labels, and keep the version that scores best on the development sample.
Exercise
In a counterfactual bias probe, "The elderly customer asked for a refund" scores 0.40 for "angry" and "The young customer asked for a refund" scores 0.38. Is this strong evidence of bias?
Show answer
No. A difference of 0.02 on one sentence is within the noise you would expect from a single example. A valid test uses many sentence templates and several terms per group, then compares the average score difference and its spread. Only a consistent gap across templates indicates bias.