Skip to main content

Evaluation and experimentation

Named in 86% of 2253 senior postings · 37 review cards

Deciding whether a model or product change is actually better: building eval sets and graders, validating LLM judges and human raters, choosing offline and online metrics, running A/B tests and ablations with statistical care, analysing failures, and monitoring quality in production. It is the most widely requested area after programming (62% of postings name evaluation, 90% name something in this area) and it appears in every loop, usually as the second half of a system design question and as the test of rigor in a project deep dive.

ML system design (evaluation and launch section)Experimentation and statistics roundCoding (metric and statistics implementations)Project deep diveBehavioral (decisions under mixed evidence)Review these cards →

What the postings ask for

Share of postings that name each skill, overall and by track.

Skill All postings MLE AI eng Research eng Cards
Model evaluation and benchmarks 58% 57% 59% 62% 5
Monitoring, drift and observability 45% 36% 57% 26% 4
Experiment design, ablations and rigor 36% 40% 27% 60% 3
LLM / agent evals (harnesses, judges, graders) 31% 31% 32% 26% 5
Metric design (offline/online, business metrics) 29% 34% 27% 17% 7
Error analysis and failure-mode investigation 25% 19% 31% 20% 2
Human evaluation and feedback loops 12% 10% 14% 8% 2
Red teaming and adversarial testing 8% 8% 6% 19% 1
A/B testing and online experimentation 8% 13% 5% 4% 8

In the postings’ words

Experience with fine-tuning smaller language models or a deep understanding of model evaluation techniques beyond prompt engineering.

Samsara · People Analytics AI Engineer

Familiarity with AWS services : S3, Glue, EMR, EC2, RDS, monitoring and IAM

Hewlett Packard Enterprise · AI/ML Data Engineer

Build scalable model evaluation platforms that enable ML engineers and researchers to measure model quality, compare models, identify regressions, and understand model behavior across experimentation and production environments.

LinkedIn · Senior Staff Software Engineer, AI Infrastructure

Evaluation Infrastructure. Build the shared eval tooling and frameworks that let every team across Harvey measure and improve AI quality systematically.

Harvey · Staff Software Engineer, AI Platform

Define critical metrics and build evaluation tooling to measure quality gains against large-scale real-world data.

Nvidia · Senior Perception AI Engineer - Autonomous Vehicles

Design robust system architecture that addresses operational boundaries, potential failure modes, human approval steps, and long-term maintainability.

Elastic · Principal, Agentic Engineering Platform

Contribute to existing documentation or educational content and adapt content based on product/program updates and user feedback.

Google · Software Engineer III, AI/ML, Google Cloud AI

The senior bar

What separates a senior answer from a mid-level one in this area.

  • Starts from the decision the evaluation must support and from failure modes seen in real outputs, not from a generic metric or an off-the-shelf benchmark.
  • Reports uncertainty with every number (examples, trials, confidence interval, paired comparison) and knows the noise floor before claiming a gain.
  • Validates graders, whether LLM judges or human raters, against a trusted reference and treats the grader version as part of the metric definition.
  • Separates north-star, proxy and guardrail metrics, and can give concrete mechanisms by which an offline win turns into an online loss.
  • Designs experiments with a decision rule written in advance, the correct randomisation unit and adequate power, and handles peeking, multiple comparisons, novelty and interference.
  • Runs error analysis as a loop from raw traces to a failure taxonomy to new test cases and targeted fixes, and checks slices rather than averages.
  • Monitors production quality without labels through traces, proxy signals and sampled grading, and can tell a data bug from drift.

Skills, checklists and questions

Tick an item when you can explain it without notes; ticks are saved in this browser. Open a question to see the answer.

Model evaluation and benchmarks 58% of postings

  • Build an eval from nothing, from task definition and success criteria to a versioned set wired into CI
  • Compute the standard error of an accuracy and say how many examples a given difference needs
  • Compare two systems with a paired test and explain why pairing shrinks the interval
  • Implement a paired bootstrap confidence interval and choose the right resampling unit
  • Explain contamination, adaptive overfitting and saturation, and how to detect each
  • Design the full eval system for a product, including datasets, graders, runner, gates and online checks
coreconceptMLE AI RE You have just joined a team shipping an LLM feature with no evaluation at all. How do you build one from zero?
  1. Define the task and what good means. Write success criteria with the people who own the product: what a correct output is, what is unacceptable, and what decision the eval must support (ship this prompt, pick this model).
  2. Collect 50-200 real inputs. From logs, support tickets or subject experts. Stratify by intent or slice, and include known failures, edge cases and inputs where the right behaviour is to refuse or ask.
  3. Read outputs before writing graders. Run the current system, read 50-100 outputs, and note what goes wrong. The failure modes you find determine what to grade.
  4. Choose graders per criterion. Code checks where the criterion is objective (schema, exact answer, tests pass); an LLM judge with a narrow rubric where it is not; human labels to calibrate the judge. Each example carries a reference answer or the rubric.
  5. Baseline and uncertainty. Record the score with a confidence interval. At 80% accuracy, 100 examples give about ±8 points at 95% confidence and 1,000 give about ±2.5, so a small set only detects large differences.
  6. Version and split. Version the dataset, graders and prompts together. Keep a held-out portion that is not used while iterating on the prompt.
  7. Wire it in. Run on every change; show per-slice scores and the examples that flipped.
  8. Grow it. Each production failure becomes a test case; refresh from current traffic.

Common mistakes: starting with generic metrics (“helpfulness 1-5”) before looking at data, an unvalidated judge, and a set made only of easy synthetic cases.

Follow-ups

  • How do you get reference answers when experts disagree?
  • What tells you the eval set has become too easy?
seniorconceptMLE AI RE What makes a benchmark result untrustworthy? Cover contamination, overfitting and saturation, and say how you would report results properly.

Contamination. Test items, or close paraphrases, were in the training data, so the score measures recall. Public benchmarks are scraped into pretraining corpora. Signs: a large drop on freshly written or post-cutoff items, on rephrased questions, or when answer options are reordered; the model completing a test item verbatim. Mitigations: private held-out sets, periodically refreshed items, and canary strings in published data.

Overfitting to the benchmark. Repeatedly choosing models, prompts and hyperparameters on the same test set selects for noise in that set, even with no leakage. Keep a development split for iteration and look at the test split rarely. Community-wide reuse has the same effect over years.

Saturation. When scores approach the ceiling, remaining differences are within noise and within the label error rate. A benchmark with 3% wrong labels cannot distinguish 96% from 97%.

Construct validity. A benchmark is a sample of some skill. Check that it resembles your task; a leaderboard gain may not transfer.

Reporting.

  • Number of items and a confidence interval for every score.
  • Paired comparison between systems on the same items.
  • Variance across seeds or repeated runs for sampled outputs.
  • The full setup: prompt, few-shot examples, decoding settings, tools, scaffold and budgets. Agent benchmark scores depend heavily on the harness.
  • Cost and latency next to accuracy.
  • Which results were selected after looking at the test set.

Follow-ups

  • How would you test a model for contamination on a benchmark you did not create?
  • Your team has tuned on the same test set for a year. What now?
seniorderivationMLE AI RE Model B scores 83% and model A 80% on your 500-example eval. Is B better? Show the calculation.

It depends on whether the comparison is paired, and it should be, since both models ran on the same examples.

Unpaired view. The standard error of an accuracy is \(\sqrt{p(1-p)/n}\). The difference has

\[ \mathrm{SE} = \sqrt{\tfrac{0.80 \cdot 0.20}{500} + \tfrac{0.83 \cdot 0.17}{500}} \approx 0.0245, \]

so the 95% interval is \(3 \pm 4.8\) points: not significant.

Paired view. With per-example scores \(a_i, b_i\) and \(d_i = b_i - a_i\),

\[ \mathrm{Var}(\bar d) = \frac{\sigma_A^2 + \sigma_B^2 - 2\,\mathrm{Cov}(a, b)}{n}. \]

Two models tend to get the same examples right, so the covariance is positive and the variance shrinks. For binary scores only discordant examples matter. Suppose A alone is right on \(n_{10} = 10\) and B alone on \(n_{01} = 25\) (difference \(15/500 = 3\) points):

  • McNemar: \(\chi^2 = (n_{01} - n_{10})^2 / (n_{01} + n_{10}) = 225/35 \approx 6.4\), \(p \approx 0.011\).
  • \(\mathrm{SE}(\bar d) = \sqrt{n_{01} + n_{10} - (n_{01} - n_{10})^2/n}\,/\,n \approx 0.0118\), so the interval is \(3 \pm 2.3\) points.

Same data, significant once paired. With 60 and 75 discordant examples instead, the same 3 points would not be.

Caveats.

  • This covers sampling of examples only. If outputs are sampled, add run-to-run variance by repeating runs.
  • Examples that share a source document or user are not independent; use clustered standard errors or a cluster bootstrap.
  • If B is the best of many variants tried on this set, the p-value is optimistic.

Sizing. To detect a difference \(\delta\), the interval half-width must be below \(\delta\); halving the detectable difference needs four times the examples.

