Rana Maninder Singh
Lesson 9 of 9MLOps

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

ResourceLink
CourseMLOps
Tracking lessonMLflow Tracking
Drift lessonMonitoring & 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.txt

Pinned 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.1

Offline 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

StageArtefactDesk check
Scriptargparse entrypointRuns without a notebook kernel
Environmentrequirements.txt + optional DockerSame pins on laptop and CI
Model filejoblib dumpLoad round-trips predict
Trackingparams, metrics, git SHAComparable runs
ServeFastAPI + pydanticHealth + validated JSON
Monitorprediction log + drift testOn-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

HabitWhy
One main() + if __name__ == "__main__"Importable without side effects
argparse for paths and hyperparamsCI and humans share the same CLI
Pin versions"Works on my machine" is not a release
No secrets in repoDB 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 == 4

Save 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.

FieldExamples
Paramsn_estimators, max_depth, test_size
Metricsf1_score, precision, recall
Tagsdataset=week_12, owner=retention
Artifactsmodel 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) > 10

Real 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 0

Serve checklist (FastAPI)

ItemDesk note
Pydantic request modelReject bad types before predict
/healthLoad balancer / uptime checks
Model load once at startupAvoid reload per request
Pin fastapi / uvicorn / pydanticMatch 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 == 2

Drift — 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.0

Also log predictions (id, timestamp, score, model version) for audit — without dumping PAN or phone numbers into a shared store.


Decision table — promote or not

SignalPrefer promoteHold back
Holdout F1 vs last championClear win on frozen testTie or loss
Drift KS on key featuresStableSudden jump
Serving healthGreen for soak windowCrash loops
ReproducibilityPins + git SHA loggedMystery 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

  1. Name four fields worth logging for every experiment run.
  2. Why pin versions in docs/mlops/requirements.txt before Dockerising?
  3. Which library dumps and loads the sklearn model in the demo?
  4. True or false: it is fine to log raw customer phone numbers as MLflow artifacts by default.
  5. What does the offline JSONL logger store that matches MLflow's mental model?
  6. Why validate request bodies with pydantic before calling predict?
  7. What does a two-sample KS test compare for drift?
  8. Which package pin is mlflow==2.18.0 from?
  9. Why record a git commit hash on production candidates?
  10. True or false: a green holdout metric alone is enough if serving health is crashing.

Related lessons

LessonTopic
Notebook to scriptargparse entrypoints
Saving modelsjoblib + env pins
FastAPI serveREST + validation
Docker for MLImage reproducibility
MLflow trackingParams and metrics
Deploy free hostHealth checks
Monitoring & driftKS and audit logs
CapstoneEnd-to-end churn deploy