🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

A/B Testing LLMs: Statistics That Hold Up

LLMOps in ProductionLLM A/B TestingđŸŸĸ Free Lesson

Why LLM experiments need more care than button-copy tests

A classic A/B test changes one interface element and measures a click. An LLM experiment typically changes a prompt, a model, or a retrieval configuration, and the outcome is a generated answer judged by users, by a model, or by downstream business events days later. Three properties make the classic playbook inadequate. Outputs are stochastic, so variance within a single variant can exceed the difference between variants. Assignment must often be held stable per conversation rather than per request, or users experience two different assistants mid-thread. And the cost of each sample is metered, which means the standard advice of "just run it longer" has a budget attached.

The statistical machinery is not exotic — two-sample tests, proportion tests, and bootstrap resampling cover almost every case — but the experimental design around it decides whether the numbers mean anything. Pre-registering the hypothesis, fixing the sample size before launch, and refusing to stop early without correction are habits that separate experiments from anecdotes.

There is also a governance dimension. A prompt change that shifts refusal behaviour or tone is a product decision affecting every user in the treatment group. Running it as a silent fifty-fifty split without a rollback plan and an ethics review where appropriate is not rigorous; it is careless with other people's experience. Treat large behavioural shifts like releases: smaller traffic share, longer observation, and an explicit decision owner.

Choosing a metric you can defend

The primary metric should be attributable to the variant and observable within the experiment window. Task success — did the user's request actually complete — beats satisfaction scores when it is measurable. Thumbs-up rates are cheap and noisy: they skew toward extremes, correlate with user mood, and are gamed by phrasing. Judged quality from a model evaluator is consistent but inherits the judge's biases, so calibrate it against human labels before trusting small differences.

Pair every primary metric with guardrails that must not regress: refusal rate, p95 latency, cost per conversation, and escalation-to-human rate. An experiment that improves satisfaction while doubling cost is not a win; it is a trade that should be made explicitly by someone with a budget.

Hypotheses, sample size and the peeking problem

Write the hypothesis as a numeric claim before launching: "the treatment increases task completion by at least three absolute percentage points against the control." Then compute the required sample size from the minimum detectable effect, the desired power, and the observed variance of the metric. For a continuous metric the standard two-sample approximation uses the pooled standard deviation and the z-scores for your alpha and power; for a proportion it uses the baseline rate and the absolute difference you want to detect. Doing this calculation is also the moment you discover the experiment you can afford: a three-point detectable effect on a metric with high variance may need more traffic than the product receives in a month, which is valuable information before launch rather than after.

The peeking problem deserves special emphasis in LLM experiments because dashboards make it irresistible. Checking a frequentist p-value every hour and stopping when it crosses 0.05 inflates the false-positive rate dramatically. Either fix the horizon and stop once, or use a sequential testing procedure designed for repeated looks, or use a Bayesian decision rule with a pre-declared threshold. What you must not do is monitor a classical test and stop whenever it looks good.

python
import math
from dataclasses import dataclass


@dataclass
class PowerAnalysis:
    baseline_mean: float
    mde: float              # minimum detectable effect (absolute)
    std_dev: float
    alpha: float = 0.05
    power: float = 0.80

    def n_per_arm(self) -> int:
        z_alpha = 1.959964  # two-sided 5 percent
        z_beta = 0.841621    # 80 percent power
        numerator = 2 * (z_alpha + z_beta) ** 2 * self.std_dev ** 2
        return math.ceil(numerator / self.mde ** 2)


class TwoSampleTest:
    def __init__(self, alpha: float = 0.05):
        self.alpha = alpha

    def t_test(self, control: list[float], treatment: list[float]) -> dict:
        n_c, n_t = len(control), len(treatment)
        mean_c = sum(control) / n_c
        mean_t = sum(treatment) / n_t
        var_c = sum((x - mean_c) ** 2 for x in control) / (n_c - 1)
        var_t = sum((x - mean_t) ** 2 for x in treatment) / (n_t - 1)
        se = math.sqrt(var_c / n_c + var_t / n_t)
        if se == 0:
            return {"lift": 0.0, "p_value": 1.0, "significant": False}
        t_stat = (mean_t - mean_c) / se
        # normal approximation is adequate for the sample sizes LLM tests need
        p_value = math.erfc(abs(t_stat) / math.sqrt(2))
        return {
            "lift": (mean_t - mean_c) / mean_c if mean_c else 0.0,
            "p_value": p_value,
            "significant": p_value < self.alpha,
            "se": se,
        }

Report the confidence interval on the lift alongside the p-value. An interval from minus one to plus nine points tells a very different story than one from four to six, even when both produce the same significance decision.

Tests for continuous and binary outcomes