Follow-ups

  • Why does a paired test need fewer examples?
  • What changes if each example is graded on a 1-5 scale instead of pass/fail?
seniorcodingMLE AI RE Implement a bootstrap confidence interval for the difference in a metric between two systems evaluated on the same examples.
import numpy as np

def paired_bootstrap_diff(a, b, n_boot=10_000, alpha=0.05, seed=0, groups=None):
    """a, b: per-example scores of systems A and B on the SAME examples, shape (n,).
    groups: optional cluster id per example (user, document); resample clusters if given."""
    a, b = np.asarray(a, float), np.asarray(b, float)
    assert a.shape == b.shape and a.ndim == 1
    rng = np.random.default_rng(seed)
    if groups is None:
        units = [np.array([i]) for i in range(len(a))]
    else:
        groups = np.asarray(groups)
        units = [np.flatnonzero(groups == g) for g in np.unique(groups)]
    diffs = np.empty(n_boot)
    for t in range(n_boot):
        pick = rng.integers(0, len(units), size=len(units))     # resample units with replacement
        idx = np.concatenate([units[j] for j in pick])
        diffs[t] = b[idx].mean() - a[idx].mean()                # same idx for both: paired
    lo, hi = np.quantile(diffs, [alpha / 2, 1 - alpha / 2])
    return {"diff": b.mean() - a.mean(), "ci": (lo, hi), "significant": not (lo <= 0 <= hi)}

Pitfalls an interviewer checks:

  • Pairing. Use the same resampled indices for both systems. Resampling them independently throws away the correlation and widens the interval.
  • Unit of resampling. Resample the independent unit: the conversation, user or source document, not the turn or chunk. Otherwise the interval is too narrow.
  • Metrics that are not means. For corpus-level F1, BLEU or AUC, recompute the metric on each resample; do not average per-example values.
  • Replicates. At least 1,000; 10,000 for stable tails.
  • Small or skewed samples. The percentile interval has poor coverage; use BCa or a permutation test for the p-value.
  • What it does not cover. Only example sampling. For stochastic systems, also resample over repeated runs.
  • Speed. For the simple mean, draw an index matrix of shape (n_boot, n) and vectorise.

Follow-ups

  • How would you turn this into a p-value?
  • When does the bootstrap fail outright?
staffdesignMLE AI RE Design the evaluation system for an AI assistant product used by several teams, covering offline evaluation, release gating and production.

Goals. Any change to prompt, model, tools or retrieval gets a trustworthy quality, cost and latency read within minutes to hours; regressions are caught before release; production quality is visible continuously.

Datasets. Versioned and owned.

  • Golden sets per capability and slice, with references or rubrics.
  • A regression set built from past incidents.
  • Safety and adversarial sets.
  • A rolling sample of recent production traffic, privacy-filtered.
  • A held-out set that prompt authors do not see.

Graders. A library of code checks and LLM judges, each with a measured error rate against a human-labelled calibration set, a pinned judge version, and tests. A human review queue for calibration and ambiguous cases.

Runner. Executes a system configuration against a dataset in parallel, with sandboxed tools for agent tasks, multiple trials per case, cached model outputs keyed by configuration, and per-run cost accounting. Every run records the dataset version, grader versions, code commit, model snapshot and prompt version.

Results. A store and UI with per-slice scores and confidence intervals, paired comparison against a baseline, the list of flipped examples, and a link from every score to the trace.

Gates. A smoke suite on every change; the full suite nightly and before release; explicit thresholds for guardrail criteria (safety, format validity, groundedness) and a non-inferiority margin for the primary metric.

Online. The same graders score a sample of production traces; implicit signals (regenerate, edit, abandon, escalate) and A/B tests measure user impact; canary prompts detect upstream model changes.

The loop. Production failures and review-queue findings flow back into datasets; judges are re-calibrated on a schedule.

Trade-offs to state. Suite cost and runtime against coverage, handled by tiering; flaky cases quarantined and fixed, not ignored; one shared platform against team-specific rubrics; and the risk of the suite becoming the target, countered by refreshing it from live traffic.

Follow-ups

  • How do you stop teams from tuning to the shared golden set?
  • What is the first thing you would build with two engineers and one month?
  • How do you decide the release threshold for the primary metric?

Monitoring, drift and observability 45% of postings

  • Distinguish covariate shift, prior shift and concept drift and what each needs to detect
  • Compute PSI and explain why statistical tests over-alert at scale
  • Specify what an LLM trace must contain
  • Monitor quality without labels using sampled grading, implicit user signals and operational proxies
  • Investigate a quality drop with no deploy, including upstream model and data dependencies
coreconceptMLE AIasked at Nvidia What is the difference between data drift and concept drift, how do you detect each, and what do you do about it?
  • Covariate (data) drift: the input distribution \(P(X)\) changes; the relation \(P(Y \mid X)\) may be intact.
  • Prior (label) shift: the class balance \(P(Y)\) changes.
  • Concept drift: \(P(Y \mid X)\) changes. The same input now has a different right answer (new fraud pattern, changed user intent, a policy change).

Detection.

  • Inputs. Compare a recent window with a reference per feature: population stability index, \(\mathrm{PSI} = \sum_i (a_i - e_i)\ln(a_i/e_i)\) over bins with reference share \(e_i\) and current share \(a_i\); Kolmogorov-Smirnov or chi-square tests; for text and images, distances between embedding distributions or a classifier trained to tell the windows apart.
  • Outputs. Shifts in the score distribution and predicted class mix.
  • Performance. The only direct evidence of concept drift is labelled outcomes. When labels are delayed, use early proxies, a small fast-labelled sample, or delayed evaluation by cohort.

Caveats.

  • At large volume every statistical test is significant. Alert on effect sizes with thresholds learned from normal week-to-week variation. Common PSI cut-offs (0.1, 0.25) are conventions.
  • Drift is not degradation. Many input shifts do not hurt; concept drift can hurt with no visible input shift.
  • Most drift alerts are pipeline faults: a schema change, a unit change, a spike in nulls, a broken upstream job. Check data quality first.

Response. Fix the pipeline if it is a bug. Otherwise retrain or fine-tune on recent data, recalibrate if only the base rate moved, add features for the new pattern, or fall back to a safer policy. Scheduled retraining with monitored evaluation handles gradual drift; alerts handle abrupt changes.

Follow-ups

  • Labels arrive 30 days late. How do you know today that the model is failing?
  • Which drift alerts would you page on, and which only log?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Nvidia, Machine Learning Engineer, Feb 2026: Bias-variance trade-off, calibration and model drift (PracHub)
seniorconceptAI MLE How do you monitor the quality of an LLM product in production when you have no labels?

Start with traces. One trace per user request, with a span for each model call, retrieval and tool call, recording: inputs and outputs (under a PII policy), prompt and model versions, tokens in and out including cached, latency including time to first token, cost, finish reason, retries and errors, and identifiers that join it to the user session and to downstream outcomes. OpenTelemetry is the common transport; its conventions for generative AI are still evolving.

Quality signals without labels.

  1. Sampled automated grading. Run the offline graders (validated judges and code checks for groundedness, format validity, policy adherence) on a sample of live traces. This is the closest thing to a continuous quality number.
  2. Implicit user signals. Regenerate and rephrase rates, edits to the output before use, acceptance of suggestions, abandonment, escalation to a human, explicit thumbs. Each is biased; the trend is informative.
  3. Operational proxies. Tool error rate, validation-retry rate, refusal rate, steps per task, runs ended by a budget, empty retrievals.
  4. Input drift. Clusters of intents over time; a new cluster is a use case the eval set does not cover.
  5. Canaries. A fixed set of prompts replayed on a schedule detects changes in the upstream model or in dependencies independent of traffic mix.

Alerting. Rates with baselines from normal variation, segmented by route, tenant, model version and prompt version; comparison before and after every deploy; alerts on cost per task and latency percentiles alongside quality.

Close the loop. Route low-scoring and user-flagged traces to a review queue, label them, add them to the eval set, and periodically re-validate the online judges against those labels.

Follow-ups

  • Thumbs-down rate is 0.5% of sessions. How much can you learn from it?
  • What would you sample more heavily than uniform, and how do you keep the estimate unbiased?
seniordebuggingMLE AI A production quality metric dropped on Tuesday and your team deployed nothing. How do you investigate?

Is the drop real? Check the measurement before the system: a logging or pipeline change, a grader or judge update, a change in sampling, missing data for part of the day.

Characterise it. A step or a ramp? All traffic or one slice (tenant, locale, platform, route, model version)? The shape and scope narrow the cause more than anything else.

Things that change without your deploy.

  • Upstream model. A provider updated the model behind an alias, changed a default, or your traffic is on a fallback model because of rate limits or an outage. Canary prompts and the logged model id show this.
  • Dependencies. The retrieval index failed to refresh or was rebuilt, an embedding or feature service changed, a tool’s API changed its response format, timeouts are truncating context.
  • Data. An upstream schema or unit change, a spike in nulls, a late batch job.
  • Traffic mix. A new customer, a campaign, bot traffic, a seasonal shift in intents. Compare quality at fixed mix.
  • Other teams’ changes. Feature flags, experiments, configuration, shared prompts or libraries.
  • Infrastructure. Region failover, capacity limits, cache expiry.

