Session S27

Evaluation & Safety

Every claim about a model rests on a test score, and the score changes with the random seed and with which examples are in the test set. What makes a test score trustworthy, how large is its noise, what goes wrong when you compare many scores, and what can a model do that one aggregate score does not show?

Deep Learning · CS 4715/5715 · University of Idaho

Quiz 4 takes the last 30 minutes of today's class

  • In Canvas, 6:45–7:15 PM, with closed materials (Tier 0). It covers S23–S26. Today's session, S27, is not on the quiz. Online (Web) students and students with flexible-time arrangements may use their assigned flexible completion window.

Quiz 4 is the last quiz of the course, and all four count. There is no final exam.

S26 showed what each technique saves and what it changes

S26 made training and serving affordable. Its answer, clause by clause:

  • 16-bit numbers: fp16 has more precision and less range; bf16 keeps fp32's range and gives up precision. Training copes with an fp32 master copy, loss scaling and 16-bit passes.
  • Training memory: mixed-precision Adam keeps 16 bytes per parameter, 12 of them optimizer state. ZeRO shards them across GPUs, and stage 3 costs communication.
  • Shrinking: int8 is 4 times smaller than fp32; in the experiment it cost about 1% error, unless one outlier coarsened the grid. Pruning saves time only when structured, and large language models are mostly quantized instead. Distillation trains a smaller network.
  • Serving: each conversation's KV cache limits how many conversations fit; reading the weights limits the speed. Batching raises the throughput while each conversation slows.

Every saving comes with a change, so neither the saving nor "no loss" can be claimed without measuring it.

Today answers four questions, one part each

partthe question it answers, and how
1 · The test setWhat makes a test score trustworthy? Train, decide and test on separate data; leakage and benchmark contamination break the separation without any error message.
2 · The noise in a scoreHow large is its noise? Retraining with five seeds gives one error bar, and resampling the test set gives another.
3 · Many comparisonsWhat goes wrong when you compare many scores? The best of twenty identical runs looks like a win, and an LLM benchmark score has noise of its own.
4 · SafetyWhat can a model do that one aggregate score does not show? Fail one group, or reveal who was in its training data. Both are measured, and the measurements are written down.

Train, decide and test on separate data; leakage breaks the separation

Part 1 · The test set. Train on the first part, make every decision on the second, and touch the third once, at the end. Every decision based on the test set makes its score less trustworthy.

Each part has one job.traintrain on itvalidationdecide on ittesttouch onceEach extra look makesit a validation set.preprocessing fitbefore the splitduplicatesacross splitstime seriessplit randomlyLLMs: benchmarkcontaminationmean and stdfor normalizationtraintesttraintestthe same exampleon both sidestimetraintesttrained on a later point,tested on an earlier onetraining corpus:the internetbenchmark itemsthe benchmark ison the internetThe symptom in all three is the same: great test numbers and a worse deployed model.

If you tune until the test number improves, the test set has become a second validation set, and its number overstates how the model does on new data.

An LLM may have seen its benchmark during training, so its score can be too high

The training corpus is a crawl of the internet, and the benchmark's questions and answers are posted on the internet. The model may have seen the test, verbatim or paraphrased.

  • This is hard to rule out. A string search misses paraphrased items, benchmarks are republished, and closed training corpora cannot be inspected from outside.
  • GSM1k (Zhang et al., 2024) rebuilt GSM8k, a grade-school math benchmark, from new problems of the same style and difficulty. Some models scored up to 8 points lower, and others scored about the same.
  • The models did not drop by the same amount, so contamination can change which model ranks first.

A benchmark score is trustworthy only if the model has not seen the items, and that is less likely the longer the benchmark has been public.

Self-check on the test set, question (a)

(a) You standardize features with the whole dataset's mean and standard deviation, then split. Which leak from the previous pages is this, and how do you fix it?

(a) This is preprocessing fit before the split: the mean and standard deviation were computed from the test examples too. Compute them on the training set only, then apply the same two numbers to validation and test.

Self-check on the test set, question (b)

(b) You train a model to predict tomorrow's sales from past days, and you split the days into train and test at random. Why is the test score higher than the accuracy you will get after deployment?

(b) With a random split, most test days have later days in the training set. Sales on nearby days are similar, so the model has in effect seen data from after each test day. After deployment no later days exist. Split by time instead: train on the earlier days and test on the later ones.

Self-check on the test set, question (c)

(c) On GSM1k some models scored up to 8 points below their GSM8k score, and others scored about the same. What does that suggest about the first group's GSM8k scores, and which explanation did the previous page give?

(c) A harder benchmark would lower every model's score. Only some models dropped, so those models' GSM8k scores were too high: they had probably seen GSM8k items during training.

If any decision or training item used the test set, its score overstates accuracy on new data.

A test score is a random variable

Part 2 · The noise in a score. "This model scores 86.2, that one 86.4, so we ship the second one." Each number depends on three random choices:

which examples are in the test setwhich seed initialized the weightsthe order of the minibatchesthis model: 86.2that one: 86.4None of these choices depends on which model is better.small noise: 86.4 is higher than 86.2large noise: the two cannot be told apart86.086.286.486.6Without the size of the noise,86.4 and 86.2 cannot be compared.The error-bar widths are schematic.
  • A measured score is the true score plus noise. The true score is the accuracy on all the data the model could ever be tested on, which nobody can measure.
  • An accuracy \(p\) averages \(n\) test examples of 0 or 1, so its standard deviation is \(\sqrt{p(1-p)/n}\) and shrinks like \(1/\sqrt n\). Since \(1/\sqrt{4n}=\tfrac12\cdot1/\sqrt n\), detecting a difference half as large takes four times the test data.

