Sub topic 11
Split the Data and Avoid Leakage
This chapter assumes you can read basic Python and JSONL, have called an LLM API, and know what a proportion and a sample size are. It also assumes you have a tagged dataset like the one built in earlier chapters, where each case has a stable id, an input, a reference, tags, and a source.
Why a single pile of cases is not enough
Suppose you have 300 cases. You run the app, see 71% accuracy, change the prompt, and see 78%. You keep changing the prompt. After twenty rounds you report 91%. Is the app really that good?
Probably not. Each prompt change was chosen because it fixed cases you could see. Over many rounds, the prompt becomes tuned to those specific cases. The score measures how well you fit the dataset, not how well the app handles new inputs. This is overfitting to the eval set.
The remedy is to split the data into two parts:
- Dev set: cases you look at, read failures from, and tune against.
- Test set: cases you do not inspect while iterating. You run them rarely, to check that gains on dev carry over.
A large gap between dev and test scores tells you that you have overfit. If you had only one set, you could not see it.
What leakage is
Leakage is any path by which information about test cases reaches the process that builds or tunes the app. It makes the test score look better than real performance. Common paths are listed below.
| Leak path | Example | Effect |
|---|---|---|
| Near-duplicate cases | "Can I return a laptop after 45 days?" in dev, "Can I send back a laptop after 45 days?" in test | Fixing the dev case also fixes the test case |
| Test cases in the prompt | A failing test case pasted into a few-shot example | The app has seen the answer |
| Test failures read and acted on | You read the test failures and add a rule for them | Test becomes a second dev set |
| Synthetic cases from a shared seed | A generator is shown a test case and asked for "more like this" | Variants of test cases land in dev |
| Model training exposure | A public benchmark that the model saw during training | Scores reflect memory, not skill |
| Retrieval corpus overlap | The answer document was written from the test reference | A RAG app finds the answer verbatim |
Most of these are process errors, not code errors. The code in this chapter prevents the mechanical ones. The rest need discipline.
Split deterministically by case id
A common first attempt is random.shuffle(cases) followed by slicing. This works once. When you add 50 new cases next month and shuffle again, many cases change sides. A case that you tuned against is now in the test set, and the test set is contaminated.
A better approach is to derive the split from the case id. The same id always gives the same split, no matter when you run it or how big the dataset is.
import hashlib
def split_for(case_id, test_percent=20):
digest = hashlib.sha256(case_id.encode("utf-8")).hexdigest()
return "test" if int(digest, 16) % 100 < test_percent else "dev"Here is how it behaves:
- The hash of
"refund-001"is fixed, sosplit_for("refund-001")returns the same value on every run. - Adding new cases never moves old ones.
- The split is approximately 20% test. With few cases, the actual share can be off by several points.
- Python's built-in
hash()is not suitable. For strings it is randomized per process, so the split would change between runs. Usehashlib.
This method depends on stable ids. If you rename an id, the case may change sides. Treat ids as permanent, as the schema chapter advised.
Split by group, not only by case
Id hashing treats each case as independent. Often they are not. Consider these groups:
- Several questions written about the same support article.
- A base question and its paraphrases.
- Multiple turns from one conversation.
- Cases generated from one seed document.
If members of one group fall on both sides, the dev case teaches the app something about the test case. The fix is to hash a group key instead of the case id.
import hashlib
def split_for_group(case, test_percent=20):
key = case.get("group") or case["id"]
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()
return "test" if int(digest, 16) % 100 < test_percent else "dev"This assumes you added an optional group field to the schema. Cases without a group fall back to their own id. Choose the group key at creation time. Adding it later means some cases will move sides, so you must re-audit the test set.
Stratify so small slices appear on both sides
Hashing is random, so a slice with 12 cases can end up with 0 or 1 test cases. Then you cannot report a test score for that slice. Check the counts after splitting.
from collections import Counter
def split_report(cases, splitter):
counts = Counter()
for c in cases:
side = splitter(c)
for tag in c["tags"]:
counts[(tag, side)] += 1
tags = sorted({tag for tag, _ in counts})
for tag in tags:
print(f"{tag:20s} dev={counts[(tag, 'dev')]:4d} test={counts[(tag, 'test')]:4d}")Run split_report(cases, split_for_group) after each dataset change. If a slice that matters has too few test cases, you have three options:
- Add more cases to that slice. This is the best fix.
- Accept that the slice has no reliable test score, and say so in the report.
- Assign specific cases to a side by hand, with an explicit
splitfield. This breaks automatic assignment, so record why.
Do not quietly reshuffle until the counts look good. That is a form of peeking.
Remove near-duplicates before splitting
Exact duplicate ids are easy to reject, as the loader in the earlier chapter does. Duplicate inputs with different ids are harder. Production logs often contain the same question many times with small variations in spelling or punctuation.
A cheap check is to normalize the text and compare.
import re
from collections import defaultdict
def normalize(text):
text = text.lower()
text = re.sub(r"[^a-z0-9\s]", "", text)
return re.sub(r"\s+", " ", text).strip()
def find_duplicate_inputs(cases):
seen = defaultdict(list)
for c in cases:
seen[normalize(c["input"])].append(c["id"])
return {k: ids for k, ids in seen.items() if len(ids) > 1}This catches case and punctuation differences only. It misses paraphrases such as "send back" versus "return". For those, compare embeddings of the inputs and flag pairs above a similarity threshold, then review the flagged pairs by hand. Pick the threshold by looking at real pairs from your data, not from a rule of thumb. Where you find a near-duplicate pair, either drop one case or give both the same group key so they land on the same side.
Check overlap between the dataset and the app
Leakage also happens inside the app, not only inside the dataset. Check these:
- Few-shot examples. Each example in the prompt should come from outside the test set. Ideally it also comes from outside the dev set, so that dev scores are not inflated by examples the app can copy.
- Fine-tuning data. If you fine-tune a model, exclude every eval case, and every near-duplicate, from the training file.
- Retrieval content. If the knowledge base was written or edited using eval references, the retriever finds the answer by construction. Evaluate on questions that were written independently of the documents where possible.
- Public benchmarks. A widely published dataset may have appeared in the model's training data. Your private cases from production logs are less likely to have. Treat scores on public sets as weaker evidence.
A simple guard is a test that fails your build if any test input appears in your prompt files.
def assert_no_test_in_prompt(test_cases, prompt_text):
prompt_norm = normalize(prompt_text)
leaked = [c["id"] for c in test_cases if normalize(c["input"]) in prompt_norm]
assert not leaked, f"test inputs found in prompt: {leaked}"This reuses normalize from the previous section. It catches pasted inputs only, not paraphrases.
Rules for using the test set
The split is only useful if you treat the test set differently.
- Do not read individual test failures while iterating. Look at the aggregate score only.
- Run the test set on a schedule or before a release, not after every edit.
- If you do read test failures and change the app because of them, those cases are now dev cases. Move them, bump the dataset version, and collect new test cases to replace them.
- Keep a log of how many times each test set version has been scored. Many looks at a fixed test set lets chance gains accumulate, much like the dev set problem.
- When the test set is spent, replace it. Fresh production cases are the best source.
Reading the dev and test gap
After a run, compare the two scores, along with the uncertainty from the dataset-size chapter.
| Observation | Likely meaning | Action |
|---|---|---|
| Dev and test close, both within noise | Healthy | Continue |
| Dev well above test, gap larger than the confidence interval | Overfitting to dev, or leakage into dev | Audit few-shot examples and duplicates, add dev diversity |
| Test above dev | Test set is easier, or smaller and noisy | Check slice mix and difficulty tags |
| Both high, but production complaints continue | Dataset misses real inputs | Return to sourcing and coverage |
A gap by itself is not proof of leakage. With 60 test cases, a three-point difference is well within noise. Use bootstrap_ci on each side before drawing a conclusion.
Putting it together
A minimal workflow looks like this:
- Load cases and reject duplicate ids.
- Report duplicate inputs and resolve them.
- Assign each case a side with
split_for_group. - Print
split_reportand check slice counts. - Tune against dev only.
- Run test at agreed checkpoints and compare with dev.
- Record the split rule and dataset version with every reported score.
Exercise
You add 40 new cases next month and want to re-split. A teammate suggests shuffling all cases with a fixed random seed and taking the last 20%. Why is this a poor choice, and what should you do instead?
Show answer
A seeded shuffle depends on the order and number of cases. Adding 40 cases changes the shuffle, so many old cases move sides. Dev cases you have tuned against can land in test, which contaminates it. Hash the permanent case id (or a group key) so each case keeps its side regardless of dataset size.
Exercise
Your dev set scores 88% and your test set scores 74%, with 50 test cases. What should you check before concluding that the app is overfit?
Show answer
Compute a bootstrap confidence interval for the test score. With 50 cases it is wide, perhaps ten points or more, so part of the gap may be noise. Then check slice and difficulty mix on both sides, and look for near-duplicates or few-shot examples that overlap with dev. If the gap still exceeds the interval, treat it as overfitting or leakage into dev.
Exercise
Why is hash(case_id) % 100 a bad way to assign splits in Python?
Show answer
Python randomizes string hashing per process (hash randomization), so the same id can get a different split on each run. Use a stable digest such as SHA-256 from hashlib.