Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·178

AI MLOps

The operational lifecycle that keeps models and AI features correct after launch: the loop of data, training, evaluation, registry, deployment, monitoring, feedback and retraining, maturity levels, dataset versioning and reproducible pipelines, experiment tracking with parameters, metrics and artefacts, the model registry with versions, aliases and approval stages, feature pipelines and feature stores with point-in-time correctness and training–serving skew, artefact storage and model packaging, end-to-end lineage, drift detection and retraining triggers, rollout strategies (shadow, canary, A/B, blue-green) and fast rollback, LLMOps specifics (prompt and configuration registries, evaluation gates, model gateways, pinned provider versions, fine-tune pipelines), governance and documentation, with MLflow code and a promotion gate in Python.

25 topics · ~15 min read · 28-question quiz
Updated Suggest a correction

Start here: shipping models like you ship code

A model in a notebook is an experiment. A model in production needs what any production software needs: a record of exactly what was built and from what, a way to test a new version against the current one before it reaches users, a careful rollout, monitoring, and a fast way back. MLOps is that discipline for models (and, for applications built on LLMs, for prompts, retrieval settings and evaluation sets too: "LLMOps").

The lifecycle in one line

track experiments → register versions → gate on evaluation → canary to a slice of traffic → promote → monitor for drift and quality → retrain or roll back.

What the lab did with MLflow

Three tumour-classifier versions (a logistic regression, a gradient-boosted model and a deliberately weak one) were trained, logged and registered in MLflow 3.17. The current model carried the alias champion:

Step What happened
gate v2 vs champion on a fixed 100-case golden set equal accuracy, worst case (90% bound) 2 points worse: within the 3-point margin → canary
gate v3 vs champion 10 points worse, lost 11 cases and won 1 → rejected
canary: 10% of new cases to v2 10 cases: too few to conclude anything; real canaries run until enough data accumulates
promote move the champion alias to v2: 10 ms; rollback is the same move back

And on the way, MLflow refused to save the gradient-boosted model until the lab explicitly declared one of its internal types trustworthy, because a tampered model file of that type could crash the server or read memory when loaded. Model files are code-like artefacts; treat them as part of your supply chain (Volume 10).

Drift: when the world changes

Production data drifts away from training data. A drift score such as PSI compares distributions. In the lab, a unit change (millimetres sent as centimetres) gave PSI 12.4, impossible to miss; but two samples of 100 unchanged rows scored up to 0.35, above the common "investigate at 0.25" rule of thumb. Set alarm thresholds from your own data's normal variation, and remember drift isn't the same as accuracy loss: added scanner noise barely moved PSI (0.09) yet cut accuracy from 97% to 95%.

How deep to go in MLOps

Volume 17 defines six mastery levels; for MLOps they look like this:

Level You can…
L1 explain tracking, registries, gates, canaries, drift and rollback
L2 log experiments, register models and deploy a version with a tool like MLflow
L3 design evaluation gates, data/model lineage, drift metrics and retraining triggers
L4 debug training–serving skew, silent degradation and failed rollouts
L5 design an ML/LLM platform: pipelines, feature stores, registries, monitoring, governance
L6 run MLOps at organisational scale with compliance, cost control and audits

The loop

The roadmap's lifecycle:

data → training → evaluation → registry → deployment → monitoring → feedback → retraining

dataversioned trainingtracked runs evaluationgates registryversions · aliases deploymentcanary · rollback monitoringquality · drift feedbacklabels · signals retrainingtrigger lineage + metadatacode · data · params · metrics
The MLOps loop. Versioned data feeds reproducible training pipelines; candidate models are evaluated against gates and registered with lineage; approved versions are deployed gradually; monitoring watches quality, drift and cost; feedback and labels flow back into the data, and retraining runs on a schedule or when triggers fire. Each stage records metadata so any production prediction can be traced to its code, data and parameters.