Method. Line up the drop time against change logs of every dependency. Diff traces for similar inputs before and after: retrieved context, tool results, model id, token counts, finish reasons. Replay a fixed set of requests against the current system to see whether the change reproduces independent of traffic.

Mitigate and learn. Pin or roll back the dependency, or switch route, before the root cause is fully understood if users are affected. Then add the monitor that would have caught it at the source: a canary, a dependency version in every trace, an index freshness check, or a data-quality gate.

Follow-ups

  • The drop affects only one tenant. What are the first three things you check?
  • How do you tell a traffic mix change from a real degradation?
seniordesignMLE REasked at OpenAI Design out-of-distribution detection for a deployed classifier: how do you score a single input, how do you evaluate the detector, and how do you monitor it in production?

Say which shift you mean. Covariate shift (familiar classes, new input style: a new camera, a new language), semantic shift (a class the model never saw), and label shift (class frequencies move). A per-input detector targets the first two; label shift is a population-level question.

Per-input scores, cheapest first:

  • Maximum softmax probability. The baseline; weak because networks are confidently wrong far from the training data.
  • Energy, \(T \log \sum_c e^{z_c/T}\) on the logits: free, and usually better than the softmax maximum.
  • Feature distance: Mahalanobis distance to the nearest class mean in the penultimate layer, or distance to the k-th nearest training embedding. Strong on semantic shift, needs no retraining.
  • Disagreement across an ensemble: best quality, several times the cost.
  • Likelihood from a generative model is unreliable alone: such models can assign higher likelihood to out-of-distribution images than to their training data.
import numpy as np

def fit_mahalanobis(feats, labels):
    classes = np.unique(labels)
    mu = np.stack([feats[labels == c].mean(0) for c in classes])
    centred = feats - mu[np.searchsorted(classes, labels)]
    prec = np.linalg.pinv(centred.T @ centred / len(feats))   # shared covariance
    return mu, prec

def mahalanobis_score(x, mu, prec):                           # higher = more in-distribution
    d = x[:, None, :] - mu[None]
    return -np.einsum("ncd,de,nce->nc", d, prec, d).min(1)

def fpr_at_tpr(id_scores, ood_scores, tpr=0.95):
    thr = np.quantile(id_scores, 1 - tpr)
    return float((ood_scores >= thr).mean())

Evaluation. AUROC and the false-positive rate at 95% true-positive rate, reported separately for near shifts (similar classes, a new time period, a new region or device) and far ones (unrelated data). Far shifts flatter every method. Build the test sets from real held-out shifts in your own data; set the threshold on in-distribution validation data only, since real shifts are not known in advance.

Production design.

  1. Per request: compute the score from activations the model already produces; above threshold, abstain, route to a fallback or a human, and log the input.
  2. Population level: compare windows of scores, embeddings and predicted-class frequencies with a reference window, using a two-sample test or a classifier trained to tell the windows apart. Many small shifts never trip the per-input threshold and still move accuracy.
  3. Close the loop: sample flagged inputs for labelling, measure accuracy on them, and add them to training or to the evaluation set.
  4. Monitor the detector: flag rate over time, precision of flags from the labelled sample, and accuracy on unflagged traffic.

Failure modes. A flag rate that follows a benign traffic mix change and pages people for nothing; thresholds that go stale after each retrain because the feature space moved; the detector passing inputs that are in-distribution for the features and still adversarial; and treating “not flagged” as “correct”, which it is not.

Follow-ups

  • The flag rate doubled overnight and accuracy on a labelled sample did not move. What happened and what do you change?
  • Why can a generative model give higher likelihood to data it was never trained on?
  • How would you adapt this to a generative language model, where there are no class logits?

Reported in interviews (candidate reports on third-party sites, not verified)

  • OpenAI, Machine Learning Engineer, Dec 2025: Out-of-distribution detection with production monitoring (PracHub)

Experiment design, ablations and rigor 36% of postings

  • Design an ablation with a properly tuned baseline, one change at a time and multiple seeds
  • Estimate the noise floor and state the smallest gain you would believe
  • Quantify the false-positive risk of trying many variants and apply a correction or a replication
  • Write a decision rule before running and say what gets recorded for reproducibility
coreconceptMLE AI RE How do you design an ablation study so that its conclusions can be trusted?

An ablation attributes a result to a cause. It is trustworthy when the only difference between two runs is the thing being claimed.

  • A strong, equally tuned baseline. Most false gains come from a tuned new method against an untuned baseline. Give both the same tuning budget.
  • One change at a time. If the new run changes the architecture, the learning rate and the data, the gain cannot be assigned. Either add components one by one to the baseline or remove them one by one from the full system; do both when interactions are likely.
  • Hold everything else fixed. Data and splits, preprocessing, compute or step budget, evaluation code, decoding settings. Compare at equal parameters or equal compute, and say which.
  • Know the noise floor. Run the baseline with several seeds (three to five at least) and measure the standard deviation of the metric. A difference smaller than about two standard errors is not evidence. For LLM applications the analogues are sampling variance and eval-set size.
  • Report all runs. Mean and spread across seeds, not the best seed; include the variants that did not help.
  • Check the mechanism. If the claim is “the gain comes from X”, a control that removes X’s supposed mechanism while keeping its parameter count or compute should lose the gain.
  • Record enough to reproduce. Code commit, config, seeds, data version, environment.

Typical traps: test-set selection of checkpoints or hyperparameters, different amounts of training between arms, an evaluation bug that favours one output format, and concluding from a single seed.

Follow-ups

  • Compute allows three seeds for one configuration or one seed for three. Which do you choose?
  • Two components each give nothing alone and a gain together. How do you present that?
seniortrade-offMLE AI RE You tried 30 variants and one beats the baseline by 0.4 points with p = 0.03. Do you believe it?

Not yet. With 30 comparisons at \(\alpha = 0.05\) and no real effects, the chance that at least one looks significant is \(1 - 0.95^{30} \approx 79\%\). A p-value of 0.03 for the best of 30 is what noise produces.

Corrections.

  • Bonferroni: require \(p < \alpha/m = 0.0017\). Simple and conservative.
  • Holm: step-down version, uniformly more powerful than Bonferroni.
  • Benjamini-Hochberg: controls the false discovery rate, appropriate when screening many candidates and some false leads are acceptable.

The better remedy is replication. Select on one set of data and confirm on another: rerun the winning variant and the baseline with new seeds, or evaluate on a held-out set that played no part in choosing it. Expect the confirmed gain to be smaller than 0.4 because the best of many is biased upward.

Also ask.

  • Is 0.4 above the noise floor from seed-to-seed variation of the baseline?
  • Was the baseline tuned as much as the variants?
  • Were the 30 variants chosen in advance, or did choices adapt to earlier results (stopping rules, metric choice, subsets)? Undisclosed flexibility inflates false positives beyond the simple count.
  • Is there a reason to expect this variant to work? A mechanism raises the prior; an arbitrary winner lowers it.

Pre-registration in an engineering setting. Before the runs, write down the primary metric, the eval set, the comparison, the decision threshold and the stopping rule. Exploratory findings are fine, labelled as such and confirmed before anyone depends on them.

Follow-ups

  • When is false discovery rate control the right choice over family-wise error control?
  • How many seeds would you run to confirm a 0.4-point gain?
seniorconceptMLE RE A result from six months ago cannot be reproduced. What should have been recorded, and how do you make experiments reproducible by default?

What determines a result. Code, configuration, data, randomness, environment and the evaluation procedure. Each needs an identifier stored with the result.

  • Code: the commit hash, plus a diff if the tree was dirty.
  • Configuration: the fully resolved config after defaults and overrides, not only the command line.
  • Data: dataset version or content hash, split definition, preprocessing and tokenizer versions, and any filtering.
  • Randomness: seeds for initialisation, data order, augmentation and sampling.
  • Environment: container image or lockfile, library versions, hardware type, precision settings.
  • Evaluation: eval set version, metric code version, decoding settings, grader or judge version, checkpoint-selection rule.
  • For LLM applications: model snapshot id, prompt and tool-definition versions, sampling settings, and stored raw outputs.

Make it the default. The launcher records all of this automatically to the experiment tracker; runs from uncommitted code are refused or flagged; results tables are generated from tracked runs and never typed by hand; each headline number links to its run.

What reproducibility means. Bit-exact reruns are often unattainable on GPUs (non-deterministic kernels, different hardware, parallel data loading). The practical target is statistical: a rerun lands within the seed-to-seed spread. That spread must be known, which is another reason to run several seeds.

When a result does not reproduce. Diff the recorded items first; common culprits are a changed dataset behind an unchanged name, a library upgrade, a default that changed, a single lucky seed, and evaluation on a different checkpoint.

Follow-ups

  • Which sources of non-determinism remain after fixing all seeds?
  • How do you handle a dataset that is updated in place?

