MLOps Desk Reference
Lesson opener
In one line: This lesson covers mlops desk reference in plain English, with steps you can reuse at work.
Why it matters: This skill shows up in day-to-day analysis and delivery work.
Before this lesson: Nothing, this is a starting point.
Before you start
| Resource | Link |
|---|---|
| Course | MLOps |
| Tracking lesson | MLflow Tracking |
| Drift lesson | Monitoring & data drift |
Desk card for reproducible train → track → serve → monitor loops. Not a path course — use while shipping a churn or retention model with the MLOps lessons.
Pinned libraries
pip install -r docs/mlops/requirements.txtPinned in docs/mlops/requirements.txt:
scikit-learn==1.5.2
pandas==2.2.3
numpy==2.1.3
joblib==1.4.2
fastapi==0.115.5
uvicorn==0.32.1
pydantic==2.10.2
mlflow==2.18.0
scipy==1.14.1Offline demos use the standard library plus numpy, joblib, and scipy pins above. Real MLflow UI needs mlflow==2.18.0. Serving demos use FastAPI / pydantic pins when you leave the notebook.
Lifecycle map
| Stage | Artefact | Desk check |
|---|---|---|
| Script | argparse entrypoint | Runs without a notebook kernel |
| Environment | requirements.txt + optional Docker | Same pins on laptop and CI |
| Model file | joblib dump | Load round-trips predict |
| Tracking | params, metrics, git SHA | Comparable runs |
| Serve | FastAPI + pydantic | Health + validated JSON |
| Monitor | prediction log + drift test | On-call can audit |
Indian workplace example: a Hyderabad retention team comparing last week's forest vs logistic must answer from tracked metrics, not scrolled notebook cells.
Notebook → script checklist
| Habit | Why |
|---|---|
One main() + if __name__ == "__main__" | Importable without side effects |
argparse for paths and hyperparams | CI and humans share the same CLI |
| Pin versions | "Works on my machine" is not a release |
| No secrets in repo | DB passwords and API keys stay in env |
import argparse
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description="Train churn model")
p.add_argument("--max-depth", type=int, default=5)
p.add_argument("--data", required=True)
return p
args = build_parser().parse_args(["--data", "churn.csv", "--max-depth", "4"])
print(args.data, args.max_depth)
assert args.max_depth == 4Save and load with joblib
import tempfile
from pathlib import Path
import joblib
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
X = rng.normal(size=(40, 3))
y = (X[:, 0] + X[:, 1] > 0).astype(int)
model = LogisticRegression(max_iter=500).fit(X, y)
with tempfile.TemporaryDirectory() as td:
path = Path(td) / "model.joblib"
joblib.dump(model, path)
loaded = joblib.load(path)
pred = int(loaded.predict(X[:1])[0])
print(pred)
assert pred in (0, 1)Pair the dump with the exact requirements.txt (and Docker image tag) so Bengaluru CI and a laptop in Pune load the same binary behaviour.
Experiment tracking shape (MLflow-compatible fields)
Log params, metrics, tags, and artifacts. Do not log secrets, raw PII, or full customer CSVs. Record git commit (or bundle hash) on every candidate that might go to production.
| Field | Examples |
|---|---|
| Params | n_estimators, max_depth, test_size |
| Metrics | f1_score, precision, recall |
| Tags | dataset=week_12, owner=retention |
| Artifacts | model file, confusion matrix image |
Offline JSONL logger (same mental model as mlflow.log_param / mlflow.log_metric):
import json
import tempfile
import uuid
from datetime import datetime, timezone
from pathlib import Path
def start_run(experiment: str) -> dict:
return {
"run_id": uuid.uuid4().hex[:12],
"experiment": experiment,
"started_at": datetime.now(timezone.utc).isoformat(),
"params": {},
"metrics": {},
}
def log_param(run: dict, key: str, value) -> None:
run["params"][key] = value
def log_metric(run: dict, key: str, value: float) -> None:
run["metrics"][key] = float(value)
run = start_run("churn")
log_param(run, "max_depth", 5)
log_metric(run, "f1_score", 0.81)
with tempfile.TemporaryDirectory() as td:
path = Path(td) / "runs.jsonl"
with path.open("a", encoding="ascii") as f:
f.write(json.dumps(run) + "\n")
line = path.read_text(encoding="ascii").strip()
print(run["run_id"], run["metrics"]["f1_score"])
assert "f1_score" in run["metrics"]
assert len(line) > 10Real MLflow Python shape (same fields; needs mlflow==2.18.0):
# requires: server
# Illustrative — start a local tracking URI before running in a notebook
import mlflow
with mlflow.start_run(run_name="churn-forest"):
mlflow.log_param("max_depth", 5)
mlflow.log_metric("f1_score", 0.81)
# mlflow.sklearn.log_model(model, "model")
print("logged")CLI reminders (bash fence for humans; not executed by the course runner):
mlflow ui --backend-store-uri ./mlruns
mlflow runs list --experiment-id 0Serve checklist (FastAPI)
| Item | Desk note |
|---|---|
| Pydantic request model | Reject bad types before predict |
/health | Load balancer / uptime checks |
| Model load once at startup | Avoid reload per request |
| Pin fastapi / uvicorn / pydantic | Match docs/mlops/requirements.txt |
from pydantic import BaseModel, Field
class ChurnRequest(BaseModel):
tenure_months: int = Field(ge=0)
tickets_30d: int = Field(ge=0)
req = ChurnRequest(tenure_months=14, tickets_30d=2)
print(req.tenure_months, req.tickets_30d)
assert req.tickets_30d == 2Drift — KS test sketch
Compare a reference feature distribution to live traffic. Significant shift → investigate data or upstream joins before blaming the model.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
ref = rng.normal(0.0, 1.0, size=500)
live = rng.normal(0.4, 1.1, size=500)
stat, p = stats.ks_2samp(ref, live)
print(round(float(stat), 4), round(float(p), 6))
assert 0.0 <= stat <= 1.0
assert 0.0 <= p <= 1.0Also log predictions (id, timestamp, score, model version) for audit — without dumping PAN or phone numbers into a shared store.
Decision table — promote or not
| Signal | Prefer promote | Hold back |
|---|---|---|
| Holdout F1 vs last champion | Clear win on frozen test | Tie or loss |
| Drift KS on key features | Stable | Sudden jump |
| Serving health | Green for soak window | Crash loops |
| Reproducibility | Pins + git SHA logged | Mystery notebook only |
How to use this card at work
Print or pin the tables, then open only the matching course lesson when a row needs a longer WHY. In Bengaluru and Pune standups, lead with units stakeholders already use — INR, orders, tickets — and name the pinned library versions so a teammate can reproduce the same snippet tomorrow. Prefer seasonal naive or a classical baseline beside any fancy number; desk cards exist to stop tribal knowledge, not to replace the full lessons.
Keep secrets in environment variables. Treat prices, FX rates, and model names as dated planning figures and re-check the provider or finance page before you budget. Prefer fail-closed behaviour for payouts and quarantine for dashboard freshness, the same way production pipelines do. If a formula here disagrees with a lesson that was updated later, trust the lesson and file a content fix.
Schedule an owner who re-runs the Monday scripts. Cards without owners quietly rot after the first festival week. Link official docs from Sources so reviews stay grounded. Use Indian workplace examples (UPI, GSTIN, IST calendars) without inventing APIs or hard-coding keys.
When two teammates disagree in Slack, open this card side by side with the live readout: if the formula is missing from the card, the experiment or forecast design is not finished. Write the threshold and the control model into the ticket before anyone tunes numbers. That habit is how Bengaluru ops and Pune finance stay aligned without a second war room. Keep scikit-learn==1.5.2, joblib==1.4.2, fastapi==0.115.5, and mlflow==2.18.0 from docs/mlops/requirements.txt so serve and track scripts match CI. Re-open the MLOps lessons when a promote decision needs the longer failure-mode narrative. Record model version, data hash, and owner in the same ticket as the promote rule.
Verified against the pinned course libraries documentation, September 2026.
Test yourself
- Name four fields worth logging for every experiment run.
- Why pin versions in
docs/mlops/requirements.txtbefore Dockerising? - Which library dumps and loads the sklearn model in the demo?
- True or false: it is fine to log raw customer phone numbers as MLflow artifacts by default.
- What does the offline JSONL logger store that matches MLflow's mental model?
- Why validate request bodies with pydantic before calling
predict? - What does a two-sample KS test compare for drift?
- Which package pin is
mlflow==2.18.0from? - Why record a git commit hash on production candidates?
- True or false: a green holdout metric alone is enough if serving health is crashing.
Related lessons
| Lesson | Topic |
|---|---|
| Notebook to script | argparse entrypoints |
| Saving models | joblib + env pins |
| FastAPI serve | REST + validation |
| Docker for ML | Image reproducibility |
| MLflow tracking | Params and metrics |
| Deploy free host | Health checks |
| Monitoring & drift | KS and audit logs |
| Capstone | End-to-end churn deploy |