The data are 2,000 training and 1,000 test points from two overlapping Gaussian classes

Experiment 1 is reading 4.5's script. It draws the data once, from a generator with its own seed, so every training run sees the same points:


import torch
import torch.nn as nn

# Fixed dataset (its own seed, independent of training seeds):
# two overlapping Gaussian blobs in 2D
g = torch.Generator().manual_seed(0)
def blobs(n, gen):
    y = (torch.rand(n, generator=gen) < 0.5).long()         # (n,) labels 0/1
    centers = torch.tensor([[-0.8, -0.8], [0.8, 0.8]])      # (2, 2)
    x = centers[y] + torch.randn(n, 2, generator=gen)       # (n, 2)
    return x, y

x_tr, y_tr = blobs(2000, g)
x_te, y_te = blobs(1000, g)
  

The two classes overlap, so no classifier reaches 100%

−4−4−2−2002244x1x2class 0 (label 0): 512 points,centered at (−0.8, −0.8)class 1 (label 1): 488 points,centered at (0.8, 0.8)the center of each classThe 1,000 test points x_te, y_te,drawn by blobs(1000, g) from thegenerator seeded 0.

Each label is 0 or 1 with probability 0.5. Class 0 is centered at \((-0.8,-0.8)\) and class 1 at \((0.8,0.8)\), with standard deviation 1 in each coordinate, so the two classes overlap. No classifier can reach 100% on these data.

One run trains a network of a given width for 500 Adam steps

Each run trains on x_tr, y_tr for 500 Adam steps and returns its accuracy on x_te, y_te. The width hidden is the number of units in the hidden layer. The seed sets both the initial weights and the order of the minibatches, so each seed gives a different trained network.


def run(hidden, seed, steps=500):
    torch.manual_seed(seed)   # controls init AND minibatch order
    net = nn.Sequential(nn.Linear(2, hidden), nn.ReLU(), nn.Linear(hidden, 2))
    opt = torch.optim.Adam(net.parameters(), lr=1e-2)
    for step in range(steps):
        idx = torch.randint(0, len(x_tr), (64,))                        # (64,)
        loss = nn.functional.cross_entropy(net(x_tr[idx]), y_tr[idx])   # logits (64, 2)
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        return (net(x_te).argmax(1) == y_te).float().mean().item()      # mean of (1000,)
  

Experiment 1 trains two widths five times each on the same data


for hidden in [16, 32]:
    accs = torch.tensor([run(hidden, seed) for seed in range(5)])       # (5,)
    print(f"hidden={hidden:2d}  accs: {[f'{a:.3f}' for a in accs.tolist()]}")
    print(f"hidden={hidden:2d}  mean {accs.mean().item():.4f} "
          f"+/- {accs.std().item():.4f} (std over 5 seeds)")
  

Each width is trained with five seeds on the same data. Will the five accuracies of width 16 and the five of width 32 overlap, or will one width be clearly higher?

With one seed either width can look better; with five seeds neither does

Answer: they overlap. The printout, one dot per run:

hidden=16seeds 0–4mean 0.8618 ± 0.0018hidden=32seeds 0–4mean 0.8602 ± 0.00290123401234seed 4 alone: width 16 is higherseed 1 alone: width 32 is higher0.8560.8580.8600.8620.864accuracyEach dot is one run’s accuracy as the script prints it; the bars are mean ± one std over 5 seeds.Data from generator seed 0 (2,000 training, 1,000 test points); training seeds 0–4 for each width.

Averaged over five seeds, the two widths cannot be told apart

  • Averaged over five seeds, width 32 is 0.16 percentage points lower than width 16 (0.8602 against 0.8618). That is less than either width's standard deviation over seeds (0.0018 and 0.0029).
  • With five seeds the two widths cannot be told apart. That is a useful result: further tuning of the width is not worth the compute.

Mean ± std over seeds is the error bar for seed noise.

The bootstrap resamples the test set to measure test-set noise

Experiment 1 measured seed noise, the change in a score from one training seed to another. Test-set noise is the change in a score when the test set holds different examples. We have only one test set, so we cannot draw a new one. The bootstrap imitates a new test set by drawing 1,000 examples from the one we have, with replacement. For one trained model (hidden=16, seed 0), it recomputes the accuracy on each resample and repeats 10,000 times.

01112130415161718091correct (1000,)one 0/1 per test example30361772940.857119026480.9correct[idx](10000, 1000)torch.randint(0, n, (n_boot, n))resample with replacement.mean(dim=1)accs(10000,)2.5%97.5%one accuracy per resample95% CI = [lo, hi]Ten cells stand for 1,000. A resampled cell shows the index it copies, shaded when the copied value is 1.

bootstrap_ci returns the accuracy and the 2.5% and 97.5% quantiles

The middle 95% of the 10,000 accuracies is a 95% bootstrap confidence interval (CI). If the test set were drawn again, the accuracy would fall inside this interval about 95% of the time.


def bootstrap_ci(correct, n_boot=10000, gen=None):
    n = len(correct)                                       # correct: (1000,) 0/1
    idx = torch.randint(0, n, (n_boot, n), generator=gen)  # (10000, 1000)
    accs = correct[idx].mean(dim=1)                        # one accuracy per resample
    lo = torch.quantile(accs, 0.025).item()                # 2.5% of accs lie below lo
    hi = torch.quantile(accs, 0.975).item()
    return correct.mean().item(), lo, hi
  