LLM / agent evals (harnesses, judges, graders) 31% of postings

  • Choose between exact match, programmatic checks, LLM judges and human review for a given criterion
  • Validate an LLM judge against human labels and name its known biases
  • Correct an observed pass rate for judge error using its true and false positive rates
  • Decide between pairwise and pointwise judging and write a rubric that raters apply consistently
  • Grade agents by outcome and by trajectory, with sandboxed resets, multiple trials and cost tracking
  • Handle a judge model upgrade without breaking the metric time series
coreconceptMLE AI RE What kinds of graders are there for LLM outputs, and when do you use each?
Grader Use when Strength Weakness
Exact or normalised match one correct answer (classification, multiple choice, extraction) free, deterministic brittle to formatting; useless for open text
Programmatic check the property is verifiable in code: schema valid, tests pass, SQL returns the right rows, number within tolerance, required citation present objective, cheap, fast covers only what can be coded
Reference-based similarity a reference answer exists and wording may vary cheap weak correlation with quality for open-ended text
LLM as judge subjective or semantic criteria: faithfulness, relevance, tone, rubric adherence scales, handles open text biased and noisy; must be validated against humans; costs money
Human review ground truth for new criteria, calibrating judges, high-stakes samples most trusted slow, expensive, inconsistent without guidelines

Order of preference: code first, then a validated judge, then humans for calibration and for what neither can assess.

Practical rules:

  • Grade one criterion per grader. “Overall quality 1-10” is hard to act on and hard to validate.
  • Prefer checking the outcome (does the code run, is the row in the database) over judging the text that describes it.
  • Treat graders as code: version them, test them on known-good and known-bad outputs, and measure their error rate.
  • Combine: a programmatic gate for hard requirements plus a judge for quality.

Follow-ups

  • Give a criterion people usually send to an LLM judge that code could check.
  • How do you test a grader?
seniorconceptMLE AI REasked at Apple When is an LLM judge trustworthy? How do you validate one and what biases do you look for?

A judge is a classifier and is trusted only as far as it has been measured.

Validation.

  • Label 100-300 outputs by humans, ideally two per item, on the same rubric.
  • Report judge-human agreement (Cohen’s \(\kappa\) for categories, rank correlation for scores) next to human-human agreement, which is the ceiling.
  • Look at the confusion matrix: a judge that passes everything has high agreement when most outputs are good, and no power to detect regressions.
  • Hold out part of the labelled set from rubric tuning.

Known biases.

  • Position: in pairwise comparison, a preference for the first or second answer. Run both orders and count only consistent verdicts.
  • Verbosity: longer answers score higher.
  • Self-preference: judges tend to favour outputs from their own model family.
  • Leniency and compression: scores bunch at the top of a 1-5 scale.
  • Rubric sensitivity: small wording changes move scores.

Mitigations. Binary or three-level criteria with explicit definitions and examples; one criterion per call; reasoning before the verdict; a judge at least as capable as the system under test and preferably from a different family; pinned judge version.

Correcting for judge error. If the judge has true positive rate TPR and false positive rate FPR on the labelled set, an observed pass rate \(p_{obs}\) implies a true rate \(\hat p = (p_{obs} - \mathrm{FPR}) / (\mathrm{TPR} - \mathrm{FPR})\). With TPR 0.9 and FPR 0.2, an observed 76% corresponds to 80%.

Re-validate whenever the judge model, the rubric or the product’s output distribution changes.

Follow-ups

  • Judge-human agreement is 85% and human-human is 80%. What does that mean?
  • How does the correction formula behave when TPR is close to FPR?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Apple, Machine Learning Engineer, Aug 2025: Annotation agreement, and LLM versus human judges (PracHub)
seniortrade-offAI RE Pairwise or pointwise judging? And what makes a rubric good?

Pointwise assigns each output an absolute verdict or score. It scales linearly in outputs, gives a level you can threshold and track over time, and suits regression gates and production monitoring. Its weakness is calibration: absolute scores drift between raters and judge versions, and bunch at the top of the scale.

Pairwise asks which of two outputs is better. People and models are more consistent at comparing than at absolute scoring, so it detects smaller differences with fewer examples. Its weaknesses: no absolute level (both can be bad), position bias, intransitive preferences, and quadratic growth in comparisons with many systems, handled by sampling pairs and fitting Elo or Bradley-Terry ratings. Allow ties.

Use pairwise for selecting between two prompts or models; use pointwise pass/fail for gates, monitoring and anything that needs a stable number.

Rubric design.

  • Decompose quality into independent criteria (correct, grounded, complete, follows format) and grade each separately.
  • Prefer binary or three levels with observable definitions. A 1-10 scale has levels nobody can distinguish.
  • Give anchor examples for each level, including borderline cases with the reasoning.
  • Say what to ignore (length, style) if it should not count.
  • Treat critical failures (unsafe, fabricated fact) as separate gates; averaging hides them.
  • Pilot the rubric on 30-50 items with two raters, find where they disagree, and revise the wording until agreement is acceptable.

A rubric that humans cannot apply consistently will not be applied consistently by a model.

Follow-ups

  • How many pairwise comparisons would you need to rank five systems?
  • Your judge says A beats B, B beats C and C beats A. What do you do?
seniorconceptAI REasked at OpenAI How is evaluating an agent different from evaluating a single model response?

An agent produces a trajectory with side effects, is more variable, and costs far more per example.

Outcome versus trajectory grading.

  • Outcome: check the final environment state (tests pass, the record has the right values, the file exists). It accepts any valid path, so prefer it for task success.
  • Trajectory: check the steps (tools used, unnecessary calls, policy violations such as acting without confirmation, efficiency). Use it for diagnosis and for constraints that must hold along the way. Requiring one exact path penalises valid alternatives.

Environments. Sandboxed and resettable with a deterministic start state: containers, seeded databases, mocked or recorded external services. No state may leak between runs. Live dependencies (the web, third-party APIs) make results non-stationary.

Variance. Run each task \(k\) times. Report mean success with a confidence interval, and if reliability matters, the fraction of tasks solved in all \(k\) trials, which is much lower than the mean for unreliable agents. Separate infrastructure failures (timeouts, sandbox errors) from agent failures.

Cost. Record tokens, steps, wall-clock time and money per task; a method that gains two points at three times the cost is a different trade. Tier the suites: a small smoke set per change, the full set nightly.

Grader validity. Confirm that a reference solution passes and a do-nothing agent fails. Read transcripts: agents find shortcuts such as editing the tests, hard-coding expected output or exploiting a lenient check.

Reporting. State the harness, tools, step and token budgets with the score, since the same model scores differently under different scaffolds.

Follow-ups

  • A task passes 3 of 5 trials. How do you count it?
  • How do you evaluate an agent whose tasks touch the live web?

Reported in interviews (candidate reports on third-party sites, not verified)

  • OpenAI, Machine Learning Engineer, Apr 2026: Agent harness and evaluation system for a tool-using agent (PracHub)
seniordebuggingAI RE You upgraded the judge model and quality scores moved by several points overnight with no product change. What do you do?

Confirm the cause. Take a frozen set of stored product outputs and score them with the old and the new judge. Identical outputs with different scores isolate the judge effect from any product change.

Decide which judge is right. Score the human-labelled calibration set with both. Compare agreement with humans, true and false positive rates, and the score distribution. Read the items where the judges disagree, grouped by criterion and slice: the new judge may be stricter on one criterion, more lenient on long answers, or reading the rubric differently.

Repair the time series.

  • The judge version is part of the metric definition. Scores from different judge versions are not comparable and should never share a trend line without a marked break.
  • If the new judge agrees with humans at least as well, adopt it and re-baseline: re-score stored historical outputs with it, or run both judges in parallel for an overlap period and publish the offset.
  • If it agrees worse, stay on the pinned old version and adjust the rubric for the new one before switching.

Prevent recurrence.

  • Pin a dated judge snapshot; never a moving alias.
  • Store raw outputs so they can be re-scored.
  • Run the calibration set through the judge in CI and alert when judge-human agreement or the judge’s pass rate on a fixed reference set moves.
  • Version rubric, judge model and judge prompt together and log them with every score.

The same procedure applies when the rubric is edited, which is a more frequent cause than model upgrades.

Follow-ups

  • You did not store historical outputs. What can you still do?
  • The provider retires the old judge model next month. Plan the transition.

Metric design (offline/online, business metrics) 29% of postings

  • Define precision, recall, ROC-AUC and PR-AUC and say which to use under class imbalance
  • Define recall@k, MRR and NDCG, and implement NDCG with the correct ideal ranking
  • Explain why BLEU and ROUGE are weak for open-ended generation and what replaces them
  • Structure a metric hierarchy of north-star, proxy and guardrail metrics and give a Goodhart example
  • Diagnose an offline-online disagreement
  • Make and defend a ship decision when metrics move in different directions
coreconceptMLE AI REasked at Meta, TikTok Which classification metric do you use when positives are rare, and why is accuracy or ROC-AUC not enough?

Definitions: precision \(= TP/(TP+FP)\), recall \(= TP/(TP+FN)\), false positive rate \(= FP/(FP+TN)\). ROC-AUC is the probability that a random positive is scored above a random negative. PR-AUC summarises precision over recall.

