TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Mini Project: a Monitored Model Service

Mini Project: a Monitored Model Service

You will build the whole loop of this course for one small model: train and package it with its metadata, serve it with FastAPI, log every prediction, watch the logs for drift, retrain when the data moves, promote the new model only if it passes a gate, and keep a way back. Every step runs in your browser. At the end, a write-up template turns your results into the kind of report a team would review before trusting the system.

The project uses the course's running example: a credit-risk-style classifier on 8 generated features (make_classification with 2,000 rows, 5 informative features, random_state=0), modelled by a scikit-learn pipeline of a scaler and a logistic regression. Each step below is a separate program that rebuilds what it needs, so you can run them in any order.

Step 1: train, evaluate and package

Train on 1,500 rows and test on 500 held-out rows (stratified split). Save the whole pipeline, not just the classifier, and write a metadata record next to it: what the model expects, how it was evaluated, which data it saw, and a hash that identifies the exact file.

python · try it yourself
import hashlib
import io
import json

import joblib
import numpy as np
import sklearn
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

FEATURES = ["income", "debt_ratio", "age", "tenure", "late_payments", "utilisation", "inquiries", "accounts"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=500, stratify=y, random_state=0)

model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
proba = model.predict_proba(X_te)[:, 1]
metrics = {"accuracy": round(accuracy_score(y_te, proba >= 0.5), 3), "roc_auc": round(roc_auc_score(y_te, proba), 3)}

buf = io.BytesIO()
joblib.dump(model, buf)
blob = buf.getvalue()
meta = {
    "name": "risk-model",
    "version": 1,
    "features": FEATURES,
    "threshold": 0.5,
    "metrics": metrics,
    "evaluation": "stratified holdout, 500 of 2000 rows, random_state=0",
    "train_data_sha256": hashlib.sha256(X_tr.tobytes() + y_tr.tobytes()).hexdigest()[:16],
    "artifact_sha256": hashlib.sha256(blob).hexdigest()[:16],
    "sklearn": sklearn.__version__,
}
print(json.dumps(meta, indent=2))
print(f"artifact size: {len(blob)} bytes")

restored = joblib.load(io.BytesIO(blob))
print("restored model agrees on all test rows:", bool(np.array_equal(restored.predict(X_te), model.predict(X_te))))
{
  "name": "risk-model",
  "version": 1,
  "features": [
    "income",
    "debt_ratio",
    "age",
    "tenure",
    "late_payments",
    "utilisation",
    "inquiries",
    "accounts"
  ],
  "threshold": 0.5,
  "metrics": {
    "accuracy": 0.856,
    "roc_auc": 0.933
  },
  "evaluation": "stratified holdout, 500 of 2000 rows, random_state=0",
  "train_data_sha256": "8a1f0d01456285eb",
  "artifact_sha256": "f9987976b6985236",
  "sklearn": "1.7.0"
}
artifact size: 1601 bytes
restored model agrees on all test rows: True

What to check: the metadata names the evaluation (split, size, seed), the library version the file needs, and two hashes. The data hash ties the model to its training set (experiment tracking, DVC); the artifact hash lets the service refuse a file that is not the one that was evaluated (artifacts and signatures, security). On your own machine you would write model.joblib and model.json to disk, or log both to MLflow.

Step 2: serve it and log every prediction

The service validates each request against a schema, answers with the score, the decision and the model version, and appends every prediction with an id to a log. A health endpoint reports which model is loaded. All endpoints are async def, because the browser has no threads (FastAPI basics); on a server you would start it with uvicorn service:app.

python · try it yourself
import asyncio
import uuid

import httpx
import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

FEATURES = ["income", "debt_ratio", "age", "tenure", "late_payments", "utilisation", "inquiries", "accounts"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=500, stratify=y, random_state=0)
MODEL = {"version": 1, "pipe": make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr), "threshold": 0.5}
LOG = []

class Applicant(BaseModel):
    features: list[float] = Field(min_length=8, max_length=8)

app = FastAPI()

@app.get("/health")
async def health():
    return {"status": "ok", "model_version": MODEL["version"]}

@app.post("/predict")
async def predict(a: Applicant):
    x = np.array(a.features)
    if not np.all(np.abs(x) < 20):
        raise HTTPException(status_code=422, detail="feature value out of range")
    score = float(MODEL["pipe"].predict_proba(x[None, :])[0, 1])
    rid = str(uuid.UUID(int=len(LOG) + 1))                    # deterministic ids for the demo
    LOG.append({"id": rid, "version": MODEL["version"], "x": a.features, "score": score})
    return {"id": rid, "score": round(score, 3), "approve": score < MODEL["threshold"], "model_version": MODEL["version"]}

