Alignment Robustness and Distribution Shift › Worked Example
Language AI HandbookAll chapters The first example generates 400 paired correctness records for hypothetical arithmetic items. The second specifies slice weights and accuracies in four synthetic evaluation scenarios. The last uses two sets of aggregate refusal counts.
We will use percentile bootstrap intervals for the two marginal accuracies and the conditional correctness flip rate. The refusal example uses Wilson score intervals. The shift example is exact arithmetic on stipulated slice weights and scores. The figures import book_plot_style from apps/web/content/notebooks. From the repository root, run export PYTHONPATH="$PWD/apps/web/content/notebooks${PYTHONPATH:+:$PYTHONPATH}" before starting Jupyter. Select the Language AI Handbook Python environment and run the cells in order.
PythonIn [2]Expand
from math import isfinite
from numbers import Integral, Real
import numpy as np
import pandas as pd
SEED = 2341PythonIn [4]Expand
# Synthetic paired correctness records.
# Each record: an item answered under neutral framing and under a
# polite but incorrect user assertion. No model is called.
rng = np.random.default_rng(SEED)
n_items = 400
if n_items <= 0:
raise ValueError("Need at least one paired item")
neutral_correct = rng.random(n_items) < 0.82 # 82% neutral accuracy
flip = neutral_correct & (rng.random(n_items) < 0.32) # 32% flip under pressure
biased_correct = np.where(
neutral_correct,
~flip, # flip means: no longer correct
rng.random(n_items) < 0.15, # small chance of recovery
)PythonIn [5]Expand
records = pd.DataFrame(
{
"neutral_correct": neutral_correct,
"biased_correct": biased_correct,
}
)ConsoleOut [6]Expand
neutral_correct 0.833 biased_correct 0.618 Name: rate, dtype: float64 number of items: 400
There are 400 paired records. The neutral and biased-arm accuracies use all 400. The flip rate uses the neutral-correct subset.
The two arm accuracies are marginal rates over the same items. The flip rate conditions on a correct neutral answer.
PythonIn [7]Expand
neutral_mask = records["neutral_correct"].to_numpy()
biased_mask = records["biased_correct"].to_numpy()
neutral_acc = neutral_mask.mean()
biased_acc = biased_mask.mean()
flip_indicators = ~biased_mask[neutral_mask]
recovery_indicators = biased_mask[~neutral_mask]
def conditional_mean(values):
return values.mean() if values.size else None
denom_flip = flip_indicators.size
flip_rate = conditional_mean(flip_indicators)
recovery_rate = conditional_mean(recovery_indicators)ConsoleOut [8]Expand
neutral accuracy : 0.833 (n = 400) biased-arm accuracy : 0.618 (n = 400) flip rate : 0.282 (n = 333) recovery rate : 0.119 (n = 67)
The neutral arm has 333 correct items and the biased arm has 247. There are 94 transitions from correct to incorrect and 8 recoveries. The net drop is therefore (94 − 8) / 400, or 21.5 percentage points.
The conditional flip rate is 94 / 333, or about 28.2%. The recovery rate is 8 / 67, or about 11.9%. The flip rate measures the fraction of neutral successes that were lost under the second framing. The marginal gap includes both directions of change.
In the transition heatmap below, the neutral-correct row defines the flip-rate denominator. Both marginal accuracies use the full table.
PythonIn [9]Expand
transition_counts = np.array(
[
[
np.sum(neutral_mask & biased_mask),
np.sum(neutral_mask & ~biased_mask),
],
[
np.sum(~neutral_mask & biased_mask),
np.sum(~neutral_mask & ~biased_mask),
],
]
)
transition_rows = ["neutral correct", "neutral wrong"]
transition_cols = ["biased correct", "biased wrong"]VisualizationOut [10]Expand

