Skip to content
AI systems and infrastructure Core 28 min read

MLOps: experiments, pipelines, monitoring

MLOps is the engineering that keeps a machine-learning system correct after the notebook: experiments you can reproduce, pipelines that rebuild the model without heroics, releases that cannot quietly make things worse, and monitoring that notices when the world has moved. The idea to keep: a model is a function of code, data, configuration and randomness, and ML systems fail silently. So you version all four inputs, test the data as well as the code, and watch the outputs.

10,000 ft

In conventional software a bug usually throws an error. In ML, a stale feature, a shifted input distribution or a changed upstream API produces confident, plausible, wrong outputs. Sculley et al.'s Hidden Technical Debt in Machine Learning Systems (2015) put it memorably: the model code is a small box in the middle of a large system of data collection, feature extraction, configuration, serving and monitoring, and most of the debt lives in that system. MLOps is the discipline for that system. It sits between the training recipe (how to run one good experiment), data in production (how data drifts and feeds back), serving (how predictions are delivered) and evals in practice (how quality is measured). For LLM products the artefact changes, from trained weights to prompt + model version + retrieval index + tools, but the loop is the same.

2,000 ft

The ML lifecycle is a loop. Each arrow is something to automate, version or monitor:

  1. Data: collect, label, validate against a schema, and snapshot with a version.
  2. Experiment: train with tracked code, config, data version and seeds, so every result has a run ID you can reproduce.
  3. Pipeline: turn the winning experiment into an automated, cached DAG (ingest → validate → train → evaluate → register) that can rerun on new data.
  4. Release: register the model with its lineage, pass gates (offline evals, slice regressions, latency and cost budgets), then roll out by shadow → canary → full, with rollback.
  5. Monitor: system health, input drift, output distribution, outcome quality as labels arrive. Alerts feed back into data collection and retraining.

The MLOps loop
The MLOps loop. Data schema-validated versioned snapshot, Experiments tracked runs: code · config · data · seed, Pipeline automated DAG, cached by input hash, Registry model + lineage + card, Release gates evals · slices · latency · cost, Production shadow → canary → full, Monitoring system · drift · outcomes, new data, hard cases, triggersThe MLOps loop. Data schema-validated versioned snapshot, Experiments tracked runs: code · config · data · seed, Pipeline automated DAG, cached by input hash, Registry model + lineage + card, Release gates evals · slices · latency · cost, Production shadow → canary → full, Monitoring system · drift · outcomes, new data, hard cases, triggers

Ground level

Why ML needs its own operations discipline

