Lab 11 &12¶
Production ML: A/B Testing, Redeployment, Covariate Shift & Automated Retraining¶
Simulated rideshare traffic · scikit-learn · CPU only
Your tip-prediction model is live. In this lab you will decide whether a new model is really better, roll it out safely, notice when the world changes underneath it, and retrain it automatically.
Read → Run → Measure → Complete the TODOs. Run the demonstrations, then complete the eight TODOs and the final challenge. Rerun every cell on your machine; your numbers will be close to, but not exactly, the ones quoted in the text.
Everything runs offline in a normal Jupyter or Kaggle notebook. The "production traffic" is simulated inside the notebook, so you do not need a cloud account, Docker, or any download.
Lab map¶
| Part | Topic | TODOs |
|---|---|---|
| 1 | The production world: simulator, model registry, traffic router | — |
| 2 | A/B testing a new model | 1 – 3 |
| 3 | Safe redeployment: shadow, canary, rollback | 4 |
| 4 | Detecting covariate shift | 5 – 6 |
| 5 | Managing shift and automated retraining | 7 – 8 |
| — | Final challenge: monsoon with delayed labels | challenge |
Prerequisites: pandas, scikit-learn and the model-versioning ideas from Lab 6 (model cards, promote/rollback).
Set up the environment¶
The lab needs only NumPy, pandas, matplotlib, SciPy, scikit-learn and joblib, which are pre-installed on Kaggle and in most Python environments. Set INSTALL_PACKAGES = True only if an import in the next cell fails.
INSTALL_PACKAGES = False
if INSTALL_PACKAGES:
import subprocess, sys
subprocess.check_call([sys.executable, "-m", "pip", "install",
"numpy", "pandas", "matplotlib", "scipy", "scikit-learn", "joblib"])
import json, time, shutil, hashlib, warnings
from pathlib import Path
import importlib.metadata as metadata
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import joblib
from scipy import stats
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_predict
from sklearn.metrics import accuracy_score, roc_auc_score
from IPython.display import display
warnings.filterwarnings("ignore")
SEED = 203
np.random.seed(SEED)
ARTIFACTS = Path("lab8_artifacts")
if ARTIFACTS.exists():
shutil.rmtree(ARTIFACTS) # start every run with an empty model registry
ARTIFACTS.mkdir()
versions = {p: metadata.version(p) for p in ["numpy", "pandas", "scipy", "scikit-learn", "joblib"]}
print("Versions:", versions)
Versions: {'numpy': '2.1.3', 'pandas': '2.3.3', 'scipy': '1.16.3', 'scikit-learn': '1.6.1', 'joblib': '1.6.0'}
Part 1 · The production world¶
Simulate the rideshare traffic¶
We continue with the Gujarat rideshare app from Lab Evaluation 2. For every ride the app predicts whether the rider will tip (tipped = 1), so it can decide when to show the tip screen.
simulate_rides(n, week, seed) generates one week of ride requests. From week 4 the monsoon arrives: more people take cabs for long trips, waits get longer and surge pricing becomes common. The monsoon(week) intensity ramps from 0 to 1 over weeks 4–7 and then stays at 1.
The rule that decides whether a rider tips, tip_probability(...), never changes. Only the mix of inputs changes. This is covariate shift.
| Kind of shift | What changes | Example in this app |
|---|---|---|
| Covariate shift | $P(x)$ changes, $P(y \mid x)$ stays the same | Monsoon → many more long rides |
| Label (prior) shift | $P(y)$ changes, $P(x \mid y)$ stays the same | Festival week → everyone tips more |
| Concept drift | $P(y \mid x)$ changes | A redesigned tip screen changes rider behaviour |
FEATURES = ["distance_km", "fare", "wait_min", "surge", "hour", "driver_rating"]
TARGET = "tipped"
def monsoon(week):
"""Monsoon intensity: 0 up to week 3, ramps up over weeks 4-7, then stays at 1."""
return float(np.clip((week - 3) / 4, 0, 1))
def tip_probability(distance, wait, surge, hour, rating):
"""The 'true' tipping rule of riders. It does NOT depend on the week."""
evening = ((hour >= 18) | (hour <= 2)).astype(float)
rush = ((hour >= 8) & (hour <= 10)).astype(float)
logit = (-0.3 + 1.5 * (rating - 4.3) / 0.4 - 0.12 * (wait - 7)
+ 0.30 * (distance - 5) - 0.12 * np.maximum(distance - 13, 0) ** 2
+ 1.3 * evening - 1.6 * rush - 0.4 * surge)
return 1 / (1 + np.exp(-logit))
def simulate_rides(n, week=0, seed=0, season=None):
"""One week of ride requests. `season` overrides monsoon(week) if given (0..1)."""
rng = np.random.default_rng(seed)
m = monsoon(week) if season is None else season
distance = np.round(rng.gamma(2.2, 1.8 * (1 + 2.0 * m), n) + 0.5, 2)
surge = rng.binomial(1, 0.20 + 0.40 * m, n)
fare = np.round(25 + 12 * distance * (1 + 0.5 * surge) + rng.normal(0, 8, n), 2)
wait = np.round(rng.gamma(2.0, 3.0 * (1 + 0.5 * m), n) + 1, 1)
hour = rng.integers(0, 24, n)
rating = np.round(np.clip(rng.normal(4.3, 0.4, n), 2.5, 5.0), 1)
tipped = rng.binomial(1, tip_probability(distance, wait, surge, hour, rating))
return pd.DataFrame({
"request_id": [f"W{week:02d}-{seed}-{i:05d}" for i in range(n)],
"user_id": rng.integers(1, 5001, n), "week": week,
"distance_km": distance, "fare": fare, "wait_min": wait, "surge": surge,
"hour": hour, "driver_rating": rating, TARGET: tipped})
week0 = simulate_rides(3000, week=0, seed=11)
week8 = simulate_rides(3000, week=8, seed=12)
display(week0.head())
display(pd.DataFrame({"week 0 (dry)": week0[FEATURES + [TARGET]].mean(),
"week 8 (monsoon)": week8[FEATURES + [TARGET]].mean()}).round(2))
fig, axes = plt.subplots(1, 3, figsize=(13, 3))
for ax, col in zip(axes, ["distance_km", "wait_min", "surge"]):
ax.hist(week0[col], bins=30, alpha=0.6, density=True, label="week 0")
ax.hist(week8[col], bins=30, alpha=0.6, density=True, label="week 8")
ax.set_title(col); ax.legend()
plt.tight_layout(); plt.show()
| request_id | user_id | week | distance_km | fare | wait_min | surge | hour | driver_rating | tipped | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | W00-11-00000 | 2125 | 0 | 3.94 | 72.93 | 4.0 | 0 | 20 | 4.2 | 0 |
| 1 | W00-11-00001 | 4520 | 0 | 7.86 | 160.40 | 8.0 | 1 | 12 | 5.0 | 1 |
| 2 | W00-11-00002 | 532 | 0 | 3.18 | 85.52 | 2.0 | 1 | 7 | 3.9 | 0 |
| 3 | W00-11-00003 | 1013 | 0 | 5.46 | 95.25 | 6.0 | 0 | 8 | 4.2 | 0 |
| 4 | W00-11-00004 | 1405 | 0 | 6.05 | 130.52 | 4.0 | 1 | 13 | 4.6 | 0 |
| week 0 (dry) | week 8 (monsoon) | |
|---|---|---|
| distance_km | 4.55 | 12.55 |
| fare | 85.10 | 220.96 |
| wait_min | 6.97 | 10.02 |
| surge | 0.20 | 0.60 |
| hour | 11.65 | 11.52 |
| driver_rating | 4.30 | 4.30 |
| tipped | 0.48 | 0.48 |
Syntax clarity:
np.random.default_rng(seed)rng = np.random.default_rng(seed) rng.gamma(2.2, 1.8, n); rng.binomial(1, 0.2, n); rng.integers(0, 24, n)
default_rngcreates an independent random generator. The sameseedalways gives the same "week" of data, regardless of what other cells ran before. That is why the lab passes a different seed for every simulated week.np.maximum(distance - 13, 0)works element by element: it is 0 for rides up to 13 km and grows for longer rides. Long rides (≥ 13 km) are flat-fare intercity trips, where tips drop sharply. Remember this; it matters in Part 4.
Train the first two models¶
Train both models on week 0 (6,000 rides), holding out 20% as an offline validation set:
- v1:
StandardScaler+LogisticRegression, the model currently in production. - v2:
HistGradientBoostingClassifier, a candidate that a teammate says is better.
train_df = simulate_rides(6000, week=0, seed=1)
fit_df, val_df = train_test_split(train_df, test_size=0.2, random_state=SEED, stratify=train_df[TARGET])
def make_v1():
return make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
def make_v2():
return HistGradientBoostingClassifier(max_depth=3, learning_rate=0.05, max_iter=200, random_state=SEED)
v1 = make_v1().fit(fit_df[FEATURES], fit_df[TARGET])
v2 = make_v2().fit(fit_df[FEATURES], fit_df[TARGET])
offline = {name: accuracy_score(val_df[TARGET], m.predict(val_df[FEATURES])) for name, m in [("v1", v1), ("v2", v2)]}
print("Offline validation accuracy:", {k: round(v, 4) for k, v in offline.items()})
Offline validation accuracy: {'v1': 0.7267, 'v2': 0.7642}
Keep models in a model registry¶
This is the Lab 6 idea in miniature. Every version gets a folder holding model.joblib and a model_card.json. One file, registry.json, records which version is in production and keeps a history of every promotion and rollback.
A redeployment then means changing one pointer, and a rollback means changing it back.
REGISTRY = ARTIFACTS / "registry"
def register_model(model, version, metrics, train_weeks, notes=""):
folder = REGISTRY / version
folder.mkdir(parents=True, exist_ok=True)
joblib.dump(model, folder / "model.joblib")
card = {"version": version, "model_class": type(model).__name__, "features": FEATURES,
"train_weeks": train_weeks, "metrics": metrics, "notes": notes,
"registered_at": time.strftime("%Y-%m-%d %H:%M:%S")}
(folder / "model_card.json").write_text(json.dumps(card, indent=2))
return card
def load_model(version):
return joblib.load(REGISTRY / version / "model.joblib")
def read_registry():
path = REGISTRY / "registry.json"
return json.loads(path.read_text()) if path.exists() else {"production": None, "history": []}
def set_production(version, reason):
reg = read_registry()
reg["history"].append({"time": time.strftime("%H:%M:%S"), "from": reg["production"],
"to": version, "reason": reason})
reg["production"] = version
(REGISTRY / "registry.json").write_text(json.dumps(reg, indent=2))
return reg
register_model(v1, "v1", {"offline_val_acc": round(offline["v1"], 4)}, [0], "scaler + logistic regression")
register_model(v2, "v2", {"offline_val_acc": round(offline["v2"], 4)}, [0], "hist gradient boosting")
set_production("v1", "initial deployment")
print(json.dumps(read_registry(), indent=2))
{
"production": "v1",
"history": [
{
"time": "11:09:45",
"from": null,
"to": "v1",
"reason": "initial deployment"
},
{
"time": "11:11:35",
"from": "v1",
"to": "v1",
"reason": "initial deployment"
}
]
}
Route traffic between models¶
A router decides which model answers each request. For experiments, the assignment must be:
- random, so the two groups are comparable,
- sticky, so the same user always sees the same model (otherwise one rider gets a mix of both experiences),
- independent across experiments, so being in the treatment group of one test says nothing about the next.
Hashing the user id with an experiment-specific salt gives all three properties without storing a lookup table.
def bucket(user_id, salt):
"""Stable pseudo-random bucket 0..99 for a user within one experiment."""
digest = hashlib.md5(f"{salt}:{user_id}".encode()).hexdigest()
return int(digest[:8], 16) % 100
class Router:
def __init__(self, control_version, candidate_version=None, candidate_pct=0, salt="exp"):
self.control_version = control_version
self.candidate_version = candidate_version
self.candidate_pct = candidate_pct
self.salt = salt
self.models = {"control": load_model(control_version)}
if candidate_version is not None:
self.models["candidate"] = load_model(candidate_version)
def assign(self, user_id):
if self.candidate_version is not None and bucket(user_id, self.salt) < self.candidate_pct:
return "candidate"
return "control"
def serve(self, requests):
"""Predict for a batch of requests; returns a prediction log (no labels yet)."""
log = requests[["request_id", "user_id", "week"]].copy()
log["variant"] = [self.assign(u) for u in requests["user_id"]]
log["model_version"] = log["variant"].map({"control": self.control_version,
"candidate": self.candidate_version})
log["prediction"] = -1
for variant, model in self.models.items():
mask = (log["variant"] == variant).to_numpy()
if mask.any():
log.loc[mask, "prediction"] = model.predict(requests.loc[mask, FEATURES])
return log
def attach_outcomes(log, requests):
"""Labels arrive later (after the ride). Join them to the prediction log."""
out = log.merge(requests[["request_id", TARGET]], on="request_id")
out["correct"] = (out["prediction"] == out[TARGET]).astype(int)
return out
def summarize(log):
return log.groupby("variant").agg(requests=("request_id", "size"), users=("user_id", "nunique"),
accuracy=("correct", "mean")).round(4)
# Demonstration: production only (no candidate) for one week
router = Router("v1")
reqs = simulate_rides(4000, week=1, seed=21)
log = attach_outcomes(router.serve(reqs), reqs)
display(log.head())
display(summarize(log))
| request_id | user_id | week | variant | model_version | prediction | tipped | correct | |
|---|---|---|---|---|---|---|---|---|
| 0 | W01-21-00000 | 2723 | 1 | control | v1 | 1 | 1 | 1 |
| 1 | W01-21-00001 | 4396 | 1 | control | v1 | 1 | 0 | 0 |
| 2 | W01-21-00002 | 3436 | 1 | control | v1 | 0 | 0 | 1 |
| 3 | W01-21-00003 | 3381 | 1 | control | v1 | 0 | 0 | 1 |
| 4 | W01-21-00004 | 3214 | 1 | control | v1 | 0 | 0 | 1 |
| requests | users | accuracy | |
|---|---|---|---|
| variant | |||
| control | 4000 | 2743 | 0.73 |
Syntax clarity:
hashlib.md5(...).hexdigest()andint(x, 16)
f"{salt}:{user_id}".encode()turns the string into bytes, andmd5hashes them. The same input always gives the same 32-character hex string, and a tiny change (a different salt) gives an unrelated one.int(digest[:8], 16)reads the first 8 hex characters as a base-16 integer (0 to about 4.3 billion), and% 100maps it to a bucket from 0 to 99. A user goes to the candidate whenbucket < candidate_pct.- MD5 is fine here because we need speed and uniformity, not security.
Part 2 · A/B testing a new model¶
Offline, v2 beats v1 by about 4 percentage points. Offline is not online: the validation set could be stale, the serving code could differ, and real users could react differently. An A/B test settles the question on live traffic.
| Step | What you do |
|---|---|
| 1 | Fix the hypothesis and one primary metric before starting (here: prediction accuracy, the share of correct tip predictions) |
| 2 | Compute the sample size needed to detect the smallest difference you care about |
| 3 | Split traffic randomly and stickily between control (A) and candidate (B) |
| 4 | Run until the planned sample size is reached. Do not stop early because the numbers look good |
| 5 | Test significance and report a confidence interval |
| 6 | Decide: ship, do not ship, or extend the test |
TODO 1 · Check the traffic assignment¶
Before trusting an experiment, check the assignment itself. For users 1 … 5000 and Router("v1", "v2", candidate_pct=50, salt="ab-v1-v2"), compute and print:
- The fraction of users assigned to
"candidate"(it should be close to 0.50). - Stickiness: call
assignthree times for every user and confirm that all three answers are identical for every user. - The fraction of users whose variant changes when you use the salt
"ab-v1-v3"instead (it should be about 0.50). In one comment, explain why every experiment gets its own salt. - The candidate fraction when
candidate_pct=10.
Hints: use a list comprehension over range(1, 5001) and np.mean. Build a second Router for each salt or percentage.
Check: the asserts in the cell pass once you set the flag to True.
users = range(1, 5001)
assignment_check = {
"candidate_fraction_50": None, # TODO
"sticky": None, # TODO: True/False
"changed_with_new_salt": None, # TODO
"candidate_fraction_10": None, # TODO
}
# TODO: implement the four checks above.
# Why does every experiment get its own salt? ->
if False: # set True after implementing
assert 0.47 < assignment_check["candidate_fraction_50"] < 0.53
assert assignment_check["sticky"] is True
assert 0.45 < assignment_check["changed_with_new_salt"] < 0.55
assert 0.08 < assignment_check["candidate_fraction_10"] < 0.12
print(assignment_check)
Run the A/B test¶
Register the experiment, then route 50% of users to v2 for two weeks of traffic (weeks 1–2, 4,000 rides per week). Labels arrive after each ride, so you can join them to the prediction log and compare the two variants.
ab_router = Router("v1", "v2", candidate_pct=50, salt="ab-v1-v2")
ab_logs = []
for week in [1, 2]:
reqs = simulate_rides(4000, week=week, seed=100 + week)
ab_logs.append(attach_outcomes(ab_router.serve(reqs), reqs))
ab_log = pd.concat(ab_logs, ignore_index=True)
ab_log.to_csv(ARTIFACTS / "ab_test_log.csv", index=False)
ab_summary = summarize(ab_log)
display(ab_summary)
| requests | users | accuracy | |
|---|---|---|---|
| variant | |||
| candidate | 3987 | 1984 | 0.7698 |
| control | 4013 | 1978 | 0.7396 |
Is the difference real?¶
Each prediction is either correct or not, so each variant has a proportion of correct predictions: $\hat p_A = x_A/n_A$ and $\hat p_B = x_B/n_B$. The two-proportion z-test asks whether the gap could be just noise.
$$\hat p = \frac{x_A + x_B}{n_A + n_B}, \qquad z = \frac{\hat p_B - \hat p_A}{\sqrt{\hat p(1-\hat p)\left(\frac{1}{n_A} + \frac{1}{n_B}\right)}}, \qquad \text{p-value} = 2\,\big(1 - \Phi(|z|)\big)$$
The 95% confidence interval for the difference uses the unpooled standard error:
$$(\hat p_B - \hat p_A) \pm 1.96\sqrt{\frac{\hat p_A(1-\hat p_A)}{n_A} + \frac{\hat p_B(1-\hat p_B)}{n_B}}$$
$\Phi$ is the standard normal CDF: stats.norm.cdf. A small p-value (< α = 0.05) means a gap this large would be unlikely if the models were equally good.
TODO 2 · Implement the two-proportion z-test¶
Implement two_proportion_ztest(x_a, n_a, x_b, n_b, alpha=0.05). It should return a dict with p_a, p_b, diff, z, p_value, ci_low, ci_high and significant.
Then apply it to ab_log (A = control, B = candidate) and print a one-line decision: ship v2 or not.
Hints: stats.norm.cdf, stats.norm.ppf(1 - alpha/2) (≈ 1.96 for α = 0.05) and np.sqrt. Count successes with ab_log.groupby("variant")["correct"].sum().
Check: for 520/1000 vs 560/1000 the expected answer is z ≈ 1.79 and p ≈ 0.073. A chi-square test without continuity correction gives χ² = z² and the same p-value.
def two_proportion_ztest(x_a, n_a, x_b, n_b, alpha=0.05):
# TODO: implement the formulas above
raise NotImplementedError("TODO 2")
if False: # set True after implementing
ref = two_proportion_ztest(520, 1000, 560, 1000)
assert abs(ref["z"] - 1.7946) < 1e-3 and abs(ref["p_value"] - 0.0727) < 1e-3
chi2, p_chi2, _, _ = stats.chi2_contingency([[520, 480], [560, 440]], correction=False)
assert abs(chi2 - ref["z"] ** 2) < 1e-6 and abs(p_chi2 - ref["p_value"]) < 1e-9
print("Reference check passed:", {k: round(v, 4) for k, v in ref.items() if k != "significant"})
# TODO: apply to ab_log and print the decision
TODO 3 · Plan the sample size, and see why you must not peek¶
(a) Sample size. Implement sample_size_per_arm(p_a, p_b, alpha=0.05, power=0.8):
$$n = \left\lceil \frac{\left(z_{1-\alpha/2} + z_{\text{power}}\right)^2\,\big(p_a(1-p_a) + p_b(1-p_b)\big)}{(p_b - p_a)^2} \right\rceil$$
Print n for detecting 0.73 → 0.76 and 0.73 → 0.74. How many weeks of traffic (4,000 rides per week, split 50/50) does each one need?
(b) Peeking. Simulate 300 A/A tests, where both arms use the same model, so any "significant" result is a false positive. Simulate each request's correctness directly as Bernoulli(0.73) and use 4,000 requests per arm.
- Honest analyst: tests once, at the end.
- Peeking analyst: tests after every 250 requests per arm and stops at the first p < 0.05.
Print both false-positive rates. Explain in one comment why they differ.
Hints: rng.binomial(1, 0.73, size=4000); np.cumsum gives the success counts at every checkpoint; reuse two_proportion_ztest.
Check: the honest rate should be close to 5%. The peeking rate should be several times larger.
def sample_size_per_arm(p_a, p_b, alpha=0.05, power=0.8):
# TODO
raise NotImplementedError("TODO 3a")
# TODO 3a: print n for 0.73->0.76 and 0.73->0.74, and the weeks of traffic needed
# TODO 3b: A/A simulation, honest vs peeking false-positive rates
aa_result = {"honest_fpr": None, "peeking_fpr": None}
# Why do they differ? ->
Part 3 · Safe redeployment¶
Winning an A/B test does not make the rollout safe. The new model still has to be deployed without hurting users if something breaks.
| Strategy | How it works | Rollback |
|---|---|---|
| Big-bang | Replace the old model for 100% of traffic at once | Slow and painful |
| Blue–green | Run old (blue) and new (green) side by side, then switch the router | Flip the pointer back |
| Shadow (dark launch) | New model sees real traffic, but its predictions are only logged, never used | Nothing to roll back |
| Canary | Send 5% → 25% → 50% → 100% of traffic, checking guardrail metrics at each stage | Automatic, at the failing stage |
The registry's production pointer and the router's candidate_pct are all we need for blue–green, canary and rollback.
Shadow-deploy a buggy model¶
A teammate retrained the model and registered it as v3. Offline it looks great. However, the new serving code sends the features in the wrong order. That kind of bug never shows up in an offline notebook evaluation.
A shadow deployment runs v3 on real requests next to production and compares the two sets of predictions before any user sees them.
class ColumnOrderBug:
"""Wraps a model; simulates serving code that sends the features in reverse order."""
def __init__(self, model):
self.model = model
def predict(self, X):
X_bad = X[FEATURES[::-1]].copy()
X_bad.columns = FEATURES # same column names, wrong values!
return self.model.predict(X_bad)
v3_core = HistGradientBoostingClassifier(max_depth=4, learning_rate=0.05, max_iter=300,
random_state=SEED).fit(fit_df[FEATURES], fit_df[TARGET])
v3_offline = accuracy_score(val_df[TARGET], v3_core.predict(val_df[FEATURES]))
register_model(ColumnOrderBug(v3_core), "v3", {"offline_val_acc": round(v3_offline, 4)}, [0],
"deeper boosting (serving code has a column-order bug)")
print("v3 offline validation accuracy (evaluated WITHOUT the serving bug):", round(v3_offline, 4))
def shadow_compare(prod_version, shadow_version, requests):
prod, shadow = load_model(prod_version), load_model(shadow_version)
t0 = time.perf_counter(); p = prod.predict(requests[FEATURES]); t_prod = time.perf_counter() - t0
t0 = time.perf_counter(); s = shadow.predict(requests[FEATURES]); t_shadow = time.perf_counter() - t0
return {"agreement": float(np.mean(p == s)),
"prod_ms_per_1k": 1000 * t_prod / len(requests) * 1000,
"shadow_ms_per_1k": 1000 * t_shadow / len(requests) * 1000,
"prod_acc_after_labels": accuracy_score(requests[TARGET], p),
"shadow_acc_after_labels": accuracy_score(requests[TARGET], s)}
reqs = simulate_rides(4000, week=3, seed=301)
display(pd.DataFrame([{"shadow": "v2", **shadow_compare("v1", "v2", reqs)},
{"shadow": "v3", **shadow_compare("v1", "v3", reqs)}]).round(4))
v2 agrees with production on most requests, as expected for a slightly better model. v3 disagrees far more often, which is a red flag even before labels arrive. In a real system, a sudden drop in agreement or a jump in the share of one predicted class is a cheap and fast alarm.
Shadow mode needs no user exposure, but it doubles compute and cannot measure effects that depend on users seeing the prediction. A canary measures real outcomes on a small slice of users.
TODO 4 · Canary rollout with automatic rollback¶
Implement canary_rollout(prod_version, cand_version, stages=(5, 25, 50), requests_per_stage=4000, max_drop=0.02, min_requests=150, week=3, seed=400). For each stage:
- Create
Router(prod_version, cand_version, candidate_pct=stage, salt=f"canary-{cand_version}"). - Simulate
requests_per_stagerides (useseed + stage index), then serve them and attach outcomes. - Compute the control and candidate accuracy and the candidate request count. The guardrail passes if
candidate_n < min_requests(too little data to judge yet) orcandidate_acc >= control_acc - max_drop. - If the guardrail fails, roll back: call
set_production(prod_version, ...)with a reason that names the stage, then stop.
If every stage passes, promote with set_production(cand_version, ...). Return (status, stage_table), where status is "promoted" or "rolled_back".
Run it first for v3 (expected outcome: rolled back at 5%), then for v2 (expected outcome: promoted). Print both stage tables and the registry history.
Hints: reuse Router, attach_outcomes and summarize; summarize(log).loc["candidate", "accuracy"].
Check: after both runs, read_registry()["production"] == "v2", and the history contains a rollback entry that mentions v3.
def canary_rollout(prod_version, cand_version, stages=(5, 25, 50), requests_per_stage=4000,
max_drop=0.02, min_requests=150, week=3, seed=400):
# TODO: implement the staged rollout described above
raise NotImplementedError("TODO 4")
if False: # set True after implementing
status_v3, table_v3 = canary_rollout("v1", "v3")
display(table_v3); print("v3:", status_v3)
status_v2, table_v2 = canary_rollout("v1", "v2")
display(table_v2); print("v2:", status_v2)
reg = read_registry()
assert status_v3 == "rolled_back" and status_v2 == "promoted" and reg["production"] == "v2"
assert any("v3" in h["reason"] for h in reg["history"])
display(pd.DataFrame(reg["history"]))
Why a guardrail and not a significance test? A canary has to be fast and conservative. At 5% traffic you will rarely have the sample size to prove the candidate is better. You only need enough evidence that it is not clearly worse (a guardrail) before exposing more users. The A/B test in Part 2 is where you prove improvement.
Part 4 · Detecting covariate shift¶
The registry's production model (v2, once TODO 4 is complete) now runs for 12 weeks, from the dry season into the monsoon. We do have labels here, so we can see the true accuracy. In a real system, labels often arrive late (days for tips, months for loan defaults) or never. Monitoring therefore has to start with the inputs.
WEEKS = range(0, 12)
WEEK_DATA = {w: simulate_rides(3000, week=w, seed=500 + w) for w in range(0, 16)}
prod_model = load_model(read_registry()["production"])
weekly = pd.DataFrame([{"week": w, "monsoon": monsoon(w),
"accuracy": accuracy_score(WEEK_DATA[w][TARGET], prod_model.predict(WEEK_DATA[w][FEATURES])),
"mean_distance": WEEK_DATA[w]["distance_km"].mean(),
"long_ride_share": (WEEK_DATA[w]["distance_km"] > 13).mean()} for w in WEEKS])
display(weekly.round(3))
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(weekly["week"], weekly["accuracy"], marker="o", label="production accuracy (v2)")
ax.axvspan(3.5, 11, color="tab:blue", alpha=0.08, label="monsoon")
ax.set_xlabel("week"); ax.set_ylabel("accuracy"); ax.legend(); plt.show()
Accuracy falls even though the tipping rule never changed. The model learned from week-0 data, in which rides over 13 km were rare. In that region it has almost no data, so it extrapolates the "longer ride → more tip" trend from short rides, which is exactly where the true rule turns down. Covariate shift hurts when production moves into regions the training data barely covered.
Compare distributions with a two-sample test¶
The Kolmogorov–Smirnov (KS) test compares two samples of one feature. Its statistic is the largest gap between the two empirical CDFs, from 0 (identical) to 1 (no overlap).
ks_rows = []
for f in FEATURES:
for w in [1, 8]:
res = stats.ks_2samp(train_df[f], WEEK_DATA[w][f])
ks_rows.append({"feature": f, "week": w, "ks_stat": res.statistic, "p_value": res.pvalue})
display(pd.DataFrame(ks_rows).pivot(index="feature", columns="week", values=["ks_stat", "p_value"]).round(4))
With thousands of rows, KS p-values become tiny even for harmless differences. A p-value tells you whether there is any difference, not how big it is. Production monitors therefore also track an effect size. The most common one in industry is the Population Stability Index (PSI):
$$\text{PSI} = \sum_{i=1}^{B} (c_i - r_i)\,\ln\frac{c_i}{r_i}$$
Here $r_i$ and $c_i$ are the fractions of the reference (training) and current data that fall in bin $i$. The bins are the deciles of the reference data. Rule of thumb: < 0.1 stable · 0.1–0.25 moderate shift · > 0.25 major shift.
TODO 5 · Implement PSI¶
Implement psi(reference, current, bins=10, eps=1e-4):
- For a continuous feature, take the bin edges as the quantiles of
referenceatnp.linspace(0, 1, bins + 1), remove duplicate edges withnp.unique, then set the first edge to-infand the last to+inf. - For a feature with ≤
binsdistinct values (such assurgeorhour), use one bin per distinct value instead. Edges halfway between consecutive values work. - Compute the fraction of each sample in every bin with
np.histogram, clip the fractions ateps(to avoidlog(0)), then apply the formula.
Check: PSI of a sample with itself is 0. Two samples from the same normal distribution give a PSI below 0.02. N(0,1) against N(1,1) gives a PSI above 0.25. surge in week 0 against week 8 gives a PSI above 0.25, which proves the discrete case works.
def psi(reference, current, bins=10, eps=1e-4):
# TODO: implement the guided steps above
raise NotImplementedError("TODO 5")
if False: # set True after implementing
rng = np.random.default_rng(0)
x = rng.normal(0, 1, 5000)
assert psi(x, x) < 1e-9
assert psi(x, rng.normal(0, 1, 5000)) < 0.02
assert psi(x, rng.normal(1, 1, 5000)) > 0.25
assert psi(train_df["surge"], WEEK_DATA[8]["surge"]) > 0.25
print("PSI checks passed. surge PSI week 8:", round(psi(train_df["surge"], WEEK_DATA[8]["surge"]), 3))
TODO 6 · Build a weekly drift monitor¶
(a) PSI per feature per week. For weeks 1–11, compute the PSI of every feature against train_df (the production model's training data). Store the result as psi_table, a DataFrame with one row per week and one column per feature, plus a max_psi column. Display it and plot max_psi and the weekly accuracy (from weekly) on twin y-axes. Print the first week in which any feature exceeds 0.25.
(b) Domain classifier. A single model can detect shift across all features at once. Label training rows 0 and production rows 1, then check whether a classifier can tell them apart. Implement domain_auc(X_ref, X_cur). It should use cross_val_predict(HistGradientBoostingClassifier(max_depth=3, max_iter=100, random_state=SEED), ..., cv=5, method="predict_proba") and return the ROC-AUC. Report the AUC for weeks 1, 5 and 8.
Hints: pd.concat; np.r_[np.zeros(n_ref), np.ones(n_cur)]; ax.twinx(). An AUC near 0.5 means the classifier cannot tell the two apart, so there is no shift.
Check: weeks 1–3 should have max_psi well under 0.1 and an AUC close to 0.5. The monsoon weeks should be clearly higher. In one comment, name the feature that drifts most and connect it to the accuracy drop.
psi_table = None # TODO (a)
def domain_auc(X_ref, X_cur):
# TODO (b)
raise NotImplementedError("TODO 6b")
# TODO: plots, first week over 0.25, AUC for weeks 1, 5, 8
# Which feature drifts most, and how does it explain the accuracy drop? ->
Part 5 · Managing shift and automated retraining¶
| Response | Needs new labels? | Idea |
|---|---|---|
| Retrain on recent data | Yes | Fit the model again on a window of the latest labeled weeks |
| Importance weighting | No, only unlabeled production inputs | Re-weight the old training rows so that they look like production |
| Fallback / human review | No | Route very uncertain or far out-of-distribution requests elsewhere |
| Better features / models | Yes | Give the model inputs that generalize (e.g. a "flat-fare trip" flag) |
Importance weighting. Under covariate shift, $P(y \mid x)$ is unchanged, so training rows are still correct, just in the wrong proportions. Weight every training row by
$$w(x) = \frac{p_{\text{prod}}(x)}{p_{\text{train}}(x)} \;\approx\; \frac{P(\text{prod} \mid x)}{1 - P(\text{prod} \mid x)} \cdot \frac{n_{\text{train}}}{n_{\text{prod}}}$$
using the domain classifier from TODO 6. Most scikit-learn models accept these weights through fit(X, y, sample_weight=w).
TODO 7 · Importance weighting vs. retraining¶
- Implement
importance_weights(X_train, X_prod, clip=(0.1, 10)). Fit aHistGradientBoostingClassifier(max_depth=3, max_iter=100, random_state=SEED)domain classifier on train (0) vs prod (1), apply the formula to the training rows and clip the result. - Using week 7 inputs only (no labels) as
X_prod, compute weights fortrain_df. Print the min, max and mean weight and the effective sample size $\text{ESS} = (\sum w)^2 / \sum w^2$. - Evaluate three models on week 8 labels:
- A: the current production model, unchanged.
- B:
make_v2()trained ontrain_dfwithsample_weight(no new labels used). - C:
make_v2()trained on week 7 with its labels (WEEK_DATA[7]).
- In 2–3 sentences: why does B help only partly? What can importance weighting never fix?
Check: expect A < B < C on week 8. The ESS should be far smaller than len(train_df).
def importance_weights(X_train, X_prod, clip=(0.1, 10.0)):
# TODO
raise NotImplementedError("TODO 7")
# TODO: weights, ESS, and the A/B/C comparison on week 8
answer_todo7 = """
...
"""
Automate retraining¶
Real systems do not retrain by hand. A retraining policy decides when to retrain. A champion/challenger gate decides whether the retrained model (challenger) actually replaces the current one (champion).
run_policy(policy) below simulates weeks 1–11:
- Serve the week's traffic with the current model and record its accuracy and
max_psi(against the model's own training data). - At the end of the week, the labels arrive.
- If
policy(week, log)returnsTrue, train a challenger on the lastwindowweeks of labeled data. Hold out 30% of the newest week, and promote the challenger only if it is at least as accurate as the champion on that holdout.
Two simple policies are provided: never and every_4_weeks. If TODO 5 is not finished yet, max_psi will appear as NaN.
def run_policy(policy, weeks=range(1, 12), window=2, week_data=None, label_delay=0):
week_data = WEEK_DATA if week_data is None else week_data
model = make_v2().fit(train_df[FEATURES], train_df[TARGET])
reference = train_df[FEATURES]
labeled = {0: train_df}
log = []
for week in weeks:
reqs = week_data[week]
try:
max_psi = max(psi(reference[f], reqs[f]) for f in FEATURES)
except NotImplementedError:
max_psi = np.nan
row = {"week": week, "accuracy": accuracy_score(reqs[TARGET], model.predict(reqs[FEATURES])),
"max_psi": max_psi, "retrained": False, "promoted": False}
log.append(row)
if week - label_delay >= 1: # labels of (week - delay) arrive now
labeled[week - label_delay] = week_data[week - label_delay]
if policy(week, pd.DataFrame(log)):
row["retrained"] = True
newest = max(labeled)
holdout = labeled[newest].sample(frac=0.3, random_state=week)
recent = pd.concat([labeled[w] for w in sorted(labeled)[-window:]])
recent = recent[~recent["request_id"].isin(holdout["request_id"])]
challenger = make_v2().fit(recent[FEATURES], recent[TARGET])
champ_acc = accuracy_score(holdout[TARGET], model.predict(holdout[FEATURES]))
chall_acc = accuracy_score(holdout[TARGET], challenger.predict(holdout[FEATURES]))
if chall_acc >= champ_acc:
model, reference = challenger, recent[FEATURES]
row["promoted"] = True
return pd.DataFrame(log)
def never(week, log):
return False
def every_4_weeks(week, log):
return week % 4 == 0
def policy_summary(name, log):
return {"policy": name, "mean_acc_w1_11": log["accuracy"].mean(),
"mean_acc_w7_11": log.loc[log["week"] >= 7, "accuracy"].mean(),
"retrains": int(log["retrained"].sum()), "promotions": int(log["promoted"].sum())}
logs = {"never": run_policy(never), "every_4_weeks": run_policy(every_4_weeks)}
display(logs["every_4_weeks"].round(3))
display(pd.DataFrame([policy_summary(k, v) for k, v in logs.items()]).round(4))
Syntax clarity: functions as arguments
run_policy(never)passes the functionneveritself, without calling it. Inside,policy(week, pd.DataFrame(log))calls whichever function you passed. Any function with the signature(week, log) -> boolis a valid policy, so you can plug in new ones without changingrun_policy.
TODO 8 · Write retraining triggers and compare policies¶
- Write
drift_triggered(week, log): retrain when the latestmax_psiis above 0.25. This needs no labels. - Write
performance_triggered(week, log): retrain when the latest weekly accuracy is below 0.74. This needs labels. - Run all four policies (
never,every_4_weeks,drift_triggered,performance_triggered). Show a summary table (usepolicy_summary) and one plot of accuracy against week for every policy, with a marker on each week where a retrain happened. - Answer in
answer_todo8: which policy would you deploy for this app, and why? Consider the cost of a retrain, how quickly accuracy recovers, and what happens if tip labels arrive two weeks late.
Hints: log.iloc[-1]["max_psi"]; ax.scatter on the rows where retrained is true.
Check: never stays low after week 7. Both triggered policies should recover with fewer retrains than you would need from weekly retraining.
def drift_triggered(week, log):
# TODO
raise NotImplementedError("TODO 8")
def performance_triggered(week, log):
# TODO
raise NotImplementedError("TODO 8")
# TODO: run the four policies, summary table, plot
answer_todo8 = """
...
"""
Submit your work¶
Submit the notebook with:
- All eight TODOs completed, with outputs from your run (keep the
if Falsechecks switched toTrue). - The A/B decision with its p-value and confidence interval, the canary tables and the registry history.
- The drift monitor table and plot, the importance-weighting comparison and the retraining-policy comparison.
- The final challenge below.
Never invent numbers: every value you report must come from a cell that ran.
Read more¶
Canary release (Fowler) · Blue–green deployment (Fowler) · Trustworthy Online Controlled Experiments · Data distribution shifts and monitoring (Chip Huyen) · scipy.stats.ks_2samp · scikit-learn sample weights
Complete the lab challenge¶
Monsoon in, monsoon out, with labels arriving late¶
The provided challenge_season(week) describes a whole season: dry until week 3, the monsoon ramps up over weeks 4–7, stays at full strength through week 10, then retreats over weeks 11–13 back to dry weather. Tip labels now arrive 2 weeks late: at the end of week w, you only receive the labels of week w − 2.
CHALLENGE_DATA holds weeks 1–16 (3,000 rides each). The provided baseline_log shows the never policy on this scenario.
Tasks
- Design an automated retraining policy for this scenario. You may adapt
run_policy(it acceptsweek_data=andlabel_delay=) or write your own loop. Decide when to retrain (with a 2-week label delay, think about which signals you can use), on what data (window size, importance weighting toward the current inputs) and how a new model is gated (champion/challenger and/or canary). - Keep a model registry: register every promoted model with a model card (training weeks, holdout accuracy, trigger reason) and record each promotion in
registry.json. - Report a plot of weekly accuracy and max PSI over weeks 1–16 for
neverand your policy, with retrain markers. Add a table of mean accuracy (weeks 1–16 and weeks 8–16), the number of retrains and the number of promotions. - Write a short design note (5–8 lines) covering your trigger, data window, gate, rollback plan and what you would monitor if labels never arrived.
Pass criteria: at most 5 retrains in weeks 1–16, and mean accuracy over weeks 8–16 at least 3 percentage points above never. Every model in production must have passed your gate.
def challenge_season(week):
if week <= 10:
return monsoon(week)
return float(np.clip((13 - week) / 3, 0, 1)) # retreats over weeks 11-13
CHALLENGE_DATA = {w: simulate_rides(3000, week=w, seed=900 + w, season=challenge_season(w)) for w in range(1, 17)}
print("season:", {w: round(challenge_season(w), 2) for w in range(1, 17)})
baseline_log = run_policy(never, weeks=range(1, 17), week_data=CHALLENGE_DATA, label_delay=2)
print("never: mean acc w1-16 = %.4f | w8-16 = %.4f" % (baseline_log["accuracy"].mean(),
baseline_log.loc[baseline_log.week >= 8, "accuracy"].mean()))
# INDEPENDENT CHALLENGE WORKSPACE: implement your own solution below.
# Add code/Markdown cells as needed; all plots must appear in this notebook.
challenge_summary = {
"trigger": "",
"data_window_and_weighting": "",
"promotion_gate": "",
"rollback_plan": "",
"monitoring_without_labels": "",
"retrains": None,
"mean_acc_w8_16": None,
"never_mean_acc_w8_16": None,
}
# TODO: policy, registry entries, plot, table, design note.