Task success, conversion, and escalation are binary, so analyse them with a two-proportion z-test using the pooled variance under the null. Continuous metrics — judged scores, latency, tokens per request — suit the two-sample t-test, with the bootstrap as the safe alternative when distributions are heavily skewed, which latency almost always is. When the same user contributes multiple conversations, cluster by user or aggregate to a per-user mean first; treating correlated observations as independent inflates effective sample size and manufactures significance.

MethodOutcome typeDistribution assumptionNotes
Two-proportion z-testBinaryNone beyond large nDefault for success rates
Two-sample t-testContinuousApproximately normal meansNeeds variance check
BootstrapAnyNoneCostly but robust to skew
Cluster-aware variantsRepeated measuresModel-specificRequired for per-user data

Cost as a co-primary metric

Every LLM experiment should log tokens and dollars per assignment alongside quality. The analysis then becomes a two-dimensional decision: quality improvement at flat cost is a win; quality flat with a cost reduction is a win; quality up and cost up requires an explicit willingness-to-pay judgment from the product owner. Presenting those three cases as equivalent "wins" in a results deck is how teams accidentally double their inference bill over two quarters of successful experiments.

Bandits when traffic is scarce

When traffic cannot support a fixed-horizon test, multi-armed bandits trade statistical purity for faster regret reduction. Thompson sampling maintains a posterior per arm — a beta distribution for binary rewards — samples from each, and serves the arm with the highest sample. Good arms accumulate traffic automatically; poor arms are abandoned without waiting for a full power analysis. Use bandits for optimisation under scarcity, and reserve fixed-horizon tests for decisions that need a defensible, pre-registered answer.

python
import random
from dataclasses import dataclass, field


@dataclass
class Arm:
    name: str
    successes: int = 0
    failures: int = 0

    @property
    def pulls(self) -> int:
        return self.successes + self.failures

    @property
    def mean_reward(self) -> float:
        return self.successes / self.pulls if self.pulls else 0.0


class ThompsonSampler:
    def __init__(self, arms: list[Arm]):
        self.arms = arms

    def select(self) -> Arm:
        sampled = []
        for arm in self.arms:
            alpha = arm.successes + 1
            beta = arm.failures + 1
            sampled.append((random.betavariate(alpha, beta), arm))
        sampled.sort(key=lambda pair: pair[0], reverse=True)
        return sampled[0][1]

    def observe(self, arm_name: str, success: bool) -> None:
        for arm in self.arms:
            if arm.name == arm_name:
                if success:
                    arm.successes += 1
                else:
                    arm.failures += 1
                return
        raise KeyError(arm_name)

    def summary(self) -> list[dict]:
        return [
            {"arm": a.name, "pulls": a.pulls, "mean": round(a.mean_reward, 4)}
            for a in self.arms
        ]

Bandits optimise; they do not certify. When the decision needs a publishable answer — a model swap affecting every user — graduate the winning arm into a fixed-horizon test and run it to the pre-computed sample size.

Reading results without fooling yourself

Before believing a result, run the checklist. Was the hypothesis and horizon pre-registered? Was the sample size computed rather than accumulated? Is assignment stable per conversation? Do confidence intervals exclude both zero and your minimum interesting effect? Did any guardrail regress? Does the effect hold when analysed per user rather than per request? And does it replicate on a second experiment window — LLM effects frequently fail to replicate when the traffic mix shifts.

A result that survives that list is rare, valuable, and safe to ship. Everything else is a hypothesis wearing a p-value.

Common Mistakes

Stopping an experiment the moment the p-value crosses 0.05

Fix: Fix the horizon in advance or use a sequential procedure designed for repeated monitoring.

Analysing per-conversation outcomes as if each user contributed one independent sample

Fix: Cluster by user or aggregate to per-user means so correlated observations do not inflate significance.

Declaring victory on quality while ignoring cost per conversation

Fix: Make cost a co-primary metric and route cost-increasing wins to an explicit budget decision.

Launching without computing the required sample size

Fix: Run a power analysis first; if the detectable effect exceeds your traffic budget, redesign the metric or the scope.

Key Takeaways

  • Pre-register the hypothesis, minimum detectable effect, and horizon before launching; everything else follows from those numbers.
  • Compute sample size with a power analysis and treat the result as the experiment's affordability check.
  • Peeking at classical p-values and stopping early is the most common way LLM experiments produce false wins.
  • Match the test to the outcome: proportion tests for binary success, t-tests or bootstraps for continuous scores, cluster-aware variants for repeated users.
  • Log cost per assignment and treat cost as a co-primary metric, not a footnote.
  • Use Thompson sampling when traffic is scarce; reserve fixed-horizon tests for decisions that need a defensible answer.
  • Require replication across a second window before shipping, because LLM effects often fail to transfer across traffic mixes.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement