Sub topic 13
Saving and Reusing the Model
This chapter assumes you can run Python, understand training and test sets, and have trained the IMDB classifier from the earlier chapters with Hugging Face Transformers. The goal is to preserve both the model and the tokenizer so another program can make the same kind of predictions later.
What must be saved
A fine-tuned classifier has two important parts:
- The model contains the learned neural network weights and its configuration.
- The tokenizer converts new text into the token IDs that the model expects.
Save both parts together. Saving only the model is not enough because a different tokenizer can produce different inputs.
The model configuration should also contain the label mapping. For example, label ID 0 might mean NEGATIVE, while label ID 1 means POSITIVE. Keeping this mapping with the model prevents an application from accidentally reversing the output labels.
| Artifact | Purpose |
|---|---|
| Model weights | Stores the learned parameters |
| Configuration | Stores the model type, label count, and label names |
| Tokenizer files | Reproduce tokenization for new text |
| Training checkpoint | Allows a later training run to resume |
Creating a reusable model directory
After training, use Trainer.save_model and tokenizer.save_pretrained. Both methods write files into a directory. The directory can be copied to another machine or uploaded to a model repository.
from pathlib import Path
from transformers import pipeline
output_dir = Path("imdb-distilbert")
output_dir.mkdir(parents=True, exist_ok=True)
# trainer and tokenizer come from the completed fine-tuning run.
trainer.save_model(str(output_dir))
tokenizer.save_pretrained(str(output_dir))
print(f"Saved reusable model to {output_dir.resolve()}")
classifier = pipeline(
task="text-classification",
model=str(output_dir),
tokenizer=str(output_dir),
)
texts = [
"A warm, funny film with a great cast.",
"Two hours I will never get back.",
]
for result in classifier(texts):
print(result)The pipeline loads the model configuration and tokenizer from the same directory. It returns a label and a score for each input. The score is the model's confidence for the returned label, not a guarantee that the prediction is correct.
A training checkpoint has a different purpose. During training, TrainingArguments can save checkpoints after each epoch. A checkpoint may include optimizer state, scheduler state, and the current training step. These files let you resume training. For deployment, save the final or best model instead of depending on a temporary checkpoint path.
Loading the model in another program
A production program usually loads the pipeline once and reuses it for many requests. Loading the model inside every request wastes time and memory.
from transformers import pipeline
classifier = pipeline(
"text-classification",
model="imdb-distilbert",
tokenizer="imdb-distilbert",
)
def classify_review(review: str) -> dict:
result = classifier(review, truncation=True, max_length=256)[0]
return {
"label": result["label"],
"score": round(float(result["score"]), 4),
}
print(classify_review("The story was slow, but the acting was excellent."))The truncation=True and max_length=256 settings keep inference consistent with training. Without truncation, a long review may exceed the model's supported sequence length.
Sharing and versioning
For reliable reuse, record the following information with each model version:
- Base checkpoint, such as
distilbert-base-uncased - Dataset version and preprocessing rules
- Label names and their numeric IDs
- Maximum sequence length
- Training hyperparameters
- Evaluation results and the chosen validation checkpoint
You can upload a saved directory to the Hugging Face Hub, if your project permits sharing it. A repository gives the model a stable name and version history. Keep private or sensitive training data out of the repository.
Exercise
Why should the tokenizer be saved with the fine-tuned model?
Show answer
The tokenizer defines how new text becomes model inputs. Using a different tokenizer can produce different token IDs and make the model's predictions unreliable.