MLOps and LLMOps
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
| Stage | Description |
|---|---|
| Data | It is used to collect, clean, version and document the data a model learns from |
| Training and evaluation | Train candidates and score them on a fixed test or evaluation set |
| Versioning and registry | It is used to record each model with its data, settings and scores, so any version can be reproduced or rolled back |
| Release gate | It is used to promote a new version only if it beats the current one on agreed checks |
| Deployment | Serve the model behind an API, often to a few users first; see "Deploying Models and AI Apps" |
| Monitoring | Watch quality, drift, latency and cost; see "Monitoring Quality, Cost and Latency" |
| Retraining or rollback | It 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.
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)")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 changes | Why it matters | What to do |
|---|---|---|
| Prompts | A one-word edit can change answers | Version prompts like code and rerun the evaluation set |
| Retrieved documents | Outdated documents give outdated answers | Track document versions and refresh dates |
| The provider's model | Hosted models are updated or retired | Pin a model version; re-test before switching |
| Cost per request | Longer prompts and answers cost more | Log tokens and cost for every request |
| Safety | New attacks and misuse appear | Log flagged requests; see "Guardrails" |
| User feedback | Ratings show problems tests missed | Review 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:
- Why does each registry record include a fingerprint of the data?
- Why did v3 not replace v2?
- Why did the overall input average fail to show the drift?
Key Takeaways
Quick reference
| Need | Practice |
|---|---|
| Reproduce a model | Record data fingerprint, settings, code version and scores |
| Decide a release | Same evaluation set, a minimum gain, no failing safety checks |
| Detect drift | Compare per-feature distributions with training data |
| Undo a bad release | Keep the previous version ready to roll back |
| Data fingerprint | hashlib.sha256(array.tobytes()).hexdigest() |
Was this tutorial helpful?