Online Experiments and Production Evaluation › Code: the practical loop

Michael BrenndoerferDecember 1, 20263 min read
Language AI HandbookAll chapters
Part 57 of 67Dynamic, Interactive, and Agentic Evaluation
Chapter 439Online Experiments and Production Evaluation › Code: the practical loop
Reading section 10 of 15 · Code: the practical loop · 3 minSection 10 of 15 · 3 min

Section 10 of 15 · 3 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The final cells combine the efficacy interval, the ranking statistic and the canary gates.

Use the same assigned population in the final efficacy estimate and the reported assignment check.

First, a small helper that computes the standard two-proportion ITT contrast with a confidence interval and a label for the decision state.

PythonIn [30]
CollapseExpand
def itt_two_proportion(assigned, outcome):
    """ITT contrast of two binary outcome rates, grouped by assignment."""
    assigned = np.asarray(assigned)
    outcome = np.asarray(outcome)
    if assigned.ndim != 1 or assigned.shape != outcome.shape:
        raise ValueError("Supply one outcome for each assignment.")
    if set(assigned) != {"base", "cand"} or not np.isin(outcome, [0, 1]).all():
        raise ValueError("Supply both assignment arms and binary outcomes.")
    is_t = assigned == "cand"
    y_t = outcome[is_t]
    y_c = outcome[~is_t]
    p_t, n_t = y_t.mean(), len(y_t)
    p_c, n_c = y_c.mean(), len(y_c)
    diff = p_t - p_c
    se = np.sqrt(p_t * (1 - p_t) / n_t + p_c * (1 - p_c) / n_c)
    z = stats.norm.ppf(0.975)
    return {"diff": diff, "se": se, "lo": diff - z * se, "hi": diff + z * se}


def decision(ci):
    if ci["lo"] > 0:
        return "positive efficacy interval"
    if ci["hi"] < 0:
        return "negative efficacy interval"
    return "inconclusive (CI includes zero)"

The efficacy label describes where the fixed-look interval falls relative to zero.

For the interleaving summary, reuse the session-level sign test defined above.

Reuse the fixed-checkpoint rate bound in the final gate calculation.

PythonIn [31]
CollapseExpand
from fractions import Fraction


def gate_value(value):
    if isinstance(value, (bool, np.bool_)):
        return None
    if isinstance(value, (int, np.integer)):
        return int(value) if value >= 0 else None
    if (
        isinstance(value, (float, np.floating))
        and np.isfinite(value)
        and value >= 0
    ):
        return Fraction(*value.as_integer_ratio())
    return None


def guardrail_report(canary, thresholds):
    report = {}
    for name in ("harm", "error"):
        threshold = thresholds.get(f"{name}_ub")
        try:
            rate, upper = rate_bound(
                canary.get(f"{name}_events"), canary.get(f"{name}_n")
            )
        except ValueError:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing counts",
            }
            continue
        rate_cap = gate_value(threshold)
        if rate_cap is None or rate_cap > 1:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing rate cap",
            }
            continue
        report[name] = {
            "rate": rate,
            "ub99": upper,
            "threshold": threshold,
            "breach": gate_value(upper) > rate_cap,
        }

    for name, key in (
        ("latency", "p95_latency"),
        ("cost", "median_scaled_cost"),
    ):
        value, threshold = canary.get(key), thresholds.get(key)
        measured, cap = gate_value(value), gate_value(threshold)
        if measured is None or cap is None:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing measurement or cap",
            }
            continue
        report[name] = {
            "value": value,
            "threshold": threshold,
            "breach": measured > cap,
        }
    return report

Now apply these functions to the synthetic data we already built, to show the assembled decision.

PythonIn [32]
CollapseExpand
itt = itt_two_proportion(ab["arm"].values, ab["resolved"].values)
inter = team_draft_test(
    interleave_log["a_clicks"].values, interleave_log["b_clicks"].values
)
guard = guardrail_report(
    {
        "harm_events": harm_cand.sum(),
        "harm_n": len(harm_cand),
        "error_events": err_cand.sum(),
        "error_n": len(err_cand),
        "p95_latency": lat_p95,
        "median_scaled_cost": cost_p50,
    },
    {
        "harm_ub": 0.0060,
        "error_ub": 0.0120,
        "p95_latency": 1500.0,
        "median_scaled_cost": 2.00,
    },
)
any_breach = any(row["breach"] for row in guard.values())
ConsoleOut [33]
CollapseExpand
Primary metric (ITT):
  effect=+0.0344  95% CI=[+0.0166, +0.0522]
  decision: positive efficacy interval

Interleaving (relative preference):
  A wins=936, B wins=899, p=0.40069215977663536

Guardrails:
  harm     {'rate': 0.002, 'ub99': np.float64(0.007012195349280362), 'threshold': 0.006, 'breach': True}
  error    {'rate': 0.006666666666666667, 'ub99': np.float64(0.013631708414812527), 'threshold': 0.012, 'breach': True}
  latency  {'value': np.float64(1797.3445235426595), 'threshold': 1500.0, 'breach': True}
  cost     {'value': np.float64(1.6269257240997714), 'threshold': 2.0, 'breach': False}

Any guardrail breach: True

Overall: HALT rollout

The three failed gates are safety clearance, error-rate clearance and observed p95 latency. The median scaled cost passes. The positive primary interval is insufficient for a ramp under these rules, so the result is HALT rollout.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy