Sub topic 13
Saving and reusing the model
Training produces weights in memory. They are useful only if you can store them, load them in another process, and get the same predictions. This chapter covers what a saved model contains, how to reload it, how to pick the right checkpoint, how to share it, and what changes if you trained with LoRA.
It assumes you have finished the Trainer chapters. You should have a trainer, a tokenizer, and the checkpoint variable from the IMDB DistilBERT example. You should also know that pipeline wraps a tokenizer and a model.
What a saved model contains
A fine-tuned model is more than a weights file. To reproduce its predictions you need three things:
- The weights, including the trained classification head.
- The configuration, which records the architecture, the number of labels, and the label names.
- The tokenizer files, so new text is split into the same tokens the model saw during training.
save_pretrained writes all of these into one folder.
| File | Purpose |
|---|---|
| `model.safetensors` | The weights, stored in the safetensors format, which cannot run code when loaded |
| `config.json` | Architecture settings, `num_labels`, `id2label`, `label2id` |
| `tokenizer.json`, `vocab.txt` | The vocabulary and tokenization rules |
| `tokenizer_config.json`, `special_tokens_map.json` | Settings such as lowercasing and the special tokens `[CLS]` and `[SEP]` |
| `training_args.bin` | Trainer arguments, written by `trainer.save_model` |
Exact file names vary by library version and tokenizer type. The three roles stay the same.
Saving the final model
The Trainer already has the best model in memory if you set load_best_model_at_end=True. Saving takes two calls, and both are needed.
trainer.save_model("imdb-distilbert")
tokenizer.save_pretrained("imdb-distilbert")trainer.save_model writes the weights and config. It does not always write the tokenizer unless you passed one to the Trainer, so call tokenizer.save_pretrained on the same folder explicitly. A folder with weights but no tokenizer is a common cause of "it worked in my notebook" failures.
You can also save the model directly, without a Trainer:
trainer.model.save_pretrained("imdb-distilbert")Reloading the model
There are two ways to load the folder. Use the Auto classes when you want control over tokenization and batching. Use pipeline when you want a label and score for each string.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
path = "imdb-distilbert"
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForSequenceClassification.from_pretrained(path)
model.eval()
texts = ["A warm, funny film with a great cast.", "Two hours I will never get back."]
batch = tokenizer(texts, truncation=True, max_length=256, padding=True, return_tensors="pt")
with torch.no_grad():
logits = model(**batch).logits
probs = torch.softmax(logits, dim=-1)
for text, p in zip(texts, probs):
label_id = int(p.argmax())
print(model.config.id2label[label_id], round(float(p[label_id]), 3), "-", text)Three details matter here:
model.eval()turns off dropout. Without it, predictions differ slightly on every call.torch.no_grad()skips gradient bookkeeping, which saves memory and time.padding=Truepads to the longest text in this batch. This is the same dynamic padding idea the data collator used during training.
The pipeline version is shorter:
from transformers import pipeline
classifier = pipeline("text-classification", model="imdb-distilbert")
print(classifier(
["A warm, funny film with a great cast.", "Two hours I will never get back."],
truncation=True,
max_length=256,
))Passing truncation=True matters. DistilBERT accepts at most 512 tokens, and a longer review makes the pipeline raise an error. Use the same max_length you trained with, so inference sees inputs shaped like the training inputs.
Labels survive only if you saved them
The label names come from id2label in config.json. The earlier training example passed id2label and label2id to from_pretrained, so the saved config contains NEGATIVE and POSITIVE. If you had skipped them, the pipeline would return LABEL_0 and LABEL_1. The model would still be correct, but you would have to remember what 0 and 1 mean.
You can check a saved model without loading the weights:
from transformers import AutoConfig
config = AutoConfig.from_pretrained("imdb-distilbert")
print(config.num_labels, config.id2label)If the labels are wrong in a saved folder, change them when you load:
model = AutoModelForSequenceClassification.from_pretrained(
"imdb-distilbert",
id2label={0: "NEGATIVE", 1: "POSITIVE"},
label2id={"NEGATIVE": 0, "POSITIVE": 1},
)Checkpoints versus the final model
During training, the Trainer writes a checkpoint-N folder under output_dir at each save step. With save_strategy="epoch" you get one folder per epoch. These checkpoints also hold the optimizer and scheduler state, so they are much larger than the final model. They exist so training can resume.
| Artifact | Contains | Use it for |
|---|---|---|
| `output_dir/checkpoint-N` | Weights, optimizer state, scheduler state, trainer state | Resuming an interrupted run |
| Folder from `save_model` plus tokenizer | Weights, config, tokenizer | Inference, sharing, deployment |
To resume a run that stopped, call trainer.train(resume_from_checkpoint=True). The Trainer finds the latest checkpoint in output_dir.
With load_best_model_at_end=True and metric_for_best_model="f1", the model in memory when train() returns is the best epoch by validation F1. That is not necessarily the last epoch. So trainer.save_model after training saves the best model, which is usually what you want. To see which checkpoint was chosen:
print(trainer.state.best_model_checkpoint)
print(trainer.state.best_metric)Checkpoint folders can fill a disk. Setting save_total_limit=2 in TrainingArguments keeps only the newest two plus the best one.
The save and reload path
Sharing on the Hugging Face Hub
The Hub hosts model folders as Git repositories. After you authenticate with huggingface-cli login or an access token, pushing takes two calls:
model.push_to_hub("your-username/imdb-distilbert")
tokenizer.push_to_hub("your-username/imdb-distilbert")Anyone can then load it by name, with no local folder:
classifier = pipeline("text-classification", model="your-username/imdb-distilbert")New repositories are public unless you pass private=True. Before pushing, add a model card, a README.md that states the training data, the metrics on the held-out test set, the labels, and known limits. A reader should know that this model was trained on movie reviews and may do poorly on product complaints or tweets. For private data, keep the repository private, or skip the Hub and copy the folder to storage you control.
To pin a deployment to a specific version, load with revision="<commit-hash>". Otherwise a later push to the same repository changes what your service loads.
Saving a LoRA model
A model trained with LoRA saves differently. save_pretrained on a PEFT model writes only the adapter, which is a few megabytes, not the full base weights. The folder holds adapter_config.json, which records the base model name, plus the adapter weights.
from peft import LoraConfig, PeftModel, TaskType, get_peft_model
from transformers import AutoModelForSequenceClassification
checkpoint = "distilbert-base-uncased"
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
def load_base():
return AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
lora_config = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=8,
lora_alpha=16,
lora_dropout=0.1,
target_modules=["q_lin", "v_lin"],
modules_to_save=["pre_classifier", "classifier"],
)
peft_model = get_peft_model(load_base(), lora_config)
# ... train with the same Trainer setup, then:
peft_model.save_pretrained("imdb-distilbert-lora")
# Later, in a new process: rebuild the base model, then attach the adapter.
reloaded = PeftModel.from_pretrained(load_base(), "imdb-distilbert-lora")
merged = reloaded.merge_and_unload()
merged.save_pretrained("imdb-distilbert-merged")Note the modules_to_save line. PEFT already trains and saves the final classifier layer for sequence classification. DistilBERT also has a pre_classifier layer, which is newly initialized at random, and it is not covered by the default. If it is left out, the saved adapter does not contain it, and a freshly loaded base model gets a different random pre_classifier. Predictions then change after reloading. Listing both layers avoids this.
merge_and_unload folds the adapter into the base weights and returns a plain model. The merged folder loads with AutoModelForSequenceClassification and works with pipeline, with no PEFT dependency at serving time. Keep the unmerged adapter if you want several small adapters for different tasks on one shared base. Save the tokenizer next to either version.
Common errors
- Missing tokenizer. Loading fails with an error about missing tokenizer files. Fix it by calling
tokenizer.save_pretrainedon the model folder. - Wrong tokenizer for the weights. Loading
bert-base-casedtokenization for adistilbert-base-uncasedmodel runs without errors but gives poor predictions. Always load both from the same folder. LABEL_0outputs.id2labelwas not set before training. Set it at load time as shown above.- Different predictions on each run.
model.eval()was not called. - Out-of-memory or length errors at inference. You did not truncate. Pass
truncation=True, max_length=.... - Slow or large-scale inference. Move the model to a GPU with
device=0inpipeline, ormodel.to("cuda"), and send texts in batches withbatch_size=rather than one string per call. - Adapter loads with the wrong results. The base model passed to
PeftModel.from_pretraineddiffers from the one used in training, or a trained head layer was not saved.
A final check before you ship: reload the saved folder in a fresh Python process and compare its predictions with the in-memory model on a few dozen validation texts. They should match to a few decimal places. This catches missing files and layers that were not saved.
Exercise
You trained with load_best_model_at_end=True, then called trainer.save_model("out") and copied only out/ to a server. Loading with pipeline("text-classification", model="out") fails, and a colleague says it would also have returned LABEL_0 and LABEL_1 if it had worked. What two things were missed, and how do you fix each?
Show answer
First, the tokenizer was never saved into out/, so the pipeline cannot find tokenizer files. Fix it by running tokenizer.save_pretrained("out") and copying the new files. Second, id2label and label2id were not passed to from_pretrained when the model was created, so the saved config.json has no label names. Fix it by loading the model with id2label and label2id set (keeping the numeric order the head was trained with) and saving again, or by passing them when loading.