The bootstrap is run on all 1,000 test examples and on the first 200

The first seven lines repeat run(16, 0) from Experiment 1, so this is the network that scored 0.863. The new lines keep correct, one 0 or 1 per test example, and call bootstrap_ci twice: on all 1,000 test examples and on the first 200. The second call shows what a smaller test set does to the interval.


torch.manual_seed(0)
net = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2))
opt = torch.optim.Adam(net.parameters(), lr=1e-2)
for step in range(500):
    idx = torch.randint(0, len(x_tr), (64,))
    loss = nn.functional.cross_entropy(net(x_tr[idx]), y_tr[idx])
    opt.zero_grad(); loss.backward(); opt.step()

with torch.no_grad():
    correct = (net(x_te).argmax(1) == y_te).float()   # 0/1 per test example

gb = torch.Generator().manual_seed(1)
acc, lo, hi = bootstrap_ci(correct, gen=gb)                # all 1,000 test examples
print(f"test n=1000: acc {acc:.4f}  95% bootstrap CI [{lo:.4f}, {hi:.4f}]  "
      f"width {hi-lo:.4f}")
acc, lo, hi = bootstrap_ci(correct[:200], gen=gb)          # the first 200 only
print(f"test n= 200: acc {acc:.4f}  95% bootstrap CI [{lo:.4f}, {hi:.4f}]  "
      f"width {hi-lo:.4f}")
  

One model's 95% interval is 4.3 points wide

The two calls print these intervals:

all 1,000 examples0.84100.8840acc 0.8630, width 0.0430first 200 examples0.84500.9300acc 0.8900, width 0.08500.840.860.880.900.920.94One network, hidden=16 with training seed 0, on Experiment 1’s data; resampling generator seed 1.
  • With 1,000 test examples, one model's 95% interval is 4.3 points wide. This is the uncertainty of one model's accuracy, not of the 0.16-point difference between the two widths in Experiment 1.
  • On the first 200 examples alone the accuracy is 0.89 and the interval is about twice as wide. A small test set can give a high score by chance.

The bootstrap measures one trained model's test-set noise, not its seed noise.

A paired bootstrap resamples the same examples for both models

To compare two models, bootstrap the difference between their accuracies on the same test examples.

  1. For each test example, record whether each model is correct. This gives two vectors of 0s and 1s, one per model.
  2. Draw one set of indices with replacement and use it for both vectors, so that both models' answers to an example are resampled together. Compute the difference between the two accuracies.
  3. Repeat 10,000 times. The middle 95% of the differences is the 95% interval of the difference.
012345678911101111011110110101model A, 0 or 1 per test examplemodel B, 0 or 1 per test example3036177294one resample of indicesthe same indices for both models01011111110100111111model A, resampledmodel B, resampled0.80.7difference 0.8 − 0.7 = 0.1,one difference per resampleTen cells stand for 1,000. A shaded cell holds a 1 (correct). The two models differ on example 6.

The 95% interval of the difference between the two widths includes 0

  • Both models are tested on the same examples. A resample with more hard examples lowers both accuracies, and the subtraction cancels that change. The interval of the difference is therefore narrower than either model's own interval.
  • One model is more accurate than the other only if the interval of the difference does not include 0.
  • With seed 0, hidden=16 scores 0.863 and hidden=32 scores 0.860, and the two networks disagree on 3 of the 1,000 test examples. The 95% interval of the difference is from 0.0 to 0.7 points. It includes 0, so this test set does not show that width 16 is better.

Self-check on the noise in a score, questions (a) and (b)

(a) With seed 1, hidden=32 scores 0.864 and hidden=16 scores 0.862, each trained once. In Experiment 1 the standard deviation over seeds was 0.0018 for width 16 and 0.0029 for width 32. Is the difference between the two scores enough to say that width 32 is better?

(b) The bootstrap interval [0.8410, 0.8840] belongs to hidden=16. Does it show whether hidden=16 is better than hidden=32?

(a) No. The difference is 0.864 − 0.862 = 0.002. That is about one standard deviation of the seed noise for width 16 and less than one for width 32, so another seed could reverse the order. Train each width with several seeds and compare the means.

(b) No. The interval is the test-set noise of one model's accuracy. A comparison needs the interval of the difference, from a paired bootstrap on the same test examples.

Self-check on the noise in a score, question (c)

(c) With your test set, a 95% interval is about 2 points wide. How many times larger must the test set be for the interval to be 1 point wide?

(c) Four times larger. The width shrinks like \(1/\sqrt n\), so halving it needs \(\sqrt n\) to double, and \(n\) to be 4 times as large.

Seed noise and test-set noise are different error bars; a comparison needs both.

The best of many scores is too high, even when the runs are identical

Part 3 · Many comparisons. Part 2 compared two scores. Tuning compares many and reports the best one. Experiment 3 shows what that selection does: it calls Experiment 1's run twenty times with hidden=16 and seeds 0–19, so the twenty networks differ only by seed.

hidden=16, identical config, seeds 0–19012345678910111213141516171819select the highestmean 0.8606, std 0.0020worst: seed 13, 0.8570best: seed 4, 0.8640best − worst = 0.0070: 7 test examples out of 10000.8560.8580.8600.8620.864accuracySame data as Experiment 1 (generator seed 0); each box is one hidden=16 run with its seed.
  • The highest of the twenty accuracies is 0.7 points above the lowest and 0.34 points above the mean.
  • If these had been 20 different settings, a report would claim a 0.7-point improvement. Here the settings are identical, so the whole difference comes from the seed.