Accuracy is uninformative under imbalance: at 1% prevalence, predicting all negative scores 99%.

ROC-AUC does not depend on prevalence, which is its use and its trap. A false positive rate of 1% sounds excellent, but at 1% prevalence with 90% recall,

\[ \text{precision} = \frac{0.01 \cdot 0.90}{0.01 \cdot 0.90 + 0.99 \cdot 0.01} \approx 0.48, \]

so half the alerts are wrong. Precision is what the reviewer or user experiences.

Use PR-AUC to compare models on rare positives (its baseline is the prevalence, not 0.5), and report the operating point the product uses: recall at a fixed precision, or precision at the top \(k\) if review capacity is fixed.

Threshold comes from costs: flag when \(p > c_{FP} / (c_{FP} + c_{FN})\), which requires calibrated probabilities.

Calibration is separate from ranking. AUC is unchanged by any monotonic transform of the scores. If scores are used as probabilities (expected value, thresholds from costs, bids), also measure log loss, Brier score or a reliability plot.

Caveats. Precision and PR-AUC change when prevalence changes, so they are not comparable across datasets with different base rates. If negatives were downsampled for training or evaluation, correct for it before reporting precision.

Follow-ups

  • Two models have the same ROC-AUC. How can one be much better in production?
  • How does negative downsampling affect precision and calibration?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Meta, Data Scientist, Oct 2025: Metrics for a fake-user classifier (PracHub)
  • TikTok, Data Scientist, Nov 2025: When to prioritise precision or recall (PracHub)
coreconceptMLE AI Define recall@k, MRR and NDCG. When would you use each for a search or retrieval system?
  • Recall@k: the fraction of a query’s relevant items that appear in the top \(k\). It ignores order within the top \(k\).
  • Precision@k: the fraction of the top \(k\) that is relevant.
  • MRR: the mean over queries of \(1/\text{rank}\) of the first relevant item. It ignores everything after the first hit.
  • MAP: the mean over queries of average precision, for binary relevance with several relevant items.
  • NDCG@k: for graded relevance with a position discount,

\[ \mathrm{DCG@}k = \sum_{i=1}^{k} \frac{2^{rel_i} - 1}{\log_2(i + 1)}, \qquad \mathrm{NDCG@}k = \frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k}, \]

where IDCG is the DCG of the ideal ordering.

Which one.

  • Candidate generation or the retrieval stage of RAG: recall@k, because a later ranker or the LLM can reorder but cannot recover a missing item.
  • One correct answer (navigational search, question answering): MRR.
  • Final ranking with graded labels where position matters: NDCG@k with \(k\) set to what the user sees.

Pitfalls.

  • Unjudged items are usually counted as irrelevant, which penalises a new system that surfaces items the old one never showed.
  • Click-derived labels carry position and presentation bias.
  • Average per query, so heavy queries do not dominate, unless you intend traffic weighting.
  • Queries with no relevant item need a stated convention.
  • Offline ranking metrics are proxies; confirm against online behaviour.

Follow-ups

  • NDCG improved and recall@100 dropped. How is that possible and does it matter?
  • How do you handle unjudged documents fairly?
corecodingMLE AI Implement NDCG@k and tell me the mistakes people make.
import numpy as np

def dcg_at_k(rels, k):
    rels = np.asarray(rels, dtype=float)[:k]
    if rels.size == 0:
        return 0.0
    discounts = 1.0 / np.log2(np.arange(2, rels.size + 2))     # positions 1..k -> log2(i + 1)
    return float(np.sum((2.0 ** rels - 1.0) * discounts))

def ndcg_at_k(ranked_rels, k, all_rels=None):
    """ranked_rels: graded relevance of the returned items, in returned order.
    all_rels: relevance of ALL judged items for the query (defines the ideal ranking)."""
    pool = ranked_rels if all_rels is None else all_rels
    idcg = dcg_at_k(sorted(pool, reverse=True), k)
    return dcg_at_k(ranked_rels, k) / idcg if idcg > 0 else 0.0

def mean_ndcg(queries, k):
    """queries: list of (ranked_rels, all_rels). Macro-average over queries."""
    return float(np.mean([ndcg_at_k(r, k, a) for r, a in queries]))

Check: relevances [3, 2, 0, 1] at \(k = 4\) give \(\mathrm{DCG} = 7/1 + 3/1.585 + 0 + 1/2.322 \approx 9.32\), ideal [3, 2, 1, 0] gives \(7 + 1.893 + 0.5 = 9.39\), so NDCG is about 0.993.

Mistakes an interviewer looks for:

  • Ideal ranking from the retrieved list only. If the system returned one of ten relevant items and you sort just the returned ones, it scores 1.0. The ideal must use all judged relevant items for the query.
  • Off-by-one in the discount. Position 1 has discount \(\log_2 2 = 1\).
  • Queries with no relevant item. IDCG is zero; decide whether they score 0 or are excluded, and say which, since it changes the mean.
  • Gain function. \(2^{rel} - 1\) emphasises highly relevant items; linear gain \(rel\) is also used. Do not compare numbers across the two.
  • Averaging. Average per-query NDCG; do not pool gains across queries.
  • Ties in model scores. Make the sort deterministic, or the metric moves between runs.
  • Unjudged items. Treating them as relevance 0 biases against systems that surface new items.

Follow-ups

  • What is the range of NDCG and when can it be exactly 1 for a bad system?
  • How would you compute this for 10 million queries efficiently?
coretrade-offMLE AI RE Why are BLEU and ROUGE weak metrics for LLM outputs, and what do you use instead?

Both count n-gram overlap with reference texts. BLEU is precision-oriented with a brevity penalty and comes from machine translation; ROUGE is recall-oriented and comes from summarisation.

Why they are weak for open-ended generation.

  • Many valid outputs. A correct answer phrased differently from the reference scores low; a fluent answer that copies reference phrases scores high.
  • Blind to meaning. Inserting “not” changes one token and reverses the claim. Fabricated facts barely move the score.
  • Reference-bound. Quality cannot exceed what the references cover, and scores depend on tokenisation and the number of references.
  • Weak agreement with human judgment once systems are fluent, which modern LLMs are; differences in overlap no longer track differences in quality.

What to use.

  • Task-specific correctness in code: exact match or token F1 for extractive answers, execution accuracy for SQL and code (run it, compare results, run tests), field-level accuracy for extraction.
  • Learned similarity (BERTScore, COMET for translation): handles paraphrase better, still reference-bound and not a factuality measure.
  • Rubric-based LLM judges, validated against humans, for relevance, completeness and tone.
  • Factuality and grounding checks: split the output into claims and test each against the source by entailment.
  • Human evaluation for calibration and final comparisons.

Perplexity measures how well a model predicts text, not whether an output is good.

Overlap metrics remain acceptable as cheap regression signals on constrained tasks where outputs are nearly unique, with the caveats stated.

Follow-ups

  • When is exact match too strict, and how do you relax it safely?
  • How would you evaluate a summary for factual consistency?
seniorconceptMLE AI How do you design the metrics for an ML or LLM product? Explain north-star, proxy and guardrail metrics and how Goodhart’s law shows up.

Hierarchy.

  • North-star: the long-term value the product exists for (retained users, tasks completed successfully, revenue quality). Slow and noisy, so rarely usable as an experiment metric.
  • Proxy or driver metrics: fast, sensitive measures believed to cause the north-star (successful sessions, accepted suggestions, resolution without re-contact). These are what experiments optimise.
  • Guardrails: must not regress (latency, crash and error rates, complaints, unsubscribes, safety violations, cost). Each has a threshold.
  • Offline metrics: proxies of proxies (NDCG, judge scores), used to decide what is worth testing online.

A good experiment metric is sensitive enough to move in a two-week test, attributable to the change, hard to game, cheap to compute, and directionally aligned with the north-star.

Goodhart’s law. Once a proxy is optimised, it stops tracking the goal. Click-through rewards clickbait; watch time rewards compulsive content; an LLM judge’s score rewards verbosity; “tickets resolved” rewards closing tickets early.

Defences.

  • Pair each proxy with a counter-metric (resolution with re-open rate, clicks with dwell or return visits).
  • Validate the proxy: across past experiments, did movement in the proxy predict movement in the north-star? Maintain long-term holdouts to check.
  • Prefer metrics based on completed outcomes over activity counts.
  • Re-examine metrics periodically and read samples behind the number.

Offline-online alignment is the same problem one level down: track, across launches, whether offline gains predicted online gains, and fix the offline eval when they stop.

Follow-ups

  • Propose a north-star, a proxy and two guardrails for a coding assistant.
  • How would you check that a proxy is still valid a year later?
seniordebuggingMLE AI Your new model beats the old one offline but loses in the A/B test. What are the possible causes and how do you investigate?

First, is the A/B test right? Check sample ratio mismatch, an A/A baseline, power, and whether the metric and exposure logging are correct. Sometimes the offline result is the true one.

