Skip to content
Data for AI Core 41 min read

Data in production: drift, monitoring, feedback loops

A model is a snapshot of a distribution, and the moment it ships the distribution starts to move: users change, upstream pipelines change, the world changes, and the model itself changes what happens next. This page is about noticing, measuring and correcting that movement: what to monitor when labels arrive late or never, which statistics detect shift and what they cannot see, how to correct for shift without new labels, and how a deployed model quietly writes its own future training data.

10,000 ft

Every guarantee in evaluation rests on one assumption: test data and future data come from the same distribution as training data. Production breaks that assumption in three ways. Pipelines break (a unit changes, a column goes null, a feature is computed differently at serving time). The world drifts (new users, new products, seasons, a pandemic). And the model acts on the world (a recommender shapes what is clicked, a credit model decides whose repayment is ever observed, an assistant's answers end up on the web its successor is trained on). The discipline that handles this sits between MLOps, statistics and causal inference. It closes the loop of this track: data is collected, filtered, labelled, and then, in production, generated again.

2,000 ft

Treat a deployed model as a loop, not a pipe. Requests from the world pass through serving; everything (inputs, outputs, model and prompt versions, feedback) is logged; monitors watch that log at several layers; an alert triggers a diagnosis that asks one question first (is this a bug, a real shift, or a loop the model created?), and the action follows from the answer: fix the pipeline, re-weight or recalibrate, retrain, or roll back. Two dashed edges make it a loop: the log becomes training data, and the model's decisions change what the world does next.

The production data loop
The production data loop. The world users, markets, sensors, Serving features + model + prompt, Logged inputs, outputs, versions, feedback, Monitors quality, drift, performance, Diagnose bug, shift or loop?, Act fix pipeline, recalibrate, retrain, roll back, requests, alert, new version, decisions change what happens next, training dataThe production data loop. The world users, markets, sensors, Serving features + model + prompt, Logged inputs, outputs, versions, feedback, Monitors quality, drift, performance, Diagnose bug, shift or loop?, Act fix pipeline, recalibrate, retrain, roll back, requests, alert, new version, decisions change what happens next, training data

  1. Log everything needed to replay a prediction: the exact features or prompt the model saw, its output, and every version involved.
  2. Monitor in layers, from cheap and fast (schema, nulls, latency) to slow and meaningful (accuracy on delayed labels, business outcome).
  3. Detect shift with two-sample tests, but judge it by effect size and by its effect on the model, not by p-values.
  4. Name the kind of shift (covariate, label, concept), because each has a different correction and some cannot be seen without labels.
  5. Break feedback loops on purpose with exploration, logged propensities and held-out traffic.

Ground level

What actually goes wrong

When practitioners describe production failures, the headline is rarely an elegant concept drift. It is a pipeline. Google's Rules of Machine Learning define training–serving skew as a difference between performance during training and during serving, and list three causes: a discrepancy between how the training and serving pipelines handle data, a change in the data between training and serving, and a feedback loop between the model and the algorithm. The same guide records that a stale table in Google Play, left unrefreshed for six months, cost 2% of install rate when it was finally refreshed, and it uses as its example of silent breakage a feature column that drops from 90% coverage to 60%. The team that built TensorFlow Data Validation reports that it runs at Google across hundreds of product teams and petabytes of data a day precisely because such errors are common and cheap to catch early (Polyzotis et al., 2019). An interview study of 18 ML engineers found the same thing from the human side: production work is dominated by validation, versioning and debugging data, not by modelling (Shankar et al., 2022).

So the taxonomy of production problems has four branches, in rough order of frequency:

Problem What changed Example Detectable without labels?
Pipeline bug / skew the code between world and model a currency switches from rupees to lakhs; a feature is computed with a 1-day lag at training and none at serving yes: schema, range and skew checks
Covariate shift \(p(\mathbf{x})\) a marketing push brings younger users; a new phone model changes image statistics yes
Label (prior) shift \(p(y)\) fraud rate doubles during a festival season; flu prevalence rises in winter partly: via the prediction mix
Concept shift \(p(y \mid \mathbf{x})\) the same transaction pattern now means fraud; the same query now wants a different answer no, not even in principle

The first row is an engineering failure with an engineering fix. The other three are the statistics of dataset shift: the joint distribution \(p(\mathbf{x}, y)\) the model meets in production is not the one it was fitted to. It helps to see the three side by side.

Covariate shiftp(x) moves; p(y|x) fixedp(y=1|x)Label shiftp(y) moves; p(x|y) fixedy = 0y = 1Concept shiftp(x) fixed; p(y|x) movesp(y=1|x)p(x)trainingproductionunchanged
The three kinds of dataset shift. Covariate shift: inputs move into a different region while the rule mapping inputs to labels stays put. Label shift: each class still looks the same, but their proportions change (here class 0 becomes far more common). Concept shift: the inputs look exactly as before, but the rule has moved, so nothing computed from inputs alone can reveal it.

Why the factorisation matters

The joint distribution can be factored two ways, \(p(\mathbf{x}, y) = p(\mathbf{x})\,p(y \mid \mathbf{x}) = p(y)\,p(\mathbf{x} \mid y)\), and each named shift says which factor moved while the other stayed put (Moreno-Torres et al., 2012 give the unifying definitions). This is not pedantry; it is the whole basis of correction:

  • Covariate shift keeps \(p(y \mid \mathbf{x})\). If the model learned that conditional well wherever it saw data, it is still right there; what changes is where it is evaluated. The fix is to re-weight training examples towards the new \(p(\mathbf{x})\) (importance weighting), and the danger is regions the training data never covered.
  • Label shift keeps \(p(\mathbf{x} \mid y)\): a positive case still looks like a positive case, there are just more or fewer of them. Bayes' rule then says exactly how the model's posterior should change, and the new prior can be estimated from unlabelled data.
  • Concept shift changes the mapping itself. No re-weighting of old data helps, and no statistic of \(\mathbf{x}\) can detect it, because \(p(\mathbf{x})\) may not have moved at all. Only fresh labels reveal it.

Which assumption is plausible is a causal question. Label shift fits problems where \(y\) causes \(\mathbf{x}\): a disease causes symptoms, so when prevalence rises, the symptoms of each disease stay the same. Covariate shift fits problems where \(\mathbf{x}\) causes \(y\), or where the change is in who arrives (a new acquisition channel) rather than how the world works.

Monitoring in layers

The fundamental constraint of production monitoring is label delay. A recommender learns whether you clicked within seconds; a fraud model learns about a chargeback weeks later; a credit model learns whether a loan defaults after months or years; an LLM assistant usually never learns whether its answer was right. So you monitor what you can see now as a proxy for what you will see later, and you stack signals from fastest to most meaningful:

What to monitor, from fastest to most meaningful
What to monitor, from fastest to most meaningful. 1. System health latency, errors, cost, timeouts, 2. Data quality schema, nulls, ranges, freshness, volume, 3. Input drift feature and embedding distributions, 4. Output drift prediction mix, confidence, length, refusals, 5. Proxy and feedback signals clicks, thumbs, edits, escalations, 6. Ground-truth performance accuracy, calibration, per slice, What to monitor, from fastest to most meaningful. 1. System health latency, errors, cost, timeouts, 2. Data quality schema, nulls, ranges, freshness, volume, 3. Input drift feature and embedding distributions, 4. Output drift prediction mix, confidence, length, refusals, 5. Proxy and feedback signals clicks, thumbs, edits, escalations, 6. Ground-truth performance accuracy, calibration, per slice,

The top layers are fast, cheap and noisy about what matters; the bottom layers are slow, expensive and exactly what matters. Three practical rules follow.

  • Data-quality checks are assertions, not statistics. A schema (types, allowed values, ranges, required fields, expected volume) catches most pipeline bugs deterministically. Write it down from the training data, review it like code, and fail loudly on violation. Rule #37 of the Google guide gives the ultimate skew test: run the same example through the training and serving paths and check that the predictions are identical. Rule #29 removes the most common cause: log the features as computed at serving time and train on those logs.
  • Monitor the model's outputs, not just its inputs. A model compresses hundreds of input features into one prediction; drift in an unused feature is noise, while drift in the predicted class mix or the confidence distribution is drift the model actually felt. Rabanser, Günnemann and Lipton's empirical study of shift detection found that two-sample tests on the outputs of a pre-trained classifier ("black-box shift detection") worked surprisingly well across a broad set of shifts, even ones that violated the label-shift assumption the method was derived under (Failing Loudly, 2019).
  • Slice everything. An aggregate metric that holds steady can hide a new segment that fails completely while the old majority improves. Monitor per language, per region, per device, per customer tier, per intent: the slices where you expect shift to arrive first.

Drift statistics, and what a number means

For one feature, a two-sample test compares a reference window (training data, or last month) with a production window. Four statistics cover most needs:

Statistic Definition Good for Watch out
PSI (population stability index) \(\sum_i (a_i - e_i)\ln(a_i/e_i)\) over bins binned numeric or categorical features; effect size depends on binning; biased upward at small \(n\)
Kolmogorov–Smirnov \(D = \sup_x \lvert F_{\text{ref}}(x) - F_{\text{cur}}(x)\rvert\) continuous features; gives a p-value p-value goes to zero for trivial shifts at large \(n\)
Chi-squared \(\sum_i (O_i - E_i)^2 / E_i\) categorical features same large-\(n\) problem
Domain classifier AUC of a model trained to tell reference from production many features or embeddings at once needs held-out evaluation; AUC 0.5 means no detectable shift

For embeddings and other high-dimensional inputs, univariate tests on every coordinate are hopeless (hundreds of tests, all correlated). The options are a multivariate kernel test such as maximum mean discrepancy, univariate tests on a low-dimensional projection (PCA, or better, the model's own outputs), or a domain classifier. The domain classifier has a second gift, used later on this page: its predicted probabilities are a density-ratio estimate, so it also tells you how to re-weight.

A worked PSI. A feature was split into four quartile bins on the training data, so the expected shares are \(e = (0.25, 0.25, 0.25, 0.25)\). This week's production shares are \(a = (0.10, 0.20, 0.30, 0.40)\). Term by term:

Bin \(e_i\) \(a_i\) \(a_i - e_i\) \(\ln(a_i/e_i)\) term
1 0.25 0.10 −0.15 −0.9163 0.1374
2 0.25 0.20 −0.05 −0.2231 0.0112
3 0.25 0.30 +0.05 +0.1823 0.0091
4 0.25 0.40 +0.15 +0.4700 0.0705
PSI 0.2282

Every term is non-negative (the two factors always share a sign), so bins cannot cancel. The conventional reading, inherited from credit scoring, is that PSI below 0.1 is stable, 0.1 to 0.25 deserves a look, and above 0.25 is a major shift; 0.23 would get a look. These thresholds are folk rules, not theorems. The maths section shows that PSI is exactly the symmetrised KL divergence, which gives it a meaning, and also that it has a bias you must subtract at small samples.

Significance is not importance. Run the code in Build it and you will see a feature whose mean moved by 0.05 standard deviations: PSI 0.0027 (nothing), KS p-value \(6.6\times10^{-12}\) (overwhelming). With 50,000 samples per window a KS test detects shifts far too small to matter. Use tests to ask "is there any shift at all?" on small windows, use effect sizes (PSI, KS \(D\), Wasserstein distance in the feature's own units) to ask "how much?", and decide alert thresholds from what the shift does to the model, ideally measured by replaying historical shifts. Then correct for multiple comparisons: 300 features tested daily at \(\alpha = 0.05\) give about 15 false alarms a day, which is how drift dashboards come to be ignored.

The picture to keep

Drift detection is a smoke alarm with a sensitivity dial. Turned up (large windows, p-values), it goes off when you make toast. Turned down (PSI thresholds), it can miss a slow fire. The dial should be set by the cost of the fire, which means by the model's sensitivity to each feature, not by the feature's own statistics.

Correcting label shift without new labels

Label shift is the one kind of shift you can both detect and correct from unlabelled production data, because of a simple identity. If \(p(\mathbf{x} \mid y)\) is unchanged, the model's confusion behaviour per true class is unchanged too, so the distribution of predicted labels in production is a known linear mixture of the unknown production class prior.

A worked example. A fraud model has sensitivity 0.9 and false-positive rate 0.2, measured on validation data where fraud prevalence was 20%. In production it flags 30% of transactions. If only the prevalence \(\pi\) changed:

\[ 0.30 = 0.9\,\pi + 0.2\,(1 - \pi) \quad\Longrightarrow\quad \pi = \frac{0.30 - 0.2}{0.9 - 0.2} = 0.143. \]

Fraud prevalence has fallen to about 14%, even though the flag rate looks high. Now correct the model's probabilities. A transaction scored 0.5 under the training prior has posterior odds 1; the prior odds moved from \(0.2/0.8 = 0.25\) to \(0.143/0.857 = 0.167\), a factor of \(0.667\), so the corrected odds are \(0.667\) and the corrected probability is \(0.667/1.667 = 0.40\). With more than two classes this becomes a small linear system, black-box shift estimation (Lipton, Wang and Smola, 2018), and the Build it code solves a three-class version that recovers the true production prior (0.581, 0.319, 0.100 against a true 0.6, 0.3, 0.1) and the oracle accuracy, from unlabelled data alone. The older alternative is an EM procedure that alternates between re-weighting posteriors and re-estimating the prior (Saerens, Latinne and Decaestecker, 2002); it needs calibrated probabilities, while BBSE needs only an invertible confusion matrix.

Correcting covariate shift: importance weights

Under covariate shift, any expectation over the production distribution can be rewritten as a weighted expectation over the training distribution, with weight \(w(\mathbf{x}) = p_t(\mathbf{x})/p_s(\mathbf{x})\). That gives two uses: re-weight the training loss to fit the production distribution (Shimodaira, 2000), and, more often in practice, estimate production accuracy from old labels. The density ratio comes from the domain classifier: train it to separate reference from production, and its odds, rescaled by the sample sizes, are \(w\).

In the Build it simulation the model's accuracy on reference data is 0.868; production inputs have moved towards a region where the model is weak; the importance-weighted estimate from reference labels only is 0.635, against a true (hidden) production accuracy of 0.636. The price shows in the weights: the largest is 92, and 20,000 reference examples carry the information of about 4,500. The further the shift, the fewer effective samples, and when production reaches regions the reference never covered, the weight is infinite and no re-weighting can help. That is the moment to label new data.

Estimating performance without any labels. If the model's probabilities are calibrated on the production distribution, its expected accuracy is the mean of its confidence; tools such as NannyML's confidence-based performance estimation build on this. Calibration itself degrades under shift, so a refinement learns a confidence threshold on labelled source data such that the share of source examples above it matches source accuracy, then reports the share of production examples above it (Garg et al., 2022). All such estimators assume no concept shift; treat them as early warnings, and keep a trickle of fresh labels as the ground truth.

Feedback loops: the model changes its own data

The subtlest production problems are not caused by the world drifting on its own but by the model pushing it. Sculley et al. (2015) named these hidden feedback loops in their catalogue of ML technical debt. They come in four shapes.

How a model writes its own future training data
How a model writes its own future training data. Model version t, Action rank, approve, flag, answer, World reacts only to what was shown or allowed, Logged outcomes labels exist only for chosen actions, Retrain on the log, version t+1, Exploration and logged propensities, keeps the log informativeHow a model writes its own future training data. Model version t, Action rank, approve, flag, answer, World reacts only to what was shown or allowed, Logged outcomes labels exist only for chosen actions, Retrain on the log, version t+1, Exploration and logged propensities, keeps the log informative

Selective labels. A credit model approves some applicants; repayment is observed only for them. Retrain on that log and the model learns \(p(y \mid \mathbf{x}, \text{approved})\); it never gets evidence about the people it rejects, so a segment wrongly rejected stays rejected forever. Lakkaraju et al. formalised this as the selective labels problem (2017); it is the ML form of Heckman's sample-selection bias from econometrics.

Degenerate loops in ranking. A recommender shows what it predicts will be clicked; only shown items can be clicked; clicks become training data. Items it underrates are never shown, so the underrating is never corrected, and the log comes to measure the old model's taste as much as the users'. The bandits page makes this precise: a greedy policy can lock onto a worse arm forever, and exploration is what buys information.

Runaway amplification. Ensign et al. modelled predictive policing with Pólya urns: patrols go where past incidents were recorded, and incidents are discovered where patrols go. Without correction the allocation runs away from the true crime rates, towards whatever the system happened to believe early on. Their fix filters the data rather than the model: if police are sent to area A 90% of the time, an incident discovered there is kept only 10% of the time, a rejection-sampling form of the Horvitz–Thompson estimator, and the system then learns the true rates (Runaway Feedback Loops in Predictive Policing, 2018).

Performativity. Sometimes the prediction changes the very outcome it predicts: a credit score changes how applicants behave, a traffic forecast changes routes. Perdomo et al. call this performative prediction (2020): the data distribution is a function \(\mathcal{D}(\theta)\) of the deployed parameters. Repeatedly retraining on the data your last model induced converges, under smoothness and strong-convexity conditions and when the distribution is not too sensitive to \(\theta\), to a performatively stable point: a model that is optimal for the distribution it itself creates. That point need not be the model with the lowest loss you could achieve if you accounted for your own influence.

The remedies share one idea: keep some of the data independent of the model. Hold out a small random slice of traffic that the model does not decide (a random approval band, random recommendations, a control group); log the probability with which each action was taken, so that later models can be trained and evaluated with inverse-propensity weights, the counterfactual approach Bottou et al. used on Bing's ad placement (Counterfactual Reasoning and Learning Systems, 2013); and version every model so the log can say which policy produced each row.

Your test set is downstream of your model too

If evaluation data is sampled from production logs, it inherits the deployed model's selection. A new model that would serve users the old one never showed can look worse on such a test set simply because those cases are absent. Evaluate candidate policies on randomised traffic, or with propensity-weighted off-policy estimators, not on the champion's own log.

Data in production for LLM systems

Language-model products have the same loop with different instruments.

  • Inputs are text, so drift is semantic. Embed the prompts and monitor the embedding distribution with a domain classifier, or cluster them and track the cluster mix (topics, intents, languages, lengths). A new cluster is often a new use case nobody designed for.
  • Outputs need a judge. Ground truth rarely arrives, so teams sample production traffic and score it with rubric-based LLM judges and periodic human review, the machinery of evals in practice. Cheap output monitors (length, refusal rate, tool-call error rate, schema-validation failures, latency, cost per request) catch many regressions before any judge runs.
  • The model under you can change. Chen, Zaharia and Zou compared March and June 2023 versions of GPT-3.5 and GPT-4 behind the same API names and found large behaviour changes; GPT-4's accuracy at identifying prime versus composite numbers fell from 84% to 51% (How is ChatGPT's behavior changing over time?, 2023). Pin model versions where the provider allows it, log the version on every request, and re-run your golden set whenever any version (model, prompt, retrieval index, embedding model, tool schema) changes. Re-embedding a corpus with a new embedding model is a schema change for a RAG index: old and new vectors are not comparable.
  • User feedback is a biased label. Thumbs-up and thumbs-down come from a self-selected few, skew towards strong reactions, and reward answers that please over answers that are right. Implicit signals (the user rephrased, copied the answer, escalated to a human, abandoned) are more plentiful and also biased. Use them to find cases for human review and golden sets, not as training labels without review; labelling and human feedback covers how to turn them into reliable labels.
  • The web is now partly model-written. When generative models are trained recursively on generated data, the tails of the original distribution disappear first and later generations collapse towards a narrow mode (Shumailov et al., Nature 2024). Every lab's future crawl contains its predecessors' outputs; provenance and the mixing of fresh human data (collection and curation) are the defence.
  • Production traces are the best fine-tuning and eval data you will get, and the most dangerous. They contain personal data, they over-represent what the current system already handles, and an assistant's failures are often the cases users stopped attempting. Curate them deliberately, with consent and redaction, and sample failures on purpose.

How this shows up in Jarvis

In Jarvis code computes and the model routes and explains, so the production data that matters most is not the model's text but two distributions around it. The mix of questions users ask is the router's input distribution, and it moves with the calendar (tax season, a market fall, salary months): that is covariate shift on intent, and the per-intent slices are where to look first. The contract with the planning engine (field names, units, which numbers are nominal and which are in today's money) is the training–serving-skew surface: a renamed or re-scaled field produces fluent, confident, wrong explanations that no drift statistic on text would flag. Live fixtures that pin that contract are Jarvis's data-quality layer, the equivalent of a schema check.

Retraining: when, on what, and how to ship it

Retraining is not free and not automatically safe. The usual policies, roughly in order of maturity:

  • Scheduled retraining (nightly, weekly) is simple and handles slow drift, but wastes compute when nothing changed and is too slow for sudden shifts.
  • Triggered retraining fires on a monitor (drift above a threshold, performance below one). Use it with care: a trigger on input drift alone retrains on pipeline bugs.
  • Continual or online updating suits fast-moving targets such as ads and feeds, at the cost of needing strong automated validation, because there is no human between data and deployment.

Whatever triggers it, the new model should pass the same gate: train on a point-in-time-correct dataset (features as they were known at prediction time, never later values, the leakage trap from features and tabular data); evaluate on a recent held-out window and on fixed golden slices; deploy in shadow (predict on live traffic without acting) and compare; then canary to a small share with automatic rollback. Keep the previous model warm. And retrain from versioned data, so that any model can be rebuilt and any row can be traced back to its source.

A famous drift: Google Flu Trends

Launched in 2008, Google Flu Trends estimated influenza-like illness from search queries. In February 2013 Nature reported that it was predicting more than double the proportion of doctor visits that the US Centers for Disease Control reported. Lazer et al. found that it had overestimated in 100 of 108 weeks from August 2011, with errors that were autocorrelated and seasonal. They blamed two things: overfitting (the original model picked 45 terms out of about 50 million candidates to fit 1,152 data points), and "algorithm dynamics", Google's own changes to search, such as suggested additional search terms, which altered what people typed. They also showed that simply recalibrating against CDC data available with a two-week lag would have removed most of the error (The Parable of Google Flu, 2014). Every branch of this page is in that story: an upstream system changed the inputs, the relationship between queries and illness drifted, and nobody recalibrated against the delayed ground truth.

History

Concept drift was named in machine learning by Schlimmer and Granger's 1986 paper Incremental learning from noisy data, whose STAGGER system tracked a target concept that changed over time; Widmer and Kubat's Learning in the presence of concept drift and hidden contexts (1996) added windowing and the idea that drift is often a hidden context switching. The statistical side arrived from econometrics, where Heckman's 1979 work on sample-selection bias was the ancestor of selective labels, and from Shimodaira's 2000 analysis of covariate shift and importance-weighted likelihood. The 2009 MIT Press volume Dataset Shift in Machine Learning (Quiñonero-Candela, Sugiyama, Schwaighofer and Lawrence) gathered the field, and Gama et al.'s survey on concept drift adaptation (2014) organised the streaming-data methods.

The production view came from industry. Sculley et al.'s Hidden Technical Debt in Machine Learning Systems (NeurIPS 2015) named feedback loops, undeclared consumers and data dependencies as the costs nobody budgets for; Google's Rules of ML and the TFX data-validation system (2017–2019) turned training–serving skew into something you can test. In deep learning, Lipton et al. (2018) and Rabanser et al. (2019) made shift detection practical for high-dimensional models, WILDS (Koh et al., 2021) collected real distribution shifts from hospitals, satellites, wildlife cameras and code into a benchmark, and performative prediction (2020) gave the feedback loop a formal theory. The LLM era added two new chapters: models drifting behind stable API names, and models training on their own outputs.

First principles

Why shift is inevitable. Learning theory's guarantees bound the error on new samples from the training distribution. Nothing in empirical risk minimisation says anything about another distribution. A deployed model is used in the future, and the future is a different distribution whenever anything that generated the data has a time dependence: user mix, product, prices, language, adversaries. Adversarial domains (fraud, spam, abuse) are the extreme: the data moves because the model works, since adversaries adapt to whatever it catches.

Why concept shift is invisible without labels. Suppose \(p_t(\mathbf{x}) = p_s(\mathbf{x})\) but \(p_t(y \mid \mathbf{x}) \ne p_s(y \mid \mathbf{x})\). Any monitor that does not see \(y\) computes a statistic \(T(\mathbf{x}_1, \ldots, \mathbf{x}_n)\), possibly through the model's outputs \(f(\mathbf{x}_i)\). Its distribution depends only on \(p(\mathbf{x})\), which is the same before and after, so every unlabelled test has exactly its false-alarm rate as its power. This is a theorem about information, not a limitation of current tools; the only way out is labels (or proxies that correlate with labels).

Why each correction needs its assumption. From unlabelled production data you can estimate \(p_t(\mathbf{x})\), nothing more. The production joint \(p_t(\mathbf{x}, y)\) has more degrees of freedom than \(p_t(\mathbf{x})\) can pin down, so some factor must be assumed fixed. Covariate shift fixes \(p(y \mid \mathbf{x})\) and identifies \(p_t\) as \(p_t(\mathbf{x})\,p_s(y \mid \mathbf{x})\); label shift fixes \(p(\mathbf{x} \mid y)\) and identifies \(p_t\) through \(p_t(y)\). Choose the assumption from the causal direction of the problem; if neither is plausible, buy labels.

Why loops need randomness. To learn \(p(y \mid \mathbf{x}, a)\) for an action \(a\) you must observe outcomes of \(a\) in the relevant \(\mathbf{x}\). A deterministic policy takes one action per \(\mathbf{x}\), so outcomes of every other action are never observed there; no amount of logged data from it identifies their effects. Randomisation with known probabilities makes every action observable with positive probability, which is exactly the condition (positivity, or overlap) that inverse-propensity estimators require.

The maths

PSI is the symmetrised KL divergence. Write the binned production and reference distributions as \(a\) and \(e\). Then

\[ \mathrm{PSI} = \sum_i (a_i - e_i)\ln\frac{a_i}{e_i} = \sum_i a_i \ln\frac{a_i}{e_i} + \sum_i e_i \ln\frac{e_i}{a_i} = \mathrm{KL}(a\,\|\,e) + \mathrm{KL}(e\,\|\,a), \]

the Jeffreys divergence (entropy, cross-entropy and KL). For the worked example, \(\mathrm{KL}(a\|e) = 0.1064\) and \(\mathrm{KL}(e\|a) = 0.1218\), summing to 0.2282. For small differences, expand \(\ln(a_i/e_i) \approx \delta_i/e_i\) with \(\delta_i = a_i - e_i\) to get \(\mathrm{PSI} \approx \sum_i \delta_i^2/e_i\), the chi-squared divergence (0.200 for the example; the approximation is good below about 0.1).

Derivation: the small-sample bias of PSI

Suppose there is no shift: both windows sample the same bin probabilities \(p_i\), with \(n\) reference and \(m\) production samples. The estimated shares are independent with \(\operatorname{Var}(\hat e_i) = p_i(1-p_i)/n\) and \(\operatorname{Var}(\hat a_i) = p_i(1-p_i)/m\), so \(\mathbb{E}[(\hat a_i - \hat e_i)^2] = p_i(1-p_i)\left(\tfrac1n + \tfrac1m\right)\). Using the chi-squared approximation,

\[ \mathbb{E}[\mathrm{PSI}] \approx \sum_{i=1}^{B} \frac{p_i(1-p_i)}{p_i}\left(\frac1n + \frac1m\right) = (B-1)\left(\frac1n + \frac1m\right). \]

With \(B = 10\) bins and 500 samples per window that is 0.036 of pure noise, a third of the way to the "investigate" threshold; with 50,000 per window it is 0.00036. The Build it code measures 0.0004 for identical distributions at \(n = 50{,}000\) and 0.043 for a negligible shift at \(n = 500\). Subtract the expected null value, or compare against PSIs of reference-vs- reference windows of the same size, before believing a small-sample PSI.

Importance weighting is unbiased. For any function \(g\) (a loss, or an indicator of a correct prediction), if \(p_s(\mathbf{x}) > 0\) wherever \(p_t(\mathbf{x}) > 0\),

\[ \mathbb{E}_{\mathbf{x}\sim p_t}[g(\mathbf{x})] = \int g(\mathbf{x})\,p_t(\mathbf{x})\,d\mathbf{x} = \int g(\mathbf{x})\,\frac{p_t(\mathbf{x})}{p_s(\mathbf{x})}\,p_s(\mathbf{x})\,d\mathbf{x} = \mathbb{E}_{\mathbf{x}\sim p_s}[w(\mathbf{x})\,g(\mathbf{x})]. \]

Under covariate shift, \(g\) may involve \(y\) too, because \(p(y \mid \mathbf{x})\) is common to both domains. The support condition is the formal version of "the reference must cover production".

The domain classifier is a density-ratio estimator. Pool \(n_s\) reference and \(n_t\) production points and label them \(d = 0\) and \(d = 1\). The Bayes-optimal classifier is

\[ c(\mathbf{x}) = P(d=1 \mid \mathbf{x}) = \frac{n_t\,p_t(\mathbf{x})}{n_t\,p_t(\mathbf{x}) + n_s\,p_s(\mathbf{x})} \quad\Longrightarrow\quad w(\mathbf{x}) = \frac{p_t(\mathbf{x})}{p_s(\mathbf{x})} = \frac{n_s}{n_t}\,\frac{c(\mathbf{x})}{1 - c(\mathbf{x})}. \]

Its AUC is a drift score (0.5 when the domains are indistinguishable), its feature importances say which features drifted, and its odds are the weights. The same trick appears in quality filtering, where a quality classifier is a density ratio towards a reference corpus.

What the weights cost. The self-normalised estimate \(\sum_j w_j g_j / \sum_j w_j\) has roughly the variance of a plain mean over Kish's effective sample size

\[ n_{\text{eff}} = \frac{\left(\sum_j w_j\right)^2}{\sum_j w_j^2}, \qquad \frac{n_{\text{eff}}}{n} \to \frac{1}{\mathbb{E}_s[w^2]} = \frac{1}{1 + \chi^2(p_t \,\|\, p_s)}. \]

For a pure mean shift of a unit Gaussian by \(\mu\), \(\chi^2 = e^{\mu^2} - 1\), so \(n_{\text{eff}}/n = e^{-\mu^2}\): a shift of half a standard deviation keeps 78% of your data, one standard deviation 37%, two standard deviations 1.8%. Information about production decays like a Gaussian in the size of the shift. (In the Build it example the theoretical ratio is 0.15 while the sample shows 0.23: the weights' variance lives in rare, extreme points that a finite sample under-represents, so a sample ESS is optimistic exactly when it matters.)

Derivation: black-box shift estimation

Let \(f\) be any fixed classifier with \(K\) outputs, and assume label shift: \(p_t(\mathbf{x} \mid y) = p_s(\mathbf{x} \mid y)\). Then the distribution of \(f\)'s prediction given the true class is the same in both domains, \(p_t(\hat y = i \mid y = j) = p_s(\hat y = i \mid y = j)\). The production distribution of predictions is

\[ \mu_i := p_t(\hat y = i) = \sum_j p_s(\hat y = i \mid y = j)\,p_t(y = j) = \sum_j \underbrace{p_s(\hat y = i,\, y = j)}_{C_{ij}}\;\underbrace{\frac{p_t(y=j)}{p_s(y=j)}}_{w_j}. \]

So \(\boldsymbol{\mu} = C\mathbf{w}\), with \(C\) (\(K\times K\)) estimated from labelled source validation data and \(\boldsymbol{\mu}\) (\(K\)) from unlabelled production predictions. If \(C\) is invertible, \(\hat{\mathbf{w}} = \hat C^{-1}\hat{\boldsymbol{\mu}}\). Lipton et al. bound the error of \(\hat{\mathbf{w}}\) in terms of the smallest singular value of \(C\): a classifier that confuses classes makes \(C\) near-singular and the estimate noisy, but even a weak classifier gives a consistent estimate.

To correct posteriors, apply Bayes' rule in both domains. Because \(p(\mathbf{x} \mid y)\) is shared,

\[ p_t(y \mid \mathbf{x}) = \frac{p(\mathbf{x}\mid y)\,p_t(y)}{\sum_k p(\mathbf{x}\mid k)\,p_t(k)} = \frac{w_y\,p_s(y \mid \mathbf{x})}{\sum_k w_k\,p_s(k \mid \mathbf{x})}, \]

which is the two-line correction in the code (multiply by \(w\), renormalise). It is only as good as the calibration of \(p_s(y\mid\mathbf{x})\); the argmax decision, however, improves even for a mildly miscalibrated model.

In practice

  • Start with logging and schemas, not drift dashboards. Most incidents are pipeline bugs; a schema check and a serve-time feature log catch them deterministically. Add statistical drift monitors once the assertions are in place.
  • Choose the reference window on purpose. Training data catches skew; a trailing window (last week) catches sudden change; a same-period-last-year window separates seasonality from drift. Many teams monitor against two.
  • Alert on what the model feels. Weight feature-drift alerts by feature importance, monitor prediction and confidence distributions, and set thresholds by replaying past incidents rather than by textbook PSI cut-offs.
  • Keep a label budget in production. A small, steady stream of randomly sampled, freshly labelled production examples is the only defence against concept shift and the only honest calibration check. Size it with the binomial confidence intervals of statistics for experiments and evals.
  • Keep a control. A few per cent of randomised or model-free traffic makes feedback loops measurable and gives future models unbiased training data.
  • Version everything together. A prediction is reproducible only if you know the data snapshot, feature code, model weights, prompt, retrieval index and dependency versions. The tooling is covered in MLOps.
  • Open-source tools (as of 2026): Evidently for drift and data-quality reports, NannyML for performance estimation without labels, Alibi Detect for drift and outlier detectors including MMD and classifier-based tests, and TensorFlow Data Validation for schema and skew checks.

Common misconceptions

\"No input drift means the model is fine\"

Concept shift leaves \(p(\mathbf{x})\) unchanged and is invisible to every unlabelled monitor. Input drift monitors are necessary, never sufficient; only fresh labels or reliable proxies measure performance.

\"Drift means retrain\"

Drift in a feature the model barely uses changes nothing; drift caused by a pipeline bug is made permanent by retraining on it. Diagnose first: is it a bug, a real shift, or the model's own feedback? Then choose between fixing, recalibrating, re-weighting and retraining.

\"Retraining on fresh production data removes bias\"

Production data is filtered by the current model's decisions. Retraining on it can lock in the model's blind spots (selective labels) or amplify its preferences (degenerate loops). Fresh data is unbiased only if some of it was collected independently of the model.

Build it

Three NumPy programs, each a few seconds on a laptop: drift statistics and their traps, label-shift estimation and correction, and covariate-shift detection with importance-weighted performance estimation. NumPy only; the KS p-value uses the asymptotic Kolmogorov series.

1. PSI against KS, and the large-sample trap.

import numpy as np

rng = np.random.default_rng(0)

def psi(ref, cur, bins=10, eps=1e-6):
    """Population stability index with quantile bins fixed on the reference."""
    edges = np.quantile(ref, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    e = np.histogram(ref, edges)[0] / len(ref) + eps
    a = np.histogram(cur, edges)[0] / len(cur) + eps
    return float(np.sum((a - e) * np.log(a / e)))

def ks(ref, cur):
    """Two-sample Kolmogorov-Smirnov statistic and asymptotic p-value."""
    grid = np.sort(np.concatenate([ref, cur]))
    F = np.searchsorted(np.sort(ref), grid, side="right") / len(ref)
    G = np.searchsorted(np.sort(cur), grid, side="right") / len(cur)
    d = np.max(np.abs(F - G))
    ne = len(ref) * len(cur) / (len(ref) + len(cur))
    lam = (np.sqrt(ne) + 0.12 + 0.11 / np.sqrt(ne)) * d
    k = np.arange(1, 101)
    p = 2 * np.sum((-1) ** (k - 1) * np.exp(-2 * k**2 * lam**2))
    return float(d), float(min(max(p, 0.0), 1.0))

ref = rng.normal(0, 1, 50_000)                     # training-time feature
weeks = {
    "same distribution":   rng.normal(0.00, 1.0, 50_000),
    "tiny shift, mu+0.05": rng.normal(0.05, 1.0, 50_000),
    "real shift, mu+0.5":  rng.normal(0.50, 1.2, 50_000),
}
print(f"{'production week':22s} {'PSI':>7s} {'KS D':>7s} {'KS p':>10s}")
for name, cur in weeks.items():
    d, p = ks(ref, cur)
    print(f"{name:22s} {psi(ref, cur):7.4f} {d:7.4f} {p:10.2e}")

# Same tiny shift, smaller samples: the p-value is a function of n, PSI is not.
print("\ntiny shift (mu+0.05) at different sample sizes")
for n in [500, 5_000, 50_000]:
    r, c = rng.normal(0, 1, n), rng.normal(0.05, 1, n)
    d, p = ks(r, c)
    print(f"n={n:6d}  PSI={psi(r, c):.4f}  KS p={p:.2e}")

Output:

production week            PSI    KS D       KS p
same distribution       0.0004  0.0050   5.64e-01
tiny shift, mu+0.05     0.0027  0.0230   6.55e-12
real shift, mu+0.5      0.2298  0.1931   0.00e+00

tiny shift (mu+0.05) at different sample sizes
n=   500  PSI=0.0433  KS p=1.44e-01
n=  5000  PSI=0.0016  KS p=9.69e-01
n= 50000  PSI=0.0030  KS p=1.54e-12

Read the two failure modes off the table. At \(n = 50{,}000\) the KS test calls a 0.05-sigma shift overwhelming. At \(n = 500\) the PSI of that same negligible shift is 0.043, mostly the \((B-1)(1/n + 1/m) = 0.036\) noise floor derived above.

2. Label shift: estimate the new prior and fix the model, with no production labels.

import numpy as np

rng = np.random.default_rng(1)
means = np.array([-2.0, 0.0, 2.0])            # x | y=k ~ N(means[k], 1), k = 0, 1, 2

def sample(n, prior):
    y = rng.choice(3, size=n, p=prior)
    return rng.normal(means[y], 1.0), y

def posterior(x, prior):
    """Bayes-optimal p(y | x) under a given class prior (the 'model')."""
    logp = -0.5 * (x[:, None] - means) ** 2 + np.log(prior)
    p = np.exp(logp - logp.max(1, keepdims=True))
    return p / p.sum(1, keepdims=True)

p_src = np.array([1/3, 1/3, 1/3])             # training prior
p_tgt = np.array([0.60, 0.30, 0.10])          # production prior (unknown to us)

# 1. On labelled source validation data: the joint confusion matrix C[i, j] = P(yhat=i, y=j).
xv, yv = sample(20_000, p_src)
yhat_v = posterior(xv, p_src).argmax(1)
C = np.zeros((3, 3))
np.add.at(C, (yhat_v, yv), 1)
C /= len(yv)

# 2. On unlabelled production data: the distribution of predicted labels.
xt, yt = sample(20_000, p_tgt)                # yt is used ONLY for scoring below
probs_t = posterior(xt, p_src)
mu = np.bincount(probs_t.argmax(1), minlength=3) / len(xt)

# 3. BBSE: mu = C w  =>  w = C^{-1} mu,  where w_j = p_tgt(j) / p_src(j).
w = np.linalg.solve(C, mu)
w = np.clip(w, 0, None)
est = w * p_src / np.sum(w * p_src)
print("true production prior     ", p_tgt)
print("predicted-label histogram ", mu.round(3))
print("BBSE estimate             ", est.round(3))

# 4. Correct the model: p_tgt(y|x) is proportional to w_y * p_src(y|x).
adj = probs_t * w
adj /= adj.sum(1, keepdims=True)

def report(name, p):
    acc = (p.argmax(1) == yt).mean()
    nll = -np.log(p[np.arange(len(yt)), yt]).mean()
    print(f"{name:28s} accuracy {acc:.3f}   log-loss {nll:.3f}")

report("model as trained", probs_t)
report("after BBSE prior correction", adj)
report("oracle (true prior)", posterior(xt, p_tgt))

Output:

true production prior      [0.6 0.3 0.1]
predicted-label histogram  [0.544 0.323 0.133]
BBSE estimate              [0.581 0.319 0.1  ]
model as trained             accuracy 0.787   log-loss 0.477
after BBSE prior correction  accuracy 0.815   log-loss 0.428
oracle (true prior)          accuracy 0.814   log-loss 0.428

The raw predicted-label histogram (0.544, 0.323, 0.133) is a biased estimate of the prior, because the classifier's errors smear mass towards the middle class; inverting \(C\) removes the smear. The corrected model matches the oracle that knows the true prior.

3. Covariate shift: detect it, weight it, and estimate production accuracy from old labels.

import numpy as np

rng = np.random.default_rng(2)
sig = lambda z: 1 / (1 + np.exp(-z))

# Concept p(y=1 | x) is FIXED; only p(x) moves (covariate shift).
def label(x):  return (rng.random(len(x)) < sig(4 * (np.abs(x) - 1.5))).astype(int)
def model(x):  return (x > 1.5).astype(int)   # learned where negative x was rare

xs = rng.normal(0.0, 1.0, 20_000); ys = label(xs)   # labelled reference set
xt = rng.normal(-1.0, 1.2, 20_000); yt = label(xt)  # production; yt for scoring only

# 1. Domain classifier: logistic regression on [1, x, x^2], 0 = reference, 1 = production.
X = np.concatenate([xs, xt]); d = np.r_[np.zeros(len(xs)), np.ones(len(xt))]
F = np.c_[np.ones_like(X), X, X**2]
theta = np.zeros(3)
for _ in range(3000):                                 # plain gradient descent
    theta -= 0.5 * F.T @ (sig(F @ theta) - d) / len(d)
c = sig(F @ theta)
rank = np.argsort(np.argsort(c))                       # AUC via Mann-Whitney ranks
auc = (rank[d == 1].sum() - d.sum() * (d.sum() - 1) / 2) / (d.sum() * (1 - d).sum())
print(f"domain-classifier AUC {auc:.3f}   (0.5 = no detectable shift)")

# 2. Density ratio on the reference points: w(x) = p_t(x)/p_s(x) = (n_s/n_t) c/(1-c).
cs = c[: len(xs)]
w = (len(xs) / len(xt)) * cs / (1 - cs)
ess = w.sum() ** 2 / (w**2).sum()
print(f"weights: mean {w.mean():.2f}, max {w.max():.1f}, effective sample size {ess:,.0f} of {len(xs):,}")

# 3. Estimate production accuracy from REFERENCE labels only, reweighted.
correct_s = (model(xs) == ys)
print(f"accuracy on reference data          {correct_s.mean():.3f}")
print(f"importance-weighted estimate        {np.sum(w * correct_s) / w.sum():.3f}")
print(f"true production accuracy (hidden)   {(model(xt) == yt).mean():.3f}")

Output:

domain-classifier AUC 0.746   (0.5 = no detectable shift)
weights: mean 1.00, max 92.4, effective sample size 4,507 of 20,000
accuracy on reference data          0.868
importance-weighted estimate        0.635
true production accuracy (hidden)   0.636

The model was fitted where negative inputs were rare, so it never learned that large negative \(x\) is also positive. Production moved there; accuracy fell from 0.868 to 0.636, and the weighted estimate saw it without a single production label. (The domain classifier is evaluated on the same points it was fitted on, which is acceptable for three parameters; with a flexible model, fit and score on separate halves.)

Things to try

  • In program 1, sweep the number of bins from 4 to 50 for the "same distribution" week and compare the PSI with \((B-1)(1/n + 1/m)\).
  • In program 1, simulate 300 unshifted features and count how many KS tests reject at \(p < 0.05\); then apply a Bonferroni correction.
  • In program 2, move the class means closer together (say \(-1, 0, 1\)) and watch the condition number of \(C\) and the error of the BBSE estimate grow.
  • In program 2, add a little concept shift (move one class mean in production) and see how far the label-shift correction degrades.
  • In program 3, move production further away (\(\mu = -2\)) and track the ESS and the error of the weighted estimate. Then make production cover \(x < -4\), where the reference has almost no data, and see the estimate break.
  • Simulate a selective-labels loop: approve only applicants the model scores above a cut-off, retrain on approved outcomes only for ten rounds, and compare with a version that approves a random 5% regardless of score.

Check yourself

Name the three kinds of dataset shift by which factor of p(x, y) changes, and say which can be detected without labels.

Covariate shift: \(p(\mathbf{x})\) changes, \(p(y\mid\mathbf{x})\) fixed; detectable from inputs. Label shift: \(p(y)\) changes, \(p(\mathbf{x}\mid y)\) fixed; detectable through the input or prediction distribution, and the new prior is estimable (BBSE). Concept shift: \(p(y\mid\mathbf{x})\) changes; undetectable from unlabelled data when \(p(\mathbf{x})\) is unchanged.

Compute the PSI for expected shares (0.5, 0.5) and actual shares (0.4, 0.6).

\((0.4-0.5)\ln(0.8) + (0.6-0.5)\ln(1.2) = 0.0223 + 0.0182 = 0.0405\). Stable by the usual rule of thumb, unless the windows are small: with 500 samples each and 2 bins the null expectation is \(1\times(2/500) = 0.004\), so 0.04 is ten times the noise floor and real.

A KS test on 2 million rows per day rejects for 280 of your 300 features. What do you do?

Nothing alarming has necessarily happened: at that sample size, KS rejects for shifts far too small to matter. Look at effect sizes (KS \(D\), PSI, Wasserstein in feature units), weight by feature importance, check whether the model's output distribution and proxy metrics moved, and set thresholds from replayed incidents. Also check the reference window: comparing against training data from a year ago guarantees seasonal "drift".

A disease classifier was validated at 10% prevalence with sensitivity 0.8 and false-positive rate 0.1. In a new hospital it flags 24% of patients. Estimate the prevalence there, assuming label shift.

\(0.24 = 0.8\pi + 0.1(1-\pi)\), so \(\pi = 0.14/0.7 = 0.20\). Prevalence has doubled. Label shift is plausible here because disease causes symptoms; it would be doubtful if the new hospital used different scanners, which changes \(p(\mathbf{x}\mid y)\).

Why does the domain classifier's AUC measure shift, and why should you not fit and score it on the same data when it is a flexible model?

If the domains are identical, no classifier can beat chance, so AUC is 0.5 in expectation; the more separable the domains, the higher the AUC. A flexible model can memorise which points came from which sample and reach a high AUC on its own training data even with no shift, so you must evaluate it on held-out points (or by cross-validation).

Your reference set has 10,000 labelled examples. Production is the reference distribution shifted by 1.5 standard deviations in one Gaussian feature. Roughly how many reference examples' worth of information does an importance-weighted estimate have?

\(n_{\text{eff}}/n \approx e^{-\mu^2} = e^{-2.25} \approx 0.105\), so about 1,000. A sample ESS computed from the weights will tend to report more, because the rare large weights that drive the variance are under-sampled.

Hard: a loan model is retrained monthly on outcomes of approved loans. Approval rates and observed default rates have been stable for a year. Argue that the model may still be getting worse, and design a fix.

Stable observed defaults are computed only on approved applicants, a population the model selects; any segment it wrongly rejects never produces outcomes, so errors of rejection are invisible and self-confirming (selective labels). Meanwhile the applicant population may shift in the rejected region without any monitored metric moving. Fixes: approve a small random band below the cut-off (or randomise near the threshold) and log approval probabilities; train and evaluate with inverse-propensity weights; monitor the score distribution of all applicants, not just approved ones; compare against an independent signal such as bureau-reported outcomes on rejected applicants where legally available.

Hard: your LLM assistant's thumbs-up rate rose from 61% to 68% after a prompt change, and its judge-rated correctness on a golden set is unchanged. What could explain it, and what would you check?

Possibilities: the new prompt makes answers more agreeable or confident (users reward tone, not correctness); the mix of who gives feedback changed (fewer frustrated users stayed to vote); traffic mix shifted towards easier intents; the golden set no longer reflects production. Check per-intent slices and the share of sessions with any feedback, sample thumbs-up answers for human correctness review, compare implicit signals (rephrases, escalations), and refresh the golden set from recent traffic.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

  • Evidently — Drift, data-quality and LLM-evaluation reports; read its choice of default tests per data type.
  • NannyML — Confidence-based performance estimation without labels.
  • Alibi Detect — MMD, classifier and learned-kernel drift detectors, including for text and embeddings.

Where this leads