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 · Concept · 20 min · revision 2

Champion vs Challenger: Automated Promotion Gates

Build a promotion gate that re-scores the production model and three candidate models on the same current labelled set, compares them overall and per slice, estimates the noise in the gain with a paired bootstrap, and applies rules written in advance (minimum margin, interval above zero, slice guard-rails, minimum slice size) to promote one candidate and keep the champion against the other two.

Contentsand lesson path

What you will learn

  • Implement a promotion gate that compares a candidate model with the current production model on overall and slice metrics before it is registered for release.

01. Why it matters

A pipeline that retrains every week also produces a new model every week, and most of those models should not replace the one in production. Some are trained on broken data, some are no better, and some are better on average but worse for a group of customers that matters. The model in production is called the champion; a newly trained model that wants its place is a challenger. A promotion gate is the pipeline step that compares the two and decides, by rules written down in advance, whether the challenger is registered for release.

Without a gate, either a person decides by looking at a dashboard, which does not scale and is not consistent, or every new model goes straight to production. With a gate, a bad training run ends as a recorded "keep the champion" decision instead of an incident. In this lesson you build one in plain Python. You need Python 3.12 with NumPy, pandas, SciPy and scikit-learn; every script runs in a few seconds.

Terminal
mkdir promotion-gate && cd promotion-gate
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "numpy==2.5.5" "pandas==3.1.1" "scipy==1.18.1"
python -m pip install "scikit-learn==1.9.1"

02. Score both models on the same current data

data.py generates churn data for two periods. Six months ago (then), churn depended on tenure, fees and support calls. Now customers react more strongly to price, and store customers react strongly to bad service. models.py trains the champion on the old data and records the AUC it had on the old holdout when it was promoted. It then trains three challengers that stand for three runs of this week’s pipeline: fresh is a correct run on recent data, store_lost comes from a run where a broken join dropped 90% of the store customers, and stale comes from a run whose query read the old snapshot again. Finally it saves current.csv: 3,000 recent customers whose labels are known and that no model was trained on.

Python · data.py
"""Customer data for two periods: when the champion was trained, and now."""
import numpy as np
import pandas as pd

FEATURES = ["tenure_months", "monthly_fee", "support_calls", "channel"]


def customers(n: int, period: str, seed: int) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    channel = rng.choice(["online", "store", "partner"], n, p=[0.62, 0.33, 0.05])
    tenure = rng.integers(1, 73, n)
    fee = rng.normal(60, 18, n).round(2)
    calls = rng.poisson(1.2, n)
    store = (channel == "store").astype(float)
    if period == "then":
        logit = -1.0 + 0.6 * calls - 0.04 * tenure + 0.02 * (fee - 60)
    else:  # now: customers react more to price, and store customers to bad service
        logit = (-1.0 + 0.6 * calls - 0.04 * tenure + 0.045 * (fee - 60)
                 + store * (0.9 * calls - 0.6))
    churned = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    return pd.DataFrame({"tenure_months": tenure, "monthly_fee": fee,
                         "support_calls": calls, "channel": channel,
                         "churned": churned})
Python · models.py
import json
from pathlib import Path

import joblib
import numpy as np
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

from data import FEATURES, customers


def recipe():
    prep = make_column_transformer(
        (StandardScaler(), ["tenure_months", "monthly_fee", "support_calls"]),
        (OneHotEncoder(), ["channel"]))
    return make_pipeline(prep, LogisticRegression(max_iter=1000))


def fit(df):
    return recipe().fit(df[FEATURES], df["churned"])


Path("models").mkdir(exist_ok=True)
# Six months ago: the champion was trained and scored on the data of that time.
then_train, then_holdout = customers(4000, "then", 1), customers(2000, "then", 2)
champion = fit(then_train)
logged = roc_auc_score(then_holdout["churned"],
                       champion.predict_proba(then_holdout[FEATURES])[:, 1])
joblib.dump(champion, "models/champion.joblib")
Path("models/champion_card.json").write_text(json.dumps({"auc_at_promotion":
                                                          round(logged, 3)}))

# This week: three runs of the training pipeline produced three challengers.
recent = customers(4000, "now", 3)
lost = np.random.default_rng(5).random(len(recent)) < 0.9
challengers = {
    "fresh": fit(recent),                                       # correct run
    "store_lost": fit(recent[~((recent["channel"] == "store") & lost)]),  # bad join
    "stale": fit(customers(6000, "then", 11)),                  # read old snapshot
}
for name, model in challengers.items():
    joblib.dump(model, f"models/{name}.joblib")