Selecting the best of many runs needs four safeguards

  1. Decide which comparisons you will make before you run anything, so that you cannot choose the comparison that happens to look best.
  2. Report every run of a sweep, not only the best one. A sweep trains one model for each of several values of a hyperparameter.
  3. Retrain the best configuration with new seeds, and keep it only if it is still the best.
  4. Treat a difference smaller than the standard deviation of identical runs as no difference.

The more scores you compare, the higher the best one is by chance alone.

On MMLU, a 0.3-point difference is smaller than one model's noise

A leaderboard reports "A: 86.2, B: 85.9 on MMLU". MMLU is a benchmark of multiple-choice questions on 57 subjects, and its test set has 14,079 four-choice questions.

  • With Part 2's formula, the standard deviation of A's accuracy is \(\sqrt{0.862\cdot0.138/14079}\approx0.0029\). A 95% interval reaches 1.96 standard deviations to each side of the score: \[1.96\sqrt{\frac{0.862\cdot0.138}{14079}}\approx0.0057,\quad\text{about }\pm0.57\text{ points.}\]
  • The 0.3-point difference is smaller than ±0.57 points, so the two scores do not show that A is better.
  • To compare A and B, run a paired bootstrap on the same 14,079 questions and read the interval of the difference.

Report a benchmark difference together with an estimate of its noise.

An LLM benchmark score has four more sources of error

  • Contamination (Part 1). The model may have seen the questions during training, and nobody can measure by how much that raised its score.
  • Prompt sensitivity. The same model scores differently when the questions are formatted differently, so two labs' scores for one model can differ by more than two models do.
  • Saturation. When the best models all score near 100%, the benchmark can no longer separate them.
  • Goodhart's law. When a benchmark score becomes the goal, models are tuned to the benchmark, and the score stops measuring general ability.

Self-check on many comparisons, questions (a) and (b)

(a) You train one model for each of 20 learning rates. The best accuracy is 0.6 points above the worst. Twenty runs of one identical configuration differed by 0.7 points from best to worst. Can you say that the best learning rate is better than the others?

(b) You select the best of 20 runs and train it again with a new seed. Why is the new score usually lower?

(a) No. The 0.6-point difference is smaller than the 0.7 points that identical runs differ by, so it can come from the seed alone. Report all 20 results, then retrain the best learning rate with new seeds and check that it is still the best.

(b) Each score is the model's true accuracy plus seed noise. The highest of 20 scores is usually one whose noise was positive. A new seed draws new noise, which is as likely to be negative as positive, so the new score is usually lower.

Self-check on many comparisons, question (c)

(c) Model A scores 86.2 and model B scores 85.9 on MMLU, which has 14,079 questions. One model's 95% interval is about ±0.57 points. Does the 0.3-point difference show that A is better? Name one other reason, besides test-set noise, why the two scores could differ.

(c) No. The 0.3-point difference is smaller than the ±0.57-point noise of either score. Another reason is prompt sensitivity: the two models may have been evaluated with differently formatted questions. Contamination is another: one model may have seen more of the questions during training.

The best of many noisy scores is too high by chance, so a difference smaller than the noise does not show that one model is better.

One aggregate score does not show which examples the model gets wrong

Part 4 · Safety. A test score can be clean and have little noise, and still not show where the model fails.

  • An aggregate score is the average over all test examples, so it does not show on which examples the model is wrong.
  • Bias here means that the model's accuracy on one group of examples is far below its accuracy on another group. In real data, a group can be defined by any feature that is related to a group of people.
  • A model can also reveal its training data: from its outputs, an outsider can tell whether a given example was used to train it.

Here safety means that the model does not harm the people it is used on: it does not fail one group, and it does not reveal its training data.

A husky-versus-wolf classifier relied on snow in the background

A classifier was trained to tell huskies from wolves (Ribeiro et al., KDD 2016). In its training photos the wolves were on snow, so snow predicted "wolf" better than the animal did, and the classifier relied on the snow. Reading 4.6's experiment rebuilds this case with two features.

in the experimentin the husky example
the label \(y\)husky or wolf
the feature skill, which determines the labelwhat the animal looks like
the attribute \(s\), which does not cause the labelwhether the background has snow
\(s\) equals \(y\) in 90% of the training datain the training photos, the background mostly matches the animal
\(s\) equals \(y\) in 50% of the data at deploymentin later photos, the background is unrelated to the animal
skillwhat the animal looks likelabel yhusky or wolfattribute ssnow in the backgrounddeterminesequals ys equals y in 90% of the training data and in 50% of the data at deployment; it does not cause y.

Which feature will the trained model rely on, and which examples will it get wrong at deployment?

In this dataset, an attribute \(s\) matches the label 90% of the time in training and 50% at deployment

make_data draws the feature skill and the attribute \(s\) of the previous page's table. p_match is the probability that \(s\) equals the label. It is 0.9 for the training data and 0.5 for the test data, which stand for the data at deployment. The code is from reading 4.6:


torch.manual_seed(0)

def make_data(n, p_match):
    skill = torch.randn(n)                              # (n,)
    y = (skill + 0.7 * torch.randn(n) > 0).float()      # noisy function of skill
    match = (torch.rand(n) < p_match).float()
    s = match * y + (1 - match) * (1 - y)               # s = y w.p. p_match
    x = torch.stack([skill, s], dim=1)                  # (n, 2)
    return x, y

