Save and Load
Keep your model.
Training takes time, and sometimes money. So when it's done, we save the model to disk. Then any program can load it, and use it, without training again.
- Training costs time
- Save it to disk
- Load it anywhere
Saving
Trainer dot save model writes everything to a folder. Without a trainer, any model has save pretrained. And remember to save the tokenizer too. A model is useless without its matching tokenizer. Loading is the same from pretrained we've used all along. Just give it the folder, instead of a Hub name.
| key | value |
|---|---|
| trainer.save_model(dir) | model + tokenizer |
| model.save_pretrained(dir) | any model |
| tok.save_pretrained(dir) | don't forget it |
| from_pretrained(dir) | load from a folder |
What's in the folder?
Our model was trained, and saved, in intent model. We list each file, with its size. Then we load the tokenizer, and the model, from that folder. And we classify one message. Argmax picks the highest score. ID to label turns it back into a name. Run it. The weights are in model dot safetensors, about two hundred and seventy megabytes. The config describes the model, and the tokenizer files are there too. And the loaded model works.
import os, torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
for f in sorted(os.listdir("intent-model")):
print(f"{f:24} {os.path.getsize(f'intent-model/{f}') / 1e6:7.2f} MB")
tok = AutoTokenizer.from_pretrained("intent-model")
model = AutoModelForSequenceClassification.from_pretrained("intent-model")
inputs = tok("Can I still return Rebecca?", return_tensors="pt")
with torch.no_grad():
best = model(**inputs).logits.argmax(-1).item()
print("Prediction:", model.config.id2label[best])config.json 0.00 MB model.safetensors 267.84 MB tokenizer.json 0.71 MB tokenizer_config.json 0.00 MB training_args.bin 0.01 MB Prediction: return
Also uses _setup.py
from train import trainer
trainer.train()
trainer.save_model("intent-model")Also uses prep.py
from datasets import load_dataset
from transformers import AutoTokenizer
INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)
def prepare(row):
enc = tok(row["message"], truncation=True, max_length=32)
enc["label"] = label2id[row["intent"]]
return enc
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])Also uses train.py
import numpy as np
from transformers import (AutoModelForSequenceClassification, DataCollatorWithPadding,
Trainer, TrainingArguments)
from prep import tok, data, MODEL, label2id, id2label
model = AutoModelForSequenceClassification.from_pretrained(
MODEL, num_labels=5, id2label=id2label, label2id=label2id)
args = TrainingArguments(output_dir="intent-model", num_train_epochs=2,
per_device_train_batch_size=16, learning_rate=5e-5,
eval_strategy="epoch", logging_strategy="epoch",
save_strategy="no", report_to="none")
def accuracy(pred):
return {"accuracy": (np.argmax(pred.predictions, -1) == pred.label_ids).mean()}
trainer = Trainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], data_collator=DataCollatorWithPadding(tok),
compute_metrics=accuracy)Safetensors
What's safetensors? It's a file format for model weights. Older models used pickle files, which can run hidden code when you load them. That's a security risk. Safetensors only stores numbers. It's safe, and fast to load. Prefer it whenever you can.
| key | value |
|---|---|
| safetensors | the weights file format |
| Old pickle files | can run hidden code |
| safetensors | only numbers, safe |
| Bonus | very fast to load |
Summary
Let's recap. Save model writes the weights, config, and tokenizer to a folder. From pretrained loads them back. And safetensors is the safe weights format. Next, using our model in a real program.
Key takeaways- save_model / save_pretrained
- from_pretrained(folder)
- safetensors