customers(3000, "now", 4).to_csv("current.csv", index=False)   # labelled, unseen
print("champion logged AUC at promotion:", round(logged, 3))
print("saved:", ", ".join(["champion"] + list(challengers)), "and current.csv")
Terminal
python models.py
Expected output
champion logged AUC at promotion: 0.753
saved: champion, fresh, store_lost, stale and current.csv

Now compare the fresh challenger with the champion in two ways: against the number in the champion’s record, and against the champion re-scored on current.csv.

Python · same_set.py
import json

import joblib
import pandas as pd
from sklearn.metrics import roc_auc_score

from data import FEATURES

current = pd.read_csv("current.csv")
logged = json.load(open("models/champion_card.json"))["auc_at_promotion"]


def auc_now(name):
    model = joblib.load(f"models/{name}.joblib")
    p = model.predict_proba(current[FEATURES])[:, 1]
    return roc_auc_score(current["churned"], p)


champion, fresh = auc_now("champion"), auc_now("fresh")
print(f"fresh challenger, current set     {fresh:.3f}")
print(f"champion, logged at promotion     {logged:.3f}  gain {fresh - logged:+.3f}")
print(f"champion, re-scored, current set  {champion:.3f}  gain {fresh - champion:+.3f}")
Terminal
python same_set.py
Expected output
fresh challenger, current set     0.817
champion, logged at promotion     0.753  gain +0.064
champion, re-scored, current set  0.805  gain +0.012

Against the logged number, the challenger seems to gain 0.064 AUC. Against the champion on the same rows, it gains 0.012. The champion did not get better in six months; the data changed, and the current customers happen to be easier to rank. The two numbers in the first comparison measure different populations, so their difference mixes the effect of the model with the effect of the data. Only scores on the same rows isolate the model. The same rule applies the other way round: when data gets harder, comparing with a logged score makes every challenger look worse than it is.

The current set must also have complete labels. If churn is only known 60 days after a customer is scored, the newest usable rows are those scored at least 60 days ago; counting the unlabelled rows as "not churned" would bias every metric. And it must be new to every model being compared: rows that any model was trained or tuned on make that model look better than it is.

03. Overall metrics hide slices

A slice is a subset of rows that share a property, such as a sales channel, a country or a customer age band. An overall metric is dominated by the largest slices, so an improvement on a big slice can hide a loss on a smaller one. slices.py scores all four models once on the current set and builds a table of AUC overall and per channel.

Python · slices.py
import joblib
import pandas as pd
from sklearn.metrics import roc_auc_score

from data import FEATURES

NAMES = ["champion", "fresh", "store_lost", "stale"]


def score_all(df):
    """Probabilities of every model on the same rows."""
    return {n: joblib.load(f"models/{n}.joblib").predict_proba(df[FEATURES])[:, 1]
            for n in NAMES}


def slice_table(df, probs, by="channel"):
    rows = {"overall": {n: roc_auc_score(df["churned"], p) for n, p in probs.items()}}
    for value, idx in df.groupby(by).groups.items():
        g = df.loc[idx]
        rows[value] = {n: roc_auc_score(g["churned"], p[idx]) for n, p in probs.items()}
    table = pd.DataFrame(rows).T.round(3)
    sizes = [len(i) for i in df.groupby(by).groups.values()]
    table.insert(0, "rows", [len(df)] + sizes)
    return table


if __name__ == "__main__":
    current = pd.read_csv("current.csv")
    print(slice_table(current, score_all(current)).to_string())
Terminal
python slices.py
Expected output
         rows  champion  fresh  store_lost  stale
overall  3000     0.805  0.817       0.809  0.806
online   1846     0.791  0.797       0.801  0.787
partner   165     0.725  0.753       0.752  0.726
store     989     0.843  0.853       0.827  0.846

store_lost is slightly better than the champion overall (0.809 against 0.805) and better on online customers, but it falls from 0.843 to 0.827 on the store channel, the slice its training run lost. A gate that looks only at the overall row would promote a model that serves one customer in three worse. A guard-rail is a rule that a challenger may not make any important slice worse by more than a set amount, whatever it does overall. Choose the slices with the business before you see results: segments with different behaviour, segments where errors are costly, and groups you must treat fairly.

04. Is the gain bigger than the noise?