x_tr, y_tr = make_data(4000, p_match=0.9)   # strong correlation in training
x_te, y_te = make_data(4000, p_match=0.5)   # correlation absent at deployment
  

A linear model with one weight on each feature is trained on the training data

The model computes one number from skill and \(s\) and predicts label 1 when that number is positive. It is trained for 2,000 Adam steps with the binary cross-entropy loss of S24.


model = nn.Linear(2, 1)                     # one weight on skill, one on s
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(2000):
    # S24's BCEWithLogitsLoss as a function
    loss = nn.functional.binary_cross_entropy_with_logits(model(x_tr).squeeze(1), y_tr)
    opt.zero_grad(); loss.backward(); opt.step()
  

The script prints both weights, then the accuracy on all test examples and on each group

After training, reading 4.6 prints the two learned weights, then the accuracy on the training data and on the test data. The test set is split into two groups: examples where \(s\) equals the label, and examples where it does not.


w = model.weight.detach().squeeze()                  # (2,): skill, s
print(f"learned weights: skill {w[0].item():.4f}   attribute s {w[1].item():.4f}")

def acc(x, y):
    with torch.no_grad():
        return ((model(x).squeeze(1) > 0).float() == y).float().mean().item()

print(f"train accuracy (correlation 0.9): {acc(x_tr, y_tr):.4f}")
print(f"test accuracy (correlation 0.5):  {acc(x_te, y_te):.4f}")
agree = x_te[:, 1] == y_te                           # (4000,), True where s = y
print(f"  test acc when s agrees with y:    {acc(x_te[agree], y_te[agree]):.4f}")
print(f"  test acc when s disagrees with y: {acc(x_te[~agree], y_te[~agree]):.4f}")
  

Which weight is larger after training, the one on skill or the one on \(s\)? At deployment, on which of the two groups is the model less accurate?

The model puts more weight on \(s\), and one group scores below chance

Answer: the weight on \(s\) is nearly twice the weight on skill. The script's printout, drawn:

learned weightsskill2.3325attribute s4.3128accuracy01chance: 0.50.9220train(s matches y 90%)0.6725test(s matches y 50%)0.9879s equalsy0.3627s differsfrom ybelow chanceThe aggregate test accuracy averages the two groups.The bars are the values the script prints.Data from torch.manual_seed(0):4,000 training points and4,000 test points.
  • The model's prediction mostly follows \(s\). In the group where \(s\) differs from the label, following \(s\) gives the wrong answer, so the accuracy falls below 50%.

The model fails one group, and the aggregate accuracy does not show it

  • Training did nothing wrong: in the training data, \(s\) matches the label 90% of the time, which predicts the label better than the noisy skill does.
  • The aggregate 67% is the average of a 98.8% group and a 36.3% group. Only the per-group accuracies show that the model fails one group, so evaluate each group separately.
  • If the test set had matched the training data, with \(s\) equal to the label 90% of the time, this model would have scored about 92% and passed the evaluation. The test data must look like the data at deployment.

A model that relies on a feature which predicts the label in training but not at deployment has learned a shortcut (Geirhos et al., 2020).

train_eval trains a new model on the features and weights it is given

Two changes to training reduce the model's dependence on \(s\): remove \(s\) from the features, or keep it and give each training example a weight. Such a change is called a mitigation. train_eval trains a new model from seed 0 on the features and weights it is given. With weight=weights, each example's loss is multiplied by its weight before the average.


def train_eval(name, features, weights=None):
    torch.manual_seed(0)
    model = nn.Linear(features.shape[1], 1)
    opt = torch.optim.Adam(model.parameters(), lr=1e-2)
    for step in range(2000):
        logits = model(features).squeeze(1)
        loss = nn.functional.binary_cross_entropy_with_logits(
            logits, y_tr, weight=weights)
        opt.zero_grad(); loss.backward(); opt.step()
  

train_eval prints the accuracy of each group and the gap between them

These lines are the second half of train_eval. train_eval then prints the test accuracy on all examples and on each group. The gap is the accuracy of the group where \(s\) equals the label minus the accuracy of the other group.


# train_eval, continued
    x_eval = x_te if features.shape[1] == 2 else x_te[:, :1]
    with torch.no_grad():
        pred = (model(x_eval).squeeze(1) > 0).float()
    agree = x_te[:, 1] == y_te
    overall = (pred == y_te).float().mean().item()
    a = (pred[agree] == y_te[agree]).float().mean().item()
    d = (pred[~agree] == y_te[~agree]).float().mean().item()
    print(f"{name:22}  test acc {overall:.4f}   s==y {a:.4f}   s!=y {d:.4f}   "
          f"gap {a - d:+.4f}")
  

train_eval runs once for the earlier model and once for each mitigation

The script calls train_eval three times: for the model from the previous pages, for a model without \(s\), and for a model whose training examples are weighted.


# Baseline: both features, unweighted (the shortcut learner)
train_eval("baseline (skill + s)", x_tr)

# Fix 1: drop the attribute entirely
train_eval("drop s", x_tr[:, :1])

# Fix 2: keep s, but reweight the four (y, s) cells so s carries no signal
wts = torch.zeros(len(y_tr))
for yv in [0.0, 1.0]:
    for sv in [0.0, 1.0]:
        cell = (y_tr == yv) & (x_tr[:, 1] == sv)
        wts[cell] = len(y_tr) / (4 * cell.sum())     # equalize cell mass
train_eval("reweight (y, s) cells", x_tr, weights=wts)
  