async def main():
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        print((await client.get("/health")).json())
        for row in X_te[:3]:
            r = await client.post("/predict", json={"features": [round(v, 3) for v in row.tolist()]})
            print(r.status_code, r.json())
        r = await client.post("/predict", json={"features": [1.0] * 7})
        print(r.status_code, r.json()["detail"][0]["msg"])
        r = await client.post("/predict", json={"features": [1.0] * 7 + [500.0]})
        print(r.status_code, r.json())
    print(f"log has {len(LOG)} predictions; first id {LOG[0]['id']}")

asyncio.run(main())
{'status': 'ok', 'model_version': 1}
200 {'id': '00000000-0000-0000-0000-000000000001', 'score': 0.049, 'approve': True, 'model_version': 1}
200 {'id': '00000000-0000-0000-0000-000000000002', 'score': 0.03, 'approve': True, 'model_version': 1}
200 {'id': '00000000-0000-0000-0000-000000000003', 'score': 0.835, 'approve': False, 'model_version': 1}
422 List should have at least 8 items after validation, not 7
422 {'detail': 'feature value out of range'}
log has 3 predictions; first id 00000000-0000-0000-0000-000000000001

What to check: bad requests get 422 before the model runs, and every successful prediction has an id and a model version in both the response and the log. Without the id, the true outcome that arrives weeks later cannot be joined to the prediction (monitoring). Here class 1 is "high risk", so a score below the threshold means approve.

Step 3: watch the log for drift, retrain, gate and keep a way back

Now simulate 30 days of traffic, 200 requests a day. This step draws 8,000 rows from the generator (a different n_samples gives different data, so version 1 is retrained here on the first 2,000 rows the same way as in step 1) and uses 6,000 unseen rows as traffic. From day 16 the applicant population changes: income (feature 0) shifts by one standard deviation, and the label rule changes: every applicant with a debt_ratio (feature 1) above 0 now turns out high risk. The monitor computes the PSI of every feature against the training data each day (10 bins at the training deciles) and raises an alarm when any feature's PSI is above 0.2 (data drift). Labels arrive later; once the alarm fires, a challenger is trained on recent labelled days and must beat the champion on the newest labelled days to be promoted (retraining). The registry is a dictionary of versions with a champion alias, so a rollback is one assignment (model registry, rollback).

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# A bigger draw of the same kind of data: 2,000 rows to train and test, 6,000 fresh rows as 30 days of traffic.
X, y = make_classification(n_samples=8000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X[:2000], y[:2000], test_size=500, stratify=y[:2000], random_state=0)
v1 = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
print(f"version 1 test accuracy (500 held-out rows): {v1.score(X_te, y_te):.3f}")
registry = {"versions": {1: v1}, "aliases": {"champion": 1}}

sd0 = X_tr[:, 0].std()
days = []
for d in range(1, 31):
    Xd = X[2000 + 200 * (d - 1): 2000 + 200 * d].copy()   # 200 new rows per day, never reused
    yd = y[2000 + 200 * (d - 1): 2000 + 200 * d].copy()
    if d >= 16:
        Xd[:, 0] += sd0                                    # income shifts by one training sd
        yd = yd | (Xd[:, 1] > 0)                            # new rule: every applicant with debt_ratio > 0 is now high risk
    days.append((Xd, yd))

edges = [np.quantile(X_tr[:, j], np.linspace(0.1, 0.9, 9)) for j in range(8)]
def psi(ref_col_edges, col):
    counts = np.bincount(np.searchsorted(ref_col_edges, col), minlength=10) / len(col)
    a = np.maximum(counts, 1e-4)
    return float(np.sum((a - 0.1) * np.log(a / 0.1)))

alarm_day = None
for d, (Xd, yd) in enumerate(days, start=1):
    worst = max(range(8), key=lambda j: psi(edges[j], Xd[:, j]))
    value = psi(edges[worst], Xd[:, worst])
    acc = registry["versions"][1].score(Xd, yd)
    if d in (1, 10, 15, 16, 17, 30) or (alarm_day is None and value > 0.2):
        print(f"day {d:2d}: max PSI {value:.3f} (feature {worst}), champion accuracy {acc:.3f}")
    if alarm_day is None and value > 0.2:
        alarm_day = d
print("first alarm on day", alarm_day)