A metric computed on 3,000 rows would change on another 3,000 rows, even with the same models. A bootstrap estimates that variation from the data you have: draw rows with replacement to make a resample of the same size, recompute the statistic, repeat 1,000 times and read off the middle 95% of the results. For a comparison, use a paired bootstrap: each resample is scored by both models, and you record the difference. The two models make many of the same mistakes on the same hard rows, and pairing cancels that shared part, so the interval for the difference is much narrower than two separate intervals would suggest. fast_auc computes AUC from ranks, which gives the same value as roc_auc_score (the script asserts it) and keeps 6,000 AUC computations to a few seconds.

Python · bootstrap.py
import numpy as np
import pandas as pd
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score

from slices import score_all


def fast_auc(y, p):
    """AUC from ranks (Mann-Whitney U); equal to roc_auc_score, much faster."""
    pos = y == 1
    n_pos, n_neg = pos.sum(), len(y) - pos.sum()
    return (rankdata(p)[pos].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)


def paired_bootstrap(y, p_new, p_old, n_boot=1000, seed=0):
    """95% interval for AUC(new) - AUC(old), resampling the same rows for both."""
    rng = np.random.default_rng(seed)
    y, diffs = np.asarray(y), []
    for _ in range(n_boot):
        i = rng.integers(0, len(y), len(y))           # one resample, used by both
        diffs.append(fast_auc(y[i], p_new[i]) - fast_auc(y[i], p_old[i]))
    return np.percentile(diffs, [2.5, 97.5])


def auc_interval(y, p, n_boot=1000, seed=0):
    """95% interval for the AUC of one model on these rows."""
    rng = np.random.default_rng(seed)
    draws = (rng.integers(0, len(y), len(y)) for _ in range(n_boot))
    return np.percentile([fast_auc(y[i], p[i]) for i in draws], [2.5, 97.5])


if __name__ == "__main__":
    current = pd.read_csv("current.csv")
    probs = score_all(current)
    y = current["churned"].to_numpy()
    assert abs(fast_auc(y, probs["fresh"]) - roc_auc_score(y, probs["fresh"])) < 1e-12
    for name in ["fresh", "store_lost", "stale"]:
        gain = roc_auc_score(y, probs[name]) - roc_auc_score(y, probs["champion"])
        lo, hi = paired_bootstrap(y, probs[name], probs["champion"])
        moved = np.abs(probs[name] - probs["champion"]).mean()   # how different
        print(f"{name:<11} gain {gain:+.3f}   95% interval [{lo:+.3f}, {hi:+.3f}]"
              f"   mean change in p {moved:.3f}")
    for value in ["store", "partner"]:
        rows = (current["channel"] == value).to_numpy()
        lo, hi = auc_interval(y[rows], probs["champion"][rows])
        print(f"champion AUC on {value} ({rows.sum()} rows): 95% interval "
              f"[{lo:.3f}, {hi:.3f}]")
Terminal
python bootstrap.py
Expected output
fresh       gain +0.012   95% interval [+0.004, +0.020]   mean change in p 0.068
store_lost  gain +0.004   95% interval [-0.003, +0.011]   mean change in p 0.055
stale       gain +0.001   95% interval [-0.001, +0.003]   mean change in p 0.010
champion AUC on store (989 rows): 95% interval [0.817, 0.868]
champion AUC on partner (165 rows): 95% interval [0.627, 0.819]

The fresh challenger gains 0.012 with an interval from +0.004 to +0.020: the whole interval lies above zero, so the gain is unlikely to be noise. The interval for stale runs from −0.001 to +0.003, so its gain of 0.001 cannot be told apart from no change. That interval is narrow because stale changes the champion’s probabilities by only 0.010 on average: the two models rank customers almost identically on every resample, so their difference hardly varies. The last two lines show why slices need a minimum size. The champion’s AUC on 989 store customers is known within about ±0.025, but on 165 partner customers the interval spans almost 0.2. A guard-rail of 0.01 on such a slice would fire, or stay silent, mostly by chance.

05. The gate: rules written before the results

gate.py puts the pieces together. The rules sit at the top as data, so they are reviewed like code and cannot be bent after someone sees a result they like. A challenger is promoted only if its overall gain reaches a minimum margin (0.005 AUC, the smallest improvement worth a release), the paired interval lies above zero, and no slice with at least 200 rows loses more than 0.01. Smaller slices are reported for a person to look at. Every decision is saved with its reasons and the rules that produced it.

