Skip to content

MLDay 44 of 50ML in Production

From Notebook to Reproducible, Tracked Training

Last month the credit model scored PR-AUC 0.556 in a teammate's notebook.

7 min read

Last month the credit model scored PR-AUC 0.556 in a teammate's notebook. Today it scores 0.551, and nobody knows why. Was it the seed, a newer data file, or a setting changed in cell 14? Nobody wrote it down.

The idea

A training run has four inputs: the code, the data, the settings and the random seeds. Training is reproducible when the same four inputs give the same model, down to the last digit. So pin each one.

  • Code: one script, run with one command, kept in git, with package versions pinned. No notebook cells run out of order.
  • Settings: in a config file, a small file of named values, instead of numbers scattered through the code.
  • Data: a hash, a fingerprint of the file's bytes. SHA-256 turns any file into 64 hex characters. Change one byte and the hash changes completely, so the same hash means the same data.
  • Seeds: a seed is the starting number of a random generator. Fix it, and every "random" choice comes out the same on every run.

Then log every run. Experiment tracking keeps each run's settings, data hash, scores and files in one searchable log. This lesson uses MLflow with a local store, a single SQLite file. MLflow calls the settings parameters, the scores metrics and the saved files artifacts.

A small project looks like this:

credit/
├── config.json   settings and seeds, kept in git
├── train.py      the one command that trains
├── mlflow.db     the run log (MLflow's local store)
└── mlruns/       each run's saved files

A tiny example

Mini-batch training shuffles the rows every epoch (Day 32). Take two rows, (x,y)=(1,2)(x, y) = (1, 2) and (2,2)(2, 2), the model y^=wx\hat{y} = wx, and one row per step. Start at w=0w = 0 with learning rate 0.1. Each step moves ww by −0.1×2(wx−y)x-0.1 \times 2(wx - y)x.

Order Step 1 Step 2 Final ww
(1,2)(1, 2) first 0+0.1×4=0.40 + 0.1 \times 4 = 0.4 0.4+0.1×4.8=0.880.4 + 0.1 \times 4.8 = 0.88 0.88
(2,2)(2, 2) first 0+0.1×8=0.80 + 0.1 \times 8 = 0.8 0.8+0.1×2.4=1.040.8 + 0.1 \times 2.4 = 1.04 1.04

Same data, same settings, a different model. The shuffle order decided it, and the seed decides the order.

Try it

Run the same training twice

Training starts at w = 0, b = 0. Every epoch shuffles the 8 points and takes one step per batch. Change the batch size and the learning rate η and watch the loss curve.

0510050100steploss L (MSE, all points)

Dashed vertical lines mark the end of each epoch; the dashed curve is the previous run.

steps per epoch ⌈8 / 2⌉ = 43 epochs = 12 stepsfinal ŷ = 1.983·x + 0.52final L 1.487seed 42

The seed changes on every run.

The seed starts free. Press Run again: the dashed curve is the run before, and the final loss jumps from 1.487 to 3.187 with nothing else changed. Now press fix the seed, then Run again a few times: every run matches the last one exactly. Free the seed again, set the batch size to 8 and press Run again: every batch now holds all the points, so the shuffle has nothing left to change and the runs match anyway.

In code

train is the D28 model (Day 28) as a function of a config file. It hashes the data, trains, scores the test set and logs it all as one MLflow run. Every file it writes lands next to the script.

# script_id: day_044_reproducible_training/train
import hashlib
import json
import logging
import os
from pathlib import Path

os.environ["MLFLOW_DISABLE_AGENT_HINT"] = "1"           # silence an install hint
import mlflow
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split

logging.getLogger("mlflow").setLevel(logging.WARNING)   # hide MLflow's setup messages
HERE = Path(__file__).parent                            # every file this script writes goes here
DATA = Path(os.environ.get("ML_DATA", "datasets")) / "credit_default" / "default_of_credit_card_clients.csv"

def clean(X):                                           # D28's cleaning step
    X = X.copy()
    X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4})
    X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3})
    return X.astype(float)