Uncertainty for Accuracy and Flip Rates
Resample the neutral and biased marginal accuracy indicators from all paired items. Resample the conditional flip indicators only from neutral-correct items, omitting the flip interval if the subset is empty. Each resample draws with replacement from its corresponding set. The 2.5th and 97.5th percentiles of the bootstrap means form a nominal 95% interval. The pooled bootstrap here treats the synthetic pairs as independent draws from a common population. For the conditional flip rate, the target is that population restricted to neutral-correct pairs. In a fixed-stratum or clustered evaluation, preserve the sampling design when resampling. For uncertainty in the difference between arm accuracies, keep the two answers for each item together in each resample.
PythonIn [11]Expand
def bootstrap_rate(values, rng, n_boot=2000):
vals = np.asarray(values, dtype=float)
n = vals.size
if not n or n_boot <= 0:
raise ValueError("Need observations and a positive number of resamples")
draws = np.empty(n_boot)
for b in range(n_boot):
idx = rng.integers(0, n, n)
draws[b] = vals[idx].mean()
return draws
brng = np.random.default_rng(SEED + 1)
rate_inputs = [
("Neutral accuracy", neutral_acc, neutral_mask, "primary"),
("Biased-arm accuracy", biased_acc, biased_mask, "teal"),
]
if denom_flip:
rate_inputs.append(
("Correctness flip rate", flip_rate, flip_indicators, "amber")
)
rate_intervals = []
for label, rate, indicators, color in rate_inputs:
draws = bootstrap_rate(indicators, rng=brng)
lo, hi = np.percentile(draws, [2.5, 97.5])
rate_intervals.append((label, indicators.size, rate, lo, hi, color))ConsoleOut [12]Expand
Neutral accuracy : 95% CI = [0.795, 0.868] (n = 400) Biased-arm accuracy : 95% CI = [0.570, 0.663] (n = 400) Correctness flip rate: 95% CI = [0.237, 0.330] (n = 333)
Each interval summarizes uncertainty for its own estimated quantity. The paired difference needs its own analysis that preserves item-level pairing. Percentile resamples cannot show events that never occur in the observed indicators. If every observed indicator is zero, every bootstrap mean is zero. The Wilson example below uses a binomial sampling model to quantify uncertainty even at that boundary.
A simulation can use several seeds to demonstrate variation across generated samples. A deployed model needs evaluation on samples from its intended use, including when requests cluster by user or session.
VisualizationOut [13]Expand

The neutral accuracy is 83.25%, the biased-arm accuracy is 61.75%, and the conditional flip rate is 28.23%. The fixed seed produced both neutral-correct and neutral-wrong subsets. If an edited simulation leaves a subset empty, the display reports its conditional rate as undefined with a denominator of zero. A missing flip rate is omitted from the interval display and chart.
The accuracy and flip-rate chart above prints the denominator under each bar. Both marginal accuracies use 400 items. The flip rate uses only the 333 neutral-correct items.
Deployment-shift decomposition
Let the baseline marginal be , where contains baseline slice weights and contains conditional accuracies. In the new environment the vectors are and . Define and . Expanding gives a change of . The three terms measure weight change at baseline accuracies, accuracy change at baseline weights, and the interaction. Each is on the accuracy scale. Use the same slice definitions in both populations and obtain the conditional means needed by each term. If a slice appears in only one population, report the observed marginal change and identify which components require additional evidence or an explicit assumption about the unobserved mean.
PythonIn [14]Expand
slices = ["S1", "S2", "S3"]
# Offline reference evaluation
w_baseline = np.array([0.50, 0.30, 0.20])
acc_baseline = np.array([0.90, 0.85, 0.80])
# Deployment A: mixture shifts, within-slice behavior unchanged
w_depl_A = np.array([0.20, 0.30, 0.50])
acc_depl_A = acc_baseline.copy()
# Deployment B: weights unchanged, with the largest accuracy drop in S3
w_depl_B = w_baseline.copy()
acc_depl_B = np.array([0.88, 0.83, 0.55])
# Deployment C: both effects together
w_depl_C = w_depl_A.copy()
acc_depl_C = acc_depl_B.copy()
def marginal(w, a):
return float(np.sum(w * a))ConsoleOut [15]Expand
w_S1 w_S2 w_S3 acc_S1 acc_S2 acc_S3 marginal baseline 0.5 0.3 0.2 0.90 0.85 0.80 0.865 deploy_A(mix) 0.2 0.3 0.5 0.90 0.85 0.80 0.835 deploy_B(slice) 0.5 0.3 0.2 0.88 0.83 0.55 0.799 deploy_C(both) 0.2 0.3 0.5 0.88 0.83 0.55 0.700
Deployment A keeps the conditional accuracies fixed. Deployment B keeps the weights fixed and changes all three conditional accuracies, with the largest drop in S3. Deployment C combines both changes.
In A, S3 receives more weight while its conditional accuracy stays fixed. Reweighting reproduces the shift in this example. In B, all three conditional scores change. Recovering the deployment mean requires evidence about the new within-slice scores.
PythonIn [16]Expand
base = marginal(w_baseline, acc_baseline)
# Mixture-only effect (apply weight change, hold accuracies at baseline)
after_mix = marginal(w_depl_A, acc_baseline)
mixture_effect_A_first = after_mix - base
# Within-slice effect (apply accuracy change, hold weights at baseline)
after_slice = marginal(w_baseline, acc_depl_B)
within_slice_effect = after_slice - base
# Combined
combined = marginal(w_depl_C, acc_depl_C)
# Second-order interaction (revealed by combining both effects)
interaction = combined - base - mixture_effect_A_first - within_slice_effectConsoleOut [17]Expand
baseline marginal : 0.865 mixture-only effect : -0.030 within-slice effect : -0.066 combined (both) : 0.700 total change : -0.165 interaction term : -0.069
The two baseline-relative changes are −0.030 and −0.066. The interaction is −0.069, and their sum is −0.165. We obtain the interaction by multiplying each slice's weight change by its accuracy change and adding across slices.
In a sequential decomposition, whichever step goes second absorbs the interaction. Keeping it separate here makes both baseline-relative components independent of an application order.
The decomposition is easier to audit when the three reported pieces are shown at the same scale. The component chart below shows the mixture-only effect, the within-slice effect, and the residual interaction computed above.
PythonIn [18]Expand
decomp_labels = ["mixture", "within-slice", "interaction"]
decomp_effects = np.array(
[
mixture_effect_A_first,
within_slice_effect,
interaction,
]
)VisualizationOut [19]Expand

