Making LLM Evaluation Reproducible with MLflow
An LLM evaluation score is only useful if you can say what produced it. When the number moves from 0.82 to 0.78, was it the prompt, the model, the data, the judge, or luck? Without pinned inputs you cannot tell. This post lists the causes, how to pin each, and what MLflow 3.x provides.
In earlier work on a document-intelligence platform for construction, I introduced MLflow and Temporal, making AI evaluation reproducible and observable, and built LLM features from conversational agents to extraction pipelines. What follows is general technique, checked against the documentation, not a report on any one system.
Version notice. Written and run with MLflow 3.18.0, the version pip install mlflow gave on 1 December 2026. PyPI lists it as released on 3 November 2026 and the GitHub release page dates it 4 November (PyPI, release notes). The GenAI API is still moving, so pin the version and recheck names when you upgrade.
In short
- Six things silently change an LLM evaluation: the prompt, the model, sampling, the dataset, the judge and the glue code. Pin all six, record them on every run, and report scores with intervals: on a synthetic 50-row set the 95 per cent range is 22 points wide.
- MLflow 3.18 covers most of it: a prompt registry with numbered versions, evaluation datasets,
mlflow.genai.evaluatewith code-based scorers and LLM judges, tracing, and an experimentalquality_criteriagate. - Start with deterministic scorers, as in Trustworthy LLM Table Extraction: Layered Validation. Use an LLM judge only where code cannot check, after measuring its agreement with human labels.
- MLflow does not pin the provider's model for you, and evaluation datasets need a SQL backend, so the model identifier and the store are your responsibility.
What makes an evaluation irreproducible
Reproducible here means that, given the recorded inputs, someone else gets the same score, or one within a measured spread. Six inputs break that, each with a different fix.
| Source of drift | What happens | How to pin it |
|---|---|---|
| Prompt | Text is edited in code or a notebook, with no record of which text scored what | Registry version, loaded by number |
| Model | An alias is repointed to a newer snapshot, or serving infrastructure changes | Snapshot ID logged as a parameter |
| Sampling | Temperature, top-p, seed or max tokens differ between runs | Explicit values, logged, and repeats to measure spread |
| Dataset | Rows are added, fixed or reordered between runs | Named, versioned dataset; a new name for a new set |
| Judge | The judge model or its instructions change, moving every score | Pinned judge model and instructions; calibration against human labels |
| Glue code | Pre-processing, parsing or post-processing is changed and not recorded | Code revision logged with the run; processing inside the traced function |
Pin the model and the sampling
Anthropic's documentation says every current Claude model ID is a pinned version: weights do not change under an existing ID, and updates ship under a new ID. Only some earlier models have convenience aliases that point at the latest dated snapshot. The same page adds a caveat that affects evaluation: serving infrastructure such as the request router, safety classifiers and sampling logic can change, and occasionally produces small behavioural differences even when the ID and weights have not (Model IDs and versioning).
Two rules follow. Log the full dated or snapshot ID, never a family nickname. Treat sampling settings as inputs: set temperature, top-p, maximum tokens and any seed explicitly, and record them. A low temperature narrows the spread but does not guarantee identical text, so for any score you gate on, run the evaluation several times and keep the spread.
MLflow does not enforce any of this. It gives you places to record it: run parameters in the demo below, the model_id argument of mlflow.genai.evaluate (per its docstring in 3.18.0), and mlflow.set_active_model, which link results or traces to a logged model version (version tracking).
Version prompts, not strings
MLflow's prompt registry stores templates with {{variable}} placeholders. Calling mlflow.genai.register_prompt with an existing name creates a new version, and mlflow.genai.load_prompt loads by version URI such as prompts:/summarization-prompt/2 or by alias URI such as prompts:/summarization-prompt@production. A bare name, or @latest, loads the newest version (prompt registry).
Evaluating @latest or an alias lets the prompt change between runs without any code change. The docs give version loads an infinite cache time and alias loads 60 seconds by default. For evaluation, load by explicit version number and log the URI. Use aliases such as production for serving, where moving a pointer is intended.
Freeze the dataset
An evaluation dataset is a set of records, each with inputs and expectations (the ground truth). In MLflow, mlflow.genai.datasets.create_dataset creates a named dataset attached to an experiment, and merge_records adds records from dictionaries, a DataFrame or traces (evaluation datasets). Datasets need a tracking server with a SQL backend and are not supported on the plain file store, so the demo uses SQLite. The docs page does not describe versioning or immutability, and merge_records adds records to an existing dataset. Treat a dataset name as a release: when rows change, create triage-v2 rather than editing triage-v1, so old scores stay comparable.
Deterministic scorers first, judges second
A scorer is a function that turns an output into a score. MLflow has two kinds: code-based scorers, written with the @scorer decorator, and LLM judges, which ask a model to grade the output (scorers). Code scorers are free, instant and exactly repeatable: exact match, regular expressions, JSON schema validity, length limits. Use them wherever they can express the check.
An LLM judge adds a second model to the experiment, and that model drifts too. The quickstart notes that the built-in judges default to an OpenAI model unless you pass model=, and the scorer docs give an environment variable, MLFLOW_GENAI_JUDGE_DEFAULT_MODEL, to change the default (quickstart). Pass the judge model explicitly and log it, so a changed default cannot move scores.
Judges also have known biases. The MT-Bench paper reports position, verbosity and self-enhancement bias, and also that a strong judge agreed with human preferences over 80 per cent of the time, about as often as humans agree with each other (Zheng et al., 2023). That makes a judge usable, not neutral. Calibrate it: have people label a sample, run the judge on the same sample, and measure agreement. Raw agreement flatters a judge that mostly says "pass", so also compute Cohen's kappa, which discounts chance agreement. A toy example with synthetic labels shows the gap:
from collections import Counter
human = ["pass", "pass", "fail", "pass", "fail", "fail", "pass", "pass", "fail", "pass"]
judge = ["pass", "pass", "pass", "pass", "fail", "fail", "pass", "pass", "pass", "pass"]
def cohen_kappa(a: list[str], b: list[str]) -> float:
n = len(a)
observed = sum(x == y for x, y in zip(a, b)) / n
ca, cb = Counter(a), Counter(b)
expected = sum(ca[k] * cb[k] for k in ca.keys() | cb.keys()) / n**2
return (observed - expected) / (1 - expected)
agree = sum(x == y for x, y in zip(human, judge)) / len(human)
print(f"raw agreement {agree:.2f}, kappa {cohen_kappa(human, judge):.2f}")
raw agreement 0.80, kappa 0.55
Eighty per cent agreement sounds fine, but a kappa of 0.55 says the judge is lenient: it passed two of the four outputs that humans failed. Real data needs far more than ten labels. MLflow also documents automatic judge alignment from human feedback using DSPy; in 3.18.0, Judge.align(traces, optimizer=None) returns a new aligned judge and defaults to a MemAlign optimiser. It was not run here, since it needs a model; re-measure agreement after aligning.
A runnable comparison of two prompt versions
The demo below needs no server and no API key. It uses a SQLite file as the tracking store, registers two prompt versions, builds a five-row dataset, and evaluates a fake rule-based "model" whose behaviour depends on the prompt text. In a real system the marked line would call a model client. The scores show what the pipeline measures, not how a real model behaves.
import re
import mlflow
from mlflow.genai import scorer
from mlflow.genai.datasets import create_dataset
mlflow.set_tracking_uri("sqlite:///mlflow.db")
exp = mlflow.set_experiment("support-triage-eval")
V1 = "Classify the ticket as billing, bug or other. Ticket: {{ticket}}"
V2 = ("Classify the ticket as billing, bug or other. Answer with one lowercase "
"word and nothing else. Ticket: {{ticket}}")
p1 = mlflow.genai.register_prompt(name="triage", template=V1, commit_message="baseline")
p2 = mlflow.genai.register_prompt(name="triage", template=V2, commit_message="one word only")
print("prompt versions:", p1.version, p2.version)
ds = create_dataset(name="triage-v1", experiment_id=[exp.experiment_id],
tags={"purpose": "regression"})
rows = [
("I was charged twice this month", "billing"),
("The export button crashes the app", "bug"),
("Do you have an office in Berlin?", "other"),
("My invoice shows the wrong VAT", "billing"),
("Login page shows a blank screen", "bug"),
]
ds.merge_records([{"inputs": {"ticket": t}, "expectations": {"label": y}} for t, y in rows])
print("dataset records:", len(ds.to_df()), "digest:", ds.digest)
def make_predict(prompt_uri):
prompt = mlflow.genai.load_prompt(prompt_uri)
terse = "one lowercase word" in prompt.template
@mlflow.trace
def predict(ticket: str) -> str:
_ = prompt.format(ticket=ticket) # a real client would send this text
t = ticket.lower()
label = ("billing" if re.search(r"charg|invoice|vat", t)
else "bug" if re.search(r"crash|blank|error", t) else "other")
return label if terse else f"The category is: {label.capitalize()}."
return predict
@scorer
def exact_label(outputs: str, expectations: dict) -> bool:
return outputs == expectations["label"]
@scorer
def one_word(outputs: str) -> bool:
return len(outputs.split()) == 1
results = {}
for v in (p1.version, p2.version):
with mlflow.start_run(run_name=f"triage-v{v}"):
mlflow.log_params({"prompt_uri": f"prompts:/triage/{v}", "model": "fake-rules-1",
"temperature": 0.0, "dataset": "triage-v1"})
results[v] = mlflow.genai.evaluate(
data=ds, predict_fn=make_predict(f"prompts:/triage/{v}"),
scorers=[exact_label, one_word])
for v, r in results.items():
print(f"v{v}", {k: round(float(x), 2) for k, x in r.metrics.items()})
runs = mlflow.search_runs(experiment_ids=[exp.experiment_id], output_format="pandas")
cols = ["tags.mlflow.runName", "params.prompt_uri", "metrics.exact_label/mean"]
print(runs[cols].sort_values("tags.mlflow.runName").to_string(index=False))
BASELINE_MIN = 0.8
new = float(results[p2.version].metrics["exact_label/mean"])
if new < BASELINE_MIN:
raise SystemExit(f"gate failed: {new:.2f} < {BASELINE_MIN}")
print(f"gate passed: {new:.2f} >= {BASELINE_MIN}")
Output from MLflow 3.18.0 on Python 3.13 (progress logging omitted; the metric order within a line can vary, and the dataset digest differs from run to run):
prompt versions: 1 2
dataset records: 5 digest: e9354287
v1 {'exact_label/mean': 0.0, 'one_word/mean': 0.0}
v2 {'one_word/mean': 1.0, 'exact_label/mean': 1.0}
tags.mlflow.runName params.prompt_uri metrics.exact_label/mean
triage-v1 prompts:/triage/1 0.0
triage-v2 prompts:/triage/2 1.0
gate passed: 1.00 >= 0.8
Version 1 scores zero because the fake model, like many real ones, wraps the label in a sentence when the prompt does not forbid it, and an exact-match scorer rejects that. Version 2 fixes it. Each run carries its prompt URI and settings, and mlflow.search_runs lists them side by side. The MLflow UI offers trace-level comparison and, in 3.18, an experimental Python API for statistical comparisons that separate real change from noise (3.18.0 notes). Five rows is far too few for such a conclusion; the next section puts numbers on how many are needed.
How much of a score change is noise
Pinning removes the changes you control; chance remains, in two forms. Sampling noise is the model answering a row differently on a rerun. Dataset noise is the score depending on which rows are in the set. Repeats on a frozen dataset measure only the first; an interval over rows measures the second, usually the larger.
A stochastic fake model was evaluated on synthetic data. Each row has a success probability drawn from Beta(1.6, 0.4) (mean 0.80), and each answer is an independent coin flip with it, so the true accuracy is exactly 0.80. For each size, 2,000 evaluations were run on one fixed dataset and on a fresh dataset each time. The last two columns are the bootstrap interval from one run's per-row results (1,000 resamples), averaged over 400 runs, and how often it contained 0.80.
| Rows | Same set: sd | Same set: 95% range | Fresh set: 95% range | Bootstrap width | Bootstrap coverage |
|---|---|---|---|---|---|
| 20 | 7.8 | 30.0 | 35.0 | 32.3 | 92.5% |
| 50 | 4.8 | 18.0 | 22.0 | 21.6 | 95.8% |
| 200 | 2.3 | 9.0 | 11.5 | 10.9 | 94.8% |
| 1000 | 1.1 | 4.1 | 5.0 | 4.9 | 94.5% |
Widths in percentage points; synthetic data, seed 2026.
- Small sets cannot rank prompts. On 50 rows, identical systems routinely differ by ten points or more. Fresh-set widths follow
2 * 1.96 * sqrt(p(1-p)/n): 35.1, 22.2, 11.1 and 5.0 points. - Repeats alone understate the uncertainty. The repeated-run range is narrower at every size because the row selection is fixed. On the fixed 50-row set the mean row probability was 0.77, so every repeat was centred on the wrong value: a tight spread shows stability, not correctness.
- The bootstrap over rows is cheap and works. Its width is close to the fresh-set range and it contained 0.80 in 92.5 to 95.8 per cent of runs, falling short only at 20 rows (with 400 runs per size, coverage figures carry about 1 point of noise). It needs only the per-row scores MLflow stores.
A bootstrap interval from MLflow results
In 3.18.0, the result of mlflow.genai.evaluate has a result_df with one row per record and a <scorer>/value column per scorer. Resampling that column gives the interval (100 synthetic rows, fake model with true accuracy 0.80):
import random
import mlflow
import numpy as np
from mlflow.genai import scorer
from mlflow.genai.datasets import create_dataset
mlflow.set_tracking_uri("sqlite:///mlflow.db")
exp = mlflow.set_experiment("bootstrap-demo")
rng = random.Random(0)
ds = create_dataset(name="synthetic-100", experiment_id=[exp.experiment_id])
ds.merge_records([{"inputs": {"i": i}, "expectations": {"label": "ok"}} for i in range(100)])
def predict(i: int) -> str:
return "ok" if rng.random() < 0.8 else "no" # stochastic fake model
@scorer
def exact_label(outputs: str, expectations: dict) -> bool:
return outputs == expectations["label"]
res = mlflow.genai.evaluate(data=ds, predict_fn=predict, scorers=[exact_label])
x = res.result_df["exact_label/value"].astype(float).to_numpy()
boot = np.random.default_rng(1).choice(x, size=(10_000, len(x))).mean(axis=1)
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f"score {x.mean():.2f}, 95% bootstrap interval [{lo:.2f}, {hi:.2f}]")
score 0.71, 95% bootstrap interval [0.62, 0.80]
The run drew 71 correct out of 100, an unlucky draw (71 or fewer occurs in about 2 per cent of runs, by the binomial distribution). The true value, 0.80, sits at the upper edge of the interval; a 95 per cent interval excludes the truth in about one run in twenty. The bare 0.71 would have suggested a regression that does not exist. The bootstrap assumes independent rows; when rows share a document, resample those groups. An LLM judge adds variance that only repeated judging shows.
How many rows to detect a change
How many rows make a change detectable? Assumptions: baseline accuracy 0.80 against 0.82, 0.85 or 0.90, two-sided significance 0.05 (z = 1.96) and power 0.80 (z = 0.84). The normal approximation for two independent proportions is n = (1.96 + 0.84)^2 * (p1(1-p1) + p2(1-p2)) / d^2 rows per arm. If both prompts run on the same rows, only rows where they disagree matter; for McNemar's test it is n = (1.96*sqrt(q) + 0.84*sqrt(q - d^2))^2 / d^2, where q is the share of rows with differing outcomes. The table assumes q = 15 per cent, with the gain d as the net difference between the two kinds of disagreement (read q from two runs' per-row results in practice), and checks each size with 4,000 simulated comparisons.
| True change | Unpaired: rows per arm | Simulated power | Paired (15% disagree): rows | Simulated power |
|---|---|---|---|---|
| 2 points (0.80 to 0.82) | 6,036 | 0.795 | 2,941 | 0.800 |
| 5 points (0.80 to 0.85) | 903 | 0.789 | 469 | 0.816 |
| 10 points (0.80 to 0.90) | 197 | 0.795 | 116 | 0.847 |
Simulated power lies between 0.79 and 0.85 against the 0.80 target, so the formulas are adequate here; the paired formula is slightly conservative at 10 points. A two-point gain needs thousands of rows even when paired, so a few hundred rows cannot resolve most prompt tweaks. Running both prompts on the same rows needs 41 to 51 per cent fewer rows than the per-arm unpaired count at this disagreement rate. Miller's paper treats questions as a sample from a larger population and gives formulas for comparing two models and planning an evaluation (Miller, 2024). Keeping the best of many variants also selects for luck, so confirm the winner on fresh rows. The core of the simulation (numpy only, seed 2026):
rng = np.random.default_rng(2026)
q = rng.beta(1.6, 0.4, size=n) # per-row success probability, mean 0.80
repeats = (rng.random((2000, n)) < q).mean(axis=1) # same dataset, 2,000 repeated runs
fresh = [(rng.random(n) < rng.beta(1.6, 0.4, n)).mean() for _ in range(2000)]
np.percentile(repeats, [2.5, 97.5]), np.percentile(fresh, [2.5, 97.5])
def n_unpaired(d, p=0.80, za=1.96, zb=0.8416):
return math.ceil((za + zb) ** 2 * (p * (1 - p) + (p + d) * (1 - p - d)) / d ** 2)
What to use when
| Situation | Use |
|---|---|
| Frozen dataset, temperature 0, code scorer | Two or three repeats to confirm stability; bootstrap over rows for the interval |
| Sampled outputs or an LLM judge | Five or more repeats; bootstrap over the averaged per-row scores |
| Comparing two prompts | Same rows, paired test, planned row count |
Under 100 rows, treat a score as a smoke test. The repeat counts and the 100-row cut-off are rules of thumb, not derived from the simulation.
Gates, cost and latency
A regression gate fails the build when a score drops below an agreed floor. The demo's last lines are the simplest version: compare a metric with a threshold kept in the repository, exit non-zero. Run it in CI against a pinned prompt version and dataset name. MLflow 3.18.0 added an experimental quality_criteria parameter to mlflow.genai.evaluate: run-level thresholds written with >= or <= and joined by AND (API reference). It was not tested here, and given its experimental status a plain threshold in your own code is the safer gate.
Gates should cover cost and latency too: a prompt that scores better by tripling the output length is not a free win. MLflow tracing records latency and token usage per step. Per the token-usage page, token usage needs MLflow 3.2.0 or later, and cost tracking needs 3.10.0 or later with the server installed with the [genai] extra. Trace-level values are trace.info.token_usage and trace.info.cost. Cost can read $0.00 while tokens are tracked if the model name has no price-table match, and some providers return no token usage (token usage and cost). The demo made no model calls, so these fields were not checked; confirm they are non-empty before gating on them.
A checklist
- Prompt: register it, load by version number, log the URI.
- Model: log the full snapshot ID and all sampling parameters; repeat runs to measure spread.
- Dataset: name it like a release; never edit a dataset that old scores refer to.
- Scorers: code-based wherever possible; for judges, pin the model and instructions, then compare with human labels using kappa, not raw agreement alone.
- Glue code: keep pre- and post-processing inside the traced function and log the code revision.
- Compare: only runs that differ in one input; one change per comparison, on the same rows, with a bootstrap interval and a planned row count.
- Gate: quality, cost and latency floors in the repository, checked in CI.
What this does not cover
- No real model or judge was called. The demo shows the bookkeeping, not model behaviour. Judge alignment, cost tracking and
quality_criteriaare described from the documentation and the installed package, not run. - No server. The demo uses a SQLite file. Multi-user setups, access control and the prompt UI need
mlflow server, which was not tested here. - Nothing here makes a provider deterministic. Infrastructure changes and sampling noise remain, which is why the spread must be measured.
- Moving API. Experimental features such as
quality_criteriamay change between releases. Judge-alignment details rest on the scorer overview page and the installed source. - Toy statistics. The noise study uses synthetic, independent rows and a fake model; real rows are correlated and real judges add variance. Production drift monitoring is a separate topic.
Sources
- MLflow docs: prompt registry
- MLflow docs: evaluation datasets
- MLflow docs: evaluation quickstart
- MLflow docs: scorers and judge alignment
- MLflow API reference: mlflow.genai
- MLflow docs: token usage and cost tracking
- MLflow docs: version tracking
- MLflow v3.18.0 release notes
- PyPI: mlflow
- Claude docs: model IDs and versioning
- Miller, Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations
- Zheng et al., Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena