How to Check Whether an AI Eval Can Be Passed Without the Question: Build a Partial-Input Baseline in Python, Split by Group, and Reproduce the SNLI Hypothesis-Only Result
Build a 277-line Python audit that tests whether an AI eval can be scored without reading the question, reproduce the SNLI hypothesis-only result with a naive Bayes you write yourself, and check the...
An evaluation set (an “eval” or benchmark) is a list of questions with expected answers. A score on it only means something if answering the questions needs the skill you think it tests. This tutorial teaches a cheap check for the opposite problem, a shortcut: a clue in the data that lets a program guess the answer without doing the task. You will build a small Python tool that trains a deliberately weak classifier on only part of each item, measures how well it does with an honest confidence interval, and tells you whether that part of the input gives the answer away.
Table Of Content
- Key terms, in plain language
- Prerequisites
- Step 1: Make three toy evals whose truth you know
- Check it worked
- Step 2: Write a classifier that can only count words
- Check it worked
- Step 3: Score it fairly, and make it fail on purpose
- Reading the table
- Step 4: Hold out whole groups, and learn what the two numbers mean together
- What the numbers say
- Why group folds can score below chance
- Common mistake: trusting the random-fold number alone
- Step 5: Put an honest interval on the number
- Reading the intervals
- Step 6: Try it on real data, the SNLI hypothesis-only result
- Reading the SNLI results
- Step 7: Do not clean away the signal
- Step 8: Turn the pieces into one command with a verdict
- Check it worked
- Step 9: Test the auditor, then try to break the tests
- The bug that survived the first run
- What to do when the audit flags your eval
- Common mistakes and how to notice them
- Confirm the whole thing end to end
- Where to go next
- Sources
The idea is old and well documented. In natural language inference (NLI) datasets, each item holds a premise (one sentence), a hypothesis (a second sentence) and a label: the hypothesis follows from the premise (“entailment”), contradicts it (“contradiction”) or does neither (“neutral”). Gururangan and co-authors showed that “a simple text categorization model can correctly classify the hypothesis alone in about 67% of SNLI”, which means a model that never reads the premise already beats guessing by a wide margin (Annotation Artifacts in Natural Language Inference Data). The dataset card for SNLI lists three results of the same kind from different papers: “Poliak et al correctly predicted the label of the hypothesis 69% of the time without using the premise, Gururangan et al 67% of the time, and Tsuchiya 63% of the time” (SNLI dataset card).
By the end you will have a 277-line audit tool, three toy evals whose answers you know, a reproduction of the SNLI hypothesis-only result on a naive Bayes classifier you wrote yourself, 28 tests, and a check that the tests catch 13 planted bugs. You will also see two results you may not expect: a random train and test split can report a perfect score for the wrong reason, and a “score” below chance can be a warning sign rather than good news.
Key terms, in plain language
- Label: the expected answer of one item (for example “contradiction”).
- Majority baseline: the accuracy of a program that always answers with the most common label. If 34 percent of items have the label “entailment”, always answering “entailment” scores 0.34.
- Partial input: only part of each item, such as the hypothesis without the premise, or the answer options without the question. A partial-input baseline is a classifier that sees only that part.
- Naive Bayes: a classifier that counts how often each word appears with each label and combines those counts. It is simple on purpose. If a model this weak can beat the majority baseline, the clue is easy to find, and a stronger model is likely to find it too.
- Fold and cross-validation: you split the rows into k folds (here 5), train on four, score on the fifth, and rotate, so every row is scored by a model that never saw it.
- Group: rows that belong together because they share a template, a source document or a premise. Rows of one group tend to look alike and to share answers.
- Bootstrap interval: a range for a score, found by resampling the results with replacement many times and reading off the middle 95 percent.
Prerequisites
- Python 3.13 (everything here ran on 3.13.14 on Windows 11 with Git Bash; the commands also work on macOS and Linux, where the virtual-environment path is
.venv/bin/python). The audit tool itself uses only the standard library. - pytest 9.2.0 for the tests, and pyarrow (tested with 26.0.1) only to read the SNLI files, which Hugging Face publishes as Parquet.
- About 100 MB of free disk space (the SNLI training file is 19.6 MB as Parquet and about 88 MB as JSON lines) and a minute of patience: every step below finished in under 15 seconds on the test machine.
- No machine-learning background. You should be able to read Python functions and classes and run commands in a terminal.
Step 1: Make three toy evals whose truth you know
Before you trust an auditor on real data, point it at data where you know the answer. We will generate support-ticket evals with three labels (billing, outage, feature). Each has 45 templates and 60 rows per template, 2,700 rows in all. Template number i has its own verb and noun (so every template is recognizable) and a fixed opener and closer; each row adds a random product name and weekday and a short closing sentence. The three versions differ only in how the label is chosen:
toy_clean: the label is random and unrelated to the text. A good audit must find nothing.toy_cue: the label is random per row, but 60 percent of rows end with a sentence that hints at it (“We were charged twice.” for billing, “Everything is down.” for outage, “I wish it had dark mode.” for feature). This is a shortcut that works on any template, so about 0.6 + 0.4 × (1/3) = 0.73 accuracy is available.toy_template: the label is fixed by the template (template number modulo 3). Nothing in a row hints at the label except which template it came from.
Save this as make_toys.py in a new folder:
mkdir shortcut-lab
cd shortcut-lab
python -m venv .venv
.venv/Scripts/python.exe -m pip install pytest==9.2.0 pyarrow
# make_toys.py
"""Three toy support-ticket evals, 45 templates x 60 rows each, with a known amount of shortcut."""
import json
import pathlib
import random
DATA = pathlib.Path(__file__).parent / "data"
LABELS = ["billing", "outage", "feature"]
VERBS = ["audit", "rename", "archive", "restore", "merge", "export", "pause", "escalate", "reconcile", "refund",
"resend", "reset", "upgrade", "downgrade", "cancel", "transfer", "verify", "unlock", "migrate", "clone",
"delete", "review", "approve", "reject", "forward", "schedule", "update", "diagnose", "patch", "replace",
"rotate", "revoke", "activate", "deactivate", "resolve", "summarize", "translate", "compare", "document",
"track", "split", "bundle", "tag", "sync", "prune"]
THINGS = ["invoices", "receipts", "licenses", "seats", "API keys", "webhooks", "backups", "reports", "dashboards",
"exports", "workspaces", "projects", "domains", "certificates", "mailboxes", "teams", "roles", "tokens",
"quotas", "plans", "coupons", "orders", "shipments", "contracts", "tickets", "alerts", "schedules",
"templates", "folders", "snapshots", "tenants", "queues", "jobs", "logs", "metrics", "policies", "groups",
"labels", "notes", "forms", "rules", "drafts", "filters", "bookmarks", "widgets"]
OPENERS = ["Hi team,", "Hello,", "Quick one:", "Heads up:", "Good morning,", "Hey,", "Dear support,", "Hi,"]
CLOSERS = ["before {day}?", "by {day} if possible?", "when you get a chance?", "as soon as you can?",
"this {day}?", "today?", "before the {day} call?"]
PRODUCTS = ["Atlas", "Beacon", "Cedar", "Delta", "Ember", "Flint", "Garnet", "Harbor", "Iris", "Juniper", "Kestrel", "Lumen"]
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
CUES = {"billing": ["We were charged twice.", "The amount looks wrong.", "Please check the charge."],
"outage": ["Everything is down.", "Pages keep timing out.", "We see errors since noon."],
"feature": ["I wish it had dark mode.", "Would love an export option.", "Please add a bulk edit."]}
NEUTRAL = ["Thanks!", "Thanks a lot.", "Cheers.", "Much appreciated."]
def make(kind, seed=7, templates=45, per_template=60):
"""kind: clean (label unrelated to the text), cue (a cue sentence in 60% of rows), template (label set by the template)."""
rng = random.Random(seed)
frames = []
for i in range(templates):
pick = random.Random(1000 + i)
frames.append((pick.choice(OPENERS), VERBS[i], THINGS[i], pick.choice(CLOSERS)))
rows = []
for t, (opener, verb, thing, closer) in enumerate(frames):
for _ in range(per_template):
product, day = rng.choice(PRODUCTS), rng.choice(DAYS)
body = f"{opener} could you {verb} the {product} {thing} {closer.format(day=day)}"
label = LABELS[t % 3] if kind == "template" else rng.choice(LABELS)
tail = rng.choice(CUES[label]) if kind == "cue" and rng.random() < 0.6 else rng.choice(NEUTRAL)
rows.append({"text": f"{body} {tail}", "label": label, "group": f"t{t:02d}"})
rng.shuffle(rows)
return rows
if __name__ == "__main__":
DATA.mkdir(exist_ok=True)
for kind in ("clean", "cue", "template"):
rows = make(kind)
with open(DATA / f"toy_{kind}.jsonl", "w", encoding="utf-8", newline="\n") as out:
for row in rows:
out.write(json.dumps(row) + "\n")
print(f"toy_{kind}.jsonl: {len(rows)} rows")
Run it with the virtual environment’s Python (the commands below write python for short). It writes three JSON-lines files, one JSON object per line, into a data folder next to the script:
python make_toys.py
python step01_toys.py
toy_clean.jsonl: 2700 rows
toy_cue.jsonl: 2700 rows
toy_template.jsonl: 2700 rows
The second script, step01_toys.py, prints the label counts and two sample rows from each file, so you can see what the data looks like before any model touches it:
# step01_toys.py
import collections
import json
import pathlib
DATA = pathlib.Path(__file__).parent / "data"
for name in ("toy_clean", "toy_cue", "toy_template"):
rows = [json.loads(line) for line in (DATA / f"{name}.jsonl").read_text(encoding="utf-8").splitlines()]
labels = collections.Counter(r["label"] for r in rows)
print(f"=== {name}: {len(rows)} rows, {len({r['group'] for r in rows})} templates, labels {dict(sorted(labels.items()))}")
for r in rows[:2]:
print(f" {r['group']} {r['label']:8} | {r['text']}")
=== toy_clean: 2700 rows, 45 templates, labels {'billing': 929, 'feature': 879, 'outage': 892}
t43 billing | Hey, could you sync the Delta bookmarks when you get a chance? Thanks!
t07 feature | Hi team, could you escalate the Delta reports before the Saturday call? Thanks a lot.
=== toy_cue: 2700 rows, 45 templates, labels {'billing': 932, 'feature': 873, 'outage': 895}
t01 outage | Hi team, could you rename the Atlas receipts before the Saturday call? Much appreciated.
t10 feature | Heads up: could you resend the Harbor workspaces this Wednesday? Please add a bulk edit.
=== toy_template: 2700 rows, 45 templates, labels {'billing': 900, 'feature': 900, 'outage': 900}
t18 billing | Dear support, could you migrate the Cedar quotas today? Thanks a lot.
t41 feature | Hi, could you bundle the Garnet drafts by Saturday if possible? Much appreciated.
Check it worked
You should see 2,700 rows and 45 templates in every file. In toy_template the labels are exactly balanced at 900 each, because 45 templates split evenly three ways. Each row is a short polite request plus a closing sentence, and the group name (t07, t43) records which template made it.
Step 2: Write a classifier that can only count words
The baseline is a multinomial naive Bayes classifier, one of the two classic variants for text classification (the scikit-learn documentation calls it “one of the two classic naive Bayes variants used in text classification”). The idea fits in one sentence. For each label, add up the log of how likely each word of the item is given that label, add the log of how common the label is, and answer with the label whose total is highest. Logarithms turn products of many small probabilities into sums, which avoids numbers too small for a computer to store.
Two details matter more than they look. First, smoothing: a word seen only with one label would otherwise get probability zero for the others and veto them forever. Adding a small count to every word fixes it; in the documentation’s words, smoothing priors “prevent zero probabilities in further computations”. Second, the tokenizer. Ours lowercases the text and keeps every word, including “no”, “not” and “nobody”. That choice is deliberate and you will measure why in Step 7.
Start the module shortcut_audit.py with the tokenizer and the feature function. With ngrams=2 the features also include every pair of neighboring words, which lets the model notice phrases:
# shortcut_audit.py
"""Partial-input shortcut audit for an evaluation set (standard library only).
python shortcut_audit.py DATA.jsonl [--text-field text] [--label-field label] [--group-field group]
[--folds 5] [--ngrams 1] [--margin 0.05] [--reps 1000] [--seed 0] [--json]
Each line of DATA.jsonl is a JSON object. The text field holds the part of the input the baseline
may see, the label field the expected answer, and the optional group field the template, source
document or other cluster the row came from.
Exit codes: 0 clean, 1 shortcut or group memorization found, 2 unreadable input.
"""
import argparse
import json
import math
import random
import re
import sys
from collections import Counter, defaultdict
TOKEN = re.compile(r"[a-z0-9]+(?:'[a-z]+)?")
def tokenize(text):
return TOKEN.findall(text.lower())
def featurize(text, ngrams=1):
words = tokenize(text)
feats = list(words)
if ngrams >= 2:
feats += [a + " " + b for a, b in zip(words, words[1:])]
return feats
Then add the classifier. fit counts words per label; scores adds the prior and the smoothed word log-probabilities; predict returns the best label. Words never seen in training are ignored instead of being scored, so they cannot tilt the result toward whichever label happens to have the most training text:
# shortcut_audit.py (continued)
class NaiveBayes:
"""Multinomial naive Bayes over bag-of-words features with add-alpha smoothing."""
def __init__(self, alpha=1.0, ngrams=1):
self.alpha = alpha
self.ngrams = ngrams
def fit(self, texts, labels):
self.classes = sorted(set(labels))
self.class_count = Counter(labels)
self.counts = {c: Counter() for c in self.classes}
self.totals = Counter()
for text, label in zip(texts, labels):
feats = featurize(text, self.ngrams)
self.counts[label].update(feats)
self.totals[label] += len(feats)
self.vocab = set().union(*self.counts.values())
size = len(self.vocab)
self.denominator = {c: self.totals[c] + self.alpha * size for c in self.classes}
self.prior = [math.log(self.class_count[c] / len(labels)) for c in self.classes]
self.cache = {}
return self
def log_probs(self, feature):
row = self.cache.get(feature)
if row is None:
row = [math.log((self.counts[c][feature] + self.alpha) / self.denominator[c]) for c in self.classes]
self.cache[feature] = row
return row
def scores(self, text):
total = list(self.prior)
for feature in featurize(text, self.ngrams):
if feature in self.vocab:
for j, value in enumerate(self.log_probs(feature)):
total[j] += value
return dict(zip(self.classes, total))
def predict(self, text):
scores = self.scores(text)
return max(self.classes, key=scores.get)
Check it worked
A two-line experiment confirms the model learns a word rule:
python -c "import shortcut_audit as sa; m = sa.NaiveBayes().fit(['red apple', 'blue sky'], ['warm', 'cold']); print(m.predict('red'))"
warm
Step 3: Score it fairly, and make it fail on purpose
Now the evaluation machinery. majority_share is the bar to beat. random_folds deals the rows into five folds after shuffling with a fixed seed, and cross_val_predictions trains on four folds and predicts the fifth, five times over. The last helper, permuted_accuracies, is a sanity check you should never skip: it shuffles the labels, which destroys any real link between text and label, and runs the identical pipeline. The result must land near the majority share. If it does not, your pipeline is leaking the answer somewhere, and every number it produces is suspect.
# shortcut_audit.py (continued)
def majority_share(labels):
return Counter(labels).most_common(1)[0][1] / len(labels)
def accuracy(pred, gold):
return sum(p == y for p, y in zip(pred, gold)) / len(gold)
def correctness(pred, gold):
return [int(p == y) for p, y in zip(pred, gold)]
def random_folds(n, k, seed=0):
order = list(range(n))
random.Random(seed).shuffle(order)
folds = [0] * n
for rank, i in enumerate(order):
folds[i] = rank % k
return folds
def cross_val_predictions(texts, labels, folds, make_model):
k = max(folds) + 1
preds = [None] * len(texts)
for f in range(k):
train = [i for i, g in enumerate(folds) if g != f]
test = [i for i, g in enumerate(folds) if g == f]
model = make_model().fit([texts[i] for i in train], [labels[i] for i in train])
for i in test:
preds[i] = model.predict(texts[i])
return preds
def permuted_accuracies(texts, labels, folds, make_model, reps=5, seed=0):
"""Accuracy of the same pipeline after shuffling the labels: the sanity floor."""
rng = random.Random(seed)
scores = []
for _ in range(reps):
shuffled = labels[:]
rng.shuffle(shuffled)
scores.append(accuracy(cross_val_predictions(texts, shuffled, folds, make_model), shuffled))
return scores
The script step02_baselines.py runs all three toys through this machinery with bigram features:
# step02_baselines.py
import json
import pathlib
import shortcut_audit as sa
DATA = pathlib.Path(__file__).parent / "data"
print(f"{'dataset':14}{'majority':>10}{'random folds':>14}{'label-shuffled (5 runs)':>30}")
for name in ("toy_clean", "toy_cue", "toy_template"):
rows = [json.loads(line) for line in (DATA / f"{name}.jsonl").read_text(encoding="utf-8").splitlines()]
texts, labels = [r["text"] for r in rows], [r["label"] for r in rows]
folds = sa.random_folds(len(rows), 5, seed=0)
def make():
return sa.NaiveBayes(ngrams=2)
real = sa.accuracy(sa.cross_val_predictions(texts, labels, folds, make), labels)
shuffled = sa.permuted_accuracies(texts, labels, folds, make, reps=5, seed=0)
print(f"{name:14}{sa.majority_share(labels):10.3f}{real:14.3f}{min(shuffled):17.3f} to {max(shuffled):.3f}")
python step02_baselines.py
dataset majority random folds label-shuffled (5 runs)
toy_clean 0.344 0.347 0.317 to 0.344
toy_cue 0.345 0.737 0.313 to 0.341
toy_template 0.333 1.000 0.324 to 0.354
Reading the table
toy_clean behaves: 0.347 against a majority share of 0.344, and the label-shuffled runs land between 0.317 and 0.344. toy_cue scores 0.737, which matches the 0.73 predicted from the planted cue. toy_template scores a perfect 1.000 on text that contains no hint about the label at all. That cannot be a skill; something else is going on, and the next step explains it.
Step 4: Hold out whole groups, and learn what the two numbers mean together
Random folds put rows from the same template on both sides of the split. A model can then memorize “this phrasing means billing” from the training rows and apply it to the test rows of the same template. That is real information for a model that has seen your eval, which matters if people fine-tune on part of a benchmark, but it says nothing about whether the clue works on templates the model has never met. Group folds answer that second question: every row of a group lands in the same fold, so the test fold contains only groups the model never saw. Our version deals the groups out largest first, always to the lightest fold, which keeps the folds close in size.
# shortcut_audit.py (continued)
def group_folds(groups, k, seed=0):
sizes = Counter(groups)
if len(sizes) < k:
raise ValueError(f"need at least {k} groups for {k} folds, found {len(sizes)}")
names = sorted(sizes, key=str)
random.Random(seed).shuffle(names)
names.sort(key=lambda g: -sizes[g]) # stable sort: equal sizes keep their shuffled order
load = [0] * k
fold_of = {}
for g in names:
f = min(range(k), key=lambda j: (load[j], j))
fold_of[g] = f
load[f] += sizes[g]
return [fold_of[g] for g in groups]
# step03_groups.py
import json
import pathlib
import shortcut_audit as sa
DATA = pathlib.Path(__file__).parent / "data"
print(f"{'dataset':14}{'random folds':>14}{'group folds':>13}")
for name in ("toy_clean", "toy_cue", "toy_template"):
rows = [json.loads(line) for line in (DATA / f"{name}.jsonl").read_text(encoding="utf-8").splitlines()]
texts, labels, groups = [r["text"] for r in rows], [r["label"] for r in rows], [r["group"] for r in rows]
def make():
return sa.NaiveBayes(ngrams=2)
random_acc = sa.accuracy(sa.cross_val_predictions(texts, labels, sa.random_folds(len(rows), 5, 0), make), labels)
group_acc = sa.accuracy(sa.cross_val_predictions(texts, labels, sa.group_folds(groups, 5, 0), make), labels)
print(f"{name:14}{random_acc:14.3f}{group_acc:13.3f}")
print()
print("fold seeds for toy_template (group folds, 45 templates, 9 per fold):")
rows = [json.loads(line) for line in (DATA / "toy_template.jsonl").read_text(encoding="utf-8").splitlines()]
texts, labels, groups = [r["text"] for r in rows], [r["label"] for r in rows], [r["group"] for r in rows]
scores = []
for seed in range(10):
folds = sa.group_folds(groups, 5, seed)
scores.append(sa.accuracy(sa.cross_val_predictions(texts, labels, folds, lambda: sa.NaiveBayes(ngrams=2)), labels))
print(" accuracy by seed:", " ".join(f"{s:.3f}" for s in scores))
print(f" lowest {min(scores):.3f}, highest {max(scores):.3f}, mean {sum(scores) / len(scores):.3f}, majority share {sa.majority_share(labels):.3f}")
class FlatPrior(sa.NaiveBayes):
"""The same model with every class prior set to the same value."""
def fit(self, texts, labels):
super().fit(texts, labels)
self.prior = [0.0] * len(self.classes)
return self
flat = []
for seed in range(10):
folds = sa.group_folds(groups, 5, seed)
flat.append(sa.accuracy(sa.cross_val_predictions(texts, labels, folds, lambda: FlatPrior(ngrams=2)), labels))
print(" with a flat prior:", " ".join(f"{s:.3f}" for s in flat))
print(f" lowest {min(flat):.3f}, highest {max(flat):.3f}, mean {sum(flat) / len(flat):.3f}")
python step03_groups.py
dataset random folds group folds
toy_clean 0.347 0.326
toy_cue 0.737 0.713
toy_template 1.000 0.256
fold seeds for toy_template (group folds, 45 templates, 9 per fold):
accuracy by seed: 0.256 0.256 0.247 0.319 0.326 0.341 0.209 0.271 0.293 0.333
lowest 0.209, highest 0.341, mean 0.285, majority share 0.333
with a flat prior: 0.258 0.260 0.253 0.326 0.347 0.354 0.215 0.278 0.297 0.334
lowest 0.215, highest 0.354, mean 0.292
What the numbers say
For toy_cue the accuracy barely moves (0.737 with random folds, 0.713 with group folds): the cue works on any template, so it is a shortcut that transfers. For toy_template the score collapses from 1.000 to 0.256. The wording of a template gives away the label only to a model that has already seen that template.
Put the two numbers side by side and they sort every case into one of four outcomes:
| Random folds | Group folds | Verdict | Example in this tutorial | What it means |
|---|---|---|---|---|
| well above the majority share | well above the majority share | shortcut | toy_cue, SNLI hypothesis only |
The clue works on groups the model has never seen. Any model can pick it up. |
| well above | at or below the majority share | group memorization | toy_template |
Group wording gives the label away, but only to a model that has seen that group. A leak between your own train and test splits, not a general shortcut. |
| at the majority share | at the majority share | clean | toy_clean |
This partial input says nothing about the label. |
| far below the majority share | at the majority share | clean, but the random split leaks | SNLI premise only (Step 6) | The random split is leaking in the wrong direction. Use group folds. |
Why group folds can score below chance
The group-fold score for toy_template is 0.256, below the 0.333 you would get by guessing. Across ten different fold seeds it ranged from 0.209 to 0.341 with a mean of 0.285. This is not a bug. When whole groups are held out of a design that is balanced overall, the training counts are the totals minus the held-out counts, so any word’s lean in training points slightly away from where it sits in the held-out fold. My first guess was the class prior, so I ran the same model with every prior set equal (FlatPrior, a short subclass at the end of step03_groups.py); the mean only moved from 0.285 to 0.292, so the prior is not the main cause. The same subtraction applies to the word counts, which is my explanation for the rest; I did not isolate it further. What matters for the audit is not the exact value but the interval, which Step 5 supplies.
Common mistake: trusting the random-fold number alone
If you had stopped at Step 3, you would have reported that a word counter solves toy_template perfectly. Both statements are true, and they answer different questions. Always report the random-fold and group-fold numbers together, and say which group you used.
Step 5: Put an honest interval on the number
A single accuracy is a guess about a bigger population. The standard way to get a range is the bootstrap: resample the per-row results with replacement, compute the accuracy of each resample, sort them, and read off the 2.5th and 97.5th percentiles. Python’s random.choices does the resampling in one call (“Return a k sized list of elements chosen from the population with replacement”), and the standard-library documentation itself shows bootstrapping a confidence interval with it.
There is a catch, and it is a common statistical error in eval reports. Resampling rows assumes the rows are independent. Rows from one template are not: if the model gets one wrong, it probably gets its siblings wrong too. The fix is the cluster bootstrap: resample whole groups with replacement, and recompute the pooled accuracy from the groups drawn. The effective sample size is then the number of groups, not the number of rows.
# shortcut_audit.py (continued)
def bootstrap_ci(correct, groups=None, reps=1000, seed=0, level=0.95):
"""Percentile interval for accuracy. With groups, whole groups are resampled."""
rng = random.Random(seed)
stats = []
if groups is None:
n = len(correct)
for _ in range(reps):
stats.append(sum(rng.choices(correct, k=n)) / n)
else:
per = defaultdict(lambda: [0, 0])
for ok, g in zip(correct, groups):
per[g][0] += ok
per[g][1] += 1
clusters = list(per.values())
m = len(clusters)
for _ in range(reps):
drawn = rng.choices(clusters, k=m)
stats.append(sum(h for h, _ in drawn) / sum(t for _, t in drawn))
stats.sort()
lo = stats[int(reps * (1 - level) / 2)]
hi = stats[min(reps - 1, int(reps * (1 + level) / 2))]
return lo, hi
# step04_intervals.py
import json
import pathlib
import shortcut_audit as sa
DATA = pathlib.Path(__file__).parent / "data"
print(f"{'dataset (group folds)':24}{'accuracy':>9} {'row bootstrap':>20} {'cluster bootstrap':>20}")
for name in ("toy_cue", "toy_template"):
rows = [json.loads(line) for line in (DATA / f"{name}.jsonl").read_text(encoding="utf-8").splitlines()]
texts, labels, groups = [r["text"] for r in rows], [r["label"] for r in rows], [r["group"] for r in rows]
folds = sa.group_folds(groups, 5, 0)
pred = sa.cross_val_predictions(texts, labels, folds, lambda: sa.NaiveBayes(ngrams=2))
ok = sa.correctness(pred, labels)
row_lo, row_hi = sa.bootstrap_ci(ok, reps=1000)
cl_lo, cl_hi = sa.bootstrap_ci(ok, groups, reps=1000)
print(f"{name:24}{sum(ok) / len(ok):9.3f} [{row_lo:.3f}, {row_hi:.3f}] w{row_hi - row_lo:.3f} [{cl_lo:.3f}, {cl_hi:.3f}] w{cl_hi - cl_lo:.3f}")
python step04_intervals.py
dataset (group folds) accuracy row bootstrap cluster bootstrap
toy_cue 0.713 [0.696, 0.730] w0.034 [0.697, 0.730] w0.033
toy_template 0.256 [0.239, 0.273] w0.033 [0.143, 0.386] w0.243
Reading the intervals
For toy_cue the two methods agree (width 0.034 against 0.033), because the cue helps every template about equally and the groups behave like independent rows. For toy_template the row bootstrap claims the accuracy is 0.256 give or take 0.017, an interval 0.033 wide. The cluster bootstrap says [0.143, 0.386], 0.243 wide, which is 7.4 times wider, and it includes the 0.333 majority share. The row interval pretended to know the answer from 2,700 independent rows; there were only 45 templates.
Step 6: Try it on real data, the SNLI hypothesis-only result
SNLI (the Stanford Natural Language Inference corpus) is “a collection of 570k human-written English sentence pairs manually labeled for balanced classification with the labels entailment, contradiction, and neutral”. It is licensed under CC BY-SA 4.0 and was introduced by Bowman et al. (2015). Crowd workers were shown a photo caption (the premise) and asked to write three new sentences, one that follows from it, one that contradicts it and one that does neither. That instruction is exactly the kind of process that can leave clues. Download the three splits from Hugging Face (19.6 MB for training, about 0.4 MB each for validation and test) and convert them to JSON lines:
curl -L -o data/snli_train.parquet https://huggingface.co/datasets/stanfordnlp/snli/resolve/main/plain_text/train-00000-of-00001.parquet
curl -L -o data/snli_validation.parquet https://huggingface.co/datasets/stanfordnlp/snli/resolve/main/plain_text/validation-00000-of-00001.parquet
curl -L -o data/snli_test.parquet https://huggingface.co/datasets/stanfordnlp/snli/resolve/main/plain_text/test-00000-of-00001.parquet
python snli_to_jsonl.py
One detail from the dataset card matters here: “Dataset instances which don’t have any gold label are marked with -1 label.” Rows without an agreed label must be dropped before any scoring, or they quietly become a fourth class. The converter does that and reports how many it dropped:
# snli_to_jsonl.py
"""Turn the three SNLI parquet files into JSONL rows with premise, hypothesis and a label name."""
import json
import pathlib
import pyarrow.parquet as pq
DATA = pathlib.Path(__file__).parent / "data"
NAMES = {0: "entailment", 1: "neutral", 2: "contradiction"}
for split in ("train", "validation", "test"):
table = pq.read_table(DATA / f"snli_{split}.parquet").to_pydict()
kept = dropped = 0
with open(DATA / f"snli_{split}.jsonl", "w", encoding="utf-8", newline="\n") as out:
for premise, hypothesis, label in zip(table["premise"], table["hypothesis"], table["label"]):
if label not in NAMES: # label -1 means no gold label
dropped += 1
continue
out.write(json.dumps({"premise": premise, "hypothesis": hypothesis, "label": NAMES[label]}) + "\n")
kept += 1
print(f"{split}: kept {kept:,} rows, dropped {dropped} without a gold label")
train: kept 549,367 rows, dropped 785 without a gold label
validation: kept 9,842 rows, dropped 158 without a gold label
test: kept 9,824 rows, dropped 176 without a gold label
You will also want to see which words carry the signal. Gururangan and co-authors ranked words by pointwise mutual information (PMI) between each word and each label, with heavy smoothing that, in their words, “emphasizes word-class correlations that are highly discriminative”. Here is a version in the same spirit: PMI(word, label) is the log of how much more likely a label becomes once the word is present. I used add-100 smoothing, the same size the paper reports, but the paper’s text does not spell out how the smoothing enters its formula, so do not expect digit-for-digit agreement with its table.
# shortcut_audit.py (continued)
def pmi_words(texts, labels, per_class=8, smooth=100.0):
"""Words most tied to each label: PMI(word, label) = log(P(label | word) / P(label)), add-smooth counts."""
classes = sorted(set(labels))
n_class = Counter(labels)
n_word = defaultdict(Counter)
for text, label in zip(texts, labels):
for word in set(tokenize(text)):
n_word[word][label] += 1
out = {c: [] for c in classes}
for word, per in n_word.items():
total = sum(per.values())
for c in classes:
p_c_given_w = (per[c] + smooth) / (total + smooth * len(classes))
out[c].append((math.log(p_c_given_w / (n_class[c] / len(labels))), word, per[c] / n_class[c]))
return {c: sorted(rows, reverse=True)[:per_class] for c, rows in out.items()}
The script step05_snli.py has four parts: a hypothesis-only model trained on the full training set and scored on the test set; random folds against premise folds on a premise-closed sample of 17,000 premises (61,324 rows), once with the hypothesis and once with the premise as the only input; a tally that explains the surprising premise-only result; and the top PMI words per label.
# step05_snli.py
import json
import random
import time
from collections import Counter
from pathlib import Path
import shortcut_audit as sa
DATA = Path(__file__).parent / "data"
def load(split):
return [json.loads(line) for line in (DATA / f"snli_{split}.jsonl").read_text(encoding="utf-8").splitlines()]
train, test = load("train"), load("test")
print(f"train {len(train):,} rows from {len({r['premise'] for r in train}):,} premises; "
f"test {len(test):,} rows from {len({r['premise'] for r in test}):,} premises")
gold = [r["label"] for r in test]
print(f"majority label share on test: {sa.majority_share(gold):.4f}")
print("\n=== hypothesis only: fit on train, score on test")
for ngrams in (1, 2):
start = time.time()
model = sa.NaiveBayes(ngrams=ngrams).fit([r["hypothesis"] for r in train], [r["label"] for r in train])
ok = sa.correctness([model.predict(r["hypothesis"]) for r in test], gold)
lo, hi = sa.bootstrap_ci(ok, [r["premise"] for r in test])
kind = "unigrams" if ngrams == 1 else "unigrams+bigrams"
print(f" {kind:17} accuracy {sum(ok) / len(ok):.4f} 95% CI [{lo:.4f}, {hi:.4f}] ({time.time() - start:.0f} s)")
print("\n=== random folds against premise folds: 5 folds, 17,000 premises drawn from train")
rng = random.Random(0)
premises = sorted({r["premise"] for r in train})
rng.shuffle(premises)
keep = set(premises[:17000])
subset = [r for r in train if r["premise"] in keep]
labels, groups = [r["label"] for r in subset], [r["premise"] for r in subset]
print(f" {len(subset):,} rows, majority label share {sa.majority_share(labels):.4f}")
for field in ("hypothesis", "premise"):
texts = [r[field] for r in subset]
for name, folds in (("random", sa.random_folds(len(subset), 5, 0)), ("premise", sa.group_folds(groups, 5, 0))):
ok = sa.correctness(sa.cross_val_predictions(texts, labels, folds, sa.NaiveBayes), labels)
lo, hi = sa.bootstrap_ci(ok, groups, reps=300)
print(f" {field + ' only':16}{name + ' folds':14} accuracy {sum(ok) / len(ok):.4f} 95% CI [{lo:.4f}, {hi:.4f}]")
print("\n=== why premise-only falls below chance with random folds")
folds = sa.random_folds(len(subset), 5, 0)
pred = sa.cross_val_predictions([r["premise"] for r in subset], labels, folds, sa.NaiveBayes)
rows_of = {}
for i, premise in enumerate(groups):
rows_of.setdefault(premise, []).append(i)
tally = {"fewer": [0, 0], "equal": [0, 0], "more": [0, 0]} # [test rows, right answers]
for i, answer in enumerate(pred):
seen = Counter(labels[j] for j in rows_of[groups[i]] if folds[j] != folds[i])
best_other = max([n for label, n in seen.items() if label != labels[i]], default=0)
kind = "fewer" if seen[labels[i]] < best_other else "equal" if seen[labels[i]] == best_other else "more"
tally[kind][0] += 1
tally[kind][1] += answer == labels[i]
PHRASE = {"fewer": "less often than", "equal": "as often as", "more": "more often than"}
for kind, (rows_n, right) in tally.items():
print(f" own label seen {PHRASE[kind]:15} its best rival in the premise's training rows: {rows_n:6,} test rows, {right / rows_n:5.1%} right")
print("\n=== words most tied to each label (PMI with add-100 smoothing), hypotheses in train")
top = sa.pmi_words([r["hypothesis"] for r in train], [r["label"] for r in train], per_class=8)
for label, rows in top.items():
print(f" {label:14}" + ", ".join(f"{word} ({share:.1%})" for _, word, share in rows))
python step05_snli.py
train 549,367 rows from 150,736 premises; test 9,824 rows from 3,323 premises
majority label share on test: 0.3428
=== hypothesis only: fit on train, score on test
unigrams accuracy 0.6313 95% CI [0.6225, 0.6410] (1 s)
unigrams+bigrams accuracy 0.6526 95% CI [0.6437, 0.6613] (3 s)
=== random folds against premise folds: 5 folds, 17,000 premises drawn from train
61,324 rows, majority label share 0.3341
hypothesis only random folds accuracy 0.5908 95% CI [0.5870, 0.5949]
hypothesis only premise folds accuracy 0.5992 95% CI [0.5954, 0.6033]
premise only random folds accuracy 0.1438 95% CI [0.1410, 0.1469]
premise only premise folds accuracy 0.3332 95% CI [0.3327, 0.3337]
=== why premise-only falls below chance with random folds
own label seen less often than its best rival in the premise's training rows: 56,077 test rows, 11.8% right
own label seen as often as its best rival in the premise's training rows: 4,744 test rows, 38.2% right
own label seen more often than its best rival in the premise's training rows: 503 test rows, 73.2% right
=== words most tied to each label (PMI with add-100 smoothing), hypotheses in train
contradiction nobody (1.3%), sleeping (3.2%), no (1.5%), tv (0.8%), cat (1.3%), cats (0.4%), alone (1.1%), asleep (1.0%)
entailment outdoors (2.8%), least (0.2%), instrument (0.5%), outside (8.0%), animal (0.7%), something (1.4%), near (2.5%), moving (0.4%)
neutral tall (1.0%), first (0.6%), competition (0.7%), winning (0.3%), sad (0.6%), owner (0.5%), favorite (0.4%), vacation (0.3%)
Reading the SNLI results
The shortcut is real. On the test set, always answering the most common label scores 0.3428. A unigram naive Bayes that sees only the hypothesis scores 0.6313 (95 percent interval [0.6225, 0.6410], resampling whole premises), and adding bigrams lifts it to 0.6526 ([0.6437, 0.6613]). That sits right on Tsuchiya’s 63 percent and below the 67 and 69 percent that the dataset card credits to other classifiers, which is what you expect from a model made of word counts.
Premise folds barely change the hypothesis-only score. Random folds give 0.5908 and premise folds give 0.5992. The group-aware number is slightly higher, by 0.8 points. For this data the clue lives in the vocabulary of the hypotheses and transfers to unseen premises, as in toy_cue. Nothing in these tables says that is always so; it is why you measure.
The premise-only run is the surprise. A model that sees only the premise should be at chance, because the protocol asks the workers for one hypothesis per label for each premise, so the premise says nothing about the label. With premise folds it is: 0.3332, the 0.3341 majority share. With random folds it scores 0.1438, less than half of chance. Here is why, measured in the third block of the output. For every test row I counted how often its premise sits in the training folds with the row’s own label and with its most frequent rival label. For 56,077 of the 61,324 rows (91 percent) the rival label leads, and on those rows the model is right 11.8 percent of the time. Where the two tie it is right 38.2 percent of the time (4,744 rows), and on the 503 rows where the row’s own label leads it is right 73.2 percent of the time. The classifier is memorizing premises: it answers with the label a premise has most often in training. The protocol asks for one hypothesis per label for each premise, so a premise normally has the same number of rows for every label, and the test row has just been taken out of the training folds. Its own label is therefore almost always the one with fewer training rows, and the memory points the wrong way. A score far below chance is the signature of group leakage in a balanced design. Treat it as a bug report on your split.
The words match the literature. The paper notes that “Negation words such as nobody, no, never and nothing are strong indicators of contradiction”, that modifiers (tall, sad, popular) and superlatives (first, favorite, most) go with the neutral class, and that the original annotation example primed workers to replace specifics with words like animal and outdoors. Our PMI lists show the same families: nobody, sleeping, no, tv, cat for contradiction; outdoors, outside, animal, instrument for entailment; tall, first, competition, sad, favorite for neutral. The percentages in parentheses are small (the most frequent word in that list, “outside”, appears in 8.0 percent of entailment hypotheses), which agrees with the paper’s observation that “even the most discriminative words are not very frequent, indicating that the annotation artifacts are diverse”. No single clue explains the 63 percent; many small ones add up.
Step 7: Do not clean away the signal
Many text pipelines drop short tokens or “stop words” (very common words such as “the” and “is”) before classification. For an audit that is a trap: the cleaning that helps a classifier ignore filler also removes the clues you are hunting. Run the same SNLI test with three tokenizers, using scikit-learn’s published English stop-word list, which the script downloads and parses:
# step06_tokenizer_traps.py
import ast
import json
import urllib.request
from pathlib import Path
import shortcut_audit as sa
DATA = Path(__file__).parent / "data"
URL = "https://raw.githubusercontent.com/scikit-learn/scikit-learn/main/sklearn/feature_extraction/_stop_words.py"
request = urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0"})
source = urllib.request.urlopen(request, timeout=30).read().decode("utf-8")
STOP = set()
for node in ast.parse(source).body:
if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") == "ENGLISH_STOP_WORDS":
STOP = set(ast.literal_eval(node.value.args[0]))
NEGATIONS = {"no", "nobody", "not", "never", "none", "nothing", "nor", "without", "cannot"}
print(f"scikit-learn English stop-word list: {len(STOP)} words")
print("negation words it contains:", ", ".join(sorted(NEGATIONS & STOP)))
def load(split):
return [json.loads(line) for line in (DATA / f"snli_{split}.jsonl").read_text(encoding="utf-8").splitlines()]
train, test = load("train"), load("test")
gold = [r["label"] for r in test]
original = sa.tokenize
def run(label, tokenizer):
sa.tokenize = tokenizer
try:
model = sa.NaiveBayes().fit([r["hypothesis"] for r in train], [r["label"] for r in train])
ok = sa.correctness([model.predict(r["hypothesis"]) for r in test], gold)
finally:
sa.tokenize = original
print(f" {label:42}{sum(ok) / len(ok):.4f}")
print("\nhypothesis-only accuracy on the SNLI test set, unigram naive Bayes:")
run("default tokenizer", original)
run("drop tokens shorter than 3 letters", lambda text: [w for w in original(text) if len(w) > 2])
run("drop every stop word", lambda text: [w for w in original(text) if w not in STOP])
run("drop stop words but keep the negations", lambda text: [w for w in original(text) if w not in STOP or w in NEGATIONS])
python step06_tokenizer_traps.py
scikit-learn English stop-word list: 318 words
negation words it contains: cannot, never, no, nobody, none, nor, not, nothing, without
hypothesis-only accuracy on the SNLI test set, unigram naive Bayes:
default tokenizer 0.6313
drop tokens shorter than 3 letters 0.6284
drop every stop word 0.6081
drop stop words but keep the negations 0.6164
The list holds 318 words, and it contains all nine negation words the script looks for (“no”, “not”, “nobody”, “never”, “none” and “nothing” among them). Dropping every stop word costs 2.3 points (0.6313 down to 0.6081), so the audit would have under-reported the shortcut. Keeping the negations recovers 0.8 of those points (0.6164); the rest of the loss comes from other function words that also tilt toward a label. Dropping tokens shorter than three letters costs only 0.3 points here, because longer negations survive, but it silently deletes “no”, so the test suite in Step 9 pins that behavior anyway.
Step 8: Turn the pieces into one command with a verdict
Now package it. audit runs both fold schemes with the matching bootstrap (clusters when groups exist, rows otherwise), compares the 95 percent lower bound of each accuracy with a bar of the majority share plus a margin (0.05 by default), and returns one of three verdicts:
- shortcut: the lower bound with group folds clears the bar. The baseline beats the label frequencies on groups it never saw.
- group-memorization: only the random-fold lower bound clears the bar.
- clean: neither does.
The margin is a policy choice, not a statistical law: it is how much better than the majority baseline you tolerate before a person has to look. Using the lower bound keeps a noisy small eval from raising false alarms.
# shortcut_audit.py (continued)
def audit(rows, folds=5, ngrams=1, margin=0.05, reps=1000, seed=0):
texts = [r["text"] for r in rows]
labels = [r["label"] for r in rows]
groups = [r.get("group") for r in rows]
has_groups = all(g is not None for g in groups)
if len(set(labels)) < 2:
raise ValueError("need at least two different labels")
if len(rows) < 2 * folds:
raise ValueError(f"need at least {2 * folds} rows for {folds} folds")
def make():
return NaiveBayes(ngrams=ngrams)
majority = majority_share(labels)
bar = majority + margin
result = {"rows": len(rows), "classes": len(set(labels)), "groups": len(set(groups)) if has_groups else None,
"folds": folds, "ngrams": ngrams, "margin": margin, "majority": round(majority, 4), "bar": round(bar, 4)}
def score(fold_ids):
ok = correctness(cross_val_predictions(texts, labels, fold_ids, make), labels)
lo, hi = bootstrap_ci(ok, groups if has_groups else None, reps, seed)
return {"accuracy": round(sum(ok) / len(ok), 4), "ci": [round(lo, 4), round(hi, 4)]}
result["random"] = score(random_folds(len(rows), folds, seed))
result["grouped"] = score(group_folds(groups, folds, seed)) if has_groups else None
if result["grouped"] is not None and result["grouped"]["ci"][0] > bar:
result["verdict"] = "shortcut"
elif result["random"]["ci"][0] > bar:
result["verdict"] = "group-memorization" if has_groups else "shortcut"
else:
result["verdict"] = "clean"
return result
The rest of the module formats the report, reads JSON lines with clear error messages, and defines the command-line entry point. The exit code is 0 for clean, 1 when a shortcut or group memorization is found, and 2 when the input cannot be read, so the command can gate a build:
# shortcut_audit.py (continued)
EXPLAIN = {
"clean": "the baseline cannot beat the label frequencies by the margin",
"shortcut": "the baseline sees only part of the input and still clears the bar on groups it has never seen",
"group-memorization": "the baseline clears the bar only when a group appears on both sides of a split",
}
def format_report(r):
kind = "unigrams" if r["ngrams"] == 1 else "unigrams and bigrams"
groups = f"{r['groups']:,}" if r["groups"] else "none"
lines = [f"rows {r['rows']:,} | labels {r['classes']} | groups {groups} | naive Bayes on {kind}, {r['folds']} folds",
f"majority label share {r['majority']:.4f}",
f"random folds accuracy {r['random']['accuracy']:.4f} 95% CI [{r['random']['ci'][0]:.4f}, {r['random']['ci'][1]:.4f}]"]
if r["grouped"]:
lines.append(f"group folds accuracy {r['grouped']['accuracy']:.4f} 95% CI [{r['grouped']['ci'][0]:.4f}, {r['grouped']['ci'][1]:.4f}]")
lines.append(f"bar (majority + {r['margin']}) {r['bar']:.4f}")
lines.append(f"verdict: {r['verdict']} ({EXPLAIN[r['verdict']]})")
return "\n".join(lines)
def load_rows(path, text_field, label_field, group_field):
rows = []
with open(path, encoding="utf-8") as handle:
for number, line in enumerate(handle, 1):
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"line {number} is not valid JSON ({exc.msg})") from None
for field in (text_field, label_field):
if field not in record:
raise ValueError(f"line {number} has no field {field!r}")
row = {"text": str(record[text_field]), "label": record[label_field]}
if group_field in record:
row["group"] = record[group_field]
rows.append(row)
return rows
def main(argv=None):
parser = argparse.ArgumentParser(description="Partial-input shortcut audit for an evaluation set.")
parser.add_argument("data")
parser.add_argument("--text-field", default="text")
parser.add_argument("--label-field", default="label")
parser.add_argument("--group-field", default="group")
parser.add_argument("--folds", type=int, default=5)
parser.add_argument("--ngrams", type=int, default=1, choices=(1, 2))
parser.add_argument("--margin", type=float, default=0.05)
parser.add_argument("--reps", type=int, default=1000)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
try:
rows = load_rows(args.data, args.text_field, args.label_field, args.group_field)
result = audit(rows, args.folds, args.ngrams, args.margin, args.reps, args.seed)
except (OSError, ValueError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
print(json.dumps(result, indent=1) if args.json else format_report(result))
return 0 if result["verdict"] == "clean" else 1
if __name__ == "__main__":
sys.exit(main())
Run it on the three toys with bigrams, then on the SNLI validation split twice: once showing only the hypothesis and once showing only the premise. In both SNLI runs the group is the premise:
# step07_cli.py
import subprocess
import sys
def run(*args):
print("$ python shortcut_audit.py " + " ".join(args))
done = subprocess.run([sys.executable, "shortcut_audit.py", *args], capture_output=True, text=True, encoding="utf-8")
print(done.stdout.rstrip())
print(f"exit code {done.returncode}\n")
for name in ("toy_clean", "toy_cue", "toy_template"):
run(f"data/{name}.jsonl", "--ngrams", "2")
run("data/snli_validation.jsonl", "--text-field", "hypothesis", "--group-field", "premise")
run("data/snli_validation.jsonl", "--text-field", "premise", "--group-field", "premise")
python step07_cli.py
$ python shortcut_audit.py data/toy_clean.jsonl --ngrams 2
rows 2,700 | labels 3 | groups 45 | naive Bayes on unigrams and bigrams, 5 folds
majority label share 0.3441
random folds accuracy 0.3474 95% CI [0.3267, 0.3685]
group folds accuracy 0.3259 95% CI [0.3063, 0.3426]
bar (majority + 0.05) 0.3941
verdict: clean (the baseline cannot beat the label frequencies by the margin)
exit code 0
$ python shortcut_audit.py data/toy_cue.jsonl --ngrams 2
rows 2,700 | labels 3 | groups 45 | naive Bayes on unigrams and bigrams, 5 folds
majority label share 0.3452
random folds accuracy 0.7367 95% CI [0.7200, 0.7533]
group folds accuracy 0.7133 95% CI [0.6970, 0.7300]
bar (majority + 0.05) 0.3952
verdict: shortcut (the baseline sees only part of the input and still clears the bar on groups it has never seen)
exit code 1
$ python shortcut_audit.py data/toy_template.jsonl --ngrams 2
rows 2,700 | labels 3 | groups 45 | naive Bayes on unigrams and bigrams, 5 folds
majority label share 0.3333
random folds accuracy 1.0000 95% CI [1.0000, 1.0000]
group folds accuracy 0.2563 95% CI [0.1426, 0.3856]
bar (majority + 0.05) 0.3833
verdict: group-memorization (the baseline clears the bar only when a group appears on both sides of a split)
exit code 1
$ python shortcut_audit.py data/snli_validation.jsonl --text-field hypothesis --group-field premise
rows 9,842 | labels 3 | groups 3,319 | naive Bayes on unigrams, 5 folds
majority label share 0.3382
random folds accuracy 0.5501 95% CI [0.5412, 0.5600]
group folds accuracy 0.5692 95% CI [0.5594, 0.5788]
bar (majority + 0.05) 0.3882
verdict: shortcut (the baseline sees only part of the input and still clears the bar on groups it has never seen)
exit code 1
$ python shortcut_audit.py data/snli_validation.jsonl --text-field premise --group-field premise
rows 9,842 | labels 3 | groups 3,319 | naive Bayes on unigrams, 5 folds
majority label share 0.3382
random folds accuracy 0.1276 95% CI [0.1199, 0.1350]
group folds accuracy 0.3345 95% CI [0.3301, 0.3388]
bar (majority + 0.05) 0.3882
verdict: clean (the baseline cannot beat the label frequencies by the margin)
exit code 0
Check it worked
The exit codes are the proof. toy_clean exits 0, toy_cue exits 1 with the verdict “shortcut”, and toy_template exits 1 with “group-memorization” (its group-fold lower bound of 0.1426 sits under the 0.3833 bar, while its random-fold lower bound is 1.0000). On SNLI validation the hypothesis-only run is flagged as a shortcut (group folds 0.5692, lower bound 0.5594) and the premise-only run is clean, even though its random-fold score of 0.1276 is far from chance. The verdict logic only looks for scores that are too high; the wildly low number is your cue to look at the split.
To audit your own eval, write one JSON object per line with the part of the input you want to expose, the expected label and, if rows come in clusters, a group field. A multiple-choice benchmark can be audited by exposing only the answer options (the label is the correct letter), then again with only the question. Any run that exits 1 deserves a look. Length and position tricks need their own small baselines. In a build, a single line does it:
python shortcut_audit.py my_eval.jsonl --text-field question --label-field answer --group-field template --ngrams 2
Step 9: Test the auditor, then try to break the tests
An audit tool that is wrong in one direction will either miss shortcuts or invent them, so it deserves tests, and the tests deserve tests. The 28 tests below fall into three groups. The first group pins the tokenizer and the classifier: negations survive, unseen words are ignored, scores stay finite, and the prior decides when the text says nothing.
# test_shortcut_audit.py
import json
import math
import pathlib
import subprocess
import sys
import pytest
import make_toys
import shortcut_audit as sa
HERE = pathlib.Path(__file__).parent
def small_toy(kind):
return make_toys.make(kind, templates=30, per_template=30)
def bigram_model():
return sa.NaiveBayes(ngrams=2)
def test_tokenizer_keeps_negations():
assert sa.tokenize("Nobody is NOT here, no way") == ["nobody", "is", "not", "here", "no", "way"]
def test_tokenizer_keeps_apostrophes():
assert sa.tokenize("They don't sleep") == ["they", "don't", "sleep"]
def test_bigrams_follow_the_unigrams():
assert sa.featurize("a b c", 2) == ["a", "b", "c", "a b", "b c"]
def test_naive_bayes_learns_a_word_rule():
model = sa.NaiveBayes().fit(["red apple", "red cherry", "blue sky", "blue sea"], ["warm", "warm", "cold", "cold"])
assert model.predict("red") == "warm"
assert model.predict("blue") == "cold"
def test_unseen_words_are_ignored():
model = sa.NaiveBayes().fit(["red apple", "blue sky"], ["warm", "cold"])
assert model.predict("zzz qqq red") == "warm"
def test_unseen_words_do_not_change_the_scores():
model = sa.NaiveBayes().fit(["red apple", "red cherry", "red plum", "blue sky"], ["warm", "warm", "warm", "cold"])
assert model.scores("red") == model.scores("red zzz qqq")
def test_smoothing_keeps_scores_finite_for_a_word_seen_in_one_class():
model = sa.NaiveBayes().fit(["only warm", "cold cold"], ["warm", "cold"])
assert all(math.isfinite(v) for v in model.scores("only cold").values())
def test_the_prior_decides_when_the_text_says_nothing():
model = sa.NaiveBayes().fit(["same words"] * 10, ["z"] * 7 + ["a"] * 3)
assert model.predict("same words") == "z"
def test_majority_share():
assert sa.majority_share(["a", "a", "b", "c"]) == 0.5
The second group covers the machinery around the model: folds are balanced and shuffled, group folds never split a group, a spy model checks that cross-validation never trains on a test row, the bootstrap is reproducible and its cluster version is much wider when whole groups succeed or fail together, and shuffling labels destroys a template signal.
# test_shortcut_audit.py (continued)
def test_random_folds_cover_every_row_and_balance():
folds = sa.random_folds(103, 5, seed=1)
sizes = [folds.count(f) for f in range(5)]
assert sorted(set(folds)) == [0, 1, 2, 3, 4] and max(sizes) - min(sizes) <= 1
def test_random_folds_are_shuffled():
assert sa.random_folds(100, 5, seed=1) != [i % 5 for i in range(100)]
def test_group_folds_never_split_a_group():
groups = [f"g{i % 17}" for i in range(400)]
folds = sa.group_folds(groups, 5, seed=3)
seen = {}
for g, f in zip(groups, folds):
assert seen.setdefault(g, f) == f
def test_group_folds_are_balanced():
groups = [f"g{i % 40}" for i in range(2000)]
folds = sa.group_folds(groups, 5, seed=3)
assert [folds.count(f) for f in range(5)] == [400] * 5
def test_group_folds_refuse_too_few_groups():
with pytest.raises(ValueError, match="at least 5 groups"):
sa.group_folds(["a", "b", "c"] * 10, 5)
class Spy:
def fit(self, texts, labels):
self.train = set(texts)
return self
def predict(self, text):
assert text not in self.train, "a test row was in the training fold"
return 0
def test_cross_validation_never_trains_on_a_test_row():
texts = [f"row{i}" for i in range(50)]
sa.cross_val_predictions(texts, [0] * 50, sa.random_folds(50, 5), Spy)
def test_bootstrap_is_deterministic_for_a_seed():
ok = [1, 0, 1, 1, 0, 1] * 20
assert sa.bootstrap_ci(ok, reps=200, seed=4) == sa.bootstrap_ci(ok, reps=200, seed=4)
def test_bootstrap_interval_brackets_the_estimate():
lo, hi = sa.bootstrap_ci([1] * 70 + [0] * 30, reps=500, seed=1)
assert lo < 0.70 < hi
def test_cluster_interval_is_wider_when_whole_groups_succeed_or_fail():
ok, groups = [], []
for g in range(20):
ok += [g % 2] * 50
groups += [g] * 50
lo_r, hi_r = sa.bootstrap_ci(ok, reps=500, seed=1)
lo_c, hi_c = sa.bootstrap_ci(ok, groups, reps=500, seed=1)
assert (hi_c - lo_c) > 3 * (hi_r - lo_r)
def test_permutation_destroys_a_template_signal():
rows = small_toy("template")
texts, labels = [r["text"] for r in rows], [r["label"] for r in rows]
folds = sa.random_folds(len(rows), 5)
real = sa.accuracy(sa.cross_val_predictions(texts, labels, folds, bigram_model), labels)
shuffled = sa.permuted_accuracies(texts, labels, folds, bigram_model, reps=3)
assert real > 0.9 and max(shuffled) < 0.5
The third group checks the verdicts on small versions of the toy evals and drives the command-line tool as a subprocess, including bad input:
# test_shortcut_audit.py (continued)
@pytest.mark.parametrize("kind, verdict", [("clean", "clean"), ("cue", "shortcut"), ("template", "group-memorization")])
def test_audit_verdicts_on_the_toy_sets(kind, verdict):
result = sa.audit(small_toy(kind), ngrams=2, reps=200)
assert result["verdict"] == verdict, result
def test_audit_without_groups_has_no_grouped_result():
rows = [{"text": r["text"], "label": r["label"]} for r in small_toy("cue")]
result = sa.audit(rows, ngrams=2, reps=100)
assert result["grouped"] is None and result["verdict"] == "shortcut"
def test_audit_needs_two_labels():
with pytest.raises(ValueError, match="two different labels"):
sa.audit([{"text": f"t{i}", "label": "x"} for i in range(30)])
def run_cli(*args):
return subprocess.run([sys.executable, str(HERE / "shortcut_audit.py"), *args],
capture_output=True, text=True, encoding="utf-8")
def write_jsonl(path, rows):
path.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
def test_cli_exit_codes(tmp_path):
clean, cue = tmp_path / "clean.jsonl", tmp_path / "cue.jsonl"
write_jsonl(clean, small_toy("clean"))
write_jsonl(cue, small_toy("cue"))
assert run_cli(str(clean), "--ngrams", "2", "--reps", "100").returncode == 0
flagged = run_cli(str(cue), "--ngrams", "2", "--reps", "100")
assert flagged.returncode == 1 and "verdict: shortcut" in flagged.stdout
missing = run_cli(str(tmp_path / "nope.jsonl"))
assert missing.returncode == 2 and "error" in missing.stderr
def test_cli_rejects_a_line_that_is_not_json(tmp_path):
path = tmp_path / "broken.jsonl"
path.write_text('{"text": "a", "label": "x"}\nnot json\n', encoding="utf-8")
result = run_cli(str(path))
assert result.returncode == 2 and "line 2" in result.stderr
def test_cli_reports_a_missing_field(tmp_path):
path = tmp_path / "nolabel.jsonl"
write_jsonl(path, [{"text": "a"}] * 30)
result = run_cli(str(path))
assert result.returncode == 2 and "label" in result.stderr
def test_cli_json_output_has_the_documented_keys(tmp_path):
path = tmp_path / "toy.jsonl"
write_jsonl(path, small_toy("clean"))
result = run_cli(str(path), "--json", "--ngrams", "2", "--reps", "100")
assert {"rows", "majority", "random", "grouped", "verdict"} <= set(json.loads(result.stdout))
python -m pytest -q
............................ [100%]
28 passed in 0.85s
Passing tests only prove the code agrees with the tests. To check that they would notice a mistake, mutants.py plants 13 bugs one at a time (smoothing off, prior dropped, test rows leaking into training, a bootstrap that ignores its seed, an exit code that is always 0 and so on) and expects the suite to fail each time:
# mutants.py
"""Plant one bug at a time in shortcut_audit.py and check that the test suite notices."""
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
HERE = pathlib.Path(__file__).parent
SOURCE = (HERE / "shortcut_audit.py").read_text(encoding="utf-8")
MUTANTS = [
("smoothing switched off", "self.alpha = alpha", "self.alpha = 0.0"),
("class prior dropped", "self.prior = [math.log(self.class_count[c] / len(labels)) for c in self.classes]",
"self.prior = [0.0 for c in self.classes]"),
("unseen words are scored", "if feature in self.vocab:", "if True:"),
("tokenizer drops short words", "return TOKEN.findall(text.lower())",
"return [w for w in TOKEN.findall(text.lower()) if len(w) > 2]"),
("random folds not shuffled", "random.Random(seed).shuffle(order)", "pass"),
("group folds ignore the groups", "return [fold_of[g] for g in groups]", "return random_folds(len(groups), k, seed)"),
("training fold includes the test rows", "train = [i for i, g in enumerate(folds) if g != f]", "train = list(range(len(folds)))"),
("cluster bootstrap resamples rows", "if groups is None:", "if True:"),
("bootstrap ignores its seed", " rng = random.Random(seed)\n stats = []", " rng = random.Random()\n stats = []"),
("permutation does not shuffle", "rng.shuffle(shuffled)", "pass"),
("bar ignores the majority share", "bar = majority + margin", "bar = margin"),
("group memorization never reported", 'result["verdict"] = "group-memorization" if has_groups else "shortcut"',
'result["verdict"] = "shortcut"'),
("exit code always 0", 'return 0 if result["verdict"] == "clean" else 1', "return 0"),
]
def run_suite(text):
with tempfile.TemporaryDirectory() as tmp:
tmp = pathlib.Path(tmp)
for name in ("make_toys.py", "test_shortcut_audit.py"):
shutil.copy(HERE / name, tmp / name)
(tmp / "shortcut_audit.py").write_text(text, encoding="utf-8", newline="\n")
done = subprocess.run([sys.executable, "-X", "utf8", "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider"],
cwd=tmp, capture_output=True, text=True, encoding="utf-8")
failed = re.findall(r"^FAILED (\S+)", done.stdout, re.M)
return done.returncode, failed[0].split("::")[-1] if failed else ""
code, _ = run_suite(SOURCE)
print(f"unmutated code: {'all tests pass' if code == 0 else 'TESTS FAIL'}")
caught = 0
for label, old, new in MUTANTS:
assert SOURCE.count(old) == 1, f"{label}: pattern occurs {SOURCE.count(old)} times"
code, test = run_suite(SOURCE.replace(old, new))
caught += code != 0
print(f" {'caught ' if code != 0 else 'SURVIVED'} {label:40} {test}")
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
python mutants.py
unmutated code: all tests pass
caught smoothing switched off test_naive_bayes_learns_a_word_rule
caught class prior dropped test_the_prior_decides_when_the_text_says_nothing
caught unseen words are scored test_unseen_words_do_not_change_the_scores
caught tokenizer drops short words test_tokenizer_keeps_negations
caught random folds not shuffled test_random_folds_are_shuffled
caught group folds ignore the groups test_group_folds_never_split_a_group
caught training fold includes the test rows test_cross_validation_never_trains_on_a_test_row
caught cluster bootstrap resamples rows test_cluster_interval_is_wider_when_whole_groups_succeed_or_fail
caught bootstrap ignores its seed test_bootstrap_is_deterministic_for_a_seed
caught permutation does not shuffle test_permutation_destroys_a_template_signal
caught bar ignores the majority share test_audit_verdicts_on_the_toy_sets[clean-clean]
caught group memorization never reported test_audit_verdicts_on_the_toy_sets[template-group-memorization]
caught exit code always 0 test_cli_exit_codes
13 of 13 planted bugs caught
The bug that survived the first run
My first version of test_the_prior_decides_when_the_text_says_nothing fed ten identical texts with seven labeled “a” and three labeled “b”, and expected “a”. The “class prior dropped” mutant survived: with the prior gone, the two scores tied exactly, and Python’s max picks the first of equal values, which was the alphabetically first class, “a”, the same class the test expected. The test passed by accident. Renaming the majority class so that it sorts second ("z" against "a") made the tie-break wrong and the mutant fail. When a mutant survives, look for a test whose expected answer is also the default.
What to do when the audit flags your eval
- Report the baseline next to your model scores. A model at 0.66 on SNLI looks different when a word counter gets 0.65 without the premise. Put the partial-input score in the same table.
- Check which clue it is. Print the top words or phrases (
pmi_words) and read them. Negation words in contradiction items point to a writing habit you can fix in the next batch; a cue sentence in one template points to one template to rewrite. - Split by group when you build train, dev and test sets. If group memorization is what you found, any model fine-tuned on one part of your benchmark can recognize templates in another part. Keep every group in one split.
- Rewrite or drop the items that leak, then audit again. Removing the cue words from the data and re-running the command tells you whether a second clue was hiding behind the first.
- Do not remove words from the audit input to make the result look better. That is Step 7 in reverse: the audit gets weaker and the dataset does not get better.
Common mistakes and how to notice them
- Random folds on grouped rows. Symptom: a near-perfect score on partial input (
toy_template) or a score far below chance (SNLI premise only). Fix: pass a group field and read both numbers. - Row-level intervals on clustered data. Symptom: an interval a few thousandths wide on a dataset with a few dozen templates. Fix: resample groups.
- Comparing with 1/k instead of the majority share. On a skewed eval the majority baseline sits well above chance. The bar in this tool starts from the actual majority share.
- Forgetting unlabeled rows. SNLI’s -1 labels would become a fourth class and shift every baseline.
- Treating “clean” as proof. A naive Bayes on word counts finds only clues that show up as word frequencies. Answer position, text length and formatting are separate partial views that you should test on their own.
- Auditing once. The result belongs to one dataset version, one tokenizer and one seed. Re-run it whenever the data changes, and report the seed.
Confirm the whole thing end to end
python make_toys.pyprints three lines of 2700 rows, andpython snli_to_jsonl.pyreports 549,367 training rows kept and 785 dropped.python step07_cli.pyexits 0 fortoy_clean, 1 fortoy_cueandtoy_template, 1 for SNLI hypothesis only and 0 for SNLI premise only.python -m pytest -qshows 28 passed, andpython mutants.pyends with “13 of 13 planted bugs caught”.- Your SNLI numbers should match 0.6313 (unigrams) and 0.6526 (bigrams) to the fourth digit if the files are unchanged, because naive Bayes has no randomness. The toy numbers and every interval should match too, because every random draw is seeded.
Where to go next
- Add more partial views. For multiple-choice evals, test the options alone, the question alone, option length and the position of the longest option. For agent evals, test the task description alone against the pass or fail label.
- Add a stronger model. If a hand-written naive Bayes is flagged, a fine-tuned transformer is likely to be flagged more strongly. If it is not flagged, try a stronger model before you relax.
- Combine it with the sibling questions. This audit asks whether the benchmark is solvable without the task; the pass-rate gate tutorial asks how many runs you need to see a regression, and the Cohen’s kappa tutorial asks whether your judge agrees with people. For a different kind of leak, see the target-leakage linter, which traces features that secretly contain the target.
- See it on a published benchmark. In our audit of Google’s Fuse social-reasoning benchmark, a per-template word counter reads 98.6 percent of the held-out neutral messages correctly: the template-memorization pattern from
toy_templatein the wild. The XYBench audit and the ShellBench audit cover other ways evals go wrong. - Test your tests harder. The mutation approach here follows our mutation-testing tutorial.
Sources
- Gururangan et al., Annotation Artifacts in Natural Language Inference Data (NAACL 2018): the 67 percent SNLI hypothesis-only result, the PMI method and the word families.
- Poliak et al., Hypothesis Only Baselines in Natural Language Inference (2018): hypothesis-only models “significantly outperform a majority class baseline” on several NLI datasets.
- Hugging Face SNLI dataset card: split sizes, the -1 label, the CC BY-SA 4.0 license and the 69, 67 and 63 percent figures.
- Bowman et al., A large annotated corpus for learning natural language inference (EMNLP 2015): the SNLI corpus.
- Python documentation, random:
choices,shuffleand the bootstrap example. - scikit-learn documentation, Naive Bayes: multinomial naive Bayes and smoothing.








No Comment! Be the first one.