Reweighting gives all four \((y,s)\) cells the same total weight

The training examples fall into four cells, one for each combination of label \(y\) and attribute \(s\). Each example gets the weight \(4000/(4\cdot\text{number of examples in its cell})\), so the weights in every cell add up to \(4000/4=1000\).

cellexamplesweight per exampletotal weight
\(y=0,\ s=0\)1,843\(4000/(4\cdot1843)=0.543\)1,000
\(y=0,\ s=1\)197\(4000/(4\cdot197)=5.076\)1,000
\(y=1,\ s=0\)190\(4000/(4\cdot190)=5.263\)1,000
\(y=1,\ s=1\)1,770\(4000/(4\cdot1770)=0.565\)1,000

After weighting, among the examples with \(y=1\), \(s=0\) and \(s=1\) have equal total weight, and the same holds for \(y=0\). \(s\) no longer predicts the label, so the model has to use skill.

Both mitigations raise the accuracy to 80.7% and close the gap between the groups

The three calls print these accuracies:

s equals ys differs from ytest accchance, 0.500.510.98790.36270.6725gap +0.6252baseline (skill + s)0.80220.81220.8073gap −0.0100drop s0.78560.82850.8073gap −0.0430reweight (y, s) cellsThe bars and lines are the values the script prints; the gap is the first group’s accuracy minus the second’s.Same training and test points; train_eval trains each model from torch.manual_seed(0).
  • Both mitigations raise the test accuracy from 67.3% to 80.7%.
  • Both models now rely on skill, and skill alone predicts the label about 80% of the time.

The remaining gaps are small, and in real data removing the attribute is not enough

  • The gap between the two groups falls from 62.5 points to 1.0 point when \(s\) is removed and to 4.3 points with reweighting. The sign of these small gaps changes from seed to seed.
  • In real data, removing the attribute is not enough: other features, such as zip code, name or word choice, can predict it. Such a feature is called a proxy.

A model can learn a shortcut, and only per-group evaluation shows it

  1. A model can learn a shortcut, which is a feature that predicts the label in the training data but not at deployment.
  2. The shortcut comes from the training data, and a mitigation changes the training. Evaluation does not remove it; evaluation shows that it is there.
  3. The aggregate score does not show a shortcut. Evaluate each group separately, on test data that look like the data at deployment.
  4. After a mitigation, measure each group again. A smaller gap does not prove that the model is fair.

From a model's loss, an attacker can guess whether an example was in the training data

If an outsider can tell from a model's outputs whether an example was in its training data, the model has revealed information about that example.

  • A member is an example from the training set, and a non-member is any other example. Guessing which of the two an example is, is called membership inference.
  • The loss-threshold attack (Yeom et al., 2018) computes the model's loss on the example and guesses "member" when the loss is below a threshold.
  • The more a model overfits, the lower its loss on training examples compared with new examples, and the more accurate the attack. An attack accuracy of 0.5 is the same as random guessing.
0loss on the exampleguess “member”guess “non-member”thresholdmembers(training examples)non-members(new examples)Schematic.

The data are 150 members and 150 non-members from two moons, with 10% of the labels flipped

Reading 4.6 uses the two-moons data of S26: 150 points to train on (the members) and 150 new points from the same distribution (the non-members). 10% of the labels are flipped on purpose. A flipped label follows no pattern, so the model can fit it only by memorizing that example.


def moons(n, gen):
    t = torch.rand(n, generator=gen) * torch.pi
    x = torch.where(
        (torch.arange(n) % 2 == 0).unsqueeze(1),
        torch.stack([torch.cos(t), torch.sin(t)], dim=1),
        torch.stack([1 - torch.cos(t), 0.5 - torch.sin(t)], dim=1),
    ) + 0.2 * torch.randn(n, 2, generator=gen)
    y = (torch.arange(n) % 2).long()
    flip = torch.rand(n, generator=gen) < 0.1          # 10% mislabeled
    return x, torch.where(flip, 1 - y, y)

g = torch.Generator().manual_seed(0)
x_tr, y_tr = moons(150, g)      # small training set: easy to memorize
x_out, y_out = moons(150, g)    # non-members from the same distribution
  

16 of the 150 training points have a flipped label

−1012−101label 0: 71 pointslabel 1: 79 pointsflipped label:16 of the 150 pointsThe 150 training pointsx_tr, y_tr (the members),from the generatorseeded 0.

Each color is a label. A ringed point had its label flipped, so its color is that of the other half circle.

The attack tries every loss as the threshold and keeps the best

attack computes one loss for each of the 150 members and each of the 150 non-members. For a threshold, a member counts as a correct guess when its loss is at or below the threshold, and a non-member when its loss is above it. The loop tries every one of the 300 losses as the threshold and keeps the highest accuracy.


def attack(net):
    """Loss-threshold membership inference: guess 'member' when the model's
    loss on the example is below a threshold (best threshold reported)."""
    with torch.no_grad():
        l_in = nn.functional.cross_entropy(net(x_tr), y_tr, reduction="none")     # members
        l_out = nn.functional.cross_entropy(net(x_out), y_out, reduction="none")  # non-members
    accs = []
    for thresh in torch.cat([l_in, l_out]).sort().values:
        hits = (l_in <= thresh).float().sum() + (l_out > thresh).float().sum()
        accs.append(hits / (len(l_in) + len(l_out)))
    acc = torch.stack(accs).max()
  

The threshold is chosen with the true memberships known, so the reported accuracy is the best that any threshold could reach. A real attacker would do no better.

