Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

Worked Example: Rebuild Last Month's Model from Scratch

Rebuild a churn model from its run record alone: check the code hash, pull the recorded data version with DVC, create a fresh environment from the lock file, retrain with the resolved configuration and compare both metrics and predictions, then see what breaks when the override, the data or the environment is not pinned.

Contentsand lesson path

What you will learn

  • Version datasets and models alongside code (for example with DVC or content hashes) so that every reported result traces back to exact data, code and configuration.
  • Reproduce a past run in a clean environment from pinned dependencies, configuration files and fixed seeds, and name the remaining sources of nondeterminism.

01. The problem

On 15 October a churn model was trained and its scores were sent to the retention team. A month later, the team asks why one customer was scored as likely to leave. To answer, you need the exact model of 15 October, not a new one trained today. All you have is the project and the run record that the training script saved, the same fields a tracker such as MLflow keeps for a run (the tracking lab).

Your goal is a rebuild that you can show is the same model: identical holdout predictions, or differences below a tolerance you state in advance. The plan follows the inputs from the first lesson: code, data, configuration, environment and seed, each checked against the record before training. You need Python 3.12, DVC 3.67, uv 0.13 and a network connection for the first package download.

Project layout
rebuild-demo/
├── original/          last month's project (step 1 recreates it)
│   ├── train.py, config.toml, requirements.in, requirements.lock
│   ├── data/train.csv.dvc    pointer to the data version
│   └── runs/2026-10-15/      run_record.json, predictions.csv
├── storage/           the DVC remote
├── make_env.sh        a fresh environment from a lock file
├── check_inputs.py    compare a record with the files and environment
├── compare.py         compare the metrics and predictions of two runs
└── rebuild/           steps 3 to 6: a clean copy, as a Git clone would give
Terminal
mkdir rebuild-demo && cd rebuild-demo
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "dvc==3.67.1" "uv==0.13.8" scikit-learn

This is your everyday tool environment. scikit-learn is deliberately not pinned here, because the model will not be trained in this environment: each training run gets its own environment built from the project's lock file. Every command block below starts in rebuild-demo/; blocks that move into original/ or rebuild/ end with cd .., so you can type them one after another in the same terminal.

02. Step 1: Recreate last month's run

In real life this step happened a month ago. Here you recreate it so that the rest is runnable. train.py reads config.toml, fills in anything missing from DEFAULTS, applies --set key=value overrides from the command line, and saves the predictions on a 250-row holdout set plus a record of every input. The record keeps the resolved configuration, the values that were actually used, which is not the same as the contents of config.toml.

Python · original/make_data.py
"""Write data/train.csv: 1,000 customers; --fix makes negative spend positive."""
import csv
import sys
from pathlib import Path

import numpy as np

rng = np.random.default_rng(7)
n = 1000
tenure = rng.integers(1, 72, size=n)                       # months as a customer
spend = rng.normal(60, 25, size=n).round(2)                # monthly spend
calls = rng.poisson(1.5, size=n)                           # support calls
logit = 0.6 * calls - 0.05 * tenure + 0.01 * (spend - 60)
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
if "--fix" in sys.argv:
    spend = np.abs(spend)                                  # a later sign correction