# Labels for days 16..25 have arrived by day 30. Train a challenger on days 16..22, compare on days 23..25.
X_new = np.vstack([days[d - 1][0] for d in range(16, 23)])
y_new = np.concatenate([days[d - 1][1] for d in range(16, 23)])
X_gate = np.vstack([days[d - 1][0] for d in range(23, 26)])
y_gate = np.concatenate([days[d - 1][1] for d in range(23, 26)])
challenger = make_pipeline(StandardScaler(), LogisticRegression()).fit(np.vstack([X_tr, X_new]), np.concatenate([y_tr, y_new]))
champ = registry["versions"][registry["aliases"]["champion"]]
a_champ, a_chal = champ.score(X_gate, y_gate), challenger.score(X_gate, y_gate)
print(f"gate on days 23-25 ({len(y_gate)} rows): champion {a_champ:.3f}, challenger {a_chal:.3f}")
if a_chal >= a_champ + 0.01:
    registry["versions"][2] = challenger
    registry["aliases"]["champion"] = 2
print("champion is now version", registry["aliases"]["champion"])

registry["aliases"]["champion"] = 1                        # rollback drill: one assignment
print("after rollback drill, champion is version", registry["aliases"]["champion"])
version 1 test accuracy (500 held-out rows): 0.950
day  1: max PSI 0.122 (feature 1), champion accuracy 0.940
day 10: max PSI 0.087 (feature 1), champion accuracy 0.955
day 15: max PSI 0.070 (feature 5), champion accuracy 0.940
day 16: max PSI 0.787 (feature 0), champion accuracy 0.700
day 17: max PSI 1.335 (feature 0), champion accuracy 0.665
day 30: max PSI 1.041 (feature 0), champion accuracy 0.660
first alarm on day 16
gate on days 23-25 (600 rows): champion 0.702, challenger 0.843
champion is now version 2
after rollback drill, champion is version 1

In this run the largest daily PSI stays between 0.070 and 0.122 for the first 15 days (no false alarm at 0.2), jumps to 0.787 on day 16 for feature 0 (income), and the alarm fires the same day. The champion's daily accuracy falls from about 0.94 to 0.70 on day 16 and 0.66 on day 30. On the gate days the challenger reaches 0.843 against the champion's 0.702, passes the +0.01 rule and becomes version 2; the rollback drill moves the alias back to version 1. Note that the alarm came from the income shift: the label change alone would not have moved any input distribution.

What to check: the day of the first alarm, which feature raised it, how much accuracy the champion lost after day 16, and whether the challenger passed the gate. The gate data (days 23 to 25) is never used for training the challenger, and the challenger is trained on the original data plus the recent days, so it does not forget the part of the population that did not change.

Your turn

Extend the project in at least two of these directions, and record the numbers:

  1. Window size. Use 50 instead of 200 requests a day. How many false alarms appear before day 16? Pick a threshold or a window that keeps false alarms at zero and find the new detection delay. Compare with the drift lab.
  2. Concept drift only. Remove the income shift and keep only the label change. Does the PSI monitor fire? Add a monitor on the delayed-label error rate (Page-Hinkley or a simple moving average, see concept drift).
  3. Shadow deployment. Before promoting the challenger, serve it in shadow: run both models on every request of days 26 to 30, log both scores, and report how often their decisions disagree (deployment strategies).
  4. Batch endpoint and limits. Add /predict_batch that accepts at most 100 rows, and check that 101 rows get a 422 (FastAPI for production).
  5. Smaller model. Quantize the logistic regression's coefficients to int8 and report the agreement with the float model on the test set (quantization).
  6. On your own machine. Put the service in a Docker image (Docker for models), log the training runs to MLflow, version the data with DVC, and write a CI workflow that runs the tests and the gate (CI/CD for ML).

Write-up template

text
# risk-model: service and monitoring report

## Model
- Version, training data (rows, hash), features, threshold
- Evaluation: split, size, seed, metrics (accuracy, ROC AUC) with their uncertainty

## Service
- Endpoints, request schema, validation rules, what a rejected request returns
- What is logged per prediction (id, version, inputs, score) and where

## Monitoring
- Statistics, window, thresholds, and why those thresholds
- False alarms before the drift, detection day and delay after it

## Retraining and release
- Trigger, training window, gate data (never used for training), promotion rule
- Result of the gate, and the rollback procedure (tested: yes/no)

## Risks and open questions
- What the monitors cannot see (e.g. concept drift without labels, label delay)
- Security and governance notes (artifact hashes, who can promote, audit trail)

Test yourself

Why does the gate compare champion and challenger on days 23-25 and train the challenger only on days 16-22 (plus the original data)?

  1. To save time
  2. So the comparison uses data neither model was trained on
  3. Because days 23-25 have no drift
  4. Because the champion was trained on them

In this project, what makes a rollback a single, safe operation?

  1. Retraining the old model
  2. Keeping every version in the registry and serving whatever the champion alias points to
  3. Deleting the new version
  4. Restarting the service

Why is the challenger trained on the original training data plus the recent days instead of the recent days alone?

  1. It must be bigger
  2. So it keeps what still holds for the unchanged part of the population while learning the new pattern
  3. Because recent data has no labels
  4. To make the gate pass