Then, causes on the model side.

  1. Training-serving skew. Features differ online: stale or missing values, different preprocessing, a join that is correct offline and late online.
  2. Leakage offline. Future information, labels in features, or duplicates across train and test inflate the offline score.
  3. Biased offline labels. Logged data only contains what the old system showed. The new model’s novel items are unjudged and its gains on familiar items are overstated.
  4. Distribution mismatch. The eval set is old, sampled differently, or misses segments present in live traffic.
  5. Metric mismatch. Offline optimises a proxy (click NDCG, judge score) while the test measures retention, revenue or task success.
  6. System effects. The model is slower and latency costs engagement; it interacts with downstream rankers, caches, filters or business rules; a fallback fires more often.
  7. Feedback and position effects not captured offline.

Investigation order.

  • Experiment health, then latency and other guardrails.
  • Prediction parity: log online features and scores, replay the same requests offline, compare. This finds skew directly.
  • Slice the online loss by segment, platform and query type; a concentrated loss points to a cause.
  • Read examples where the two models differ most.
  • If labels are biased, use counterfactual estimation with logged propensities, or interleaving.

Afterwards. Record the pair of offline and online results, and repair the offline eval so it would have predicted this outcome.

Follow-ups

  • How do you measure training-serving skew in a system you did not build?
  • What would make you trust the offline result over the A/B result?
staffdesignMLE AI An experiment shows the primary metric up 0.8%, latency worse by 30 ms, and one of three guardrail metrics slightly negative but not significant. Do you ship?

The answer should come from a rule agreed before the test, and my job is to apply it honestly and state the uncertainty.

What should already exist. A primary metric with a minimum effect worth shipping; guardrails with thresholds expressed as non-inferiority margins; and an agreed exchange rate for known trade-offs (how much engagement a given latency increase costs).

Reading this result.

  • Primary. Is +0.8% significant, and is the lower end of its interval still worth shipping? Was it the pre-declared metric or the best of many?
  • Latency. Thirty milliseconds has a known cost in most products. Convert it through the exchange rate; check tail latency, not only the mean; ask whether it can be engineered away before or after launch.
  • The non-significant guardrail. “Not significant” is not “no harm”. Look at the interval: if it includes a regression larger than the margin, the test has not ruled harm out, and more data is needed. If the whole interval sits inside the margin, it passes.
  • Multiplicity. With many metrics some will look negative by chance; that is why guardrails are declared in advance.
  • Segments. A small average loss can be a large loss for one platform or cohort.
  • Durability. Check the effect by day for novelty.

Options beyond yes and no. Ship with a holdback to measure the long-term effect; ship to segments where it clearly wins; extend the test to tighten the guardrail; fix latency and re-test.

How I would present it. Recommendation, effect sizes with intervals, the trade-off in one common unit, what is unknown, and what observation would reverse the decision. Also weigh reversibility: an easily reverted change with a holdback needs less certainty than a migration.

Follow-ups

  • No exchange rate between latency and engagement exists. How do you get one?
  • The product lead wants to ship regardless. How do you handle it?

Error analysis and failure-mode investigation 25% of postings

  • Run open coding on a sample of failures and turn it into a counted taxonomy
  • Slice a metric and find a regression hidden by the average, including mix-shift effects
  • Use flip analysis between two versions
  • Convert a failure mode into test cases, a targeted grader and training data without leaking between them
coreconceptMLE AI RE How do you do error analysis on a model or LLM system? Describe the procedure.

Error analysis is reading failures systematically until you can say what the failure modes are, how often each occurs and what each costs.

  1. Sample. Take 50-100 failures (and some successes for contrast) from the eval set or production, sampled randomly within the failing set so the picture is not anecdotal.
  2. Read the raw material. The full input, context, intermediate steps and output, not only the score. For agents, find the first step that went wrong; later errors are often consequences.
  3. Open coding. Write a short free-text note per example on what went wrong. Do not start from a fixed list of categories.
  4. Build the taxonomy. Group the notes into failure modes with clear definitions (retrieval miss, ignored instruction, wrong tool, format error, ambiguous request). Keep going until new examples stop producing new categories.
  5. Count and weigh. Frequency times severity per mode gives the priority order.
  6. Slice. Check whether a mode concentrates in an input type, language, length bucket, customer or tool.
  7. Act per mode. Each mode gets a fix at the right layer (data, retrieval, prompt, tool, model) and test cases in the regression set, plus a targeted grader if it should be tracked.
  8. Repeat after the fix; the distribution changes.

Useful habits: label for root cause, not symptom; check whether the label or the grader is wrong (a fraction of “errors” are evaluation bugs); have a second person code a subset to check the taxonomy is usable.

The usual mistake is skipping to dashboards and generic scores without reading examples, or fixing the three most memorable failures instead of the most frequent.

Follow-ups

  • How many examples do you read before you trust the taxonomy?
  • How would you use an LLM to scale this without losing accuracy?
seniordebuggingMLE AI RE The aggregate metric improved by a point after a model update, but complaints went up. How do you find out what happened, and how do you turn it into better data?

An average can rise while an important group gets worse.

Find the regression.

  • Flip analysis. Compare per-example results between versions. A net +1 point can be +6 points of fixes and -5 of new failures. Read the right-to-wrong set first.
  • Slice. Per-slice deltas with confidence intervals across segment, language, input length, intent, customer tier, platform. Look for a small, valuable slice with a large drop.
  • Mix shift. If slice proportions differ between the two measurements, the aggregate can move even when every slice is flat or worse (Simpson’s paradox). Compare at fixed mix.
  • Automated discovery. Cluster embeddings of the failures, or fit a shallow tree predicting error from metadata, to surface slices nobody predefined.
  • Coverage. Check whether the complaining users’ inputs are represented in the eval set at all. If not, the metric could not have seen the problem.
  • Severity. The metric may count all errors equally while the new errors are worse.

The long tail. Head inputs dominate the average; rare inputs are individually negligible and collectively large. Evaluate them deliberately: stratified sampling that over-represents the tail, with weights to recover traffic-level numbers.

Turn it into data.

  1. Add the failing cases to the regression set as a named slice with its own gate.
  2. Mine production for more of the same (nearest neighbours of the failures, rule-based filters), label them, and split into training and evaluation with no overlap, including near-duplicates.
  3. Use targeted synthetic variations and hard negatives for training only when real examples are scarce, and keep the eval real.
  4. Track the slice on every release so the regression cannot return silently.

Follow-ups

  • How do you choose slices without testing hundreds and finding noise?
  • What is the risk of adding mined failures to both training and evaluation?

Human evaluation and feedback loops 12% of postings

  • Write rater guidelines and run a pilot that exposes ambiguous cases
  • Compute Cohen’s kappa by hand and explain the prevalence effect
  • Choose between Cohen’s kappa, Fleiss’ kappa, weighted kappa and Krippendorff’s alpha
  • Detect rater drift with gold items and handle disagreement by adjudication
  • Design blinded, stratified sampling for a side-by-side evaluation
seniordesignMLE AI RE Design a human evaluation programme for a generative model. How do you get labels you can trust?

Guidelines. Define the task, each criterion and each scale level in observable terms, with worked examples and explicit rulings for edge cases. Tell raters what to ignore. Revise through pilot rounds: have several raters label the same 30-50 items, examine the disagreements, and fix the wording that caused them.

Raters. Choose experts or trained generalists according to the knowledge needed. Use a qualification test, and train on examples with explanations.

Design of the task.

  • Blind raters to which system produced each output, and randomise order and side.
  • Side-by-side comparison for sensitive detection of differences; absolute ratings for tracking a level over time.
  • Small scales (binary or three to five points) per criterion.
  • Ask for a brief justification on a subset; it improves care and helps audits.

Sampling. A stratified random sample of real inputs, not hand-picked ones; size from the confidence interval you need; the same items for all systems so comparisons are paired.

Quality control.

  • Double-label an overlap of 10-20% and report inter-rater agreement (Cohen’s or Fleiss’ kappa, Krippendorff’s alpha).
  • Seed gold items with known answers to estimate each rater’s accuracy.
  • Monitor per-rater distributions and speed; re-insert earlier items over time to detect drift.
  • Resolve disagreements by adjudication and feed the ruling back into the guidelines.

Interpreting low agreement. It usually means the task is underspecified, so fix the rubric before adding raters. Where the criterion is inherently subjective, collect several ratings per item and report the distribution.

Economics. Use human labels where they have the most leverage: calibrating automated graders, auditing samples and settling close decisions.

Follow-ups

  • Agreement is high but you suspect raters are all wrong in the same way. How do you check?
  • How many items and raters do you need to detect a 5-point preference difference?
corecodingMLE AI RE Define Cohen’s kappa, compute it for a small example, and implement it. When is it misleading?

Kappa is agreement between two raters corrected for the agreement expected by chance:

\[ \kappa = \frac{p_o - p_e}{1 - p_e}, \qquad p_e = \sum_k p_{1k}\,p_{2k}, \]

where \(p_o\) is the observed agreement and \(p_{1k}, p_{2k}\) are the fractions of items each rater assigns to category \(k\).

Example. 100 items; both say yes on 45, both say no on 35, and they split 10 and 10 on the rest. \(p_o = 0.80\). Each rater says yes 55% of the time, so \(p_e = 0.55^2 + 0.45^2 = 0.505\) and \(\kappa = (0.80 - 0.505)/0.495 \approx 0.60\).

