MLOps and LLMOps

Updated · 7 min read
mediumPython 3.13aimlopsllmopsproductionmodel-registrydrift

MLOps (machine learning operations) is the set of practices that take a model from a notebook to a reliable product and keep it working after launch: versioning data and models, testing before release, deploying, monitoring, and retraining when the world changes. LLMOps applies the same ideas to applications built on large language models, where the things that change are also prompts, retrieved documents, model versions from a provider, cost per request and safety.

A model that scored well in testing can quietly get worse in production, because the data it sees changes. MLOps is how you notice and fix that.

The Lifecycle

StageDescription
DataIt is used to collect, clean, version and document the data a model learns from
Training and evaluationTrain candidates and score them on a fixed test or evaluation set
Versioning and registryIt is used to record each model with its data, settings and scores, so any version can be reproduced or rolled back
Release gateIt is used to promote a new version only if it beats the current one on agreed checks
DeploymentServe the model behind an API, often to a few users first; see "Deploying Models and AI Apps"
MonitoringWatch quality, drift, latency and cost; see "Monitoring Quality, Cost and Latency"
Retraining or rollbackIt is used to respond when monitoring shows a problem

Example: Versions, a Release Gate and Drift

The programs in this chapter need pip install fastapi httpx sentence-transformers scikit-learn torch transformers. Several use faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.

This program trains three versions of a digit classifier, records each in a simple registry, lets a release gate decide which runs in production, and then shows what drift does.

Version everything, gate every release, watch the data after launch
Python
import hashlib
import json
 
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
 
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25,
                                                    random_state=42, stratify=digits.target)
registry = []                                          # in real projects: MLflow, Weights & Biases, a database
 
def fingerprint(array):
    return hashlib.sha256(array.tobytes()).hexdigest()[:12]
 
def train_and_register(version, C):
    model = LogisticRegression(C=C, max_iter=5000).fit(X_train, y_train)
    record = {"version": version, "data": fingerprint(X_train), "params": {"C": C},
              "test_accuracy": round(model.score(X_test, y_test), 4)}
    registry.append(record)
    print("registered", json.dumps(record))
    return model
 
def promote(candidate, current, min_gain=0.005):
    """A release gate: only promote a new version if it is clearly better on the same test set."""
    gain = candidate["test_accuracy"] - current["test_accuracy"]
    winner = candidate if gain >= min_gain else current
    print(f"  gate: {candidate['version']} vs {current['version']}: {gain:+.4f} -> in production: {winner['version']}")
    return winner
 
v1 = train_and_register("v1", C=1.0)
production = registry[0]
v2 = train_and_register("v2", C=0.01)
production = promote(registry[1], production)
v3 = train_and_register("v3", C=0.1)
production = promote(registry[2], production)
 
# After launch: the inputs drift. Scanned digits arrive slightly shifted to the right.
shifted = np.roll(X_test.reshape(-1, 8, 8), 1, axis=2)
shifted[:, :, 0] = 0
print(f"\nv2 on data that drifted: {v2.score(shifted.reshape(-1, 64), y_test):.4f} (was {registry[1]['test_accuracy']})")
print(f"Overall input average: {X_test.mean():.2f} -> {shifted.mean():.2f} (hardly moves)")
print(f"Largest change in one pixel's average: {np.abs(X_test.mean(0) - shifted.reshape(-1, 64).mean(0)).max():.2f}"
      " (a clear warning)")
Output
registered {"version": "v1", "data": "b3f2e139ed5a", "params": {"C": 1.0}, "test_accuracy": 0.96}
registered {"version": "v2", "data": "b3f2e139ed5a", "params": {"C": 0.01}, "test_accuracy": 0.9667}
  gate: v2 vs v1: +0.0067 -> in production: v2
registered {"version": "v3", "data": "b3f2e139ed5a", "params": {"C": 0.1}, "test_accuracy": 0.96}
  gate: v3 vs v2: -0.0067 -> in production: v2
 
v2 on data that drifted: 0.4356 (was 0.9667)
Overall input average: 4.87 -> 4.85 (hardly moves)
Largest change in one pixel's average: 8.18 (a clear warning)

Explanation:

  • Each registry record stores the version, a fingerprint of the training data (b3f2e139ed5a), the settings and the test score. With these, anyone can rebuild or compare any version. Tools like MLflow or Weights & Biases do this for real projects.
  • The release gate promotes a candidate only if it beats production by at least half a point on the same test set. v2 wins (+0.0067) and goes live; v3 doesn't beat v2 (-0.0067), so v2 stays.
  • Drift: after launch, the scanned digits arrive shifted one pixel. Accuracy falls from 0.9667 to 0.4356, with no change to the model at all.
  • The overall input average barely moves (4.87 to 4.85), so a simple check would miss it. Per-pixel averages show a change of 8.18, a clear warning. Drift monitoring compares the distribution of today's inputs with the training data, feature by feature.

What LLMOps Adds

Also changesWhy it mattersWhat to do
PromptsA one-word edit can change answersVersion prompts like code and rerun the evaluation set
Retrieved documentsOutdated documents give outdated answersTrack document versions and refresh dates
The provider's modelHosted models are updated or retiredPin a model version; re-test before switching
Cost per requestLonger prompts and answers cost moreLog tokens and cost for every request
SafetyNew attacks and misuse appearLog flagged requests; see "Guardrails"
User feedbackRatings show problems tests missedReview low ratings and add them to the evaluation set

Common Mistakes

No record of what is in production. When something breaks, nobody knows which model, prompt or data caused it.

Comparing versions on different test sets. A release gate needs the same fixed set every time.

Monitoring only uptime. A service can respond in 3 ms and still be wrong; monitor quality too.

Retraining on bad data. Check new data before training on it, or the next version learns the problem.

Interview Corner

What is MLOps?

The practices and tools that make machine learning reliable in production: versioning data and models, automated evaluation and release gates, deployment, monitoring for quality and drift, and retraining or rollback.

What is data drift, and how do you detect it?

A change in the input data after deployment, so it no longer looks like the training data. Compare feature distributions over time with the training data, watch prediction distributions and quality metrics, and alert when they move beyond agreed limits.

Practice

Exercise: a stricter gate. Change min_gain to 0.01. Which version ends up in production now? When would a stricter gate be the right choice?

Check your understanding:

  1. Why does each registry record include a fingerprint of the data?
  2. Why did v3 not replace v2?
  3. Why did the overall input average fail to show the drift?

Quick check: MLOps

4 questions
1Which version did the release gate put in production?
2What happened to accuracy when the inputs drifted?
3What does LLMOps version that classic MLOps often doesn't?
4What is a release gate?

Key Takeaways

Quick reference

NeedPractice
Reproduce a modelRecord data fingerprint, settings, code version and scores
Decide a releaseSame evaluation set, a minimum gain, no failing safety checks
Detect driftCompare per-feature distributions with training data
Undo a bad releaseKeep the previous version ready to roll back
Data fingerprinthashlib.sha256(array.tobytes()).hexdigest()

Was this tutorial helpful?

Lesson 158 of 186