Python · gate.py
import json

import pandas as pd

from bootstrap import fast_auc, paired_bootstrap
from slices import score_all, slice_table

GATE = {                      # written down before anyone sees the numbers
    "min_gain": 0.005,        # overall AUC must improve by at least this much
    "ci_lower_above": 0.0,    # and the paired 95% interval must exclude no change
    "max_slice_drop": 0.010,  # no slice may lose more AUC than this
    "min_slice_rows": 200,    # slices smaller than this are reported, not gated
}


def decide(name, current, probs, table):
    y = current["churned"].to_numpy()
    gain = fast_auc(y, probs[name]) - fast_auc(y, probs["champion"])
    lo, _ = paired_bootstrap(y, probs[name], probs["champion"])
    reasons = []
    if gain < GATE["min_gain"]:
        reasons.append(f"gain {gain:+.3f} below margin {GATE['min_gain']}")
    if lo <= GATE["ci_lower_above"]:
        reasons.append(f"interval starts at {lo:+.3f}: no change is still plausible")
    for value, row in table.drop(index="overall").iterrows():
        drop = row["champion"] - row[name]
        if row["rows"] < GATE["min_slice_rows"]:
            reasons.append(f"note: {value} slice has {row['rows']:.0f} rows, not gated")
        elif drop > GATE["max_slice_drop"]:
            reasons.append(f"{value} slice AUC falls by {drop:.3f}")
    blocking = [r for r in reasons if not r.startswith("note:")]
    return {"challenger": name, "promote": not blocking, "reasons": reasons}


current = pd.read_csv("current.csv")
probs = score_all(current)
table = slice_table(current, probs)
for name in ["fresh", "store_lost", "stale"]:
    result = decide(name, current, probs, table)
    print(f"{name}: {'PROMOTE' if result['promote'] else 'KEEP CHAMPION'}")
    for reason in result["reasons"]:
        print(f"  - {reason}")
    with open(f"gate_{name}.json", "w") as f:            # the audit record
        json.dump({**result, "gate": GATE}, f, indent=1)
Terminal
python gate.py
Expected output
fresh: PROMOTE
  - note: partner slice has 165 rows, not gated
store_lost: KEEP CHAMPION
  - gain +0.004 below margin 0.005
  - interval starts at -0.003: no change is still plausible
  - note: partner slice has 165 rows, not gated
  - store slice AUC falls by 0.016
stale: KEEP CHAMPION
  - gain +0.001 below margin 0.005
  - interval starts at -0.001: no change is still plausible
  - note: partner slice has 165 rows, not gated

Each bad run is stopped for its own reason. stale is blocked by the margin and the interval. store_lost is blocked three times, and even if someone lowered the margin, the store guard-rail would still stop it. The fresh challenger passes, and in a real pipeline the next step registers it as a new version and moves the production alias to it, as the model registry lesson shows. Real gates often add rules that are not about accuracy: prediction latency, model size, or calibration at the operating threshold.

One trap remains. If the team keeps trying challengers until one passes on the same current set, the set slowly becomes a tuning set: the best of twenty tries looks better than it really is, a problem known as the winner’s curse. Refresh the current set regularly and keep it out of every tuning loop.

06. Check your understanding

Practice check · 3 questions

Designing the gate

Use the scripts and outputs of this lesson.

Q1. In `bootstrap.py`, `stale` has a much narrower interval than `store_lost` ([−0.001, +0.003] against [−0.003, +0.011]). What explains that?
Q2. Each week the team trains challengers until one passes the gate on the same current set, then promotes it. What is the main risk?
Q3. Churn is only known 60 days after a customer is scored. Which rows can the gate use as its current set?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice project requires a deliberately worse model to be rejected. Add a gate task to your pipeline.

  1. Agree the metric, the minimum margin, the slices and their guard-rails with the people who own the model, and write them into a GATE dictionary before you run anything.
  2. Load the current champion from your registry and score it and the challenger on the same recent, labelled set that neither was trained on.
  3. Train a deliberately worse challenger (drop a slice from its training data, as store_lost does) and show that the gate keeps the champion and saves a decision record with its reasons.

08. Review prompt

Without looking back, explain why the champion’s logged score cannot stand in for its score today; describe what a slice guard-rail protects against and how you would choose the slices; explain how a paired bootstrap works and why pairing narrows the interval; list the four rules of GATE; and say what the winner’s curse is and how to avoid 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