#!/usr/bin/env python3 """Capstone 8, MLOps: dataset -> data contract -> training -> validation -> experiment tracking -> model registry -> deployment -> shadow and canary -> drift -> retraining -> rollback. Standard library only. Works in ~/labs/capstones/mlops. python3 mlops.py setup build everything up to a model in production and a drifted batch python3 mlops.py verify check every stage, then retrain, shadow, canary, promote, roll back python3 mlops.py reset remove the work folder """ import hashlib import json import math import os import random import shutil import sys import time WORK = os.path.expanduser("~/labs/capstones/mlops") FEATURES = ["amount", "hour", "new_device", "country_risk"] CONTRACT = {"amount": (0.0, 20000.0), "hour": (0, 23), "new_device": (0, 1), "country_risk": (0.0, 1.0)} GATE = {"min_auc": 0.80, "max_auc_drop": 0.02} PASSES, FAILS = [], [] def ok(msg): PASSES.append(msg); print(" PASS ", msg) def bad(msg): FAILS.append(msg); print(" FAIL ", msg) def p(*parts): return os.path.join(WORK, *parts) def dump(path, obj): open(path, "w").write(json.dumps(obj, indent=1) + "\n") def load(path): return json.load(open(path)) # ---------- data def make_batch(n, seed, shift=0.0): """Synthetic card payments; fraud is more likely for large amounts, night hours, new devices, and risky countries. shift moves the amount distribution (drift).""" r = random.Random(seed) rows = [] for _ in range(n): amount = round(r.lognormvariate(4.0 + shift, 1.0), 2) hour = r.randrange(24) new_device = 1 if r.random() < 0.15 else 0 risk = round(r.random() ** 2, 3) z = -5.0 + 0.006 * amount + (1.5 if hour < 5 else 0) + 2.2 * new_device + 3.2 * risk fraud = 1 if r.random() < 1 / (1 + math.exp(-z)) else 0 rows.append({"amount": min(amount, 19999.0), "hour": hour, "new_device": new_device, "country_risk": risk, "fraud": fraud}) return rows def contract_errors(rows): errs = [] for i, row in enumerate(rows): for f, (lo, hi) in CONTRACT.items(): v = row.get(f) if not isinstance(v, (int, float)) or v is None or not lo <= v <= hi: errs.append(f"row {i}: {f}={v!r} outside [{lo}, {hi}]") if row.get("fraud") not in (0, 1): errs.append(f"row {i}: fraud label missing") return errs # ---------- model: logistic regression trained with gradient descent, standardised features def fit(rows, lr=0.3, epochs=300, seed=1): xs = [[row[f] for f in FEATURES] for row in rows] mean = [sum(c) / len(c) for c in zip(*xs)] sd = [max(1e-9, math.sqrt(sum((v - m) ** 2 for v in c) / len(c))) for c, m in zip(zip(*xs), mean)] X = [[(v - m) / s for v, m, s in zip(x, mean, sd)] for x in xs] y = [row["fraud"] for row in rows] w, b = [0.0] * len(FEATURES), 0.0 for _ in range(epochs): gw, gb = [0.0] * len(w), 0.0 for xi, yi in zip(X, y): pz = 1 / (1 + math.exp(-(sum(a * c for a, c in zip(w, xi)) + b))) for k in range(len(w)): gw[k] += (pz - yi) * xi[k] gb += pz - yi w = [a - lr * g / len(X) for a, g in zip(w, gw)] b -= lr * gb / len(X) return {"w": w, "b": b, "mean": mean, "sd": sd, "features": FEATURES} def score(model, row): z = sum(w * ((row[f] - m) / s) for w, f, m, s in zip(model["w"], model["features"], model["mean"], model["sd"])) + model["b"] return 1 / (1 + math.exp(-z)) def auc(model, rows): pos = [score(model, r) for r in rows if r["fraud"] == 1] neg = [score(model, r) for r in rows if r["fraud"] == 0] wins = sum((p_ > n) + 0.5 * (p_ == n) for p_ in pos for n in neg) return wins / (len(pos) * len(neg)) def psi(expected, actual, bins=10): """Population stability index of one feature between two batches.""" qs = sorted(expected) edges = [qs[int(len(qs) * k / bins)] for k in range(1, bins)] def dist(vals): c = [0] * bins for v in vals: c[sum(v > e for e in edges)] += 1 return [max(x / len(vals), 1e-4) for x in c] e, a = dist(expected), dist(actual) return sum((ai - ei) * math.log(ai / ei) for ei, ai in zip(e, a)) # ---------- tracking and registry def track(name, params, metrics, model, data_hash): run = {"run": name, "time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "params": params, "metrics": metrics, "data_sha256": data_hash} os.makedirs(p("runs"), exist_ok=True) dump(p("runs", name + ".json"), run) dump(p("runs", name + ".model.json"), model) return run def registry(): return load(p("registry.json")) if os.path.exists(p("registry.json")) else {"versions": []} def register(run, stage="staging"): reg = registry() v = len(reg["versions"]) + 1 reg["versions"].append({"version": v, "run": run["run"], "auc": run["metrics"]["auc"], "stage": stage}) dump(p("registry.json"), reg) return v def promote(v): reg = registry() for x in reg["versions"]: if x["stage"] == "production": x["stage"] = "archived" if x["version"] == v: x["stage"] = "production" dump(p("registry.json"), reg) def production(): reg = registry() prod = [x for x in reg["versions"] if x["stage"] == "production"] return (prod[0], load(p("runs", prod[0]["run"] + ".model.json"))) if prod else (None, None) def sha(rows): return hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).hexdigest()[:16] # ---------- commands def setup(): os.makedirs(p("data"), exist_ok=True) print("== 1. Dataset: 3,000 labelled payments for training, 1,000 for testing") train, test = make_batch(3000, 11), make_batch(1000, 12) dump(p("data", "train.json"), train); dump(p("data", "test.json"), test) print(f" fraud rate: train {sum(r['fraud'] for r in train) / len(train):.3f}, test {sum(r['fraud'] for r in test) / len(test):.3f}") print("== 2. Data contract: a batch with broken rows is rejected before training") broken = make_batch(200, 13); broken[5]["amount"] = -40; broken[9]["hour"] = 31; broken[17]["fraud"] = None dump(p("data", "batch-broken.json"), broken) errs = contract_errors(broken) print(f" batch-broken.json: {len(errs)} contract violations, rejected; first: {errs[0]}") print("== 3. Train, validate against the gate, track, register, deploy") model = fit(train) a = round(auc(model, test), 4) run = track("run-001", {"lr": 0.3, "epochs": 300, "features": FEATURES}, {"auc": a}, model, sha(train)) v = register(run) print(f" run-001: AUC {a} (gate: at least {GATE['min_auc']}) -> registered as version {v}") if a >= GATE["min_auc"]: promote(v) print(f" version {v} promoted to production") print("== 4. A new month of traffic arrives, and it has shifted (larger amounts)") dump(p("data", "live.json"), make_batch(1500, 14, shift=0.9)) print(" data/live.json written; verify.py measures drift on it") def verify(): print("== Dataset and contract") train, test, live = load(p("data", "train.json")), load(p("data", "test.json")), load(p("data", "live.json")) (ok if not contract_errors(train) else bad)("the training data meets the contract") (ok if len(contract_errors(load(p("data", "batch-broken.json")))) == 3 else bad)("the broken batch shows exactly its 3 violations") print("== Tracking and registry") run1 = load(p("runs", "run-001.json")) (ok if run1["data_sha256"] == sha(train) else bad)("run-001 records the hash of the exact data it was trained on") pv, pm = production() (ok if pv and pv["version"] == 1 else bad)("version 1 is in production") if not pm: print("\nRESULT: no model passed the validation gate, so nothing is in production; stopping") sys.exit(1) a1 = auc(pm, test) (ok if a1 >= GATE["min_auc"] else bad)(f"production AUC {a1:.3f} meets the gate of {GATE['min_auc']}") print("== Serving: the production model scores a payment") s = score(pm, {"amount": 4200.0, "hour": 3, "new_device": 1, "country_risk": 0.9}) t = score(pm, {"amount": 12.0, "hour": 14, "new_device": 0, "country_risk": 0.05}) (ok if s > 0.5 > t else bad)(f"a risky payment scores {s:.2f}, an ordinary one {t:.2f}") print("== Drift on the new month") d = psi([r["amount"] for r in train], [r["amount"] for r in live]) d2 = psi([r["hour"] for r in train], [r["hour"] for r in live]) (ok if d > 0.25 else bad)(f"amount PSI {d:.2f} > 0.25: significant drift") (ok if d2 < 0.1 else bad)(f"hour PSI {d2:.2f} < 0.1: stable") a_live = auc(pm, live) print(f" production AUC on the drifted month: {a_live:.3f} (was {a1:.3f})") print("== Retrain on recent data, compare in shadow, release by canary") recent = live[:1000] if contract_errors(recent): bad("the recent data breaks the contract") model2 = fit(train + recent, seed=2) holdout = live[1000:] a2, a_old = auc(model2, holdout), auc(pm, holdout) run2 = track("run-002", {"lr": 0.3, "epochs": 300, "data": "train + 1,000 recent"}, {"auc": round(a2, 4)}, model2, sha(train + recent)) v2 = register(run2) (ok if a2 >= a_old - GATE["max_auc_drop"] else bad)(f"shadow on {len(holdout)} recent payments: new AUC {a2:.3f}, current {a_old:.3f}") agree = sum((score(model2, r) > 0.5) == (score(pm, r) > 0.5) for r in holdout) / len(holdout) print(f" shadow: the two models agree on {agree:.1%} of decisions") r = random.Random(99) canary = [x for x in holdout if r.random() < 0.10] (ok if canary and auc(model2, canary + [x for x in holdout if x["fraud"]][:5]) > 0.5 else bad)(f"canary: version {v2} served {len(canary)} requests (10%) without errors") promote(v2) (ok if production()[0]["version"] == v2 else bad)(f"version {v2} promoted to production; version 1 archived") print("== Rollback") promote(1) pv, pm = production() (ok if pv["version"] == 1 and abs(auc(pm, test) - a1) < 1e-9 else bad)("rolled back to version 1: the same model and AUC as before") stages = {x["version"]: x["stage"] for x in registry()["versions"]} print(" registry:", stages) print("\nRESULT:", "all checks passed" if not FAILS else f"{len(FAILS)} check(s) failed") sys.exit(1 if FAILS else 0) def reset(): shutil.rmtree(WORK, ignore_errors=True) print(f"capstone 8 reset: {WORK} removed") if __name__ == "__main__": cmd = sys.argv[1] if len(sys.argv) > 1 else "" if cmd != "reset": os.makedirs(WORK, exist_ok=True) {"setup": setup, "verify": verify, "reset": reset}.get(cmd, lambda: sys.exit(__doc__))()