Sub topic 6
Hypothesis templates and how they change scores
This chapter assumes you can run the zero-shot-classification pipeline from the previous chapter. It also assumes you know that an NLI model takes a premise and a hypothesis and predicts entailment, neutral, or contradiction. Here you will look at the one piece of the pipeline that you control besides the labels: the hypothesis template.
What the template does
An NLI model cannot read a label such as billing. It reads a pair of sentences. The pipeline therefore builds a sentence from each label by inserting it into a template. The template is a string with a {} placeholder, and the default is "This example is {}.".
For the text "I was charged twice for my subscription this month." and the labels billing, technical support, and sales, the pipeline creates three premise and hypothesis pairs:
- Premise: the text. Hypothesis:
This example is billing. - Premise: the text. Hypothesis:
This example is technical support. - Premise: the text. Hypothesis:
This example is sales.
Each pair goes through the NLI model once. The template is plain Python string formatting, so the pipeline calls template.format(label) for every label.
The template does not change how many forward passes the model runs. Three labels cost three passes whatever template you use. It changes only the words the model sees, and that changes the logits.
Seeing the hypotheses
Before you tune anything, print the hypotheses a template produces. This catches grammar problems early.
labels = ["billing", "technical support", "sales"]
templates = [
"This example is {}.",
"This customer message is about {}.",
"The customer needs help with {}.",
]
for template in templates:
print(template)
for label in labels:
print(" ", template.format(label))Read each output sentence as a native speaker would. This example is technical support. is slightly odd, and The customer needs help with sales. is awkward. Odd phrasing does not break the pipeline, but it moves the scores in ways that are hard to predict.
Comparing templates on one text
The next script runs the same text and labels with three templates and prints the ranking for each.
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"]
templates = [
"This example is {}.",
"This customer message is about {}.",
"The customer needs help with {}.",
]
for template in templates:
result = classifier(text, candidate_labels=labels, hypothesis_template=template)
print(template)
for label, score in zip(result["labels"], result["scores"]):
print(f" {label}: {score:.3f}")This text is deliberately ambiguous. It mentions a crash, which points to technical support, and a payment method, which points to billing. You will usually see the same two labels at the top across templates, but the scores and sometimes the order differ. The exact numbers depend on the model version, so run it yourself instead of relying on figures from a tutorial.
Why the scores shift
The model was fine-tuned on NLI pairs, and each template makes the hypothesis resemble different training examples. Three effects matter in practice.
- Specificity.
This customer message is about billing.tells the model what kind of text it is looking at. That often separates labels better thanThis example is billing., which carries no information beyond the label. - Grammatical fit. Some labels are nouns (
billing), some are adjectives (urgent), and some are verb phrases (wants a refund). A template that fits nouns reads badly with adjectives. A bad fit adds noise that has nothing to do with the text. - Task match. A sentiment task wants
The sentiment of this review is {}.orThe reviewer felt {}.. A topic task wantsThis text is about {}.The template should describe the relation you want entailed.
None of this is a rule. A template that improves one dataset can hurt another, so you decide by measuring.
How the score is computed
How a template affects the final number depends on whether you ask for single-label or multi-label scoring, which is the subject of the next chapter. Here is the short version.
- With
multi_label=False, the pipeline takes the entailment logit of each label's pair and applies a softmax across labels. Scores sum to 1. Only the relative entailment strength between labels matters. - With
multi_label=True, the pipeline takes the contradiction and entailment logits of each pair and applies a softmax over those two values. Each label gets its own probability, and the scores do not sum to 1. The neutral logit is ignored.
The first mode is a ranking. The second mode treats each label as its own yes or no question. The manual reproduction from the previous chapter computed the second kind of score:
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
name = "facebook/bart-large-mnli"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name)
premise = "I was charged twice for my subscription this month."
labels = ["billing", "technical support", "sales"]
template = "This customer message is about {}."
entail = model.config.label2id["entailment"]
contra = model.config.label2id["contradiction"]
for label in labels:
hypothesis = template.format(label)
inputs = tokenizer(premise, hypothesis, return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits[0]
prob = torch.softmax(logits[[contra, entail]], dim=0)[1].item()
print(f"{label}: P(entailment) = {prob:.3f}")Compare these numbers with multi_label=True in the pipeline using the same template. They should match to rounding error. This confirms that the template is the only text-side difference between your hand-built pairs and the pipeline's.
Measuring a template change
Eyeballing one example tells you little. To pick a template, score each candidate on a labeled sample and compare macro F1. This script builds on the evaluation code you will meet in a later chapter.
from sklearn.metrics import f1_score
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?",
"My invoice shows the wrong company name.",
"I cannot log in after the latest update.",
"Can I get a quote for fifty seats?",
]
y_true = [
"billing", "technical support", "sales",
"billing", "technical support", "sales",
]
templates = [
"This example is {}.",
"This customer message is about {}.",
"The customer needs help with {}.",
]
for template in templates:
y_pred = [
classifier(t, candidate_labels=labels, hypothesis_template=template)["labels"][0]
for t in texts
]
score = f1_score(y_true, y_pred, average="macro")
print(f"{score:.3f} {template}")Six examples are far too few to trust. With so little data, one flipped prediction moves macro F1 by a large step, and any difference you see may be luck. Use at least a few dozen examples per label, and more if the labels are close in meaning.
Template selection and overfitting
Trying many templates on the same sample and keeping the best one is a form of tuning. If you then report that sample's score as the expected accuracy, the number is optimistic. The usual fix is to split your labeled data. Choose the template on a development set and report the result once on a held-out test set that you did not use to choose.
A second guard is to prefer a template that does well across several splits or label sets over one that wins by a hair on a single split. A large gain from rewording is a real effect. A gain of one example is not.
Common errors
- Missing placeholder. If the template has no
{}, the pipeline raises aValueErrorsaying the template could not be formatted with the labels. Make sure the braces are present. - Extra braces. A literal brace in the template, such as
{JSON}, is read as a placeholder bystr.format. Double it ({{and}}) or avoid it. - Label already contains context. A label like
a message about billingcombined withThis message is about {}.givesThis message is about a message about billing.Keep labels short and let the template carry the context. - Comparing scores across templates. Scores from different templates are not calibrated against each other. A 0.9 under one template does not mean the same confidence as 0.9 under another. Compare rankings and F1, not raw scores.
- Language mismatch. An English template with labels in another language, or an English-only NLI model on non-English text, produces unreliable pairs. Match the template language to the model and the text.
Practical guidance
- Start with the default template as your baseline.
- Write two or three templates that describe the task in natural language, and print the hypotheses to check grammar.
- Score each on a development sample with macro F1.
- Keep the simplest template that is clearly better than the baseline.
- Confirm on held-out data and record the template with your results, since the template is now part of the model's configuration.
Exercise
You run the pipeline with hypothesis_template="Classify this: {}" and three labels. A colleague says the template should instead be "This text is about {}.". List the hypotheses the pipeline creates under your colleague's template for the labels billing, sales, and technical support, and say how many forward passes the model runs for one input text.
Show answer
The hypotheses are This text is about billing., This text is about sales., and This text is about technical support. The model runs three forward passes, one per label, and the number of passes is the same under either template.
Exercise
A template improves macro F1 from 0.71 to 0.74 on the 12 examples you used to pick it. Why is it risky to report 0.74 as the expected accuracy, and what should you do instead?
Show answer
With 12 examples, a difference of 0.03 can come from one or two changed predictions, and you also selected the template using that same data, so the score is biased upward. Choose the template on a development set, then evaluate it once on a separate held-out set that is larger, and report that number.
Exercise
You switch from multi_label=False to multi_label=True without changing the template. How does the way the score is computed change, and why can two labels now both score above 0.9?
Show answer
With multi_label=False, the softmax runs across the entailment logits of all labels, so the scores sum to 1. With multi_label=True, each label gets a softmax over its own contradiction and entailment logits, so the labels are scored independently and the scores do not sum to 1. Two labels can therefore both be high when the text entails both hypotheses.