Sub topic 15
Storing and Naming Models and Outputs
A trained model is the output of three things: code, configuration, and data. If you store only the model file, you lose the link to all three. This chapter covers where model files and other outputs should live, how to name them so they can be traced back to a run, and which mistakes to avoid. It assumes you have read the earlier chapters on config files, data versioning, pipelines, and experiment tracking. It also assumes you can read basic Python and use Git.
What counts as an artifact
An artifact is any file a run produces that you may need later. Models are the obvious case, but they are not the only one.
| Artifact | Example | Typical size | Usual home |
|---|---|---|---|
| Trained model | `model.pkl`, `model.onnx`, `weights.pt` | MB to GB | Pipeline output or artifact store |
| Metrics | `metrics.json` | KB | Git or tracker |
| Predictions | `predictions.parquet` | MB to GB | Pipeline output |
| Plots and reports | `confusion_matrix.png` | KB to MB | Tracker or pipeline output |
| Fitted preprocessors | scaler, tokenizer, encoder | KB to MB | Next to the model |
| Run metadata | `metadata.json` | KB | Next to the model |
Small text files such as metrics can go in Git, because they diff well. Anything large or binary should stay out of Git, for the same reasons as the data in the earlier chapters.
Where artifacts live
There are three common places, and most projects use more than one.
- The
models/folder, tracked by the pipeline. Thedvc.yamlexample listsmodels/model.pklunderouts. DVC stores the file in its cache and adds it to.gitignore. Git records a small pointer, so each commit corresponds to one model version. - The experiment tracker's artifact store. Tools such as MLflow and Weights & Biases can upload a file with the run that produced it. The run page then links parameters, metrics, code version, and model.
- Shared object storage. A bucket such as S3, GCS, or Azure Blob lets other people and services fetch a model without access to your machine. A model registry adds stage labels such as
stagingandproductionon top.
Whatever you choose, the local models/ folder is a working directory. It is not the source of truth, and it must never be the only copy of a model you care about.
Two naming patterns
The first pattern uses a fixed name, models/model.pkl. The pipeline overwrites it on each run, and Git and DVC history supply the versions. This suits a single "current" model that is rebuilt from a known commit. You recover an old model by checking out the old commit and running dvc checkout.
The second pattern uses an immutable directory per run, such as models/20261130T095115Z_3f9c2ab_91d4e0aa/. Nothing is overwritten. This suits experiments where you train many variants and compare them side by side.
The two patterns combine well. Experiments write run directories. When one is chosen, you promote it by copying it into the pipeline's fixed path or the registry.
Avoid names like final.pkl, final_v2.pkl, and final_v2_really.pkl. They carry no information, and they cannot be sorted or compared.
Building a traceable name
A good run identifier has three parts:
- A UTC timestamp, so directories sort by time.
- The short Git commit, so you know which code produced the model.
- A short hash of the config, so identical settings are recognizable.
The hash is computed from the config serialized with sorted keys. Without sorted keys, the same settings could produce different hashes.
import hashlib
import json
import pickle
import subprocess
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
def config_hash(config):
payload = json.dumps(asdict(config), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:8]
def git_state():
try:
commit = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, check=True,
).stdout.strip()
status = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True, text=True, check=True,
).stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown", True
return commit, bool(status)
def save_run(model, config, metrics, root="models"):
commit, dirty = git_state()
created = datetime.now(timezone.utc)
run_id = f"{created:%Y%m%dT%H%M%SZ}_{commit}_{config_hash(config)}"
run_dir = Path(root) / run_id
run_dir.mkdir(parents=True, exist_ok=False)
with open(run_dir / "model.pkl", "wb") as f:
pickle.dump(model, f)
metadata = {
"run_id": run_id,
"created_at": created.isoformat(),
"git_commit": commit,
"git_dirty": dirty,
"config": asdict(config),
"metrics": metrics,
}
with open(run_dir / "metadata.json", "w") as f:
json.dump(metadata, f, indent=2)
return run_dirA call at the end of train.py might look like this:
from my_project.config import load_config
from my_project.train_utils import save_run # the module holding the code above
config = load_config("configs/train.yaml", ["learning_rate=0.01"])
model = {"weights": [0.1, 0.2]} # stand-in for a fitted model
run_dir = save_run(model, config, {"accuracy": 0.91})
print(run_dir)Three details matter here:
exist_ok=Falsemakes a name collision an error, so a run can never silently overwrite another.git_dirtyrecords whether uncommitted changes existed. A model trained from a dirty tree cannot be rebuilt from the commit alone, and this field tells you so later.- The metadata stores the full config, not only the hash. The hash is a convenient label. The config is the actual record.
If you use DVC, also record the data version. The simplest way is to copy the hashes from dvc.lock into the metadata, or to log them to the tracker.
How the pieces connect
Choosing a file format
The format determines what you need installed when you load the model and how safe loading is.
| Format | Strengths | Weaknesses |
|---|---|---|
| `pickle` / `joblib` | Works with almost any Python object | Breaks across library versions; unsafe on untrusted files |
| Framework native (`torch.save`, Keras `.keras`) | Supported by the framework | Tied to that framework |
| ONNX | Runs without the training library | Not every model converts cleanly |
| `safetensors` | Stores tensors only, with no code execution | Does not store model structure or preprocessing |
Whatever format you pick, save the preprocessing with the model. A classifier that needs a fitted scaler is not usable without it. The simplest fix is to put both in one scikit-learn Pipeline and save that single object.
Retention and cleanup
Run directories accumulate quickly. Decide on a policy before the disk fills:
- Keep every run's
metadata.jsonand metrics. They are tiny and answer most later questions. - Keep model files only for runs you might deploy or compare against.
- Delete the rest on a schedule, or let the tracker or object store expire them.
- Never delete the model that is currently in use, or the one it replaced, until the new one has proven itself.
Common errors
- Overwriting a model with no record of what it was. Use run directories, or make sure the fixed-path file is a pipeline output with versioning.
- Committing model files to Git. The repository grows permanently, because deleting the file later does not remove it from history.
- Saving weights but not the preprocessing or the config. The model cannot be applied correctly or rebuilt.
- Trusting the timestamp alone. It says when a model was made, not what made it.
- Training from a dirty working tree. The recorded commit does not match the code that ran. Check
git_dirtybefore promoting a model. - Loading a pickle in a different library version. Record the key library versions in the metadata, or pin the environment as described earlier.
Exercise
A teammate trained a model on Monday and saved it as models/model.pkl. On Wednesday they retrained with a different learning rate and saved to the same path. Your manager asks which settings produced the Monday model. What went wrong with the storage setup, and what two changes would prevent it?
Show answer
The second run overwrote the first, and no file recorded the settings, so the Monday model and its config are gone. First, write each run to its own directory named with a timestamp, the Git commit, and a config hash, and create it with exist_ok=False so a collision raises an error. Second, save a metadata.json next to the model with the full config, metrics, and commit. Alternatively, keep the fixed path but make it a DVC-tracked pipeline output, so each Git commit points to one model version.
Exercise
In saverun, why does confighash serialize the config with sort_keys=True before hashing?
Show answer
json.dumps keeps the dictionary's key order by default. Two configs with the same values but different key order would produce different strings and so different hashes. Sorting the keys makes the serialized text, and therefore the hash, depend only on the values.