Why it matters: models decay as the world changes (drift), training is not reproducible without discipline, and deploying a model is not like deploying stateless code: behaviour depends on data you can't diff by eye.

Maturity levels

Level Characteristics
0: manual Notebooks, hand-run training, models copied to servers, no monitoring
1: pipeline automation Reproducible training pipelines, tracked experiments, registry, automated evaluation, scheduled or triggered retraining
2: CI/CD for pipelines Pipeline code tested and deployed like software; automatic promotion through gates; monitoring-driven retraining; full lineage

Most teams should aim for level 1 quickly; level 2 when many models or frequent retraining justify it.

Dataset versioning

Every training run must reference an immutable dataset version (chapter 150): DVC/lakeFS commits, Delta/Iceberg snapshot ids, or content-hashed files in object storage. Record it in the run metadata. Without it, you can't reproduce a model, explain a regression or honour a deletion request ("which models were trained on this user's data?").

Experiment tracking

Track for each run: code version (git commit), data version, parameters/hyperparameters, environment (library versions, container image, hardware), metrics (per epoch and final, on validation and test), artefacts (model files, plots, confusion matrices, evaluation reports), and tags (owner, purpose).

Python
import mlflow, numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

mlflow.set_tracking_uri("sqlite:///mlruns.db")               # a tracking server URL in a team setting
mlflow.set_experiment("churn")

X, y = make_classification(n_samples=5000, n_features=20, weights=[0.85], random_state=0)
X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)

def train_and_log(learning_rate, max_depth, data_version="churn-v12"):
    with mlflow.start_run() as run:
        mlflow.set_tags({"data_version": data_version, "git_commit": "3f9c2ab", "owner": "ml-platform"})
        mlflow.log_params({"learning_rate": learning_rate, "max_depth": max_depth})
        model = HistGradientBoostingClassifier(learning_rate=learning_rate, max_depth=max_depth, random_state=0)
        model.fit(X_tr, y_tr)
        auc = roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])
        mlflow.log_metric("val_auc", auc)
        info = mlflow.sklearn.log_model(                   # saved with skops (no arbitrary pickle code)
            model, name="model", input_example=X_val[:2],
            skops_trusted_types=["sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"])
        return info.model_uri, auc                         # MLflow 3: models are first-class "logged models"

runs = [train_and_log(lr, d) for lr in (0.05, 0.1) for d in (3, 6)]
best_uri, best_auc = max(runs, key=lambda r: r[1])
round(best_auc, 3)                                          # ≈ 0.98 on this synthetic task

Other trackers: Weights & Biases, Neptune, Comet, ClearML, cloud-native (SageMaker Experiments, Vertex AI Experiments, Azure ML), and Aim. For LLM work, the same platforms track prompt experiments and evaluation runs.

Model registry

A registry is the system of record for models that may be deployed:

  • Versions of each registered model, each linked to the run (code, data, params, metrics) that produced it.
  • Aliases or stages ("champion", "challenger", "staging", "production") that deployment systems resolve, so promotion and rollback are metadata changes, not file copies.
  • Approval workflow: who approved, evaluation evidence, model card.
  • Signatures and schemas: expected inputs and outputs; validated at load and serve time.
Python
from mlflow import MlflowClient
client = MlflowClient()
mv = mlflow.register_model(best_uri, "churn-classifier")          # creates version 1, 2, ...

def promotion_gate(candidate_auc, champion_auc=None, min_auc=0.85, max_regression=0.005):
    """Deterministic, documented promotion rule; real gates add slices, fairness, latency and cost checks."""
    if candidate_auc < min_auc: return False, f"AUC {candidate_auc:.3f} below floor {min_auc}"
    if champion_auc is not None and candidate_auc < champion_auc - max_regression:
        return False, f"regresses champion ({candidate_auc:.3f} < {champion_auc:.3f})"
    return True, "passes"

ok, reason = promotion_gate(best_auc, champion_auc=None)
if ok:
    client.set_registered_model_alias("churn-classifier", "champion", mv.version)
