Use Your Fine-Tuned Model on New Messages
A fine-tuned model is only useful once it leaves the training run and starts answering new text. That takes three things: knowing what was saved and how to load it back, calling it in one line on any message, and deciding what to do when its answer is uncertain. The last part matters most in practice, because a classifier gives an answer for every input, including inputs it should not answer at all.
What a saved model holds
Saving a model gives you an ordinary folder of files. You get it by calling save_pretrained(folder) on the model and on its tokenizer, or from a Trainer that was given the tokenizer as processing_class, which saves both for you. Nothing in the folder depends on the training script that made it. Each file does one job:
model.safetensorsholds the weights: every trained number of the body and of the classification head.config.jsondescribes the model: its architecture, its sizes, and the class names, stored asid2label(from class number to name) andlabel2id(the reverse).tokenizer.jsonandtokenizer_config.jsonhold the tokenizer: its vocabulary, its rules for cutting text into tokens and its special tokens.
- topic-model/
- model.safetensors the trained weights
- config.json architecture and class namesWhere the class names live
The
id2labelmap turns the number of the winning class into its name. It was written when the model was loaded for training with the names passed in, so it comes back with every load. - tokenizer.json vocabulary and rules
- tokenizer_config.json tokenizer settings
The weights use the safetensors format. For a long time PyTorch weights were saved with Python's pickle, which can run code while a file is loaded, so opening a file from a stranger was a risk. A safetensors file holds only tensors, which makes it safe to open and fast to load. Current Transformers always saves weights this way. A very large model is split into several numbered safetensors files plus an index file, but a small classifier fits in one.
The class names in config.json look like this for a model that sorts news articles into three topics:
{
"architectures": ["DistilBertForSequenceClassification"],
"id2label": { "0": "sport", "1": "politics", "2": "science" },
"label2id": { "sport": 0, "politics": 1, "science": 2 }
}This layout is the same one a model repository on the Hugging Face Hub has. A published model is exactly such a folder, uploaded. That is why the next step, loading, works the same way for both. A folder saved by a Trainer checkpoint may also contain files about the training itself (the optimizer state, the step count); those are needed to resume training, not to use the model.
True or false?
To get readable class names back after loading a saved classifier, you have to pass the names again.
False. The names are stored in config.json as id2label and label2id, and they come back with the model.
A saved model folder and a model repository on the Hub have the same kind of files.
True. Both hold the weights, config.json and the tokenizer files, which is why the same loading call reads either.
Loading from a folder
from_pretrained() accepts either a Hub name, such as distilbert/distilbert-base-uncased, or the path to a local folder written by save_pretrained(). Given a folder, it reads config.json from it, builds the model class that config describes, and fills it with the weights from model.safetensors. The tokenizer loads from the same folder in the same way, which keeps the pair together: the token IDs the tokenizer produces mean something only to the model trained with that vocabulary.
from transformers import AutoModelForSequenceClassification, AutoTokenizer
folder = "./topic-model"
model = AutoModelForSequenceClassification.from_pretrained(folder)
tokenizer = AutoTokenizer.from_pretrained(folder)
print(model.config.id2label) # {0: 'sport', 1: 'politics', 2: 'science'}Compare this with loading the original pretrained checkpoint for classification. That checkpoint has no weights for a classification head, so the head starts from random numbers and the load report marks its weights as missing and newly initialized, with the advice to train the model first. The fine-tuned folder already holds the trained head, so every weight the model needs is found in the file and nothing is initialized at random. A report with no newly initialized weights is the sign that you loaded the trained model and not a fresh copy of the base.
A loaded model is in evaluation mode, with dropout switched off, so it is ready for inference right away; to train it further, call model.train() first. Use local_files_only=True when you want to be sure the call never reaches the network, for example on a machine without internet access: from_pretrained(folder, local_files_only=True).
True or false?
If the load report says the classifier weights were newly initialized, the model will still classify as well as it did after training.
False. Newly initialized weights are random, so its answers are guesses. Most likely the path points to the base checkpoint instead of the fine-tuned folder.
The tokenizer should be loaded from the same folder as the fine-tuned model.
True. The model learned on the token IDs of that tokenizer. A different tokenizer produces numbers that mean something else to it.
A pipeline with your model
A pipeline wraps the three steps of using a model in one call: tokenize the text, run the model, and turn its output into a readable answer. For a classifier the task is "text-classification". Point it at the model and tokenizer you loaded, and it uses the class names from their configuration.
from transformers import pipeline
classifier = pipeline(
"text-classification",
model=model,
tokenizer=tokenizer,
device="cpu",
)
result = classifier("The final went to extra time after a late goal.")
print(result) # a list with one dict: [{'label': ..., 'score': ...}]
print(result[0]["label"]) # the name of the predicted classTwo details of the result are easy to get wrong. A single string gives back a list holding one dictionary, so the answer is read with result[0]. A list of strings gives back one dictionary per string, in the same order. Each dictionary has a label, the class name looked up in id2label, and a score. If the names were never stored, the labels appear as LABEL_0, LABEL_1 and so on.
For a model with several classes, the score is the softmax probability of the winning class: the logits of all classes are turned into probabilities that sum to one, and the highest one is reported. Passing top_k=None in the call returns every class with its probability, from highest to lowest, which shows how the model spread its belief.
Leaving out device lets the pipeline pick an accelerator such as a GPU when one is present; device="cpu" keeps it on the processor. Some documentation writes the task as "sentiment-analysis", which is another name for the same "text-classification" pipeline.
>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
>>> classifier("This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end.")
[{'label': 'POSITIVE', 'score': 0.9994940757751465}]True or false?
Calling a text-classification pipeline on one string returns a dictionary, so result["label"] gives the class.
False. It returns a list with one dictionary in it. The class is result[0]["label"].
With top_k=None, the scores of all classes for one text add up to one.
True. For a model with several classes the scores are softmax probabilities, which always sum to one.
Confidence: how sure the model is
The score of the winning class is the model's confidence. A model that gives one class nearly all the probability is sure; one that spreads it over two or three classes is torn between them. That spread tells you something real. Across many tasks, correct answers tend to come with a higher top probability than wrong answers do. They also tend to score higher than texts unlike anything in the training data.
But the softmax has no way to say "none of these". It divides the probability among the trained classes only, and the highest one always wins. A text about a cooking recipe sent to a sport, politics and science classifier still gets one of those three labels. Sometimes the probability is spread out and the top score is low. Sometimes the recipe happens to share words with one class, and the top score is high.
- sport 0.94
- politics 0.04
- science 0.02
- sport 0.31
- politics 0.27
- science 0.42
The two charts are an illustration, not a measurement. Both texts get a label, and both sets of bars sum to one. The difference is the height of the winning bar. Read it as a signal, never as a guarantee: modern neural networks are often poorly calibrated, meaning that a confidence of 0.9 does not mean the model is right nine times out of ten. A wrong answer, or an answer to a text that belongs to no class, can come with a high score.
True or false?
A fine-tuned classifier returns no label when a text belongs to none of its classes.
False. Softmax spreads all the probability over the trained classes, so one of them always wins.
A wrong answer can have a higher score than a right one.
True. Confidence only tends to be higher for correct answers. Scores are not calibrated, so a confident mistake is possible.
A not-sure threshold
Since the model always answers, the decision of when not to trust it has to be added around it. The simplest rule is a threshold on the confidence: if the top score is at least the chosen value, use the label; if it is below, return no label and hand the text to a person. The pipeline has no option for this, so it is a few lines of your own code.
- New text
- Pipeline label and score
- Score at least the threshold?
- Use the label
- Not sure: a person decides
- New text to Pipeline
- Pipeline to Score at least the threshold?
- Score at least the threshold? to Use the label: yes
- Score at least the threshold? to Not sure: a person decides: no
THRESHOLD = 0.8 # chosen from validation results, never guessed
def classify(text):
best = classifier(text)[0]
if best["score"] < THRESHOLD:
return None, best["score"] # not sure: send to a person
return best["label"], best["score"]The value 0.8 above is only a placeholder. A good threshold is chosen from measurements, on a labelled set the model was not trained on, such as the validation set: look at the confidence of the correct answers and set the threshold under most of them, so that most correct answers pass. Then check it against texts that belong to no class: it should sit above their confidence, so they are turned away.
No threshold separates right from wrong perfectly, because confidence does not. The rule moves some cases to a person and lets others through, and you should know which ones:
| The answer | Its score | What the rule does |
|---|---|---|
| Correct | High | Kept: the label is used |
| Wrong | Low | Caught: a person fixes it |
| Text that fits no class | Low | Caught: a person sees it |
| Correct | Low | Turned away: a person redoes work the model got right |
| Wrong | High | Missed: the wrong label is used |
| Text that fits no class | High | Missed: it gets a label it should not have |
Moving the threshold trades these rows against each other. Raise it, and more wrong answers are caught, but more correct answers are turned away too, so people review more. Lower it, and fewer correct answers are lost, but more confident mistakes slip through. A threshold placed under most correct answers still turns some correct answers away: that is its cost, and the reason to measure how many before using it. Where texts outside every class are common, a threshold alone lets the confident ones through; training an extra class for such texts is another way to turn them away.
True or false?
A well-chosen threshold catches every wrong answer.
False. Wrong answers with a high score pass it. A threshold only catches the mistakes the model was unsure about.
Raising the threshold sends more correct answers to a person.
True. Some correct answers have modest scores. A higher bar turns more of them away along with the mistakes.
The threshold should be tuned on the test set, to get the best final result.
False. Tuning on the test set makes its result too optimistic. Choose it on the validation set and keep the test set for the honest estimate.