def train(config_path, run_name):
    cfg = json.loads(Path(config_path).read_text())
    data_hash = hashlib.sha256(DATA.read_bytes()).hexdigest()
    df = pd.read_csv(DATA).drop(columns="ID").rename(columns={"default payment next month": "default"})
    X, y = clean(df.drop(columns="default")), df["default"]
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=cfg["test_size"], stratify=y,
                                              random_state=cfg["split_seed"])
    model = HistGradientBoostingClassifier(learning_rate=cfg["learning_rate"], random_state=cfg["model_seed"])
    p = model.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    metrics = {"pr_auc": average_precision_score(y_te, p), "roc_auc": roc_auc_score(y_te, p), "trees": model.n_iter_}
    with mlflow.start_run(run_name=run_name):
        mlflow.log_params({**cfg, "data_sha256": data_hash})
        mlflow.log_metrics(metrics)
        mlflow.log_artifact(str(config_path))
    return data_hash, metrics

There are two seeds. split_seed picks the test rows. model_seed picks the 10% of training rows that early stopping holds back (Day 25). Now run the same config twice, then once with model_seed 7, and read the runs back with search_runs. In a real project config.json sits in git; here the script writes it, so it runs as one file.

# script_id: day_044_reproducible_training/train
mlflow.set_tracking_uri(f"sqlite:///{HERE / 'mlflow.db'}")
if mlflow.get_experiment_by_name("credit-default") is None:
    mlflow.create_experiment("credit-default", artifact_location=(HERE / "mlruns").as_uri())
mlflow.set_experiment("credit-default")

config = HERE / "config.json"
for name, seed in [("run 1", 42), ("run 2", 42), ("run 3", 7)]:
    config.write_text(json.dumps({"test_size": 0.2, "split_seed": 42, "model_seed": seed, "learning_rate": 0.1}))
    data_hash, m = train(config, name)
    print(f"{name}: data {data_hash[:12]}  PR-AUC {m['pr_auc']:.17f}  trees {m['trees']}")

runs = mlflow.search_runs(experiment_names=["credit-default"], order_by=["start_time DESC"], max_results=3)
show = runs[["tags.mlflow.runName", "params.model_seed", "metrics.pr_auc", "metrics.roc_auc", "metrics.trees"]]
show.columns = ["run", "model_seed", "pr_auc", "roc_auc", "trees"]
print(show.astype({"trees": int}).round(3).to_string(index=False))
run 1: data 4edce6da569b  PR-AUC 0.55070265846146027  trees 65
run 2: data 4edce6da569b  PR-AUC 0.55070265846146027  trees 65
run 3: data 4edce6da569b  PR-AUC 0.55608437223475848  trees 55
  run model_seed  pr_auc  roc_auc  trees
run 3          7   0.556    0.777     55
run 2         42   0.551    0.781     65
run 1         42   0.551    0.781     65

Runs 1 and 2 agree to all 17 digits: same code, same data hash, same config. Run 3 changed only the seed, and its PR-AUC moved by 0.005. That is more than boosting's 0.003 lead over the random forest in D28. Without the log, run 3 would look like an improvement. The rerun explains the opening puzzle: seed 7 gives 0.556 and seed 42 gives 0.551, so a seed change alone moves the score that much.

Quick check

Quick check

1. Two runs have the same code, config and seeds, but different PR-AUC. What should you check first?

2. Why log the data's hash instead of its file name?

3. In the widget, the seed is free, the batch size is 2, and you run the same settings twice. What happens?

Next

Day 45 asks whether the test score itself can be trusted when production data arrives in time order and in groups.

Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).

Next · Day 45 · 7 minValidate for Production Data← Previous: Day 43 · Reinforcement Learning Basics
Not tapped yet