Five properties make ML systems harder to operate than ordinary services:

  • Silent failure. A model with a broken input pipeline still returns predictions. Nothing crashes; quality just degrades. Monitoring must look at distributions and outcomes, not only at errors and latency.
  • Changing anything changes everything (Sculley's "CACE" principle). Inputs are entangled: add a feature, change a tokenizer, rescale one column, and every learned weight shifts. There is no local change.
  • Data is a dependency, and usually an undeclared one. Code dependencies are versioned and compiled. Data dependencies (an upstream table, a third-party API, user behaviour) change without notice. Training–serving skew, where features are computed one way offline and another way online, is the classic bug.
  • Feedback loops. A recommender changes what users click, which changes its next training set. A credit model changes who gets loans, and so whose repayment it ever observes. The model shapes its own data.
  • Experimentation is the work. Most runs are thrown away, and you need to know which change produced which result, months later.

Google's MLOps guide frames the response as extending software's CI/CD (Google Cloud, MLOps: continuous delivery and automation pipelines): continuous integration tests data, schemas and models as well as code; continuous delivery ships a pipeline that produces the model, not just a model file; and continuous training retrains automatically when data or triggers say so. It also describes three maturity levels. At level 0, every step is a manual script and a hand-off. At level 1, the training pipeline is automated, with data and model validation and metadata tracking. At level 2, the pipeline itself is built, tested and deployed by CI/CD. Most teams should aim for level 1 before anything fancier.

Experiment tracking: every result needs an address

An experiment tracker records, for every run:

What Why
Code version (commit hash, plus uncommitted diff) the function that was run
Full resolved config (hyperparameters, model, tokenizer) the arguments
Data version (dataset hash or snapshot ID, split definitions) the input
Seeds and environment (library versions, CUDA/driver, hardware) the sources of non-determinism
Metric curves (loss, eval metrics, gradient norm, learning rate) the behaviour, not just the end point
System metrics (throughput, MFU, memory, GPU utilisation) cost and efficiency (compute maths)
Artefacts (checkpoints, eval outputs, sample generations) what you will want to inspect later

Tools such as MLflow, Weights & Biases and TensorBoard store this and let you compare runs side by side. The tool matters less than the habit: no result without a run ID, and a run ID that pins every input. The Build it section derives a run ID from content hashes of code, config and data, so identical inputs give the same ID and any change, even one number in the data, gives a new one. The day-to-day hygiene of running experiments (one change at a time, baselines, seeds) is in the training recipe.

Reproducibility: four sources of difference

When two runs disagree, the difference came from one of four places:

  1. Code: including dependencies. Pin library versions; record the container image.
  2. Data: content, order and splits. Version datasets by content hash (DVC, lakeFS, or immutable snapshots in object storage). Record the shuffling seed and the exact split.
  3. Configuration: the full resolved config, after defaults and command-line overrides.
  4. Randomness and hardware: seeds for initialisation, dropout, data order and sampling. Even with identical seeds, many GPU kernels are not bitwise deterministic: floating-point addition is not associative, and parallel reductions with atomics sum in varying order. Frameworks offer deterministic modes at some cost in speed, and results also differ across GPU models and library versions.

Perfect bitwise reproducibility is rarely worth its cost. Statistical reproducibility is: run several seeds, report the mean and spread, and treat differences smaller than seed-to-seed variation as noise. That is a question for statistics for experiments.

Pipelines: the experiment, made repeatable

A pipeline is the training process written as a directed acyclic graph of steps, each with declared inputs and outputs: ingest → validate → transform/featurise → train → evaluate → register. Orchestrators (Airflow, Kubeflow Pipelines, Dagster, Metaflow, Prefect, Ray) schedule the steps, retry failures and record what ran. Three properties make a pipeline worth having:

  • Idempotent, cached steps. If a step's inputs (code + config + data hash) are unchanged, reuse its output. Only changed branches rerun.
  • Validation as a step. Check incoming data against a schema (types, ranges, missing values, category vocabularies) and against the training distribution before training. Google's TFX team found data validation one of the most valuable pieces of their platform (Katsiapis et al. 2020): bad data caught early is cheap, and bad data caught in production is expensive.
  • One feature definition. Compute features with the same code offline and online, or from a shared feature store, to avoid training–serving skew.

The registry, release gates and CI/CD

A model registry stores each trained model with its lineage (run ID, data version, metrics), a stage (candidate, staging, production, archived) and documentation, ideally a model card stating intended use, evaluation results by subgroup and known limits. Promotion between stages passes gates, automated where possible:

  • Offline quality on a fixed, versioned evaluation set, compared with the current production model, with confidence intervals.
  • Slice regressions: no important subgroup (region, language, customer tier, input length) gets worse beyond a tolerance, even if the average improves.
  • Behavioural tests: invariances (a name change should not change a credit score), directional expectations and known hard cases, kept as a regression suite.
  • Operational budgets: latency percentiles, memory, cost per prediction or per thousand tokens.
  • Safety and policy checks where relevant (guardrails).

Breck et al.'s ML Test Score turns this into a rubric of 28 specific tests and monitoring needs across data, model development, infrastructure and monitoring (Breck et al. 2017). It is a good checklist to score a system against.

Releasing: shadow, canary, A/B

Offline metrics are a hypothesis about online behaviour. Release in stages that expose the new model to reality while limiting the blast radius:

Staged rollout of a new model
Staged rollout of a new model. Candidate passed offline gates, Shadow sees live traffic, answers discarded, compare offline, Canary 1–5% of traffic, watch guardrail metrics, A/B test randomised split, measure outcome metric, Full rollout old model kept warm, Rollback one switch, regression, losesStaged rollout of a new model. Candidate passed offline gates, Shadow sees live traffic, answers discarded, compare offline, Canary 1–5% of traffic, watch guardrail metrics, A/B test randomised split, measure outcome metric, Full rollout old model kept warm, Rollback one switch, regression, loses
  • Shadow mode runs the new model on live inputs without showing its outputs. It catches crashes, latency problems, skew and large prediction differences at zero user risk.
  • Canary sends a small share of real traffic to the new model and watches guardrail metrics (errors, latency, complaint rate, refusal rate) with automatic rollback.
  • A/B tests randomise users between models and measure the outcome that matters. Size them in advance, fix the metric before looking, and beware peeking (statistics for experiments).
  • Rollback must be one switch, which means keeping the previous model deployed and its features still computed.

Monitoring: four layers

Monitor from the bottom up. Each layer catches failures the one below cannot see:

Layer Signals Catches
System latency percentiles, error rate, throughput, GPU memory, cost outages, overload, regressions in serving (serving)
Data (inputs) schema violations, missing rates, feature distributions, input length, language mix broken upstream pipelines, new user populations, drift
Model (outputs) prediction distribution, confidence, refusal rate, output length behaviour change even before labels arrive
Outcomes accuracy once labels arrive, user feedback, business metrics the thing you actually care about, often late

The hard part is that the most important layer, outcomes, arrives last or never. A fraud label arrives weeks later; a chatbot answer's quality is never labelled at all unless you sample and grade it. So production monitoring leans on the earlier layers as early warnings, and on sampled, graded production traffic as the slow ground truth.

Kinds of shift. With inputs \(x\) and labels \(y\):

  • Covariate shift: \(p(x)\) changes, \(p(y \mid x)\) does not (new users, new device types, longer prompts).
  • Label shift: \(p(y)\) changes (fraud rate doubles in a holiday season).
  • Concept drift: \(p(y \mid x)\) changes. The world's rules move: a new product makes old answers wrong, a regulation changes what is allowed.

Only the first two are visible from inputs alone. Concept drift needs labels or outcome signals.

Detecting input drift. Compare a recent window with a reference window, per feature:

  • Population Stability Index (PSI): bin the reference into quantiles and sum \((c_i - r_i)\ln(c_i/r_i)\) over bins. A common rule of thumb from credit scoring reads < 0.1 as stable, 0.1–0.25 as moderate shift and > 0.25 as major.
  • Two-sample tests: Kolmogorov–Smirnov for one numeric feature, chi-squared for categories, and kernel or classifier-based tests for high-dimensional inputs. Rabanser et al. compared methods across many shifts and found that two-sample tests on representations from a pretrained classifier worked best (Failing Loudly, 2018). For text, the analogue is testing embedding distributions.

The Build it experiment shows the two failure modes of naive drift alerts. With 20,000 reference samples a KS test is "significant" (\(p < 0.01\)) when only 2% of traffic has changed: statistical significance is not practical significance. Meanwhile PSI on decile bins stays below 0.1 even after 10% of traffic has shifted to prompts ten times longer, because they all land in one top bin. The 95th percentile of prompt length had already quadrupled, and for an LLM service that is a cost and latency event. Monitor the quantiles that drive cost and behaviour, not just a drift score.

Alert fatigue is a real failure mode. With 200 monitored features, each tested daily at a 1% false-alarm rate, you expect two false alarms every day. Use fewer, better-chosen signals, correct for multiple comparisons, require persistence (several windows in a row), and route each alert to an owner with a runbook.

Retraining and feedback loops

Retrain on a schedule (simple, predictable), on a trigger (drift or performance below a threshold), or continuously (online learning, rare outside recommendation and ads). Whichever you choose, the retrained model goes through the same gates as any other candidate. Automatic retraining without gates is how a poisoned or broken data batch reaches production.

The most valuable loop is mining hard cases. Andrej Karpathy's description of Tesla's "data engine" is the canonical example (talk): find where the model fails in the field, retrieve similar cases from fleet data, label them, add them to the training and test sets, and retrain. Every production failure becomes a permanent regression test. For LLM applications the same loop runs on traces: failed conversations become golden-set items (evals in practice).

Operating large training runs

At frontier scale, operations is a large share of the work. Meta's Llama 3 report gives rare public numbers (Llama 3 paper, §3.3.4). During a 54-day snapshot of 405 B pre-training on up to 16,384 H100s there were 466 job interruptions: 47 planned and 419 unexpected, about 78% of them confirmed or suspected hardware, led by faulty GPUs (30.1%) and GPU HBM3 memory (17.2%). That is one unexpected failure every ~3.1 hours. They still achieved over 90% effective training time, by automating detection and restart and by cutting job start-up and checkpoint time. They also note a diurnal 1–2% throughput variation with temperature, and power swings across the data centre of tens of megawatts when all GPUs pause together.

Three practices follow.

  • Checkpoint at the right interval. Checkpoint too rarely and each failure loses hours; checkpoint too often and the saves themselves eat the run. With checkpoint cost \(\delta\) and mean time between failures \(M\), Young's classic result gives the optimal interval \(\tau^\star \approx \sqrt{2\delta M}\) (derived in the maths, and used in compute maths).
  • Make checkpoints cheap. Asynchronous checkpointing copies state to host memory quickly and writes it to storage in the background, shrinking \(\delta\) from minutes to seconds, which shortens the optimal interval and cuts the waste.
  • Handle loss spikes, not just crashes. Large runs suffer loss spikes and divergence. The public logbook of Meta's OPT-175B run (chronicles) shows the standard response: roll back to an earlier checkpoint, lower the learning rate or skip the offending data, and resume. Monitor gradient norms and loss with automatic alerts.
0%10%20%30%125102050100checkpoint interval τ (minutes, log scale)GPU time wasted60 s stall (synchronous save)5 s stall (asynchronous save)dashed: √(2δM)
Fraction of a training run lost to checkpoint stalls, recomputed work and 10-minute restarts, with Llama 3 405B's observed failure rate (mean 3.1 hours between interruptions). Lines: the first-order model; dots: the Monte Carlo simulation in Build it. Each curve bottoms out at Young's interval (dashed). Cutting the stall from 60 s to 5 s, by writing checkpoints asynchronously, moves the optimum from 19 to 6 minutes and nearly halves the waste. The floor that remains is restart time, which is why large labs invest in fast recovery.

LLMOps: what changes when the model is an LLM

For an application built on a foundation model, often one you call through an API, the "model" you version is a bundle:

  • Prompt and system instructions, versioned like code and reviewed like code.
  • Model identifier, pinned to a dated version rather than a moving alias. Providers update and retire models, and an unpinned alias can change your product overnight.
  • Retrieval index and its embedding model. Re-embedding a corpus with a new embedding model is a migration, not a config change (RAG).
  • Tools, schemas and decoding parameters (temperature, structured-output schemas).

The release gate becomes an eval suite: a versioned golden set, assertion-style checks for format and facts, and LLM judges for open-ended quality, all run in CI on every prompt or model change (evals in practice). Monitoring becomes tracing: record every step of every request (inputs, retrieved documents, tool calls, outputs, tokens, latency, cost) with a shared request ID. OpenTelemetry's generative-AI semantic conventions standardise the field names. Sample traces for human or judge grading as the slow outcome signal, and track cost per request alongside latency, because a prompt change can double tokens.

In Finny's Jarvis

Jarvis follows the split code computes, the model routes and explains. That split makes it much easier to operate: the numbers in an answer come from the FIRE engine and can be checked exactly in regression tests, while the model's routing and wording are checked against golden conversations and judges. When a prompt or model version changes, both suites rerun before release. See the Jarvis case study.

First principles

Why ML fails silently. A program fails loudly when an input violates an assumption the code checks. A model's assumptions (that inputs come from the training distribution, that features mean what they meant) are statistical and implicit. Violating them does not trip any check; it moves the input into a region where the learned function is unconstrained and still returns a number. Making failures loud means writing those assumptions down as checks: schemas, ranges, distribution tests, confidence thresholds.

Why the data is part of the program. In software, behaviour is specified by code. In ML, behaviour is specified by code and data: the training set is the specification, by example. Changing data is changing the program, so it deserves the same version control, review and testing. That is the reason for dataset versioning, data validation and lineage.

Why distributions drift. The world changes (seasons, prices, regulations). Your user base changes (growth brings new populations). And your product changes the world it measures: feedback loops make the deployed model a cause of its future data. A model is fitted to a snapshot; the snapshot ages from the day it is taken.

Why the optimal checkpoint interval is a square root. Checkpointing more often reduces the work lost per failure (which grows with \(\tau\)) but increases overhead (which falls as \(1/\tau\)). Minimising the sum of a term linear in \(\tau\) and a term in \(1/\tau\) always gives an optimum at the geometric mean of their scales, hence \(\sqrt{2\delta M}\). The same structure appears in inventory theory (the economic order quantity) and in cache refresh policies.

Why staged rollouts beat offline evaluation alone. Offline evaluation measures the model on yesterday's data with yesterday's labels. Production adds today's distribution, latency, other systems' behaviour and users' reactions to the model itself. None of those can be simulated fully, so you buy information about them cheaply: shadow traffic first (no risk), then a small canary (bounded risk), then a randomised test (causal measurement).

The maths

PSI is a symmetrised KL divergence. For binned reference proportions \(r_i\) and current proportions \(c_i\):

\[ \text{PSI} = \sum_i (c_i - r_i)\ln\frac{c_i}{r_i} = \underbrace{\sum_i c_i \ln\frac{c_i}{r_i}}_{\mathrm{KL}(c\,\|\,r)} + \underbrace{\sum_i r_i \ln\frac{r_i}{c_i}}_{\mathrm{KL}(r\,\|\,c)} , \]

the Jeffreys divergence between the two histograms (KL divergence). It depends entirely on the binning: changes inside a bin are invisible, which is why tail shifts that land in the top bin barely register.

Kolmogorov–Smirnov. With empirical CDFs \(F_n\) (reference, \(n\) samples) and \(G_m\) (current, \(m\) samples), \(D = \sup_x |F_n(x) - G_m(x)|\). Under the null hypothesis of no change, \(\sqrt{nm/(n+m)}\,D\) converges to the Kolmogorov distribution, with \(P(\sqrt{\cdot}\,D > \lambda) \approx 2\sum_{k\ge1}(-1)^{k-1}e^{-2k^2\lambda^2}\). Because the scale factor grows like \(\sqrt{n}\), a fixed small \(D\) becomes "significant" as sample sizes grow. With enough traffic every tiny shift is significant, so alert on effect size (D itself, PSI, a quantile ratio), not on p-values.

Multiple testing. Testing \(m\) independent features at level \(\alpha\) gives \(P(\text{at least one false alarm}) = 1 - (1-\alpha)^m\): 87% for \(m = 200\), \(\alpha = 0.01\). Bonferroni testing at \(\alpha/m\) controls this, at the cost of sensitivity.

Derivation: Young's optimal checkpoint interval

A run checkpoints every \(\tau\) seconds of work; each checkpoint stalls training for \(\delta\). Failures arrive as a Poisson process with rate \(1/M\). Per cycle of length \(\tau + \delta\), the overhead from checkpointing is \(\delta\). When a failure happens, on average half a cycle of work is lost (uniformly distributed failure time), plus a restart cost \(R\). The expected waste per unit time is approximately

\[ w(\tau) = \frac{\delta}{\tau + \delta} + \frac{\tau/2 + R}{M} \approx \frac{\delta}{\tau} + \frac{\tau}{2M} + \frac{R}{M}\qquad(\delta \ll \tau \ll M). \]

Setting \(w'(\tau) = -\delta/\tau^2 + 1/(2M) = 0\) gives

\[ \tau^\star = \sqrt{2\delta M},\qquad w(\tau^\star) \approx \sqrt{\frac{2\delta}{M}} + \frac{R}{M}. \]

The waste at the optimum scales as \(\sqrt{\delta/M}\): making checkpoints 12× cheaper cuts that part of the waste by \(\sqrt{12} \approx 3.5\times\). The restart term \(R/M\) does not depend on \(\tau\) at all; only faster recovery reduces it. Young (1974) derived the first-order result (CACM 17(9)); higher-order corrections matter only when \(\delta\) is not small compared with \(M\).

Build it

Three small programs. The first is a drift monitor, PSI and Kolmogorov–Smirnov written out, run on a chat assistant whose traffic gradually shifts towards long pasted documents.

import numpy as np
rng = np.random.default_rng(0)

def psi(ref, cur, bins):
    """Population Stability Index: sum (c - r) * ln(c / r) over bins."""
    r = np.histogram(ref, bins)[0] / len(ref) + 1e-6
    c = np.histogram(cur, bins)[0] / len(cur) + 1e-6
    return np.sum((c - r) * np.log(c / r))

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

# Reference week: prompt lengths (tokens) of a chat assistant. Then traffic drifts:
# a new feature lets users paste documents, so a growing share of prompts are long.
ref = rng.lognormal(4.0, 0.6, 20_000)
bins = np.quantile(ref, np.linspace(0, 1, 11)); bins[0], bins[-1] = 0, np.inf   # deciles of reference
print("week  share_long  mean_len  p95_len  PSI     KS_D    KS_p")
for week, share in enumerate([0.0, 0.0, 0.02, 0.05, 0.10, 0.20]):
    n_long = int(5_000 * share)
    cur = np.concatenate([rng.lognormal(4.0, 0.6, 5_000 - n_long), rng.lognormal(6.5, 0.5, n_long)])
    d, p = ks(ref, cur)
    print(f"{week:4d}  {share:10.2f}  {cur.mean():8.0f}  {np.quantile(cur, .95):7.0f}  "
          f"{psi(ref, cur, bins):.3f}  {d:.3f}  {p:.1e}")
week  share_long  mean_len  p95_len  PSI     KS_D    KS_p
   0        0.00        66      146  0.003  0.013  4.8e-01
   1        0.00        65      146  0.001  0.008  9.7e-01
   2        0.02        80      176  0.007  0.026  8.4e-03
   3        0.05        98      295  0.027  0.051  1.4e-09
   4        0.10       131      618  0.068  0.098  6.9e-34
   5        0.20       205      952  0.223  0.198  1.4e-137

At week 3, 5% of traffic has changed and the 95th-percentile prompt is twice as long. Prefill cost and tail latency have moved, yet PSI reads a "stable" 0.027. The KS p-value is already astronomically small at week 3, and below 0.01 at week 2. One signal is too blunt, the other too sensitive; the quantiles tell the operational story.

The second simulates checkpointing a long run with Llama 3 405B's observed failure rate. It compares intervals around Young's optimum, for a synchronous 60-second save and an asynchronous 5-second one.

import numpy as np
rng = np.random.default_rng(0)
# Llama 3 405B pre-training: 419 unexpected interruptions in 54 days  ->  mean time between failures
MTBF = 54 * 24 * 3600 / 419                       # seconds (~3.1 hours)
RESTART = 600                                      # assumed: 10 min to detect, reschedule and reload

def wasted_fraction(tau, delta, horizon=200 * 24 * 3600):
    """Simulate a run that checkpoints every tau seconds (each save stalls training for delta)."""
    t, useful = 0.0, 0.0
    while t < horizon:
        fail = rng.exponential(MTBF)              # time until the next failure
        while fail > tau + delta:                  # complete compute+save cycles before failing
            fail -= tau + delta; t += tau + delta; useful += tau
        t += fail + RESTART                        # lost: partial segment, then the restart
    return 1 - useful / t

for delta in (60, 5):                              # synchronous save vs asynchronous (overlapped)
    young = np.sqrt(2 * delta * MTBF)
    print(f"checkpoint stall {delta:3d} s   Young's interval sqrt(2*delta*MTBF) = {young / 60:5.1f} min")
    for tau in (young / 4, young / 2, young, 2 * young, 4 * young):
        print(f"   every {tau / 60:6.1f} min -> {100 * wasted_fraction(tau, delta):5.1f}% of GPU time wasted")
checkpoint stall  60 s   Young's interval sqrt(2*delta*MTBF) =  19.3 min
   every    4.8 min ->  22.5% of GPU time wasted
   every    9.6 min ->  16.4% of GPU time wasted
   every   19.3 min ->  14.5% of GPU time wasted
   every   38.5 min ->  17.5% of GPU time wasted
   every   77.1 min ->  25.8% of GPU time wasted
checkpoint stall   5 s   Young's interval sqrt(2*delta*MTBF) =   5.6 min
   every    1.4 min ->  10.9% of GPU time wasted
   every    2.8 min ->   8.6% of GPU time wasted
   every    5.6 min ->   8.0% of GPU time wasted
   every   11.1 min ->   8.8% of GPU time wasted
   every   22.2 min ->  10.9% of GPU time wasted

The minimum sits at Young's interval in both cases. With the assumed 10-minute restart, the waste cannot drop below about 5% (\(R/M\)), however you checkpoint. Llama 3's reported >90% effective training time implies recovery much faster than that.

The third gives every run a content-addressed identity: a hash of the code version, the resolved config and the data. Identical inputs reproduce the ID; any change, however small, gives a new one.

import hashlib, json, numpy as np

def fingerprint(obj) -> str:
    """Content hash of anything JSON-able or array-like: same inputs, same id."""
    if isinstance(obj, np.ndarray):
        return hashlib.sha256(obj.tobytes() + str(obj.dtype).encode() + str(obj.shape).encode()).hexdigest()[:12]
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()[:12]

def run_id(code_version, config, data):
    """A run is identified by everything that can change its result."""
    parts = {"code": code_version, "config": fingerprint(config), "data": fingerprint(data)}
    return fingerprint(parts), parts

rng = np.random.default_rng(0)
data = rng.normal(size=(1000, 8)).astype(np.float32)
config = {"lr": 3e-4, "batch": 64, "seed": 0, "model": "mlp-2x128"}

base, parts = run_id("git:4f2c1e9", config, data)
print("baseline run      ", base, parts)
print("same everything   ", run_id("git:4f2c1e9", dict(config), data.copy())[0])
print("lr changed        ", run_id("git:4f2c1e9", {**config, "lr": 1e-4}, data)[0])
data2 = data.copy(); data2[17, 3] += 1e-3                # one value in one row changed
print("one datum changed ", run_id("git:4f2c1e9", config, data2)[0])
print("code changed      ", run_id("git:8a01b7d", config, data)[0])
baseline run       a1ae61211d55 {'code': 'git:4f2c1e9', 'config': '0dba14985f81', 'data': 'a6d8752074bc'}
same everything    a1ae61211d55
lr changed         b41f329d76d7
one datum changed  67ee471b2a14
code changed       a1895f0c6ab5

The same idea, content hashes of inputs as cache keys, is how pipeline orchestrators decide which steps can be skipped, and how data-versioning tools such as DVC track datasets alongside code.

Things to try

  • In the drift monitor, replace decile bins with bins that include extra edges in the tail (e.g. the reference's 99th and 99.9th percentiles). How early does PSI now react?
  • Add a categorical feature (say, detected language) with a chi-squared test, and simulate a launch in a new country.
  • Monitor 200 independent, unchanged features daily for 30 days at \(p < 0.01\). Count the false alarms, then apply Bonferroni and a "three windows in a row" persistence rule.
  • In the checkpoint simulator, set RESTART = 60 and see how close you get to Llama 3's

    90% effective training time. What MTBF would a 100,000-GPU cluster have if failures scale linearly with GPU count?

  • Extend run_id with the environment (numpy.__version__, Python version) and a seed, and store runs in a dictionary keyed by ID to make a 20-line experiment tracker with caching.

In practice

  • Start with level 1, not a platform. Version data, track experiments, automate one training pipeline with validation and a gated release, and add monitoring on a few signals that matter. Buy or adopt tools for the rest when the pain is real.
  • Write the evaluation set first. A fixed, versioned evaluation set with important slices is the backbone of every gate. It is also the first thing teams regret not having.
  • Log predictions with their inputs and model version, sampled if volumes are huge. Without them you cannot debug, label hard cases or measure drift after the fact.
  • Give every alert an owner and a runbook, and delete alerts nobody acts on.
  • Keep the previous model one switch away, with its features still computed.
  • For LLM apps, pin model versions, version prompts in the repository, and run the eval suite in CI. Track tokens and cost per request as first-class metrics.
  • Read the post-mortems. The OPT-175B logbook and the Llama 3 infrastructure section are honest accounts of what operating large runs is like.

Common misconceptions

\"MLOps is a tool you install.\"

Tools help, but the substance is practices: versioned data, reproducible runs, gated releases and outcome monitoring. A team with a spreadsheet of run IDs and a strict eval gate is ahead of one with a platform and no evaluation set.

\"Drift detected, so retrain.\"

Drift in inputs does not always hurt the model, and retraining on shifted data without labels or gates can make things worse. Drift is a reason to look: check outcome metrics and sampled grades, then decide.

\"A good offline score means it will work in production.\"

Offline evaluation assumes production looks like the evaluation set. Skew, new populations, latency limits and user adaptation all break that. This is why shadow, canary and A/B stages exist.

\"With a fixed seed, my training run is reproducible.\"

Not bitwise across GPUs, library versions or non-deterministic kernels, and not statistically if a single seed's result is within seed-to-seed noise. Reproducibility means pinning every input and reporting variation across seeds.

Check yourself

Name the four inputs that determine a training run's result, and one way to pin each.

Code (commit hash and container image), data (content hash or immutable snapshot, plus split definition and shuffle seed), configuration (the full resolved config, logged with the run), and randomness/environment (seeds, library and driver versions, hardware type; deterministic kernels if bitwise repeatability matters).

What is training–serving skew, and how do teams prevent it?

The same feature computed differently offline (training) and online (serving): different code, different time windows, a different tokenizer or normalisation. The model then sees inputs at serving time unlike those it was trained on. Prevent it by computing features with one shared code path or feature store, logging served features and comparing them with training features, and running the new model in shadow mode.

Why can't you detect concept drift from inputs alone?

Concept drift is a change in \(p(y \mid x)\), the relationship between inputs and the right answer. The input distribution \(p(x)\) can stay identical while the correct outputs change. Detecting it needs labels, outcome signals or graded samples of production outputs.

A KS test on 1 million requests per day flags drift every day with p < 1e-6. What do you do?

With that much data, tiny and harmless shifts are statistically significant. Alert on effect size instead: the KS statistic D, PSI, or ratios of operationally meaningful quantiles (p95 input length, share of a new language). Set thresholds that reflect impact, require persistence, and check whether outcome metrics moved.

A checkpoint takes 2 minutes and the job's mean time between failures is 8 hours. What interval does Young's formula give, and what waste?

\(\tau^\star = \sqrt{2 \times 120 \times 28{,}800} \approx 2{,}629\) s ≈ 44 minutes. Waste from checkpointing and lost work ≈ \(\sqrt{2\delta/M} = \sqrt{240/28{,}800} \approx 9.1\%\), plus restart time / M. Making the save asynchronous (say 10 s) gives \(\tau^\star \approx 13\) minutes and about 2.6% waste.

Hard: you ship an LLM feature with a pinned model, a versioned prompt and an eval suite. Name three ways it can still silently degrade, and the monitoring signal that would catch each.

(1) The retrieval corpus or embedding index changes or goes stale: catch it with retrieval hit-rate or relevance on sampled traces, and index freshness. (2) User inputs drift (longer documents, new languages, new intents) outside what the golden set covers: monitor input length quantiles, language mix and intent distribution, and grade sampled traces. (3) Tool or upstream API behaviour changes (schemas, error rates): monitor tool-call error rates and structured-output validation failures. A fourth: provider-side changes even under a pinned name, such as safety-filter or infrastructure updates. Watch refusal rate, output length and latency per model version.

Go deeper

Papers

Videos and lectures

Articles and guides

Code

Where this leads