Path("data").mkdir(exist_ok=True)
with open("data/train.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["tenure", "monthly_spend", "support_calls", "churned"])
    w.writerows(zip(tenure, spend, calls, churn))
print(f"data/train.csv: {n} rows, {churn.sum()} churned, {(spend < 0).sum()} negative")
TOML · original/config.toml
# Model settings. Anything not set here falls back to DEFAULTS in train.py.
n_estimators = 100
max_depth = 6
Text · original/requirements.in
scikit-learn>=1.8
Python · original/train.py
"""Train the churn model; write predictions and a record of every input to --out."""
import argparse
import hashlib
import json
import sys
import tomllib
from importlib.metadata import version
from pathlib import Path

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

DEFAULTS = {"n_estimators": 100, "max_depth": 6, "min_samples_leaf": 5,
            "holdout": 0.25, "seed": 0}
FEATURES = ["tenure", "monthly_spend", "support_calls"]


def digest(path, algo="sha256"):
    return hashlib.new(algo, Path(path).read_bytes()).hexdigest()


def resolve_config(args):
    if args.resolved_from:                       # rebuild: the exact config of a run
        return json.loads(Path(args.resolved_from).read_text())["config"]
    config = DEFAULTS | tomllib.loads(Path(args.config).read_text())
    for item in args.set:                        # command-line overrides, key=value
        key, value = item.split("=")
        config[key] = type(DEFAULTS[key])(value)
    return config


parser = argparse.ArgumentParser()
parser.add_argument("--config", default="config.toml")
parser.add_argument("--set", action="append", default=[])
parser.add_argument("--resolved-from")
parser.add_argument("--out", required=True)
args = parser.parse_args()
cfg = resolve_config(args)

data = np.genfromtxt("data/train.csv", delimiter=",", names=True)
X = np.column_stack([data[c] for c in FEATURES])
y = data["churned"].astype(int)
X_tr, X_ho, y_tr, y_ho = train_test_split(X, y, test_size=cfg["holdout"], stratify=y,
                                          random_state=cfg["seed"])
model = RandomForestClassifier(n_estimators=cfg["n_estimators"],
                               max_depth=cfg["max_depth"],
                               min_samples_leaf=cfg["min_samples_leaf"],
                               random_state=cfg["seed"]).fit(X_tr, y_tr)
proba = model.predict_proba(X_ho)[:, 1]

out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
np.savetxt(out / "predictions.csv", proba, fmt="%.10f")
record = {
    "code_sha256": digest("train.py")[:12],
    "data_md5": digest("data/train.csv", "md5"),
    "config": cfg,                               # resolved: file + defaults + overrides
    "lock_sha256": digest("requirements.lock")[:12],
    "python": "{}.{}".format(*sys.version_info[:2]),
    "packages": {p: version(p) for p in ("scikit-learn", "numpy", "scipy")},
    "holdout_auc": round(roc_auc_score(y_ho, proba), 4),
    "predictions_sha256": digest(out / "predictions.csv")[:12],
}
(out / "run_record.json").write_text(json.dumps(record, indent=2) + "\n")
print(f"holdout_auc {record['holdout_auc']} -> {out}/run_record.json")
Text · make_env.sh
# make_env.sh DIR LOCKFILE: a new virtual environment with exactly the locked packages
set -e
uv venv -q --python 3.12 "$1"
uv pip sync -q --python "$1/bin/python" "$2"
Terminal
cd original
uv pip compile -q requirements.in -o requirements.lock \
  --exclude-newer 2026-10-01T00:00:00Z
bash ../make_env.sh .venv requirements.lock
.venv/bin/python make_data.py
dvc init --no-scm -q && dvc add -q data/train.csv
dvc remote add -q -d storage ../storage && dvc push -q
.venv/bin/python train.py --set n_estimators=300 --out runs/2026-10-15
cd ..                     # back to rebuild-demo/
Expected output
data/train.csv: 1000 rows, 351 churned, 8 negative
holdout_auc 0.7579 -> runs/2026-10-15/run_record.json

The lock file was resolved as of 1 October, the environment was built from it, the data was versioned with DVC and pushed to storage/, and the model was trained with one override, n_estimators=300. make_env.sh uses uv pip sync, which installs exactly the packages in the lock file and removes anything else, so the environment holds what the lock says and nothing more.

03. Step 2: Read the record

Terminal
cat original/runs/2026-10-15/run_record.json
Expected output
{
  "code_sha256": "16586b175450",
  "data_md5": "cad23d1dc9137d995ec4e10c0896c361",
  "config": {
    "n_estimators": 300,
    "max_depth": 6,
    "min_samples_leaf": 5,
    "holdout": 0.25,
    "seed": 0
  },
  "lock_sha256": "7c7d4196960e",
  "python": "3.12",
  "packages": {
    "scikit-learn": "1.9.1",
    "numpy": "2.5.3",
    "scipy": "1.18.1"
  },
  "holdout_auc": 0.7579,
  "predictions_sha256": "b4e76ec443c0"
}

Each field pins one input. code_sha256 identifies the training code; in a Git repository you would record the commit as well and check it out. data_md5 is the content hash DVC uses, so it names the exact bytes. config holds the resolved values, including the override and the seed. lock_sha256 identifies the lock file, and python and packages let you check the environment after building it. The last two fields are the results you must reproduce: the metric and a hash of the predictions file.

04. Step 3: Code and data at the recorded versions

Start from a clean folder that holds only what version control would give you: the code, the config, the lock file, the DVC pointer and DVC's config. (With Git, this is git clone followed by git checkout <commit>.) Then dvc pull fetches the data by its hash, and check_inputs.py compares the files with the record.

Python · check_inputs.py
"""check_inputs.py RECORD [--env]: compare a run record with what is here now."""
import hashlib
import json
import sys
from importlib.metadata import version
from pathlib import Path

record = json.loads(Path(sys.argv[1]).read_text())


def digest(path, algo="sha256"):
    return hashlib.new(algo, Path(path).read_bytes()).hexdigest()


if "--env" in sys.argv:                          # run with the rebuilt interpreter
    found = {"python": "{}.{}".format(*sys.version_info[:2]),
             **{p: version(p) for p in record["packages"]}}
    wanted = {"python": record["python"], **record["packages"]}
else:
    found = {"code train.py": digest("train.py")[:12],
             "data data/train.csv": digest("data/train.csv", "md5"),
             "lock requirements.lock": digest("requirements.lock")[:12]}
    wanted = {"code train.py": record["code_sha256"],
              "data data/train.csv": record["data_md5"],
              "lock requirements.lock": record["lock_sha256"]}
bad = 0
for key, want in wanted.items():
    ok = found[key] == want
    bad += not ok
    print((f"{key:24} {'ok' if ok else 'MISMATCH':8} recorded {want[:12]:12}"
          + ("" if ok else f" found {found[key][:12]}")).rstrip())
sys.exit(1 if bad else 0)
Terminal
mkdir -p rebuild/data rebuild/.dvc
cp original/train.py original/config.toml original/requirements.lock rebuild/
cp original/data/train.csv.dvc rebuild/data/
cp original/.dvc/config rebuild/.dvc/
cp original/runs/2026-10-15/run_record.json rebuild/last-run.json
cd rebuild && dvc pull && python ../check_inputs.py last-run.json
cd ..                     # back to rebuild-demo/
Expected output
A       data/train.csv
1 file fetched and 1 file added
code train.py            ok       recorded 16586b175450
data data/train.csv      ok       recorded cad23d1dc913
lock requirements.lock   ok       recorded 7c7d4196960e

05. Step 4: A fresh environment from the lock file

Build a new environment from the recorded lock file, then run the same checker with that environment's Python, so that it reports the versions training will use.

Terminal
cd rebuild
bash ../make_env.sh .venv requirements.lock
.venv/bin/python ../check_inputs.py last-run.json --env
cd ..                     # back to rebuild-demo/
Expected output
python                   ok       recorded 3.12
scikit-learn             ok       recorded 1.9.1
numpy                    ok       recorded 2.5.3
scipy                    ok       recorded 1.18.1

NumPy is 2.5.3, the version of 1 October, although a newer one existed when this lesson was written. The record lists only three packages for a quick check; the lock file pins all seven, including the ones nobody named.

06. Step 5: Retrain with the resolved configuration and compare

--resolved-from makes train.py use the configuration stored in the record, so nobody has to remember the override. compare.py then checks more than the metric: the largest difference between any two predictions, how many holdout labels would flip at a 0.5 threshold, and whether the predictions files are byte-for-byte identical.

Python · compare.py
"""compare.py OLD_DIR NEW_DIR: metrics and predictions of two runs."""
import json
import sys
from pathlib import Path

import numpy as np

old, new = (Path(d) for d in sys.argv[1:3])
rec_old, rec_new = (json.loads((d / "run_record.json").read_text()) for d in (old, new))
p_old, p_new = (np.loadtxt(d / "predictions.csv") for d in (old, new))
changed = [k for k in rec_old["config"] if rec_old["config"][k] != rec_new["config"][k]]
print(f"holdout_auc  {rec_old['holdout_auc']} -> {rec_new['holdout_auc']}")
print(f"config keys that differ: {changed or 'none'}")
print(f"max |prediction difference|: {np.abs(p_old - p_new).max():.2e}")
print(f"labels that flip at 0.5: {int(((p_old >= 0.5) != (p_new >= 0.5)).sum())}"
      f" of {len(p_old)}")
print("predictions file identical:",
      rec_old["predictions_sha256"] == rec_new["predictions_sha256"])
Terminal
cd rebuild
.venv/bin/python train.py --resolved-from last-run.json --out runs/rebuild
.venv/bin/python ../compare.py ../original/runs/2026-10-15 runs/rebuild
cd ..                     # back to rebuild-demo/
Expected output
holdout_auc 0.7579 -> runs/rebuild/run_record.json
holdout_auc  0.7579 -> 0.7579
config keys that differ: none
max |prediction difference|: 0.00e+00
labels that flip at 0.5: 0 of 250
predictions file identical: True

Every prediction matches exactly, so this is the model of 15 October and you can answer the retention team's question with it. On the same kind of CPU with the same library versions, scikit-learn often reproduces results bit for bit. Across different hardware, and especially on GPUs, expect tiny differences and decide on a tolerance before you compare, for example a maximum prediction difference of 1e-6 and no flipped labels.

07. Step 6: What breaks when one input is not pinned

Now remove one pin at a time. First, rebuild from config.toml alone, as you would if the record held only the config file.

Terminal
cd rebuild
.venv/bin/python train.py --out runs/config-file-only
.venv/bin/python ../compare.py ../original/runs/2026-10-15 runs/config-file-only
cd ..                     # back to rebuild-demo/
Expected output
holdout_auc 0.7599 -> runs/config-file-only/run_record.json
holdout_auc  0.7579 -> 0.7599
config keys that differ: ['n_estimators']
max |prediction difference|: 4.87e-02
labels that flip at 0.5: 0 of 250
predictions file identical: False

The file says 100 trees; the real run used 300. AUC even went up slightly, and individual predictions moved by up to 0.049: a different model that looks similar. Next, simulate someone correcting the data in place, fixing the sign of 8 negative spend values, then restore the recorded version.

Terminal
cd rebuild
.venv/bin/python ../original/make_data.py --fix
python ../check_inputs.py last-run.json
.venv/bin/python train.py --resolved-from last-run.json --out runs/fixed-data
.venv/bin/python ../compare.py ../original/runs/2026-10-15 runs/fixed-data
dvc checkout --force data/train.csv.dvc
cd ..                     # back to rebuild-demo/
Expected output
data/train.csv: 1000 rows, 351 churned, 0 negative
code train.py            ok       recorded 16586b175450
data data/train.csv      MISMATCH recorded cad23d1dc913 found 5769e5d205e7
lock requirements.lock   ok       recorded 7c7d4196960e
holdout_auc 0.7578 -> runs/fixed-data/run_record.json
holdout_auc  0.7579 -> 0.7578
config keys that differ: none
max |prediction difference|: 1.01e-02
labels that flip at 0.5: 1 of 250
predictions file identical: False
M       data/train.csv

The checker catches the change before training. If you train anyway, AUC moves only in the fourth decimal, from 0.7579 to 0.7578, but one customer's label flips. A metric that looks the same is weak evidence that the model is the same; predictions are much stronger evidence. dvc checkout --force puts the recorded version back and discards the edited file.

Last, train in your everyday tool environment instead of the locked one. Your output here depends on what pip installed for you, so it is illustrative.

Terminal
cd rebuild
python ../check_inputs.py last-run.json --env
python train.py --resolved-from last-run.json --out runs/tool-env
python ../compare.py ../original/runs/2026-10-15 runs/tool-env
cd ..                     # back to rebuild-demo/
Illustrative output
python                   ok       recorded 3.12
scikit-learn             ok       recorded 1.9.1
numpy                    MISMATCH recorded 2.5.3        found 2.5.5
scipy                    ok       recorded 1.18.1
holdout_auc 0.7579 -> runs/tool-env/run_record.json
holdout_auc  0.7579 -> 0.7579
config keys that differ: none
max |prediction difference|: 0.00e+00
labels that flip at 0.5: 0 of 250
predictions file identical: True

Here a newer NumPy happened to give the same predictions. That is luck, not a guarantee: a release can change a default, a solver or a random-number routine, and you would only find out by comparing. The locked environment makes the match something you can rely on, and the checker tells you when you are not in it.

Steps 3 to 5 are what a README should turn into one command, for example bash reproduce.sh runs/2026-10-15/run_record.json, so that a colleague or a fresh container can rebuild a registered model without asking you anything.

08. Check your understanding

Practice check · 3 questions

Is it the same model?

Use the steps and outputs of this worked example.

Q1. After the in-place data correction in step 6, holdout AUC moves only from 0.7579 to 0.7578. A teammate says that is close enough to call it the same model. What does the rest of the comparison show?
Q2. In step 6, training in the tool environment with NumPy 2.5.5 instead of 2.5.3 gives identical predictions. What should you conclude?
Q3. Why does the rebuild run `check_inputs.py` before training, instead of only comparing the results afterwards?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the practice project, prove that your registered model can be rebuilt.

  1. Make your training script save a record like the one in step 2: commit, data hash, resolved configuration, lock file hash, Python and key package versions, metrics and a predictions hash. Log the same fields to your tracker.
  2. Write reproduce.sh that takes a record, builds an environment from the lock file, pulls the recorded data, checks every input and retrains with the resolved configuration.
  3. Document that one command in the README, with the tolerance you accept for predictions.
  4. Ask a peer to run it from a fresh clone, or run it in a fresh container, and compare the predictions with compare.py.

10. Review prompt

Without looking back, list the fields a run record needs for a rebuild and what each one pins; explain the difference between a config file and a resolved configuration; describe how to get the code, the data and the environment of a past run; say why a rebuild compares predictions and not only metrics; and name what can still differ when you rebuild on different hardware, and how you handle it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check