Regression Testing for LLMs: Detecting Model Drift and Output Changes
You deploy your AI feature. It works great. Three weeks later, users report subtly different behavior — answers that used to be concise are now verbose, a classifier that used to be sharp is now hedging, a summarizer is dropping key facts. Nobody changed the code. But something changed.
This is model drift: the silent degradation of LLM behavior caused by model version updates, provider-side changes, or the accumulated effect of prompt environment changes. Detecting it requires a discipline that most teams do not build until it has already cost them.
This post is about building that discipline: regression test suites for LLMs, golden dataset management, statistical testing for output distribution changes, and CI pipelines that catch drift before users do.
What Causes LLM Output Changes
Understanding the sources of drift helps you design the right detection strategy.
Model version updates. OpenAI, Anthropic, and Google update their models continuously. A gpt-4o response today may differ from the same call six months ago. Most providers do not give you guaranteed output stability on non-dated model aliases.
Prompt environment changes. Even if your prompt text is identical, changes to system messages, message ordering, or context length can shift output distributions in ways that look like model drift.
Temperature and sampling drift. At temperature > 0, outputs vary by design. Over many samples, a distribution shift can be real even when individual outputs look fine.
Provider infrastructure changes. Tokenization updates, safety filter adjustments, and load-balancing changes at the API level can all affect outputs without any model version change.
Your own code changes. Context truncation logic, input preprocessing, output postprocessing — any of these can silently change what the model sees or what you do with its response.
Building a Regression Test Suite
A regression test suite for LLMs has three components: a golden dataset, a set of metrics to compute, and a comparison baseline.
Golden Dataset Structure
Your golden dataset is a set of inputs where you have established what "good" looks like. It does not need to be large — 50 to 200 well-chosen examples beats 10,000 random ones.
{"id": "cls-001", "input": "I was charged twice this month", "expected_category": "billing", "expected_confidence_min": 0.8, "tags": ["billing", "clear"]}
{"id": "cls-002", "input": "The app keeps crashing when I open it", "expected_category": "technical_issue", "tags": ["technical", "clear"]}
{"id": "cls-003", "input": "Is there a way to export my data?", "expected_category": "feature_request", "tags": ["feature", "ambiguous"]}
{"id": "cls-004", "input": "Just wanted to say thanks for the quick response", "expected_category": "general_inquiry", "tags": ["positive", "off-topic"]}
{"id": "cls-005", "input": "What are your pricing plans?", "expected_category": "billing", "tags": ["billing", "pre-purchase"]}Include:
- Clear cases — unambiguous inputs where you are confident about the expected output
- Ambiguous cases — inputs that sit on category boundaries; useful for detecting when model behavior shifts on edge cases
- Adversarial cases — inputs designed to probe model weaknesses
- Tag metadata — so you can slice regression results by category
Running a Regression Pass
# eval/regression.py
import json
import time
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Optional
import openai
@dataclass
class RegressionResult:
id: str
input: str
expected: dict
actual_output: str
actual_parsed: Optional[dict]
passed: bool
metric_scores: dict
latency_ms: float
error: Optional[str] = None
def run_regression_suite(
dataset_path: str,
model_fn, # callable: input -> output string
scorers: dict # name -> scorer callable
) -> list[RegressionResult]:
results = []
with open(dataset_path) as f:
samples = [json.loads(line) for line in f if line.strip()]
for sample in samples:
start = time.monotonic()
try:
output = model_fn(sample["input"])
latency = (time.monotonic() - start) * 1000
scores = {}
for name, scorer in scorers.items():
scores[name] = scorer(sample, output)
passed = all(
scores.get(f"{k}_pass", True)
for k in scores
)
results.append(RegressionResult(
id=sample["id"],
input=sample["input"],
expected=sample,
actual_output=output,
actual_parsed=None,
passed=passed,
metric_scores=scores,
latency_ms=latency
))
except Exception as e:
results.append(RegressionResult(
id=sample["id"],
input=sample["input"],
expected=sample,
actual_output="",
actual_parsed=None,
passed=False,
metric_scores={},
latency_ms=0,
error=str(e)
))
return resultsSaving and Comparing Baselines
import json
from pathlib import Path
from datetime import datetime
BASELINE_DIR = Path("eval/baselines")
def save_baseline(results: list[RegressionResult], name: str) -> Path:
BASELINE_DIR.mkdir(parents=True, exist_ok=True)
baseline = {
"timestamp": datetime.utcnow().isoformat(),
"name": name,
"pass_rate": sum(1 for r in results if r.passed) / len(results),
"metric_means": compute_metric_means(results),
"results": [asdict(r) for r in results]
}
path = BASELINE_DIR / f"{name}.json"
with open(path, "w") as f:
json.dump(baseline, f, indent=2)
return path
def compare_to_baseline(
current: list[RegressionResult],
baseline_name: str,
thresholds: dict = None
) -> dict:
thresholds = thresholds or {"pass_rate_min_delta": -0.05}
baseline_path = BASELINE_DIR / f"{baseline_name}.json"
with open(baseline_path) as f:
baseline = json.load(f)
current_pass_rate = sum(1 for r in current if r.passed) / len(current)
baseline_pass_rate = baseline["pass_rate"]
delta = current_pass_rate - baseline_pass_rate
# Find regressions: samples that passed before but fail now
baseline_passed = {r["id"] for r in baseline["results"] if r["passed"]}
current_passed = {r.id for r in current if r.passed}
regressions = baseline_passed - current_passed
improvements = current_passed - baseline_passed
return {
"pass_rate_delta": delta,
"regressions": list(regressions),
"improvements": list(improvements),
"passed": delta >= thresholds.get("pass_rate_min_delta", -0.05),
"summary": f"Pass rate: {baseline_pass_rate:.1%} → {current_pass_rate:.1%} ({delta:+.1%})"
}Statistical Testing for Output Distribution Changes
When outputs are numerical scores or continuous distributions (e.g., confidence scores, quality ratings), statistical tests are more sensitive than simple pass-rate comparisons.
Kolmogorov-Smirnov Test for Distribution Shift
from scipy import stats
import numpy as np
def detect_distribution_shift(
baseline_scores: list[float],
current_scores: list[float],
alpha: float = 0.05
) -> dict:
"""
Use KS test to detect if current score distribution has shifted
significantly from baseline.
"""
statistic, p_value = stats.ks_2samp(baseline_scores, current_scores)
return {
"ks_statistic": statistic,
"p_value": p_value,
"shift_detected": p_value < alpha,
"baseline_mean": np.mean(baseline_scores),
"current_mean": np.mean(current_scores),
"mean_delta": np.mean(current_scores) - np.mean(baseline_scores)
}
# Usage
baseline_confidences = [0.95, 0.88, 0.92, 0.71, 0.99, ...] # stored from last run
current_confidences = [0.84, 0.79, 0.81, 0.68, 0.91, ...] # from current run
result = detect_distribution_shift(baseline_confidences, current_confidences)
if result["shift_detected"]:
print(f"ALERT: Distribution shift detected! p={result['p_value']:.4f}")
print(f"Mean confidence: {result['baseline_mean']:.3f} → {result['current_mean']:.3f}")Tracking Output Length Distribution
Length distribution changes are a sensitive early indicator of prompt behavior drift — models that suddenly become much more verbose or terse have usually changed in some meaningful way.
def analyze_length_drift(
baseline_outputs: list[str],
current_outputs: list[str]
) -> dict:
baseline_lengths = [len(o.split()) for o in baseline_outputs]
current_lengths = [len(o.split()) for o in current_outputs]
ks_result = detect_distribution_shift(baseline_lengths, current_lengths)
pct_change = (np.mean(current_lengths) - np.mean(baseline_lengths)) / np.mean(baseline_lengths)
return {
**ks_result,
"baseline_median_words": np.median(baseline_lengths),
"current_median_words": np.median(current_lengths),
"pct_length_change": pct_change,
"verbosity_alert": abs(pct_change) > 0.20 # Alert if >20% length change
}Managing Model Version Changes
When you intentionally upgrade to a new model version, you need to validate that quality is maintained or improved across your golden dataset before switching production traffic.
# eval/model_comparison.py
from concurrent.futures import ThreadPoolExecutor
import statistics
def compare_models(
dataset: list[dict],
model_a: str,
model_b: str,
metric_fn,
n_workers: int = 5
) -> dict:
def run_sample(sample):
output_a = call_model(model_a, sample["input"])
output_b = call_model(model_b, sample["input"])
score_a = metric_fn(sample, output_a)
score_b = metric_fn(sample, output_b)
return {
"id": sample["id"],
"score_a": score_a,
"score_b": score_b,
"winner": "A" if score_a > score_b else ("B" if score_b > score_a else "tie")
}
with ThreadPoolExecutor(max_workers=n_workers) as ex:
comparisons = list(ex.map(run_sample, dataset))
a_wins = sum(1 for c in comparisons if c["winner"] == "A")
b_wins = sum(1 for c in comparisons if c["winner"] == "B")
ties = sum(1 for c in comparisons if c["winner"] == "tie")
return {
"model_a": model_a,
"model_b": model_b,
"a_win_rate": a_wins / len(comparisons),
"b_win_rate": b_wins / len(comparisons),
"tie_rate": ties / len(comparisons),
"mean_score_a": statistics.mean(c["score_a"] for c in comparisons),
"mean_score_b": statistics.mean(c["score_b"] for c in comparisons),
"regressions": [c for c in comparisons if c["winner"] == "A"],
"improvements": [c for c in comparisons if c["winner"] == "B"]
}CI Pipeline for LLM Regression
A well-structured CI pipeline runs regression tests at the right frequency — fast checks on every PR, full regression on merge to main, comprehensive nightly runs.
# .github/workflows/llm-regression.yml
name: LLM Regression Tests
on:
pull_request:
paths:
- 'prompts/**'
- 'app/chains/**'
- 'app/llm/**'
push:
branches: [main]
schedule:
- cron: '0 2 * * *' # 2am UTC nightly
jobs:
smoke-regression:
name: Smoke Regression (PR)
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: '3.11' }
- run: pip install -r requirements.txt
- name: Run smoke regression (20 samples, cheap model)
run: |
python -m eval.regression \
--dataset eval/golden_dataset_smoke.jsonl \
--model gpt-4o-mini \
--baseline main \
--threshold-delta -0.10 \
--output eval/results/pr-${{ github.run_id }}.json
- name: Upload results
uses: actions/upload-artifact@v4
with:
name: regression-results
path: eval/results/
full-regression:
name: Full Regression (main)
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
steps:
- uses: actions/checkout@v4
- run: pip install -r requirements.txt
- name: Run full regression suite
run: |
python -m eval.regression \
--dataset eval/golden_dataset.jsonl \
--model gpt-4o \
--update-baseline \
--threshold-delta -0.05
- name: Post regression report to PR
if: always()
run: python -m eval.report --format markdown >> $GITHUB_STEP_SUMMARYGenerating Human-Readable Diff Reports
When regression tests fail, you need to know exactly what changed — not just that pass rate dropped.
def generate_regression_report(comparison: dict) -> str:
lines = [
"## LLM Regression Report",
f"**{comparison['summary']}**",
""
]
if comparison["regressions"]:
lines.append(f"### Regressions ({len(comparison['regressions'])} samples)")
lines.append("These samples passed before but fail now:")
lines.append("")
for reg_id in comparison["regressions"][:10]:
lines.append(f"- `{reg_id}`")
if len(comparison["regressions"]) > 10:
lines.append(f" ... and {len(comparison['regressions']) - 10} more")
lines.append("")
if comparison["improvements"]:
lines.append(f"### Improvements ({len(comparison['improvements'])} samples)")
for imp_id in comparison["improvements"][:5]:
lines.append(f"- `{imp_id}`")
lines.append("")
status = "PASSED" if comparison["passed"] else "FAILED"
lines.append(f"**Status: {status}**")
return "\n".join(lines)Practical Workflow: Handling a Prompt Change
When a developer modifies a prompt, the workflow should be:
- Run smoke regression against the modified prompt on 20–50 samples from the golden dataset
- Review the diff report — which specific samples changed behavior?
- Classify each regression — intentional change (prompt was improved) or unintended (prompt broke something)
- Update the golden dataset if expected outputs should change
- Gate the PR on regression passing the threshold
For teams using platforms like HelpMeTest, the end-to-end user-facing behavior should also be tested — a prompt change that improves classification accuracy but breaks the UI's display of results is still a regression from the user's perspective.
Summary
LLM regression testing is not optional for teams running AI in production. The core practices:
- Maintain a golden dataset — versioned, tagged, representative of real user inputs
- Save baselines after every significant change or deployment
- Use statistical tests (KS test, mean comparison) for continuous metrics, not just pass/fail
- Automate in CI — fast smoke tests on PR, full regression on merge, nightly drift detection
- Generate diff reports — not just a pass/fail, but exactly which samples changed and how
The teams that get blindsided by model drift are the ones without baselines. Once you have a baseline, drift becomes detectable. Once it is detectable, it becomes manageable.