train fits a network with about 67,000 parameters to the 150 training points

The last lines of attack return the attack accuracy together with the model's accuracy on the members and on the non-members and the two mean losses:


# attack, continued
    with torch.no_grad():
        tr_acc = (net(x_tr).argmax(1) == y_tr).float().mean()
        te_acc = (net(x_out).argmax(1) == y_out).float().mean()
    return acc.item(), tr_acc.item(), te_acc.item(), l_in.mean().item(), l_out.mean().item()
  

train fits an MLP with two hidden layers of width 256, about 67,000 parameters for 150 training points, using all 150 training points in every step.


def train(steps, weight_decay):
    torch.manual_seed(0)
    net = nn.Sequential(nn.Linear(2, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(),
                        nn.Linear(256, 2))
    opt = torch.optim.Adam(net.parameters(), lr=1e-3, weight_decay=weight_decay)
    for step in range(steps):
        loss = nn.functional.cross_entropy(net(x_tr), y_tr)
        opt.zero_grad(); loss.backward(); opt.step()
    return net
  

The loop trains one network three ways and attacks each

The first run trains long enough to memorize the training set. The other two use early stopping and weight decay (S07), which reduce overfitting. The experiment asks whether the attack becomes less accurate when the model overfits less.


print(f"{'model':>22} {'attack acc':>11} {'train acc':>10} {'test acc':>9} "
      f"{'loss in':>8} {'loss out':>9}")
for name, steps, wd in [("overfit (5k steps)", 5000, 0.0),
                        ("early stop (300)", 300, 0.0),
                        ("weight decay 1e-2", 5000, 1e-2)]:
    net = train(steps, wd)
    a, tr, te, li, lo = attack(net)
    print(f"{name:>22} {a:>11.3f} {tr:>10.3f} {te:>9.3f} {li:>8.4f} {lo:>9.4f}")
print("(attack acc 0.5 = coin flip; the attacker knows nothing)")
  

The more a model overfits, the more accurate the attack

The loop prints one row per model:


                 model  attack acc  train acc  test acc  loss in  loss out
    overfit (5k steps)       0.657      1.000     0.713   0.0169    3.3412
      early stop (300)       0.610      0.907     0.813   0.2178    0.6122
     weight decay 1e-2       0.540      0.840     0.807   0.3956    0.5001
(attack acc 0.5 = coin flip; the attacker knows nothing)
  
0.50.60.70.00.10.20.3train accuracy − test accuracyattack accuracychance: 0.5one point per row of the printoutweight decay 1e-20.840 − 0.807 = 0.033, attack 0.540early stop (300)0.907 − 0.813 = 0.094, attack 0.610overfit (5k steps)1.000 − 0.713 = 0.287, attack 0.657overfitearly stopweight decay

Early stopping and weight decay lower the attack's accuracy and raise the test accuracy

  • The overfit model fits every training point (train accuracy 1.000), including the flipped labels. Its mean loss is 0.017 on members and 3.34 on non-members, and the attack is right 65.7% of the time.
  • With early stopping and with weight decay, the two losses are closer, and the attack falls to 61.0% and 54.0%, close to chance (50%).
  • These two models are also more accurate on new data: 0.81 against 0.71.
  • Large models memorize too. Carlini et al. (USENIX Security 2021) sampled text from GPT-2 and found more than 600 passages, out of about 1,800 they checked, that were copied word for word from its training data.

The attack tells members from non-members mainly on the flipped labels

For the overfit model, the best threshold is a loss of 0.26. The attack guesses "member" when an example's loss is at or below the threshold and "non-member" when it is above. The table counts the 300 examples:

examplesnumberloss at or below the thresholdguessed correctly
members, label not flipped134133133
members, label flipped161515
non-members, label not flipped1289929
non-members, label flipped22220
  • The attack is correct on \(133+15+29+20=197\) of the 300 examples, which is 65.7%.
  • The model fits a label that was not flipped from the shape of the two half circles, so the loss is low for members and for most non-members, and the attack cannot tell them apart.
  • A flipped label contradicts the shape, so its loss is low mainly when the model memorized it: 15 of the 16 flipped members and 2 of the 22 flipped non-members have a low loss.

A model card records what a model was trained on, how it was evaluated, and where it fails

Datasets are used long after their collectors leave, models get reused, and the deployer is rarely the trainer. A model card writes down what the trainer knows for the people who use the model. A datasheet does the same for a dataset.

collectordatasettrainermodeldeployerdatasheet (Gebru et al., 2018)model card (Mitchell et al., 2019)
field of the model cardcontent
Model summaryarchitecture, size, framework
Intended usewhat it is for; what it is not for
Training datasource, size, known skews or gaps
Evaluationmetrics, test sets, uncertainty estimates (Part 2), with the accuracy reported per group (Part 4)
Known limitationsfailure modes you observed (be specific)
Ethical considerationsmisuse potential, bias risks, licensing

Your project report includes a model card (template in the project guide).

Before release, red-teaming searches for the ways in which a model fails

  • Red-teaming means searching for the ways in which the model fails. An ordinary evaluation looks for evidence that the model works, so it tends to miss failures.
  • Today's two measurements are examples. The per-group evaluation found the group on which the model scores 36.3%, and the membership attack guessed correctly 65.7% of the time.
  • Before you claim that your model works, look for the examples on which it fails, and report them.

Self-check on safety, question (a)

(a) A model scores 67% on the test set, and a manager calls that acceptable. The test set has two groups. The model scores 98.8% on one and 36.3% on the other. What is wrong with judging the model by the 67%?

(a) The 67% is the average of the two groups. It does not show that the model is right only 36.3% of the time on the second group, which is worse than guessing. Report the accuracy of each group.

Self-check on safety, question (b)

(b) A model predicts which job applicants to interview. The team removes the column "gender" from the features and trains again. The features still include each applicant's first name and previous job title. Can the new model still be less accurate on one gender than on the other? What should the team measure?

(b) Yes. A first name and a job title can predict gender, so they are proxies for the column that was removed, and the model can rely on them in its place. The team should measure the accuracy on each gender again after the change.

Self-check on safety, question (c)

(c) A model's mean loss is 0.02 on its training examples and 3.3 on new examples. How does the membership attack use this difference, and which two changes to training made the attack less accurate?

(c) The attack guesses "member" when the loss on an example is low. Training examples have much lower loss than new ones, so the guess is often right. Early stopping and weight decay reduce overfitting, which brings the two losses closer and the attack closer to chance.

Per-group accuracy and a membership attack measure what one aggregate score does not show.

Four mistakes in reporting a test score, each with its cause and its fix

One mistake per row:

#symptomcausefix
1the test score is high and the deployed model is worseinformation from the test set reached training (preprocessing fit before the split, duplicates, a random split of a time series)split first, then fit everything on the training set only
2a half-point "improvement" is reported with no estimate of the noiseidentical runs differ by 0.7 points and one model's test-set interval is 4.3 points wide; both are largertrain with several seeds; accept the difference only if it is larger than the seed noise and its paired-bootstrap interval excludes 0
3the best setting of a large sweep scores lower when trained againthe highest of many noisy scores is too high by chanceretrain the selected setting with new seeds before reporting it
4the aggregate accuracy is acceptable, and one group fails after deploymentthe aggregate is an average, so a low accuracy on one group does not showreport every metric per group, and judge the model by its worst group

Four mistakes in checking a model's safety, each with its cause and its fix

One mistake per row:

#symptomcausefix
5the aggregate test accuracy is high, and the model still fails a group after deploymentthe test set has the same correlation as the training set, so the group where the shortcut fails is smallevaluate on data like the deployment data, or on a test set where the attribute does not predict the label
6the attribute was removed, so the model is declared fairother features predict the attributemeasure the accuracy of each group anyway, and check whether the inputs predict the attribute
7an attacker can tell whether an example was in the training datathe model overfits, so its loss is much lower on training examplesreduce overfitting with early stopping or weight decay, and measure the attack's accuracy
8the model card is written the week of release, from memorythe card is written after the work, when details are forgottenstart it when training starts, and write down each limitation when you find it

A test score is trustworthy when the test set is used once, and its noise has two sources

  • A test score is trustworthy when every decision is made on the validation set, the test set is used once, and preprocessing is fit on the training set only. An LLM's benchmark score may be too high because the model may have seen the questions.
  • Its noise has two sources, seed noise and test-set noise. Five seeds gave standard deviations of 0.18 and 0.29 points (Experiment 1). The bootstrap gave one model a 95% interval 4.3 points wide (Experiment 2). To compare two models, use several seeds and a paired bootstrap of the difference.

The best of many scores is too high, and one aggregate score does not show which group fails

  • Comparing many scores makes the best one too high. Twenty identical runs differed by 0.7 points (Experiment 3). Decide the comparisons first, report every run, retrain the best setting with new seeds, and treat a difference smaller than the noise as no difference.
  • One aggregate score does not show which group the model fails or whether it reveals its training data. A 67% accuracy was 98.8% for one group and 36.3% for the other. Per-group accuracy and a membership attack measure both.

Report a benchmark difference together with an estimate of its noise.

HW4, the presentations and the final report remain after today

whatwhenwhat you do
CS 5715Friday, December 4All four paper responses.
HW4Wednesday, December 9,
11:59 PM Pacific
You implement bootstrap intervals and a paired comparison of two models, the methods of today's Part 2.
Presentation in classMonday, December 7 (S28), or
Wednesday, December 9 (S29)
In class, or by Zoom for Virtual Meeting and CdA students. Sign up through the link in the Canvas announcement. Upload your slides to Canvas by Friday, December 11. Every member presents a part.
Recorded presentationFriday, December 11,
11:59 PM Pacific
One 8–10 minute video per team, for teams that do not present in class. Every member presents a part.

The code defense follows your presentation, and the final report is due on December 11

whatwhenwhat you do
Code defenseafter your
presentation
The questions after an in-class presentation are the code defense. Students who submit a recording may be called for one by appointment.
Final reportFriday, December 11,
11:59 PM Pacific
The team report with a model card, AI Usage and Contributions, plus your own 1–2 page individual part; a README with exact reproduction commands. Every member submits. Report every result with an estimate of its noise, as in today's Part 2; the report is graded on it.

In a code defense you answer 2–3 questions about code you wrote, possibly on your evaluation choices, with your own code open. Students who are not presenting need not attend on December 7 or December 9. The week of December 7 is No-Exam Week, so there are no quizzes or exams.

Quiz 4 · the final 30 minutes (6:45–7:15 PM)

Everyone completes Quiz 4 in Canvas.
It covers S23–S26. Today's session, S27, is not on the quiz.

Online (Web) students and students with flexible-time arrangements may use their assigned flexible completion window.

The quiz is closed materials (Tier 0). It cannot be submitted late, and a make-up is arranged only in the three cases listed in the syllabus.