Sub topic 9
Predicting on new text
Training produces a model. Inference is what you do with it afterwards: you give it text it has never seen and read back a label. This chapter covers two ways to do that, the pipeline helper and a manual loop, and the mistakes that make predictions differ from what you measured during evaluation.
This chapter assumes you finished the Trainer chapter. You should have a fine-tuned DistilBERT sentiment model saved in the folder imdb-distilbert, and you should be comfortable with PyTorch tensors and with logits (raw, unnormalized scores).
What happens during inference
At inference time the model runs the same forward pass it ran during training, but without labels, without a loss, and without weight updates. Four steps happen in order:
- The tokenizer converts each string to token IDs and an attention mask.
- The encoder and classification head produce one logit per class.
- A softmax turns the logits into probabilities that sum to 1.
- The class with the highest probability is mapped back to a name through
id2label.
The tokenizer must match the model. Truncation settings used in training (here max_length=256) should be used again, because the model never saw longer sequences while learning.
The fast path: `pipeline`
A pipeline bundles the tokenizer, the model, and the post-processing into one callable. Point it at the folder you saved:
from transformers import pipeline
classifier = pipeline("text-classification", model="imdb-distilbert")
reviews = [
"A warm, funny film with a great cast.",
"Two hours I will never get back.",
]
print(classifier(reviews))The output is a list with one dictionary per input, for example [{'label': 'POSITIVE', 'score': 0.99}, {'label': 'NEGATIVE', 'score': 0.98}]. The score is the softmax probability of the winning class.
The label names come from the id2label mapping stored in the saved config.json. In the training chapter you passed id2label and label2id to from_pretrained, so you see POSITIVE and NEGATIVE. If you had skipped that step, you would see LABEL_0 and LABEL_1, and you would have to remember which is which.
Options you will actually use
Pass options when you call the pipeline, or when you build it.
import torch
from transformers import pipeline
classifier = pipeline(
"text-classification",
model="imdb-distilbert",
device=0 if torch.cuda.is_available() else -1,
)
long_review = "I expected little, but the second half won me over. " * 80
results = classifier(
[long_review, "Dull and predictable."],
batch_size=16,
truncation=True,
max_length=256,
top_k=None,
)
for scores in results:
print(scores)deviceselects the GPU (an integer index) or the CPU (-1). Without it, the pipeline runs on the CPU.batch_sizegroups inputs into one forward pass. It helps on a GPU and can slow things down on a CPU, so measure it.truncation=Trueandmax_length=256cut long inputs. Without truncation, an input longer than the model's limit (512 tokens for DistilBERT) raises an error.top_k=Nonereturns the score for every class instead of only the best one. With a list input, you get one list of{label, score}dictionaries per text.
The explicit path: tokenizer, model, softmax
Use the manual route when you need the raw logits, custom thresholds, or control over batching and devices. It is also the best way to understand what the pipeline does.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
path = "imdb-distilbert"
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForSequenceClassification.from_pretrained(path).to(device)
model.eval()
def predict(texts, batch_size=16, max_length=256):
"""Return a list of (label, probability) pairs, one per input text."""
outputs = []
for start in range(0, len(texts), batch_size):
chunk = texts[start : start + batch_size]
batch = tokenizer(
chunk,
truncation=True,
max_length=max_length,
padding=True,
return_tensors="pt",
).to(device)
with torch.no_grad():
logits = model(**batch).logits
probs = torch.softmax(logits, dim=-1)
for p in probs:
idx = int(p.argmax())
outputs.append((model.config.id2label[idx], float(p[idx])))
return outputs
for text, (label, prob) in zip(
["Brilliant from start to finish.", "I walked out halfway through."],
predict(["Brilliant from start to finish.", "I walked out halfway through."]),
):
print(f"{label:9s} {prob:.3f} {text}")Three lines carry most of the correctness here:
model.eval()switches off dropout. Without it, the model adds random noise and the same input can give different answers on different calls.torch.no_grad()stops PyTorch from building a gradient graph. This saves memory and time, and it does not change the output.padding=Truepads each chunk to its own longest sequence. Training used the data collator for the same purpose, so this matches the "dynamic padding" idea from earlier chapters.
Choosing between the two paths
| Need | `pipeline` | Manual loop |
|---|---|---|
| Quick check on a few strings | Best choice | More code than needed |
| Label and score only | Built in | You write the argmax |
| Raw logits or hidden states | Not exposed by default | Direct access |
| Custom decision rule (thresholds, abstaining) | Post-process the output | Natural fit |
| Full control of devices and batching | Limited | Full |
Turning probabilities into decisions
The default decision is argmax. For two classes this is the same as predicting positive when its probability is above 0.5. That cutoff is a choice, and you can change it.
Two common uses:
- Abstain when unsure. Route predictions with a top probability below a cutoff to a human or a fallback rule.
- Shift the threshold. If missing a positive is more costly than a false alarm, predict positive above a lower cutoff such as 0.3. Pick the cutoff on the validation set, never on the test set.
def decide(label, prob, min_confidence=0.75):
return label if prob >= min_confidence else "UNSURE"
for text in ["It was okay, I suppose.", "Absolutely loved it."]:
label, prob = predict([text])[0]
print(decide(label, prob), round(prob, 3), text)Common errors and how to spot them
Predictions disagree with the evaluation numbers
If accuracy during training was 92% but live predictions look much worse, check these in order:
- Different preprocessing. Training used
max_length=256, but inference used no truncation or a different length. Reuse the same settings. - Wrong tokenizer. Loading a tokenizer from the base checkpoint when you changed or added tokens. Load the tokenizer from the saved folder, which is why the previous chapter saved both.
- Model still in training mode. A missing
model.eval()makes outputs vary from call to call. - Different data. The text you predict on differs from the training data in domain, length, or style. IMDB reviews are long and informal. A model trained on them may behave badly on short tweets or formal product descriptions. This is a data shift, not a bug in your code.
Errors you will see in the terminal
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about sequence length greater than the maximum | No truncation on a long input | Pass `truncation=True` and `max_length` |
| `LABEL_0` and `LABEL_1` instead of names | `id2label` was not set when the model was created | Set `model.config.id2label` and `label2id`, then save again, or map labels yourself |
| Tensors on different devices | Model on the GPU, inputs on the CPU | Call `.to(device)` on the tokenizer output, as in the `predict` function |
| Out-of-memory error on a large list | Everything went through the model in one batch | Use a smaller `batch_size` and loop over chunks |
| Slightly different scores between runs | Dropout active, or mixed-precision rounding | Call `model.eval()`; accept tiny floating-point differences |
Padding side effects
With padding=True, a short text sitting next to a long one is padded with extra tokens. The attention mask tells the model to ignore them, so the prediction should not change. If you build tensors by hand and drop the attention_mask, the pad tokens are treated as real input and the result shifts. Always pass the full tokenizer output with **batch.
Speed
Sorting texts by length before batching reduces wasted padding, which can speed up large jobs noticeably. Restore the original order afterwards. On a CPU, a DistilBERT model handles short texts in tens of milliseconds each. For many thousands of texts, a GPU and a larger batch size are worth setting up.
Checking a prediction function
Before you ship a prediction function, test it on a few cases whose answers you know.
- Run a handful of clearly positive and clearly negative sentences.
- Run an empty string and a very long string. Both should return a result without crashing.
- Run the same list twice and confirm the scores are identical.
- Run the same texts one at a time and in one batch. The scores should agree to several decimal places.
Exercise
Your model reached 91% validation accuracy, but a teammate's script that calls model(**tokenizer(text, return_tensors="pt")) without model.eval() returns a different score each time it runs on the same text. What is the cause, and what two changes fix it and make inference cheaper?
Show answer
A model loaded with from_pretrained can be left in training mode, so dropout randomly zeroes activations on every forward pass and the logits vary between calls. Call model.eval() to turn dropout off. Wrap the forward pass in torch.no_grad() so PyTorch does not build a gradient graph, which saves memory and time without changing the output.
Exercise
You call a pipeline on a list of 5,000 product reviews, and it fails on a few very long ones with an error about sequence length. Show the call that fixes this for a model trained with max_length=256.
Show answer
Truncate at the same length used in training: classifier(reviews, batch_size=16, truncation=True, max_length=256). Truncation cuts inputs that exceed the limit, and matching max_length to training keeps the inputs consistent with what the model learned from.