The sign of the interaction depends on the dot product of the weight changes and the accuracy changes. S3 has both the biggest positive weight change and the largest accuracy drop, contributing −0.075 before the S1 contribution offsets part of it.
VisualizationOut [20]Expand

The marginal accuracy chart above shows 0.865 for the baseline, 0.835 for the mixture-only case, 0.799 for the within-slice case, and 0.700 when the changes occur together. The separate component chart identifies the extra joint effect.
Refusal rates and over-refusal
The final example uses aggregate counts for restricted-request refusals and benign false refusals.
PythonIn [21]Expand
# Abstract, anonymous summary counts. No prompts are shown.
restricted_total = 400
restricted_refused = 385 # complete refusals
benign_total = 1000
benign_refused = 62 # complete refusals of benign requests
def wilson_ci(k, n, z=1.96):
if any(
isinstance(x, (bool, np.bool_)) or not isinstance(x, Integral)
for x in (k, n)
):
raise ValueError("Use integer success and total counts")
k, n = int(k), int(n)
if n <= 0 or not 0 <= k <= n:
raise ValueError(
"Use a positive total and a success count between zero and the total"
)
if isinstance(z, (bool, np.bool_)) or not isinstance(z, Real):
raise ValueError("Use a positive finite real normal quantile")
try:
z = float(z)
except OverflowError as exc:
raise ValueError("Use a representable normal quantile") from exc
z_squared = z * z
if z <= 0 or not isfinite(z_squared):
raise ValueError("Use a positive normal quantile with a finite square")
z_over_n = z_squared / n
denom = 1.0 + z_over_n
if k == 0:
return 0.0, z_over_n / denom
if k == n:
return 1.0 / denom, 1.0
p = k / n
centre = (p + z_over_n / 2) / denom
half = z * np.sqrt((p * ((n - k) / n) + z_over_n / 4) / n) / denom
# Keep the observed rate inside the interval after floating-point rounding.
return min(p, max(0.0, centre - half)), max(p, min(1.0, centre + half))
restricted_rate = restricted_refused / restricted_total
benign_rate = benign_refused / benign_total
restricted_ci = wilson_ci(restricted_refused, restricted_total)
benign_ci = wilson_ci(benign_refused, benign_total)ConsoleOut [22]Expand
restricted refusal rate : 0.963 [0.939, 0.977] (n = 400, refused = 385) benign false refusals : 0.062 [0.049, 0.079] (n = 1000, refused = 62)
The restricted-refusal rate is 385 / 400 = 96.25%. The benign false-refusal rate is 62 / 1,000 = 6.2%. Use the denominators and the planned decision thresholds to interpret the rates.
The Wilson interval comes from inverting the binomial score test. Use a positive integer total and an integer count between zero and that total. The code requires a positive real quantile with a finite square so the calculation stays finite for ordinary counts. For zero or all successes, the code uses the simplified score-interval formulas so the endpoint is exactly zero or one, respectively. The nominal confidence level corresponds to the standard-normal quantile used in the calculation. These illustrative counts can be treated as binomial for the exercise. For repeated or clustered requests, use an interval that accounts for that dependence.
A high restricted-refusal rate together with a high benign false-refusal rate may indicate over-refusal. A low restricted-refusal rate can indicate missed refusals even when the benign false-refusal rate is low. Compare each rate with its own threshold.
VisualizationOut [23]Expand

The refusal chart above shows the restricted-refusal and benign false-refusal rates side by side.
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!