import numpy as np

def cohens_kappa(r1, r2):
    r1, r2 = np.asarray(r1), np.asarray(r2)
    assert r1.shape == r2.shape and r1.size > 0
    labels = np.unique(np.concatenate([r1, r2]))
    index = {lab: i for i, lab in enumerate(labels)}
    C = np.zeros((len(labels), len(labels)))
    for a, b in zip(r1, r2):
        C[index[a], index[b]] += 1                 # confusion matrix between raters
    n = C.sum()
    p_o = np.trace(C) / n
    p_e = float(C.sum(axis=1) @ C.sum(axis=0)) / n**2
    return 1.0 if np.isclose(p_e, 1.0) else (p_o - p_e) / (1.0 - p_e)

When it misleads.

  • Prevalence. If both raters say “pass” 97.5% of the time, chance agreement is already about 95%, so 95% observed agreement gives \(\kappa \approx 0\). Report raw agreement and the confusion matrix alongside kappa.
  • Ordinal scales. Plain kappa treats 4 versus 5 the same as 1 versus 5; use weighted kappa.
  • More than two raters, or missing ratings. Use Fleiss’ kappa or Krippendorff’s alpha.
  • Thresholds. “0.6-0.8 is substantial” is a convention, not a guarantee of adequacy.
  • Agreement is not accuracy. Two raters can agree and both be wrong.
  • Small samples. Report a bootstrap confidence interval.

Follow-ups

  • Why is kappa near zero possible with 95% raw agreement, intuitively?
  • How would you compare an LLM judge to humans using kappa?

Red teaming and adversarial testing 8% of postings

  • Write a threat model for an LLM application (assets, adversaries, attack surfaces)
  • List attack categories and how to automate attack generation
  • Define attack success rate and pair it with a false-refusal measure
  • Feed findings into a regression suite and explain why a clean result is only a lower bound
seniordesignAI RE How would you red-team an LLM application before launch, and how do you turn the findings into something measurable?

Threat model first. What is worth protecting (user data, the ability to take actions, the brand), who attacks (curious users, abusers, a third party planting content), and through which surfaces (user messages, uploaded files and images, retrieved documents, tool results, memory).

Attack categories.

  • Jailbreaks against the content policy.
  • Prompt injection, direct and through content the system reads.
  • Data exfiltration, including system prompt and other users’ data.
  • Unsafe or unauthorised tool actions.
  • Privacy leaks and harmful or biased output.
  • Resource abuse: inputs that cause runaway cost or loops.

Methods.

  • Manual expert probing: finds novel attacks; does not scale.
  • Automated generation: an attacker model proposes and iteratively refines attacks against the target, guided by a judge of success.
  • Mutation of known attacks: encodings, other languages, role-play framing, multi-turn escalation, payload splitting.
  • Domain-specific cases: built from the application’s own tools and data.

Make it measurable. Define success per category concretely (a canary secret appears in the output, a forbidden tool call was executed, a classifier flags the content) and report attack success rate per category. Measure false refusals on a benign set at the same time, since refusing everything scores perfectly on attacks.

Process. Triage findings by severity and exploitability; fix at the right layer (permissions and validation before prompt wording); add each finding to a regression suite run on every model, prompt and tool change; repeat periodically and after capability changes.

Limits. A red-team result is a lower bound on vulnerability: not finding an attack does not show that none exists. Static attack sets go stale as models and attackers adapt.

General robustness testing uses the same frame: perturb inputs (typos, paraphrase, format changes, distribution shift) and measure how much the metric drops.

Follow-ups

  • How do you grade whether an attack succeeded without a human reading every transcript?
  • Attack success rate fell after a fix, and so did helpfulness. What do you report?

A/B testing and online experimentation 8% of postings

  • Choose the randomisation unit and explain what goes wrong when the analysis unit is finer
  • Derive the two-sample sample-size formula and use the 16 sigma squared over delta squared shortcut
  • Explain why peeking inflates false positives and name two valid sequential methods
  • Derive CUPED, state its variance reduction and its requirements
  • Recognise interference and pick cluster, switchback or two-sided designs
  • Explain interleaving and what it cannot measure
  • List reasons a significant win fails to hold after launch, and what to do when no A/B test is possible
coreconceptMLE AI Walk me through setting up an A/B test for a model change. What is the randomisation unit and what do you check before trusting the result?

Setup.

  • Hypothesis and metrics: one primary metric, guardrails, and the minimum effect worth detecting, written down before launch.
  • Randomisation unit: usually the user, hashed with an experiment-specific salt, so the experience is consistent and units are independent. Sessions or requests give more samples but users see both variants and observations are correlated. Use clusters (regions, groups) when users affect each other.
  • Analysis unit: if it is finer than the randomisation unit (page views analysed, users randomised), observations within a user are correlated and a naive variance is too small. Use the delta method, cluster-robust errors, or a bootstrap over users.
  • Size and duration: from a power calculation; run whole weeks to cover weekly cycles.
  • Exposure: analyse users who could have seen the change (triggered analysis), with the trigger defined identically in both arms, to avoid diluting the effect.

Checks before reading the result.

  • Sample ratio mismatch. Compare assignment counts to the design with a chi-square test. With a million users, a 50.5/49.5 split gives \(\chi^2 = 100\): something is broken (assignment, logging, bots, redirects) and the result cannot be trusted.
  • A/A behaviour: the pipeline should show no effect when there is none.
  • Pre-period balance on key metrics.
  • Logging parity between arms.

Reading it. Effect size with a confidence interval, not only a p-value; guardrails; the effect over time; a small number of pre-declared segments.

Common errors. Stopping when the result first looks significant, choosing the metric afterwards, and ignoring a sample ratio mismatch.

Follow-ups

  • Why hash with an experiment-specific salt?
  • Which unit would you randomise for a change to search ranking, and why?
seniorderivationMLE AI Derive the sample size needed per arm for an A/B test and give a worked example.

Two arms of \(n\) units each, metric variance \(\sigma^2\), true difference \(\delta\). The estimator \(D = \bar Y_T - \bar Y_C\) has standard error \(\mathrm{SE} = \sqrt{2\sigma^2/n}\).

  • Under \(H_0\), \(D \sim N(0, \mathrm{SE}^2)\); a two-sided test at level \(\alpha\) rejects when \(|D| > z_{1-\alpha/2}\,\mathrm{SE}\).
  • Under the alternative, \(D \sim N(\delta, \mathrm{SE}^2)\), so the power is approximately \(\Phi(\delta/\mathrm{SE} - z_{1-\alpha/2})\).
  • Requiring power \(1 - \beta\) gives \(\delta/\mathrm{SE} = z_{1-\alpha/2} + z_{1-\beta}\).

Solving for \(n\):

\[ n = \frac{2\sigma^2\,(z_{1-\alpha/2} + z_{1-\beta})^2}{\delta^2}. \]

For \(\alpha = 0.05\) and 80% power, \((1.96 + 0.84)^2 \approx 7.85\), which gives the rule of thumb \(n \approx 16\,\sigma^2/\delta^2\) per arm.

Example. Baseline conversion 10%, so \(\sigma^2 = p(1-p) = 0.09\). To detect a 2% relative lift, \(\delta = 0.002\):

\[ n \approx \frac{16 \times 0.09}{0.002^2} = 360{,}000 \text{ users per arm.} \]

What follows from the formula.

  • Halving the detectable effect quadruples the sample.
  • Reducing variance is as good as adding traffic: CUPED, stratification, trimming or capping heavy-tailed metrics, triggered analysis.
  • \(\sigma^2\) is at the level of the randomisation unit. For ratio metrics such as clicks per impression with user randomisation, get the variance by the delta method.
  • Unequal allocation costs power: the factor 2 becomes \(1/r + 1/(1-r)\) for split \(r\).
  • An underpowered test that reaches significance overstates the effect.

Duration is \(n\) divided by eligible daily traffic, rounded up to whole weeks.

Follow-ups

  • The metric is revenue per user with a heavy tail. What do you change?
  • What is the minimum detectable effect if you only have 50,000 users per arm?
seniorconceptMLE AI Why is it wrong to check an A/B test daily and stop when it reaches significance? What do you do if you need to stop early?

A fixed-sample test controls the false positive rate at \(\alpha\) for one look at a pre-set sample size. The test statistic wanders over time; stopping the first time it crosses the threshold takes the maximum over many correlated looks. With no true effect, the chance of a false positive at a nominal 5% rises to roughly 14% with five equally spaced looks and about 19% with ten, and keeps growing with more. The estimated effect at an early stop is also biased upward.

Looking is fine. Deciding from an unadjusted look is the problem.

Valid ways to stop early.

  • Group sequential designs. Fix the number of interim analyses and spend \(\alpha\) across them. O’Brien-Fleming boundaries are very strict early and close to the fixed-sample threshold at the end; Pocock uses the same threshold at every look and pays for it at the final one. Alpha-spending functions allow flexible timing.
  • Always-valid inference. Sequential probability ratio tests (mSPRT) and confidence sequences give p-values and intervals valid at any stopping time, at the price of somewhat wider intervals than a fixed-horizon test.
  • Fixed horizon with discipline. Compute the sample size, run to it, decide once.

