Contents
Key concepts
Leakage taxonomy
Target leakage uses information only available after the prediction moment (an “account closed” flag in a churn model). Train–test contamination puts duplicates or the same entity on both sides of a split. Preprocessing leakage fits scalers, encoders or oversamplers on all data before splitting. Temporal leakage comes from random splits of time-ordered data; LLM benchmarks suffer contamination from web-scale pretraining. Red flags: AUC near 0.99, one dominant feature, or a jump far beyond a simple baseline.
Point-in-time correctness
Each training row must use feature values as they were available when the prediction would have been made: an as-of join on the time the value landed in the system, not the event time it describes. Use versioned or snapshot tables, and verify by recomputing features for past requests and comparing them with values logged at serving time.
Training–serving skew
Causes include duplicated transformation code in two languages, different sources or freshness, time zones and units, default values for missing data, and, for LLMs, a chat template or tool schema at training time that differs from serving. Prevent it with one transformation path and by logging the features actually served and training on those logs; detect it by comparing training and serving distributions and by shadow scoring before launch.
Data validation at boundaries
Check schema and types, null rates, ranges and allowed values, key uniqueness, row volume, freshness and distribution against a reference. Separate blocking checks from warnings, give every check an owner and an alert route, and quarantine bad partitions so one broken source does not stop every pipeline.
Types of drift
Covariate shift changes P(x) (a new market); prior or label shift changes P(y) (a fraud wave); concept drift changes P(y | x) (fraudsters adapt, so the same features mean something else). Each needs different detection and response, upstream data bugs often masquerade as drift, and seasonality must be modelled before alarms are trusted.
Monitoring when labels are late
Watch input distributions (population stability index, Kolmogorov–Smirnov tests), the prediction-score distribution, decision rates (declines, escalations) and data-quality metrics, plus early proxy labels such as disputes or user feedback. A common PSI rule of thumb: below 0.1 stable, 0.1–0.25 moderate, above 0.25 major. Set thresholds from historical week-on-week variability and monitor by segment, not averages alone.
Labels: delay, noise and imbalance
With delayed labels (chargebacks after 30–90 days) recent data is right-censored, so train and evaluate only on matured windows and never treat “no label yet” as negative. Estimate noise with double labelling and agreement statistics, find suspect labels with confident learning, and spend labelling budget where the model is uncertain. For imbalance, fix metrics first, then use class weights or negative undersampling, and correct or recalibrate the resulting probabilities.
Feature hygiene
Encode high-cardinality categoricals (merchant IDs) with out-of-fold target encoding, hashing or learned embeddings, because naive target encoding leaks the label. Missingness can be informative, so add indicator features rather than silently imputing. Feature stores give single definitions, offline and online consistency and lineage.
Worked examples
Population stability index for a score distribution
A fraud model’s score was binned into five bins on the reference month with shares [0.20, 0.30, 0.25, 0.15, 0.10]. This week’s shares are [0.10, 0.25, 0.30, 0.20, 0.15]. Historically the 95th percentile of week-on-week PSI is 0.08. Compute PSI and decide what to do.
PSI = Σ (currentᵢ − referenceᵢ) × ln(currentᵢ / referenceᵢ)
| Bin | ref | cur | (cur − ref) × ln(cur/ref) |
|---|---|---|---|
| 1 | 0.20 | 0.10 | (−0.10) × ln 0.5 = 0.0693 |
| 2 | 0.30 | 0.25 | (−0.05) × ln 0.833 = 0.0091 |
| 3 | 0.25 | 0.30 | 0.05 × ln 1.2 = 0.0091 |
| 4 | 0.15 | 0.20 | 0.05 × ln 1.333 = 0.0144 |
| 5 | 0.10 | 0.15 | 0.05 × ln 1.5 = 0.0203 |
PSI ≈ 0.122: “moderate” by the rule of thumb and above this model’s normal 0.08, so alert, but do not retrain blindly.
Next steps:
- Rule out pipeline bugs: a feature suddenly null or defaulted, a unit or currency-code change, a new upstream source.
- Find which input features moved (PSI per feature, by segment) and whether traffic mix changed (a new merchant, a marketing campaign).
- Check decision rates and early proxies (disputes) for real performance impact.
Caveats: PSI depends on the binning (use reference quantiles), is noisy with small samples, and needs a small epsilon for empty bins.
Hunting leakage behind a 0.99 AUC
A churn model shows an offline AUC of 0.99 on a random split. Walk through the investigation and show how to rebuild the training set point-in-time correctly.
1. Compare with a simple baseline. Logistic regression on three obvious features gives 0.74; a jump to 0.99 is implausible for churn.
2. Inspect the top features. SHAP shows days_since_last_login dominates. It was computed from the
warehouse snapshot taken after the churn date, so churned customers always have huge values: target
leakage. Removing it drops AUC to 0.86.
3. Check the split. 4% of customers appear in both train and test with several monthly rows each. Switching to GroupKFold by customer gives 0.83.
4. Test out of time. Train on January–September, test on November–December (October left as a gap because churn labels take 30 days to mature): 0.79. That is the number to report.
5. Rebuild point-in-time correct features. Use the time each value became available:
SELECT l.customer_id, l.prediction_ts, l.churned,
f.sessions_30d
FROM labels AS l
LEFT JOIN LATERAL (
SELECT sessions_30d
FROM feature_history AS f
WHERE f.customer_id = l.customer_id
AND f.available_at <= l.prediction_ts -- not event time
ORDER BY f.available_at DESC
LIMIT 1
) AS f ON TRUE;
6. Prevent recurrence. A unit test that recomputes features for a sample of logged serving requests and compares them with the logged values, and an alert if any single feature’s importance exceeds an agreed share.
Flow · 6 stepsHunting leakage behind a 0.99 AUC
- Compare with a simple baseline Logistic regression on three obvious features gives 0.74, so a jump to 0.99 is implausible for churn.
- Inspect the top features SHAP shows days_since_last_login dominates; it was computed after the churn date. Removing it drops AUC to 0.86.
- Check the split 4% of customers appear in both train and test with several monthly rows each. Switching to GroupKFold by customer gives 0.83.
- Test out of time Train on January–September, test on November–December (October left as a gap; labels take 30 days to mature). Result: 0.79, the number to report.
- Rebuild point-in-time features Use the time each value became available: available_at <= prediction_ts, not event time.
- Prevent recurrence A unit test recomputes features for logged serving requests and compares them with logged values; alert if one feature's importance exceeds an agreed share.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Compare with a simple baseline | Logistic regression on three obvious features gives 0.74, so a jump to 0.99 is implausible for churn. |
| 2 | Inspect the top features | SHAP shows days_since_last_login dominates; it was computed after the churn date. Removing it drops AUC to 0.86. |
| 3 | Check the split | 4% of customers appear in both train and test with several monthly rows each. Switching to GroupKFold by customer gives 0.83. |
| 4 | Test out of time | Train on January–September, test on November–December (October left as a gap; labels take 30 days to mature). Result: 0.79, the number to report. |
| 5 | Rebuild point-in-time features | Use the time each value became available: available_at <= prediction_ts, not event time. |
| 6 | Prevent recurrence | A unit test recomputes features for logged serving requests and compares them with logged values; alert if one feature's importance exceeds an agreed share. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Offline AUC 0.99 | Diagnose | random split |
| Simple baseline | Diagnose | three obvious features |
| Top feature | Diagnose | days_since_last_login |
| Split check | Diagnose | 4% overlap |
| Out-of-time test | Diagnose | Jan–Sep to Nov–Dec |
| Point-in-time features | Rebuild | available_at <= prediction_ts |
| Prevent recurrence | Prevent | logged serving requests |
Source: This page's text
Correcting probabilities after undersampling negatives
In a 1:1,000 problem you keep all positives and a random β = 1% of negatives for training. The model then outputs p_s = 0.5 for a transaction. What is the probability on the real population, and why does this matter?
Undersampling negatives multiplies the odds by 1/β, so divide them back out:
odds_true = β × p_s / (1 − p_s) ⇒ p = β p_s / (β p_s − p_s + 1)
With β = 0.01 and p_s = 0.5: p = 0.005 / (0.005 − 0.5 + 1) = 0.005 / 0.505 ≈ 0.0099.
Sanity check. The true base rate is 1/1,001 ≈ 0.001. After undersampling the training base rate is 1 / (1 + 10) ≈ 0.0909. A prediction equal to that training base rate maps back to 0.01 × 0.0909 / (0.000909 − 0.0909 + 1) = 0.000909 / 0.910 ≈ 0.001, the true base rate, as it should.
Why it matters. Thresholds set by expected cost (for example “decline when p > 0.06”), expected-loss reports and calibrated monitoring all assume true-population probabilities. Uncorrected scores from the sampled model would be about 50 times too high here. After correcting, check calibration on an untouched, naturally distributed validation set, and only ever resample after splitting the data.
What changed recently
Pretraining poisoning can plant agent backdoors
Researchers including Nicholas Carlini pretrained 0.6B–4B models from scratch on web data with planted poison, then post-trained them into command-line agents; a remote-code-execution backdoor reached about 92% success in the 4B model at a 0.1% poison rate and was still measurable at 0.0005%. Poisoned training data is now an agent-security issue, so expect questions on provenance, corpus audits and runtime limits for agents built on third-party models.
A $1.5bn settlement over how training data was acquired
A US court gave final approval to a $1.5 billion settlement over books used to train Claude, roughly $3,000 per work for about 500,000 works; the earlier ruling separated lawfully bought and scanned books from copies taken from pirate libraries. Where data came from, and whether you can prove it, is now a material legal and data-quality question.
About 250 documents can poison a model of any size
Anthropic, the UK AI Security Institute and the Alan Turing Institute found that around 250 poisoned documents implanted a trigger-to-gibberish backdoor in models from 600M to 13B parameters, so the attacker needs a roughly fixed number of documents rather than a fixed share of the corpus. Within the tested range, scale did not dilute poisoning, so per-source trust and anomaly detection matter more than corpus size; the study notes it is unclear whether the trend holds for larger models or more complex backdoors.
Mandatory training-data summaries under the EU AI Act
From 2 August 2025, providers of general-purpose AI models must publish a summary of their training content using the Commission’s template (by 2 August 2027 for models already on the market), and the AI Office can take enforcement action from 2 August 2026. Data teams need provenance records good enough to fill it: data-source categories (public, private, scraped, user and synthetic), crawler names and collection periods, and the top scraped domains.
The SWE-Bench Illusion: memorisation inflates scores
A study found that models could name the buggy file path from the issue text alone with up to 76% accuracy on SWE-bench Verified versus up to 53% on repositories outside it, and reproduced far more verbatim code there, evidence of memorisation. Contamination checks (held-out repositories, n-gram overlap, path-identification probes) are now expected when an eval set is public.
Pitfalls
- Oversampling, SMOTE or fitting encoders on the full dataset before the train–validation split.
- Treating unlabelled recent transactions as negatives, or evaluating on windows whose labels have not matured.
- Calling every metric change ‘concept drift’ without checking upstream data bugs and seasonality.
- Static thresholds on hundreds of features, producing alert fatigue; or monitoring only averages, which hides segment failures.
- Retraining immediately when an A/B test is flat instead of checking leakage, skew, metric alignment and statistical power.
- Hand-building chat templates for fine-tuning data, or training on user turns or bad agent replies copied from logs.
How interviewers probe it
- ‘Offline AUC is 0.99 — walk me through your leakage hunt’, then ‘what would you have to see to believe it?’
- ‘A big offline gain, a flat A/B test’: leakage, metric misalignment, shift, power, latency, novelty, feedback loops.
- ‘Labels arrive 30–90 days late’: censoring, proxies, maturity windows and what you monitor meanwhile.
- ‘Which automated checks would you put on the training and serving paths?’ — expect follow-ups on ownership and noisy alerts.
- LLM variant: ‘You have 20k support conversations to fine-tune on — what decides whether it helps?’
- Lead and regulated variant: how model risk management in a UK bank handles validation, monitoring and data lineage.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Your offline AUC is 0.99 on a churn model. Walk through how you would hunt for leakage.
Model answer, written in a candidate's voice
- Treat 0.99 AUC as a red flag and re-check the label and prediction timestamp first.
- Scan features for post-event or target-derived fields such as account closed, cancellation, churn reason, or post-churn activity.
- Check split integrity for duplicate or near-duplicate customers/rows across train and test, and remove ID-like or high-cardinality outcome-encoding fields.
- Verify point-in-time joins and transforms: feature timestamps precede label time; scalers, encoders, imputers, and selection are fit on train only.
- Ablate top features and re-evaluate on a strictly later time window; compare with a simple baseline and treat implausible jumps as suspicious.
What causes training–serving skew and how do you prevent and detect it?
Model answer, written in a candidate's voice
- Causes: duplicated transformation code, different data sources or freshness, timezone/unit bugs, missing-value handling.
- Prevention: one shared transformation path; log served features and train on those logs; parity tests for any second implementation.
- Detection: schema and distribution checks between training and serving, e.g. daily comparisons of served vs training statistics (TensorFlow Data Validation or similar) with drift alerts.
- Launch safety: shadow scoring before rollout and gradual rollout.
How do you build a training set where every feature value is what was known at the moment of prediction?
Model answer, written in a candidate's voice
- Key every feature by entity and valid-from event time, and join with as-of logic using feature_ts < label_ts, not <=.
- Use available-at/ingestion time as the real knowledge cutoff, not just event time, so late-arriving data is excluded.
- Persist snapshots or versioned feature tables so each historical prediction can be reconstructed exactly.
- Validate by recomputing features for past requests and comparing them to the values logged at prediction time.
You have finished this topic.
Reading
- Rules of Machine Learning: Best Practices for ML EngineeringPractical rules, including logging served features and measuring training–serving skew.
- Hidden Technical Debt in Machine Learning SystemsData dependencies, feedback loops and entanglement as the main sources of ML system debt.
- Leakage and the Reproducibility Crisis in ML-based ScienceA taxonomy of leakage types with evidence of how often it invalidates published results.
- Data Distribution Shifts and MonitoringClear treatment of covariate, label and concept shift and what to monitor in production.
- Failing Loudly: An Empirical Study of Methods for Detecting Dataset ShiftCompares shift-detection methods; two-sample tests on reduced representations work best.
- Confident Learning: Estimating Uncertainty in Dataset LabelsA principled way to find mislabelled examples, the basis of label-noise cleaning tools.
- Point-in-time joins (Feast documentation)How feature stores assemble leakage-free training sets with timestamped as-of joins.
- A small number of samples can poison LLMs of any sizeEvidence that backdoor poisoning needs a roughly fixed number of documents rather than a fraction of the corpus, with the study’s limits.
Practise this topic
- Your offline AUC is 0.99 on a churn model. Walk through how you would hunt for leakage.
- What causes training–serving skew and how do you prevent and detect it?
- How do you build a training set where every feature value is what was known at the moment of prediction?
- What automated checks would you put on data entering a training pipeline and a serving path?
- Distinguish covariate shift, prior (label) shift and concept drift, with an example of each from payments or delivery.
- Labels arrive weeks late. What would you monitor to catch problems early, and how do you set alert thresholds?
- Chargebacks arrive 30–90 days after a transaction, and some never arrive. How does this affect training, evaluation and monitoring?
- List techniques for a 1:1000 imbalanced problem and their side effects.
- A model shows a big offline improvement but the A/B test is flat. What might be happening?
- You’re assembling 20k conversations to fine-tune a support assistant. What decides whether the fine-tune helps, and what are the technical gotchas?
- Compare strategies for missing data, and when is “missingness” itself a signal?
- Design a pipeline that turns 50 million PDFs (born-digital reports, scanned forms, papers with tables and equations) into clean text for pretraining and retrieval. Choose between heuristic extractors and a vision-language OCR model, estimate the cost, and explain how you would measure quality.
- A 2025 study found that about 250 poisoned documents could implant a backdoor in language models from 600M to 13B parameters, regardless of how much clean data they saw. What does this change about how you build and check a training corpus scraped from the web?
- After fine-tuning, your team reports a large gain on a public coding benchmark. What would you check before believing it?