loaded = mlflow.pyfunc.load_model("models:/churn-classifier@champion")   # serving resolves the alias
ok, reason, loaded.predict(X_val[:3])                         # (True, 'passes', array([0, 1, 0]))

Feature pipelines and feature stores

For classical ML, features are often the hardest part to operate:

  • Feature pipelines compute features from raw data in batch (daily aggregates) and/or streaming (last-5-minute counts) and write them to an offline store (for training, with history) and an online store (low-latency key-value lookups for serving).
  • Point-in-time correctness: training examples must use feature values as of the label time (chapter 150's as-of joins), never future values.
  • Training–serving skew: the same feature computed differently in training (Python batch job) and serving (Java service) silently degrades models. One definition, used by both paths, eliminates it.
  • Feature stores (Feast, Tecton, Databricks, SageMaker, Vertex AI Feature Store, Hopsworks) provide registries of feature definitions, materialisation, point-in-time joins and online serving.

For LLM applications, the analogous problems are context pipelines: retrieval indexes, user profiles and memories kept fresh and consistent between evaluation and production (chapters 161, 170).

Artefact storage and packaging

  • Artefacts: model weights, tokenizers, preprocessing objects, evaluation reports, model cards, SBOMs. Store in versioned object storage or the registry's artefact store, content-addressed, with checksums.
  • Formats: safetensors for weights (chapter 152), ONNX or TorchScript/torch.export for portable inference, framework-native formats (MLflow pyfunc, BentoML bundles, joblib for scikit-learn with pinned versions), GGUF for local LLMs (chapter 165).
  • Containers: pin library versions; the same image for evaluation and serving where possible.
  • Signing and provenance: sign artefacts and record provenance (SLSA-style) to detect tampering (chapter 112).

Lineage

Lineage connects every production prediction back to: model version → training run → code commit, parameters, environment → dataset version → raw sources and labelling batches. And forward: which deployments, which predictions, which downstream decisions. Needed for debugging, audits, regulation (EU AI Act documentation for high-risk systems), and data-subject requests. Tools: registry + tracking metadata, OpenLineage/Marquez, DataHub, cloud lineage services.

Drift detection and retraining

Monitoring (chapter 177) feeds retraining decisions:

Drift Meaning Detect with
Data (covariate) drift Input distribution changes PSI, KS tests, embedding drift per feature
Prediction drift Output distribution changes Distribution of scores/classes
Concept drift Relationship between inputs and labels changes (fraud tactics evolve) Performance on fresh labels; delayed feedback
Upstream changes Schema changes, unit changes, broken pipelines Data validation (chapter 150)

Retraining strategies: scheduled (weekly), triggered (drift or performance below threshold), or continuous (online learning, rare in practice). Every retrained model goes through the same evaluation gates as any other candidate; automatic retraining without gates just automates regressions.

Rollout and rollback

Deploying a model changes behaviour for real users; release it like a risky feature (chapter 84's deployment strategies):

Strategy How Good for
Shadow New model receives live traffic, predictions logged but not used Validating latency, errors and agreement with the champion safely
Canary Small percentage of traffic, increasing in steps with automated checks Catching regressions with limited blast radius
A/B test Split traffic, measure business metrics with statistics (chapter 147) Proving value
Blue-green Two full environments; switch traffic at once Fast cut-over and rollback
Interleaving / bandits Mix results or adapt traffic to winners Ranking and recommendation

Rollback must be fast and boring: point the alias back to the previous version (or the gateway route back to the previous model), keep previous versions warm for high-traffic services, and decouple model rollout from code deploys. Automate rollback on guardrail breaches (error rate, latency, quality SLO burn).

LLMOps

LLM applications add their own artefacts and practices on top of the loop:

Artefact / practice What it means
Prompt and configuration registry Prompts, system instructions, tool definitions, retrieval parameters and model settings versioned together as a deployable configuration; changes reviewed like code
Evaluation gates Every change to prompts, models, retrieval or tools runs the regression suite (chapter 175) before promotion
Pinned model versions Use dated snapshot ids, not floating aliases, in production; plan migrations when providers deprecate versions, re-running evals
Model gateway One internal API in front of all providers and self-hosted models: routing, fallbacks, keys, quotas, logging, cost attribution, caching (chapter 179)
Fine-tune pipelines Dataset versions → training (LoRA/QLoRA, chapter 163) → evals → registry → serving (multi-LoRA); retrain when the base model changes
Index lifecycle Embedding model versions, re-indexing plans, freshness SLOs for RAG corpora (chapters 159–161)
Feedback loops Production traces and user feedback curated into evaluation and fine-tuning datasets, with consent and anonymisation
Release notes and model cards What changed, evaluation deltas, known limitations

A practical configuration-as-code approach: a repository containing prompt templates, tool schemas, retrieval settings and model ids per environment; CI runs evals on pull requests; merges deploy configuration to staging, then to production behind a canary.

Governance and documentation

  • Model cards (purpose, data, evaluation results by slice, limitations, intended and out-of-scope uses) and datasheets for datasets.
  • Risk classification of AI use cases (low/medium/high) determining required reviews, human oversight and monitoring depth.
  • Approvals and audit trails in the registry; separation of duties for high-risk models.
  • Responsible AI checks: fairness across groups, explainability where required, privacy reviews.
  • Regulatory alignment: EU AI Act obligations for high-risk systems (risk management, data governance, technical documentation, logging, human oversight, accuracy/robustness), sector regulations, and internal policies.

Platforms

Category Examples
Open-source building blocks MLflow (tracking, registry, evaluation), DVC, Kubeflow Pipelines, Airflow, Dagster, Prefect, Metaflow, ZenML, Feast, BentoML, KServe, Ray (train/serve)
Cloud ML platforms SageMaker, Vertex AI, Azure ML / AI Foundry, Databricks (MLflow + Unity Catalog)
LLMOps tooling Prompt registries and eval platforms (chapter 175), gateways (chapter 179), observability (chapter 177)

Start with the smallest set that gives you versioned data, tracked runs, a registry with aliases, automated evaluation gates, gradual rollout and monitoring; add the rest as the number of models grows.

Lab: a model release with MLflow

Setup. MLflow 3.17.2 with a SQLite tracking store and model registry, scikit-learn 1.9.1, on the lab machine. Data: scikit-learn's breast-cancer dataset (569 cases, 30 features), split 370 for training, a fixed golden set of 100 for release gates, and 99 "live" cases for the canary and drift experiments. Scope: a small tabular dataset makes the mechanics visible; the same steps apply to LLM applications, where the "model" version may be a prompt, a retrieval configuration or an adapter.

Experiment 1: track and register

Three candidates were trained, each in an MLflow run with its parameters and golden-set metrics, and registered as versions of tumour-classifier:

Version Run Golden AUC
v1 logistic regression, C = 1 0.9980
v2 histogram gradient boosting 0.9883
v3 logistic regression, C = 0.001 (deliberately over-regularised) 0.9714

Saving v2 first failed: MLflow's default scikit-learn serialisation (skops) found TreePredictor, a type that indexes arrays without bounds checks, so a crafted file could crash or read memory on predict(). The lab passed skops_trusted_types for that one type, because it built the model itself. Pickle-based formats would have loaded anything, including code; prefer safe formats, and verify provenance for models you didn't build.

Experiment 2: the release gate

Gate rule: on the golden set, the challenger's accuracy minus the champion's, with a 90% bootstrap lower bound (2,000 resamples), must be at least −0.03 (non-inferiority).

Champion → challenger Accuracy difference 90% lower bound Cases won / lost Decision
v1 → v2 +0.000 −0.020 1 / 1 canary
v1 → v3 −0.100 −0.160 1 / 11 reject

The gate reads models by alias (models:/tumour-classifier@champion, @challenger), so the script never hard-codes versions. In CI, a rejected gate fails the pipeline, and the reasons (which cases were lost) go in the report.

Experiment 3: canary, promotion, rollback

10% of the live cases (10) went to v2: accuracy 0.900, versus 0.967 for v1 on the other 90. That looks like a regression, but it's one misclassified case; the 95% interval for 9/10 runs from about 0.55 to 1.0. A real canary runs until the interval is narrow enough to decide, watches latency and error rates too, and stops early only on clear harm.

Promotion moved the champion alias to v2 in 10 ms; rollback is the same call with the old version. Because serving resolves the alias, neither needs a code deploy.

Experiment 4: drift, and what it doesn't tell you

PSI of the feature mean radius (10 quantile bins from training data) against 100 live rows:

Live data PSI Champion accuracy
baseline: 200 random samples of 100 unshifted rows median 0.210, 95th percentile 0.353 —
held-out rows, unchanged 0.375 0.970
values 3% larger (calibration drift) 0.368 0.960
unit change (mm sent as cm) 12.428 0.950
new scanner adds noise (σ = 2) 0.089 0.950
  • With 100 rows, sampling noise alone pushed PSI past the textbook 0.25 alarm most of the time. Calibrate thresholds on your own baseline, or use more data per window.
  • A unit change was unmistakable, but cost only 2 points of accuracy here, because 29 other features still carried the signal; in a model that leans on that feature it would be catastrophic. Schema and range checks (chapter 150) should catch it before PSI does.
  • Added noise lowered PSI below the baseline while accuracy fell from 0.97 to 0.95. Drift scores watch inputs; only outcome metrics (and delayed labels) watch quality.

Try it yourself

  1. Add a slice gate: the challenger must not be worse on the 30 largest tumours.
  2. Log the golden-set file as an MLflow artefact with its hash, and fail the gate if the hash changes without review.
  3. Simulate a canary with 500 live cases and stop it early with a sequential test.
  4. Register a prompt template as a versioned artefact and gate prompt changes the same way.

Revision sheet: MLOps

Key ideas

  • Lifecycle: data → training → tracking → registry → evaluation gates → staged rollout (shadow, canary, A/B) → monitoring → retraining/rollback.
  • Reproducibility: version code, data (snapshots/hashes), configuration, environment and seeds; record lineage.
  • Registry aliases (champion, challenger) decouple serving from versions; promotion and rollback are alias moves.
  • Gates: fixed golden sets, paired comparisons, non-inferiority margins, slice checks, safety and cost checks.
  • Monitoring: input drift (PSI, KS), prediction drift, outcome metrics with delayed labels, data-quality checks, latency/cost.
  • Training–serving skew: same feature code in both paths; feature stores with point-in-time correctness.
  • LLMOps: version prompts, retrieval configs, tools, adapters and eval sets; run evals in CI; monitor quality with sampled online evals.
  • Security: safe serialisation formats, signed artefacts, provenance for third-party models.

Numbers to remember

  • Lab: gate v1→v2 diff 0.000, lower bound −0.020 (canary); v1→v3 −0.100 (reject).
  • Lab: PSI baseline noise with 100 rows: median 0.21, p95 0.35; unit change 12.4.
  • Lab: promotion/rollback by alias in ~10 ms.

Pitfalls

  • Deploying by copying model files with no lineage.
  • Gates on tiny or changing evaluation sets.
  • Deciding canaries on a handful of requests.
  • Using textbook drift thresholds without a baseline.
  • Loading untrusted pickled models.

Glossary

  • Model registry: a versioned catalogue of models with metadata and aliases.
  • Champion / challenger: current production model / candidate replacement.
  • Canary release: sending a small share of traffic to a new version first.
  • PSI: population stability index, Σ (p − q) ln(p / q) over bins.
  • Training–serving skew: differences between training-time and serving-time data processing.