Replay Buffers and Rollback
An online model has two weaknesses that batch training does not. First, it forgets: it learns only from what arrives now, so when the stream stops showing some kind of example for a while, the model drifts away from it, even if that kind of example will come back. Second, it is exposed: every batch changes the model that is serving predictions, so one corrupted batch (a broken labelling job, a bot attack, a bug upstream) damages the live system immediately. The two standard defences are a replay buffer, which keeps a small, representative memory of the past and mixes it into every update, and versioning with rollback, which never lets an update go live unchecked and can always return to a known good model.
Replay: remember a sample of the past
The idea is old and simple: keep a buffer of past examples and train on a mix of new and old,
with drawn from the buffer. The same mechanism appears in deep reinforcement learning (experience replay), in continual learning (rehearsal) and in fine-tuning (mixing some of the original pretraining data into a fine-tuning run to limit catastrophic forgetting).
The buffer has a fixed size , but the stream is unbounded and its length unknown. Which examples should it hold? A uniform random sample of everything seen so far is a good default, and reservoir sampling (Algorithm R) maintains one in a single pass: keep the first items; when item arrives, keep it with probability , replacing a uniformly chosen slot. Item (with ) enters with probability and then survives each later step with probability , so after items
the same for every item, early or late (for the first factor is 1 and the product runs from , giving too).
From scratch: reservoir sampling
Algorithm R, and a check of the formula: run it 2,000 times on a stream of 200 items with and count how often each item ends in the buffer. Every item should be there with probability .
import numpy as np
def reservoir(stream, k, rng):
"""Algorithm R: a uniform random sample of k items from a stream of unknown length."""
buf = []
for n, item in enumerate(stream, start=1):
if n <= k:
buf.append(item) # fill the buffer first
else:
j = rng.integers(0, n) # keep the new item with probability k / n
if j < k:
buf[j] = item # it replaces a random slot
return buf
rng = np.random.default_rng(0)
N, k, reps = 200, 10, 2000
counts = np.zeros(N)
for _ in range(reps):
counts[reservoir(range(N), k, rng)] += 1
freq = counts / reps
print(f"expected inclusion probability k/N = {k / N:.3f}")
for a, b in ((0, 10), (10, 50), (50, 100), (100, 150), (150, 200)):
print(f"items {a:3d}..{b - 1:3d}: mean inclusion {freq[a:b].mean():.3f}")
print(f"min {freq.min():.3f}, max {freq.max():.3f} over all {N} items")expected inclusion probability k/N = 0.050
items 0.. 9: mean inclusion 0.052
items 10.. 49: mean inclusion 0.049
items 50.. 99: mean inclusion 0.050
items 100..149: mean inclusion 0.050
items 150..199: mean inclusion 0.051
min 0.038, max 0.061 over all 200 items
The first ten items (which always enter the buffer) and the last fifty (which arrive when the chance of entering is only ) end up with the same inclusion rate as the rest, about 0.05. The spread from 0.038 to 0.061 is sampling noise: with 2,000 runs, the standard deviation of each frequency is , and 200 items spread over a few standard deviations.
Replay against forgetting
A hard case for an online learner: the stream first shows only digits 0 to 4 (630 images), then only digits 5 to 9 (627 images), in chunks of 45. This is class-incremental learning, a severe version of the recurring drift of the previous lesson. The model is scikit-learn's SGDClassifier with partial_fit. With a replay buffer, each chunk is trained together with 45 examples drawn from the buffer, and the buffer is maintained by reservoir sampling. Accuracy is measured on the fixed test split of 540 images, separately for the old and the new digits.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import SGDClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_test, y_tr, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
rng = np.random.default_rng(0)
phase_a = rng.permutation(np.where(y_tr < 5)[0]) # the stream first shows digits 0-4 ...
phase_b = rng.permutation(np.where(y_tr >= 5)[0]) # ... then only digits 5-9
stream = np.concatenate([phase_a, phase_b])
old = y_test < 5
def accuracy(clf):
return (f"0-4 {clf.score(X_test[old], y_test[old]):.3f}, 5-9 {clf.score(X_test[~old], y_test[~old]):.3f}, "
f"all {clf.score(X_test, y_test):.3f}")
def run(buffer_size, chunk=45, replay=45):
clf = SGDClassifier(loss="log_loss", alpha=1e-4, random_state=0)
r = np.random.default_rng(1)
buf, seen = [], 0
for start in range(0, len(stream), chunk):
idx = stream[start:start + chunk]
batch = idx
if buf: # mix replayed old examples into the chunk
batch = np.concatenate([idx, r.choice(buf, min(replay, len(buf)), replace=False)])
clf.partial_fit(X_tr[batch], y_tr[batch], classes=np.arange(10))
for i in idx: # reservoir sampling into the buffer
seen += 1
if len(buf) < buffer_size:
buf.append(i)
elif buffer_size and r.integers(0, seen) < buffer_size:
buf[r.integers(0, buffer_size)] = i
if start + chunk == len(phase_a):
after_a = accuracy(clf)
return after_a, accuracy(clf)
print(f"stream: {len(phase_a)} images of digits 0-4, then {len(phase_b)} of digits 5-9, in chunks of 45")
for size in (0, 100, 300):
after_a, final = run(size)
print(f"replay buffer {size:3d}: after phase A: {after_a}")
print(f" after phase B: {final}")stream: 630 images of digits 0-4, then 627 of digits 5-9, in chunks of 45
replay buffer 0: after phase A: 0-4 0.974, 5-9 0.000, all 0.489
after phase B: 0-4 0.332, 5-9 0.959, all 0.644
replay buffer 100: after phase A: 0-4 0.948, 5-9 0.022, all 0.487
after phase B: 0-4 0.790, 5-9 0.941, all 0.865
replay buffer 300: after phase A: 0-4 0.934, 5-9 0.030, all 0.483
after phase B: 0-4 0.904, 5-9 0.937, all 0.920
Without replay, the model is good on digits 0 to 4 after phase A (0.974) and then forgets them: after phase B it gets only 0.332 of them right, while it recognises the new digits 5 to 9 (0.959). Nothing about digits 0 to 4 changed; they simply stopped appearing, and every update pushed the shared weights towards the new classes. A buffer of only 100 images (8 % of the stream, filled by reservoir sampling) brings the old digits back to 0.790 and the overall accuracy from 0.644 to 0.865; a buffer of 300 gives 0.904 on the old digits and 0.920 overall. The price is small: memory for the buffer, and a little accuracy on the newest data (0.937 instead of 0.959 on digits 5 to 9), because part of every update is spent on the old ones.
Uniform reservoir sampling is not the only choice. Class-balanced buffers keep the same number per class, which matters when some classes are rare; recency-weighted buffers favour recent data when old data is less relevant; and when raw data must not be stored (privacy, retention rules), generative replay trains a small generator to produce pseudo-examples of the past, and regularisation methods such as EWC protect important weights instead of storing data.
Versioning, guards and rollback
Replay protects against slow forgetting. Rollback protects against sudden damage. The pattern, the same in online learning and in a weekly batch-retraining pipeline:
- Never update the serving model in place. Update a copy, the candidate.
- Gate it on a labelled holdout that is never trained on (recent, so that it reflects the current concept), plus sanity checks: prediction distribution, latency, no NaN outputs, per-segment metrics.
- Version everything that passes: weights, preprocessing state (a running scaler is part of the model), the data range it was trained on, the metrics at the gate.
- Roll back to the last good version when a gate fails, when monitoring sees a regression after deployment, or when a drift detector fires and the new data turns out to be bad rather than new.
For larger changes, a candidate can also run in shadow mode (it predicts on live traffic but its predictions are only logged) or as a canary (it serves a small share of traffic) before it replaces the champion; Deployment & MLOps covers those.
From scratch: a guarded online learner
A stream of 6,000 rows in chunks of 500, a holdout of 1,000 labelled rows that is never trained on, and an SGDClassifier with a constant learning rate. Chunk 6 arrives with every label flipped, as a broken labelling job would produce. The unguarded learner applies every chunk; the guarded one updates a copy, rejects it if its holdout accuracy is more than 0.02 below the best so far, and otherwise registers it as a new version.
import copy
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier
X, y = make_classification(n_samples=7000, n_features=20, n_informative=8, random_state=0)
X_hold, y_hold = X[:1000], y[:1000] # labelled holdout, never trained on
chunks = [(X[i:i + 500], y[i:i + 500].copy()) for i in range(1000, 7000, 500)]
chunks[6][1][:] = 1 - chunks[6][1] # chunk 6 arrives with every label flipped
def stream(guarded, tolerance=0.02):
model = SGDClassifier(loss="log_loss", learning_rate="constant", eta0=0.01, random_state=0)
model.partial_fit(*chunks[0], classes=[0, 1])
versions = [copy.deepcopy(model)] # a tiny model registry: v0, v1, ...
best = model.score(X_hold, y_hold)
deployed, log = [best], []
for c, (Xc, yc) in enumerate(chunks[1:], start=1):
candidate = copy.deepcopy(model) # never update the serving model in place
candidate.partial_fit(Xc, yc)
acc = candidate.score(X_hold, y_hold)
if guarded and acc < best - tolerance: # clearly worse: reject, keep serving the old one
log.append(f"chunk {c:2d}: candidate {acc:.3f} rejected, still serving v{len(versions) - 1}")
continue
model = candidate
versions.append(copy.deepcopy(model))
best = max(best, acc)
deployed.append(acc)
log.append(f"chunk {c:2d}: candidate {acc:.3f} deployed as v{len(versions) - 1}")
return model, log, deployed
for guarded in (False, True):
model, log, deployed = stream(guarded)
print("guarded updates" if guarded else "unguarded updates")
print(" " + "\n ".join(log[3:8]))
print(f" lowest holdout accuracy ever deployed {min(deployed):.3f}, final {model.score(X_hold, y_hold):.3f}")unguarded updates
chunk 4: candidate 0.898 deployed as v4
chunk 5: candidate 0.896 deployed as v5
chunk 6: candidate 0.133 deployed as v6
chunk 7: candidate 0.904 deployed as v7
chunk 8: candidate 0.893 deployed as v8
lowest holdout accuracy ever deployed 0.133, final 0.904
guarded updates
chunk 4: candidate 0.898 deployed as v4
chunk 5: candidate 0.896 deployed as v5
chunk 6: candidate 0.133 rejected, still serving v5
chunk 7: candidate 0.902 deployed as v6
chunk 8: candidate 0.892 deployed as v7
lowest holdout accuracy ever deployed 0.892, final 0.902
The flipped chunk turns the unguarded model into one that is wrong 87 % of the time (holdout 0.133), and that model is deployed as v6. The next normal chunk repairs it (0.904), so the final number looks fine, but for the whole interval between chunks 6 and 7 the live system served almost inverted predictions: the lowest accuracy ever deployed is 0.133. The guarded learner rejects the candidate, keeps serving v5, and continues with the next chunk; the lowest accuracy it ever deployed is 0.892. The final accuracies are almost equal (0.904 and 0.902), which is the point: a final score hides what users saw along the way, and the guard is about the worst moment, not the end.
The tolerance is a trade-off like a drift detector's threshold. Too small, and normal noise (here chunk-to-chunk changes of about 0.01) rejects good updates and freezes the model; too large, and moderate damage gets through. Choose it from the observed variation of the gate metric between good updates.
Pitfalls
- A buffer that is not representative. Keeping only the last examples is a sliding window, not a memory of the past; it forgets just as the plain learner does, only later.
- Replaying data you are no longer allowed to keep. Retention limits and deletion requests apply to the buffer too; record what is in it.
- A stale holdout. If the gate's holdout comes from last year, a model that adapted correctly to a real drift fails the gate. Refresh the holdout with recent labelled data, and version it.
- A holdout that leaks into training. Then the gate always passes.
- Versioning only the weights. Rolling back the weights but not the scaler, vocabulary or feature definitions produces a model that has never existed.
- Rolling back without finding the cause. A rejected batch is a signal: find out why the labels were wrong before the next batch from the same source arrives.
Practice
- In reservoir sampling with , what is the probability that the 500th item of a stream enters the buffer when it arrives, and the probability that it is still there after 1,000 items?
- In the replay experiment, why did digits 0 to 4 drop to 0.332 without replay, although no example of them was wrong or changed?
- The guarded learner rejects every update for a week after a real change in customer behaviour. What is probably wrong, and how do you fix it?
Answers
- It enters with probability . After 1,000 items its probability of being in the buffer is : it must enter (0.02) and then survive the next 500 steps, .
- In phase B every chunk contains only digits 5 to 9. Each update lowers the scores of the old classes on these images and moves the shared weights towards the new classes; nothing in the updates reminds the model of digits 0 to 4. That is catastrophic forgetting caused by the order of the stream, not by bad data.
- The holdout still reflects the old behaviour, so a model that adapts to the new behaviour looks worse on it. Refresh the holdout with recent labelled data (and version it), and treat a sustained, drift-detector-confirmed drop differently from a single bad batch.
Test yourself
With reservoir sampling of size , what is the probability that any given item of a stream of items is in the buffer at the end?
- for every item
- Higher for early items
- Higher for late items
What does a replay buffer protect an online learner against?
- Slow inference
- Forgetting old patterns that temporarily stop appearing in the stream
- Label noise in the current batch
- Large models
Why should an online update be applied to a copy of the serving model?
- Copies train faster
- So that the update can be checked on a holdout before it serves predictions, and rejected if it is bad
- To save memory
- Because
partial_fitrequires it
A rollback restores model version v5. What else must be restored with it?
- Nothing
- Its preprocessing state and feature definitions (scaler, vocabulary, ...)
- The test set
- The learning rate of v6