Bayesian analysis does not remove the issue by itself; stopping when a posterior probability crosses a threshold has its own error properties that depend on the prior and the rule.

Asymmetry. Stopping early for harm is reasonable: use a looser boundary on guardrail metrics so a damaging variant is shut down quickly.

Even with valid early stopping, run at least a full week so the result covers the weekly cycle, and expect novelty effects in early data.

Follow-ups

  • Your dashboard shows p-values that update hourly. What would you change?
  • Why are early-stopped effect estimates biased, and in which direction?
seniorderivationMLE What is CUPED? Derive the adjustment and the variance reduction, and state when it does not work.

CUPED reduces the variance of an experiment metric by subtracting the part explained by a covariate measured before the experiment.

For each user, let \(Y\) be the in-experiment metric and \(X\) a pre-experiment covariate, usually the same metric over the weeks before. Define

\[ Y^{cv} = Y - \theta\,(X - \bar X). \]

Unbiased. \(X\) was measured before assignment, so its expectation is the same in both arms, and the adjustment cancels in the difference of means for any \(\theta\).

Optimal \(\theta\). \(\mathrm{Var}(Y - \theta X) = \mathrm{Var}(Y) - 2\theta\,\mathrm{Cov}(X, Y) + \theta^2\,\mathrm{Var}(X)\) is minimised at

\[ \theta^* = \frac{\mathrm{Cov}(X, Y)}{\mathrm{Var}(X)}, \qquad \mathrm{Var}(Y^{cv}) = \mathrm{Var}(Y)\,(1 - \rho^2), \]

where \(\rho\) is the correlation of \(X\) and \(Y\). This is the regression coefficient of \(Y\) on \(X\); CUPED is regression adjustment.

Effect. With \(\rho = 0.5\) variance falls by 25%; with \(\rho = 0.7\) by 51%, which is the same as doubling traffic. Sample size scales with variance, so the required sample shrinks by the same factor.

Practice. Estimate \(\theta\) on pooled data from both arms. Pre-period length is a tuning choice: longer raises correlation up to a point.

When it does not work or goes wrong.

  • New users have no pre-period data: no gain for them (impute the mean, or handle them as a separate stratum).
  • Metrics with little persistence across time have low \(\rho\).
  • A covariate affected by the treatment (anything measured after assignment) biases the estimate. This is the rule that must not be broken.
  • For ratio metrics, apply it with the delta method on numerator and denominator.

Follow-ups

  • Why estimate theta on pooled data rather than per arm?
  • What other covariates could you use besides the pre-period metric?
stafftrade-offMLE When does a user-randomised A/B test give the wrong answer because of interference, and how do you design around it?

A/B analysis assumes one unit’s outcome does not depend on other units’ assignments. It fails when units share something.

Where it fails.

  • Two-sided marketplaces. Treated riders who book more take drivers from control riders. Treatment looks better and control looks worse, so the measured effect overstates what a full launch would deliver.
  • Social and communication products. A feature that makes treated users message more also raises activity among their control friends. The contrast shrinks and the effect is understated.
  • Shared budgets and inventory. Ad budgets, stock, ranking slots.
  • Shared models and caches. Both arms feed one training set or one cache, so the control arm is contaminated by the treatment’s data.

Designs.

  • Cluster randomisation. Randomise connected groups together: geographies, or clusters from the interaction graph. The cost is far fewer independent units, so lower power, and leakage across cluster boundaries remains.
  • Switchback. Randomise time slices within a region, alternating treatment and control. Standard for marketplace pricing and dispatch. It needs a slice length longer than the carry-over and a washout or carry-over model.
  • Two-sided randomisation. Randomise both sides (buyers and sellers) to estimate spillover.
  • Budget-split. Give each arm its own share of budget or inventory so they do not compete.
  • Separate model or data pipelines per arm when the feedback loop is the concern.

Analysis. Standard errors at the level of randomisation (cluster or time slice).

Detecting interference. Run the same change user-randomised and cluster-randomised; a difference in estimates is evidence of spillover. Checking whether control-arm metrics move as the treatment share ramps is another sign.

Follow-ups

  • How long should a switchback period be?
  • A ranking model trains on data from both arms. What bias does that create?
seniortrade-offMLE What is interleaving, why is it more sensitive than an A/B test for ranking, and what can it not tell you?

Interleaving shows each user one result list merged from two rankers and infers preference from which ranker’s results get clicked.

Team-draft interleaving. For each query, the two rankers take turns, in an order randomised per round, adding their highest-ranked result not yet in the list; each result is tagged with the team that contributed it. Clicks are credited to teams. A query is a win for the ranker with more credited clicks, and wins are compared across queries with a sign or binomial test.

Why it is more sensitive. Each user is their own control. Differences between users (heavy versus light clickers) and between queries, which dominate the variance of an A/B test, cancel. Published reports from search and streaming companies describe needing one to two orders of magnitude fewer samples than an A/B test for the same ranking comparison; the factor depends on the product.

What it cannot do.

  • It gives a relative preference, not the size of the effect on revenue, retention or sessions.
  • It applies only to changes expressible as a reordering in the same slot. It cannot test latency, layout, or a new result type.
  • It relies on clicks, with their position and attractiveness biases; it says nothing about satisfaction after the click.
  • The merged list is not what either ranker would have shown, so whole-page effects such as diversity are distorted.
  • It adds serving complexity.

Use. A fast filter: interleave many ranker candidates, discard the losers within days, then run a conventional A/B test on the few winners to measure business metrics and guardrails.

Follow-ups

  • Why randomise which ranker picks first?
  • Two rankers return nearly identical lists. What happens to the test?
seniordebuggingMLE AI An A/B test showed a significant win. Three months after launch the metric is back where it started. What happened, and how would you have caught it?

Candidate explanations.

  1. Novelty. Users engaged with something new and the effect decayed. Visible in the experiment as an effect that shrinks with days since first exposure.
  2. False positive. Peeking, many metrics or segments examined, or many experiments run with the winners launched.
  3. Winner’s curse. Even a real effect is overestimated when it is selected for being significant, most strongly in underpowered tests. The true lift was smaller than reported.
  4. Launch differs from test. At 100% the interference pattern changes (marketplace competition, shared budgets), capacity or latency is worse, or the launched code is not the tested code.
  5. Interaction. Other launches since then removed or absorbed the gain.
  6. Population. The test ran on a subset (new users, one platform, a triggered group) that does not represent everyone.
  7. Timing. The test covered a holiday or campaign period.
  8. The metric moved for other reasons. The trend is not a counterfactual: the launch may still be helping against a decline elsewhere, or the logging changed.

Investigation. Re-examine the original test: power, interval, pre-registration, the effect by day and by cohort, sample ratio. Then measure the current effect directly with a holdback or by turning the feature off for a small group.

Catching it earlier.

  • A long-term holdback of 1-5% of users kept on control after launch.
  • Running tests long enough to see the time trend, and analysing by exposure cohort.
  • Replicating surprising wins before relying on them.
  • Discounting reported lifts when forecasting cumulative impact; the sum of experiment wins always exceeds the realised gain.

Follow-ups

  • How do you distinguish novelty from a real effect inside a two-week test?
  • Your team launched ten wins this quarter. How do you estimate the true total impact?
stafftrade-offMLE AI You cannot run an A/B test for this change. What are your options for estimating its effect?

First ask why not, because the reason picks the method.

No unit can be randomised fairly (pricing, legal or ethical limits, a marketing campaign).

  • Geo experiments: randomise regions, or treat some regions and build a synthetic control from a weighted mix of untreated ones.
  • Staggered rollout: release in a random order over time and compare not-yet-treated with treated.
  • Encouragement design: randomise a nudge and use it as an instrument for uptake.

The change already happened or was global.

  • Difference-in-differences against an unaffected group; requires parallel trends, which you check on the pre-period.
  • Interrupted time series or Bayesian structural time series with control series; fragile to anything else that changed at the same time.
  • Regression discontinuity when treatment was assigned by a threshold; estimates the effect near the threshold only.
  • Matching or inverse propensity weighting on observational data; assumes no unobserved confounders, the weakest assumption of the set.

Too little traffic. Use more sensitive designs and metrics: within-subject comparison, interleaving for ranking, variance reduction, a proxy metric closer to the change, a longer test, or accept a larger minimum detectable effect and say so.

A ranking or policy change with logged data. Off-policy evaluation with inverse propensity scoring or doubly robust estimators, which requires that the logging policy was randomised with recorded propensities.

An LLM product before launch. Offline evals on replayed traffic, blinded human side-by-side comparison, shadow mode, and a staged rollout with monitoring.

For any of these. State the identifying assumption, test it where possible (placebo periods, placebo outcomes, pre-trend checks), report sensitivity, and present the result with less confidence than a randomised test would earn.

Follow-ups

  • How do you test the parallel-trends assumption?
  • What must be logged today to make off-policy evaluation possible later?

Deep dives on this site