Part of World Models Handbook
Explains how world models adapt over time through offline, online, and continual learning, covering replay, catastrophic forgetting, and safe drift guardrails.
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Online, Offline, and Continual Learning
A warehouse robot spends its first month learning how boxes slide when pushed. The model is good. Then the facility installs a new conveyor belt, and the same pushes produce different outcomes. The robot's world model is now wrong, and it has no way of knowing that unless it keeps learning. If it keeps learning, it risks overwriting the month of experience it accumulated. And if it adapts too eagerly to the new belt, it may become worse at everything else.
This chapter is about that tension. Every world model we have built in this handbook was trained by minimizing some loss on some dataset, as we saw in Predictive and Generative Objectives and Data Curation and Synthetic Data. But real agents do not stop collecting data when training ends. They keep acting, keep observing, and keep receiving new transitions that may or may not resemble the ones they were trained on. The question is how to keep the model useful over time.
That question changes what a world model is. A model trained once on a fixed dataset is a snapshot of the world as it was during data collection. A model that keeps learning is a process that must decide, at every update, how much to trust the past and how much to trust the present. The design choices that govern that decision determine whether the agent accumulates competence, remains frozen in an obsolete regime, or chases its own errors into regions where it is confidently wrong.
We will work through three regimes and the problems that separate them.
- Offline learning fits a model once to a fixed dataset. It is reproducible, easy to evaluate, and easy to audit.
- Online learning interleaves updates with data collection. It is adaptive, but every update changes the data the agent will collect next.
- Continual learning faces a sequence of tasks, environments, or regimes and must perform well on all of them, not only the most recent one.
Each regime brings its own failure mode. Offline models go stale. Online models drift. Continual models forget. These are not three separate problems to be patched independently; they are three faces of a single design decision about how much weight the model should give to old data relative to new data. That decision is the subject of this chapter.
The regimes also differ in what information is available at training time. In the offline regime, the dataset is fixed before optimization begins, so every update can be evaluated against a stable objective. In the online regime, the objective itself is moving because the data distribution is generated by a policy that the model is helping to change. In the continual regime, there may be no single objective at all, only a sequence of objectives that may conflict. Each transition between regimes removes an assumption that made the previous regime easier to analyze.
We will also keep a distinction in view that runs through the whole book. A world model can be evaluated in two very different ways. Open-loop accuracy asks whether predicted futures match observed futures. Closed-loop usefulness asks whether an agent that plans with the model achieves its goals. A model can improve on the first metric while degrading on the second, because the policy is an optimizer and optimizers find the model's mistakes. Any discussion of online adaptation has to hold both metrics at once.
That distinction is worth making concrete early. Open-loop accuracy is measured by holding the model fixed, feeding it a sequence of inputs from a held-out dataset, and comparing its predictions to the recorded targets. Closed-loop usefulness is measured by placing the model inside an agent, letting the agent choose actions, and evaluating the outcomes in the real environment. The first metric treats the model as a predictor. The second treats it as a component whose errors alter the distribution of future inputs. A model can be excellent as a predictor on the data it has seen and catastrophic as a component, because the agent will deliberately steer toward the parts of the input space where the model's predictions are most favorable, not necessarily most accurate.
Continual learning is the problem of learning from a stream of tasks, environments, or data distributions presented sequentially, such that performance on earlier tasks is retained. It is sometimes called lifelong learning or incremental learning. Its central difficulty is that updates driven by new data tend to overwrite the parameters that encoded old data.
The definition above contains a subtle phrase: "presented sequentially." A continual learning problem is more than a collection of datasets because the order matters. If the agent sees task A and then task B, the update for task B can erase task A. If it sees them interleaved, the interference may be milder. If it sees task A, then task B, then task A again, it may recover some performance on A, but only by damaging B. Continual learning is therefore a study of trajectories through parameter space, not only final loss values on individual tasks.
Batch and Streaming Updates
The distinction between batch and streaming updates is about how data reaches the optimizer, not about how the optimizer works.
In the batch (or offline) setting you have a dataset collected beforehand. You choose parameters by minimizing the empirical risk
where:
- : the parameter estimate that minimizes the average loss over the dataset
- : the parameters being optimized
- : the dataset of input-target pairs,
- : the number of examples in the dataset
- : the per-example loss function, such as squared error
- : the model's prediction for input
- : the target value paired with
- : the -th input example
For a world model, is a transition input such as , is the target such as , and is the learned dynamics. This is the setting of Part V and Part VI so far. It has several properties worth naming explicitly:
- Reproducibility. The result can be reproduced when the dataset, architecture, optimization procedure, software stack, hardware, and random seeds are controlled.
- Multiple passes. You can shuffle and revisit every example as many times as you like.
- Auditability. You can inspect exactly what the model was trained on.
- Staleness. Once training stops, the model has no mechanism to notice that the world changed.
These properties are tightly connected. Reproducibility comes from the fact that the dataset is fixed, so the same optimization procedure applied to the same data yields the same result up to random seeds and hardware nondeterminism. Multiple passes are possible because the dataset is stored in full and can be revisited indefinitely; this is what allows offline training to extract many gradient steps per example. Auditability follows from the same storage: the training distribution is not a moving target but a concrete artifact that can be inspected, versioned, and checked for biases or gaps. Staleness is the price. A model that was trained on a fixed dataset has no internal signal that the world has moved on. Its errors on the new world are not necessarily large, but they are unmonitored.
In the streaming (or online) setting data arrives as a sequence and you update after each arrival:
where:
- : the parameters after processing the -th example
- : the parameters before the update
- : the learning rate at step
- : the current step index in the stream
- : the -th input and target pair arriving from the stream
- : the per-example loss function
- : the gradient of the loss on the current example with respect to the parameters
- : the model's prediction for input using the current parameters
- : the model parameters
This is stochastic approximation. Under the usual regularity assumptions on the objective, gradients, and noise, a standard route to convergence uses the classical Robbins--Monro step-size conditions. They require that the learning rates accumulate enough total step size to keep moving while the squared learning rates accumulate little enough total noise for it to average out:
where:
- : the learning rate applied at step
- : the total accumulated step size, which must diverge so the estimator can travel any distance
- : the total accumulated squared step size, which must converge so gradient noise averages out
Here is the learning rate applied at step . Such schedules are called square-summable but not summable: the first condition keeps the estimator moving in expectation, while the second keeps its variance from accumulating.
The first condition says the learning rate must not shrink so fast that the model freezes before it arrives. The second says it must shrink fast enough that accumulated gradient noise averages out. A schedule like satisfies both. The schedule and a positive constant both violate square summability; the constant still satisfies the divergent-sum condition. That persistent step size is useful in non-stationary settings because it keeps the estimator responsive, at the cost of a nonzero noise floor.
The schedule shape determines how the estimator behaves over time. The figure below compares three common choices on logarithmic axes, where the difference between square-summable and non-summable decay is easiest to read.
import numpy as np
schedule_t = np.arange(1, 201)
eta_inverse_t = 1.0 / schedule_t
eta_inverse_sqrt = 1.0 / np.sqrt(schedule_t)
eta_constant = np.full_like(schedule_t, 0.05, dtype=float)
The Robbins and Monro conditions are a useful reference point even when they do not literally apply. They describe the behavior of an estimator that is trying to converge to a fixed target in a stationary world. In a world-modeling loop, the target is not fixed: the true dynamics may change, and even if they do not, the distribution of states and actions that the model sees depends on the policy, which depends on the model. The classical conditions therefore tell us what convergence would require if the world stood still. They also tell us why practical systems use constant or slowly decaying learning rates: the agent is not trying to converge to a fixed answer, because the answer keeps moving.
A useful mental model is to separate two questions. The first is whether the optimizer can reach a good solution if one exists. The second is whether the optimizer can track a solution that changes over time. Batch learning is optimized for the first question. Streaming learning with a constant learning rate is optimized for the second. Continual learning must answer both, often without knowing which regime it is currently in.
Batch and streaming are endpoints of a spectrum. Full-batch gradient descent uses all examples per step. Mini-batch SGD uses examples per step. Pure online SGD uses one. Everything between is a design choice about how much of the historical distribution to include in each update. A replay buffer, which we turn to in the next section, is the device that lets you move along this spectrum even when data arrives one sample at a time.
The spectrum covers both batch size at a single step and how long data is retained. A method could update on a mini-batch of recent data and still be highly online if that mini-batch is discarded immediately. Another method could update on a single example drawn from a large historical buffer and behave much more like batch training. The relevant quantity is the effective age distribution of the data contributing to each update.
The learning rate as a memory knob
There is a precise sense in which the learning rate controls how much history the estimator remembers. Consider the simplest case: a scalar linear model with zero-mean and independent of . The SGD update is
where:
- : the updated parameter estimate
- : the current parameter estimate
- : the constant learning rate
- : the scalar input at step
- : the observed target at step
- : the prediction error, which drives the update
Here is the current parameter estimate, is the constant learning rate, is the scalar input at step , is the observed target, and is the prediction error that drives the update.
Writing the error as and substituting gives
where:
- : the parameter error after the update,
- : the parameter error before the update,
- : the learning rate
- : the scalar input at step
- : the zero-mean observation noise at step
- : the parameter estimate before the update
- : the parameter estimate after the update
- : the true parameter value
The first term shrinks the existing error, while the second term injects noise. Take expectations over the noise and inputs, assuming the current sample is independent of , , and :
where:
- : the expected parameter error at step
- : the learning rate
- : the variance of the inputs
- : the geometric decay rate of the bias
- : the expected parameter error at step
The bias decays geometrically at rate . A large learning rate forgets old errors quickly. A small one holds onto them. We will return to this in the worked example.
This recursion is the simplest possible model of memory in gradient descent. The current error is a weighted combination of the previous error and a noise term. The weight on the previous error is approximately one minus the learning rate times the input variance. If that weight is close to one, the estimator remembers its old error for a long time. If it is close to zero, the estimator discards its old error almost immediately. In a stationary world, a small weight is good, because the old error was itself caused by noise or by initialization and should be forgotten. In a non-stationary world, the old error may contain information about dynamics that are still partially valid, and forgetting it completely may be wasteful.
There is a second sense in which the learning rate controls memory. The stationary variance of the estimator is proportional to the learning rate. A large learning rate makes the estimator responsive but noisy. A small learning rate makes it precise but slow. The memory knob and the noise knob are the same knob, turned in opposite directions. This is the fundamental tradeoff that reappears in every method in this chapter.
Recursive least squares and the Kalman connection
For linear models there is an exact streaming estimator that avoids gradient descent entirely. Recursive least squares (RLS) maintains a parameter estimate and a covariance matrix :
where:
- : the inverse information matrix after step ; under a matching linear-Gaussian model with normalized observation noise, it is proportional to the posterior covariance of
- : the covariance before the update
- : the input (feature) vector at step
- : the parameter estimate after step
- : the parameter estimate before the update
- : the target at step
- : the prediction residual, which drives the parameter correction
- : the parameter vector being estimated
If you have read Bayesian Filtering and Belief States, this should look familiar: RLS is a Kalman filter for a constant parameter with no process noise. Under a matching linear-Gaussian model, is proportional to the posterior covariance of , and it shrinks as evidence accumulates. With persistent excitation in every parameter direction, approaches zero and the gain becomes arbitrarily small. Plain RLS then adapts increasingly slowly to a change; directions that are not sufficiently excited need not collapse.
The intuition is that RLS is not merely averaging recent samples. It is maintaining a full second-order description of what it knows. When data is plentiful and the model is confident, the covariance becomes small, so the update gain becomes small. When data is scarce or the input directions are poorly explored, the covariance remains large, so the estimator is willing to move. This is exactly the behavior a learner should have in a stationary world. It is exactly the wrong behavior in a world that changes, because the estimator becomes most confident precisely when it has seen the most data, which may be the data from before the change.
The fix is to add process noise, which produces a forgetting factor :
where:
- : the forgetting factor, with ; smaller down-weights older data more aggressively and inflates the covariance to preserve plasticity
- : the covariance after and before the update
- : the input vector at step
With , older observations are exponentially down-weighted with time constant . This is the cleanest formal statement of the memory-versus-plasticity tradeoff: the forgetting factor is a literal discount on history. A value of means the effective window is roughly 100 samples; means roughly 1000.
The forgetting factor has a statistical interpretation: it inflates the covariance carried from the previous step, expressing a belief that old information is becoming less relevant. In a Kalman interpretation this resembles process noise, although exponential forgetting generally implies a state-dependent covariance inflation rather than a fixed random-walk covariance. In a world model, the drifting quantity might be a physical coefficient, a reward function, or an entire latent dynamics model.
Update-to-data ratio
A quantity that matters in every model-based agent is the update-to-data ratio, sometimes called the replay ratio: how many gradient steps the model takes per environment step collected. In offline training the ratio is enormous (many epochs over a fixed dataset). In a purely streaming loop it is one. In practice, agents such as Dreamer and MBPO sit somewhere in between, and the choice has real consequences. A high ratio extracts more information per real interaction, which is the entire appeal of learning a model in the first place. But a high ratio also means the model is repeatedly optimized against a fixed, possibly stale dataset, so it overfits to whatever the last batch of data happened to contain. Modern practice typically sets an explicit update budget and monitors both open-loop and closed-loop metrics against it.
The update-to-data ratio is one of the few quantities in model-based learning that directly connects computational budget to statistical behavior. If the ratio is one, the model sees each transition exactly once and then moves on. If the ratio is large, the model may see the same transition many times, which can be useful when real interaction is expensive but dangerous when the transition is no longer representative. A high ratio also changes the effective learning rate schedule: many small updates on the same data can approximate a larger update, and many updates on stale data can drive the model to memorize idiosyncrasies of the buffer.
Assumptions that quietly break
The streaming update above assumes the data are drawn from a stationary distribution and that consecutive samples are independent. Neither assumption holds in a world-modeling loop.
- Stationarity fails whenever the environment changes, the agent's policy changes, or the agent's own learning changes what it does.
- Independence fails because consecutive transitions in a trajectory are highly correlated. A robot that has just turned left is likely to turn left again.
Correlated samples make the gradient an average over a stretch of trajectory rather than over the distribution of interest, which biases updates and inflates effective variance. This is one reason practical systems shuffle, buffer, and batch rather than truly updating one sample at a time. It is also why the word "online" in modern deep RL usually means "interleaved with data collection," not "one gradient step per sample with no memory."
There is a further assumption that is often invisible: the loss being minimized is assumed to be the right objective for the deployment distribution. In a stationary supervised problem, minimizing average loss on the training distribution is a reasonable proxy for minimizing loss on the test distribution. In a world model, the training distribution is generated by the agent's own behavior, and the test distribution is whatever distribution the agent will encounter in the future. Those two distributions can diverge dramatically. Minimizing loss on yesterday's data may not reduce loss on tomorrow's data if the policy has moved on.
Distribution Shift and Replay
Distribution shift is the situation where the data the model sees at deployment differs from the data it was trained on. It is the reason an offline model goes stale and the reason an online model can chase its own tail.
The classical taxonomy distinguishes three kinds of shift, and it is worth mapping each onto world models explicitly.
- Covariate shift: the distribution of inputs changes, but the conditional does not. In a world model this means the agent visits new states and new actions, but the underlying physics is unchanged. This happens constantly, because policies explore.
- Concept shift: the conditional changes while inputs stay in the same range. In a world model this is a real change in dynamics: the conveyor belt speeds up, the surface becomes slippery, gravity changes in simulation. This is what we usually mean by the world changing.
- Prior-probability shift: the label prior changes while the class-conditional input distribution remains fixed. In world-model deployments, analogous changes in goal or task frequencies can alter what the planner encounters even when the transition dynamics are unchanged.
The distinction matters because the remedies differ. Covariate shift can often be handled by collecting more data in the new input regions, because the underlying mapping is unchanged. Concept shift cannot be fixed by coverage alone; the model must update its parameters to reflect a new mapping. Prior shift may not require any change to the dynamics model at all if the dynamics are unchanged, but it can still matter for planning if the objective or the distribution of goals has changed.
When the transition function itself changes over time, the world model is non-stationary. We call this dynamics drift, and it is the hardest form of shift for a world model to handle because no amount of input coverage fixes it: the model must actively update.
Why closed-loop agents amplify shift
A supervised model that experiences covariate shift can make worse predictions on new inputs. A world model inside an agent can also induce further shift. The policy queries the model, the model returns predictions, the policy acts on those predictions, and the resulting transitions become the next training data. Model error can therefore alter the state distribution, which then changes what the model learns next. This feedback is what makes distribution shift in world models qualitatively different from distribution shift in ordinary supervised learning.
There are two consequences worth separating.
First, extrapolation is not rare, it is systematic. The policy is chosen to maximize expected return under the model. By construction, it prefers states and actions where the model predicts high return. If the model is optimistic anywhere, the policy will find that region. This is the optimizer's curse, and we will demonstrate it concretely in the code.
Second, the training distribution can narrow over time. If the agent only trains on data from the current policy, it may gradually stop seeing states that earlier policies visited. The model can become confident about a shrinking region and increasingly wrong outside it. This creates the conditions for a self-confirming loop: model errors steer the policy, and the resulting data can entrench those errors.
A useful way to see the difference from supervised learning is to imagine a classifier that is used to decide which emails reach each inbox. If the classifier makes mistakes, recipients see worse emails, but the distribution of incoming emails does not change because of the classifier's decisions. In a world model, the policy is like a classifier that decides which states to visit, and those states become the training data for the next round. The classifier is not a passive observer of its input distribution; it is an active participant in generating that distribution.
Replay as the standard remedy
The most widely used defense is experience replay. Instead of updating only on the newest transition, the agent stores transitions in a buffer and samples mini-batches from it:
where:
- : the model parameters
- : the learning rate
- : the gradient with respect to the parameters
- : the mini-batch sampled from the replay buffer
- : the number of transitions in the mini-batch
- : the loss on a buffered transition
- : the model's prediction for input
- : a transition from the buffer, with the input and the target
- : the replay buffer storing past transitions
A replay buffer is a sampled approximation to the retained history. It converts a streaming problem into something closer to a batch problem without giving up the ability to absorb new data, and is one of the main pieces of infrastructure connecting offline and online learning.
Two design choices matter most.
Buffer size controls the effective memory horizon. A small buffer tracks recent dynamics quickly and forgets older ones. A large buffer retains a broad distribution and adapts slowly. This is the same tradeoff as the forgetting factor in RLS, expressed in units of samples rather than a discount rate.
Sampling strategy controls which parts of history are emphasized.
- Uniform sampling treats every stored transition equally. It is simple, unbiased with respect to the buffer contents, and the default in most implementations.
- Prioritized sampling draws transitions with probability proportional to a priority such as the last temporal-difference error or model loss (Schaul et al., 2016). It focuses capacity on the examples the model currently gets wrong. The cost is that the sampling distribution is no longer the data distribution, so importance weights are needed to keep the gradient unbiased.
- Recency-weighted sampling blends the two, up-weighting recent transitions to track drift while still retaining a background of older data.
A replay buffer stores samples and shapes the training distribution. It determines the distribution of data that the model is trained on, and therefore the errors that the model is optimized to reduce. If the buffer is dominated by recent data, the model is optimized for the recent regime. If it contains old data, the model is optimized for a mixture of regimes. The mixture can be desirable when old data remains valid and harmful when it is obsolete.
Replay ratio and staleness
Replay introduces a second ratio to track alongside the update-to-data ratio: the replay fraction, the proportion of each batch drawn from the buffer rather than from fresh data. A replay fraction of zero is pure streaming. A fraction near one is nearly offline training on a frozen buffer.
Increasing the replay fraction stabilizes learning and reduces forgetting, but it also slows adaptation to real change, because the gradient is dominated by data that may no longer reflect the world. There is no universally correct value. What matters is that the choice is made deliberately and monitored, and that the buffer is large enough to cover the range of conditions the agent is expected to encounter.
The interaction between replay fraction and buffer size can be subtle. A large buffer with a high replay fraction produces a very stable model that changes slowly. A small buffer with a low replay fraction produces a very adaptive model that may forget quickly. A small buffer with a high replay fraction can be worse than either, because the model repeatedly trains on a narrow slice of recent history and can overfit to it while still calling it replay. The design must be considered as a whole.
Off-policy correction
When the buffer contains transitions generated by older policies, the data are off-policy with respect to the current one. For pure dynamics modeling this often matters less than it does for value learning: in a stationary Markov environment, does not depend on which policy selected . Data from any policy can therefore train the same conditional dynamics on the state-action support it covers. Hidden state, environment drift, selection effects, or inadequate support break this simple argument.
Coverage is doing real work here. Off-policy data identifies the conditional dynamics only on the region it covers. Outside that region the model is extrapolating, and that is often where the policy goes next.
This asymmetry between dynamics learning and value learning is worth emphasizing. A value function is defined relative to a policy and reward, so naive off-policy targets can be biased; importance sampling, corrected targets, or explicitly off-policy algorithms address that mismatch. A dynamics model is defined by the environment, so data collected under any policy can estimate the same transition conditional when the Markov and stationarity assumptions hold and the state-action pair lies in the data support. Replay is therefore often a natural fit for model-based learning. Its central danger is unsupported extrapolation rather than the policy label attached to an otherwise valid transition.
Catastrophic Forgetting
Catastrophic forgetting is the abrupt loss of previously learned behavior when a neural network is trained on new data. It was documented in connectionist models in the late 1980s (McCloskey and Cohen, 1989; Ratcliff, 1990) and has remained a central obstacle ever since.
The phenomenon is easy to state. Train a network on task A until it performs well. Then train the same network on task B. Performance on task A frequently collapses to near chance, even though the network has more than enough capacity to represent both tasks. The parameters that encoded A were overwritten by the gradients that encode B.
For a world model the consequences are concrete. A model that has learned the dynamics of a pick-and-place task may lose them entirely after being fine-tuned on a new task with a different gripper. A model that has learned how objects fall may lose that knowledge after adapting to a scene where nothing falls. The loss is not graceful degradation; it is erasure.
The word "catastrophic" is chosen deliberately. In many optimization problems, adding new data gently shifts the solution while preserving most of its useful structure. In neural networks trained by gradient descent, adding a new task can shift the solution so sharply that old behavior disappears. The network still has the capacity to represent the old task. The problem is that the parameters have moved to a region of parameter space that represents the new task well and the old task poorly.
Why it happens
Gradient descent has no notion of importance. Every parameter is adjusted in whatever direction reduces the current loss, and a parameter that was critical for task A is treated no differently from one that was never used. When tasks require overlapping parameters but conflicting values, the update for B necessarily damages A.
There is a geometric way to see this. The gradient for task B is a direction in parameter space that decreases . Whether it also decreases depends on the angle between the two gradients. When tasks are related, the angle is small and interference is mild. When tasks conflict, the angle is obtuse and progress on one is regression on the other. Catastrophic forgetting is severe gradient interference.
The geometry also explains why forgetting is not always total. If the gradients for two tasks are nearly orthogonal, the update for one has little effect on the other, and the network can learn both without interference. If the gradients are aligned, learning one task may help the other, which is positive transfer. The hard case is when the gradients point in opposite directions on the same parameters. Then any step toward the new task is a step away from the old one.
The stability-plasticity dilemma
The underlying tension was named by Grossberg in the 1980s. A learning system must be stable enough to retain old knowledge and plastic enough to acquire new knowledge. These requirements pull in opposite directions.
- Perfect stability means the model never changes, which means it cannot learn anything new.
- Perfect plasticity means the model always changes, which means it retains nothing.
Every continual learning method is a particular point on this spectrum. The engineering question is not whether to be stable or plastic, but where on the spectrum to sit given how fast the world is expected to change and how costly forgetting is expected to be.
The dilemma is not unique to neural networks. Any learning system that updates its parameters in response to new data faces a version of it. What makes neural networks special is the density of their representations: many tasks share parameters, and a single parameter can be important for many behaviors. That sharing is what gives neural networks their generalization power, and it is also what makes them vulnerable to interference.
Three families of solutions
Methods for mitigating forgetting fall into three broad families. In practice they are combined.
Regularization-based methods penalize changes to parameters that were important for previous tasks. The canonical example is Elastic Weight Consolidation (Kirkpatrick et al., 2017). After training on task A, EWC estimates how sensitive the loss is to each parameter using the diagonal of the Fisher information matrix , and adds a quadratic penalty when training on task B:
where:
- : the total loss while training on task B, combining the task loss with a quadratic penalty
- : the loss on task B alone
- : the regularization strength, controlling how strongly the penalty anchors important parameters
- : the Fisher information for parameter , measuring how important that parameter was for task A
- : the current value of parameter
- : the value of parameter at the end of task A
- : the parameter vector
- : the parameter index
The Fisher value itself is defined as
where:
- : input-target pairs drawn from the task-A dataset
- : an input (transition) drawn from task A
- : the target (next state) paired with
- : the model's predictive distribution over targets given inputs
- : the partial derivative with respect to parameter
- : the parameters frozen at the end of task A
- : the model parameters
- : the -th parameter
- : the task-A dataset
The Fisher value is large for parameters the model relies on and small for parameters it does not. The penalty is therefore a soft, anisotropic spring anchoring important parameters to their old values while leaving unimportant ones free to move. Related methods include Synaptic Intelligence (Zenke et al., 2017) and Memory Aware Synapses (Aljundi et al., 2018), which differ mainly in how they estimate importance.
The key intuition behind EWC is that not all parameters are equally important for a task. Near a fitted probabilistic model, and under the approximations used to derive EWC, the Fisher supplies a local curvature-based importance measure. Penalizing movement in high-Fisher directions can preserve old-task performance while leaving lower-Fisher directions more flexible; it does not guarantee that every direction behaves this way away from the anchor.
Replay-based methods keep a buffer of old examples, or a generative model of them, and mix them into the new task's batches. Gradient Episodic Memory (Lopez-Paz and Ranzato, 2017) goes further by constraining the update using episodic-memory losses from previous tasks. Averaged GEM (Chaudhry et al., 2019) replaces the per-task constraints with one constraint based on an averaged reference gradient, reducing computation and memory.
The projection in GEM is a geometric operation. It takes the current-task gradient and, when necessary, projects it so its first-order inner product with each previous task's episodic-memory gradient is nonnegative. This constrains first-order increases in the aggregate memory loss for each previous task; it is not a per-example or finite-step guarantee. The projected gradient may be smaller than the raw gradient, slowing learning of the new task.
Architectural methods isolate parameters used by different tasks. Progressive Networks (Rusu et al., 2016) freeze old columns and add a new column with lateral connections, so capacity grows while earlier features remain available for transfer. PackNet (Mallya and Lazebnik, 2018) instead iteratively prunes and freezes weights within a fixed network, using task-specific masks and the remaining free capacity. Both protect allocated weights, but their capacity and routing costs differ.
The architectural approach trades capacity and routing complexity for reduced interference. Progressive Networks explicitly use frozen old features through lateral connections and grow with the number of tasks. PackNet keeps model size fixed but consumes free parameters and requires the correct task mask at inference. Protecting parameters prevents direct overwriting of those parameters, though end-to-end retention still depends on routing and evaluation conditions.
Measuring forgetting
To compare methods you need metrics. Let denote performance on task after training through task , with tasks total. Three standard measures are:
where:
-
: performance on task after training through task (so is performance on task right after learning it, and is its performance after all tasks)
-
: the total number of tasks
-
: average accuracy across all tasks after training through task
-
: backward transfer, the average change in performance on earlier tasks after learning later ones
-
: forward transfer, performance on a new task before training it relative to a specified baseline
-
: baseline performance on task ; in the original GEM definition, test performance at random initialization
-
: the task index up to which training has proceeded
-
: the task index being evaluated
-
ACC is final average performance across all tasks. Higher is better.
-
BWT, backward transfer, measures how much learning later tasks changed performance on earlier ones. Negative BWT is forgetting. Positive BWT means the later tasks helped.
-
FWT, forward transfer, measures how much earlier tasks change performance on a new task before it is trained, relative to . In the original GEM metric, is random-initialization performance. Positive FWT indicates beneficial transfer under that baseline.
Note that these metrics are computed on a held-out evaluation set per task, not on the training data. A method that reduces training loss on task A while degrading held-out performance has not avoided forgetting; it has overfit.
The three metrics capture different aspects of continual learning. ACC measures final performance, which is what ultimately matters for deployment. BWT measures whether the model retained old skills. FWT measures whether the model can use old skills to learn new ones faster. A method with high ACC might have poor BWT if the final task is easy and the earlier tasks are irrelevant. A method with high BWT might have low ACC if it is too conservative to learn the new task well. The metrics must be read together, and they must be computed on data that the model has not trained on.
Forgetting is sometimes correct
A subtlety that the continual learning literature often understates: forgetting is not always a bug. If the world changed, the old dynamics are no longer true, and a model that insists on them is wrong. The distinction is between forgetting knowledge that is still valid and forgetting knowledge that has become obsolete.
The practical difficulty is that the agent usually cannot tell which is which. A drop in performance on old data could mean the model degraded, or it could mean the old data is no longer representative. Resolving this ambiguity is one of the central problems of continual adaptation, and it is the subject of the next section.
This ambiguity has an important consequence for method design. A method that aggressively prevents forgetting may be preserving obsolete knowledge. A method that aggressively allows forgetting may be discarding valid knowledge. The right balance depends on the environment's rate of change and on the agent's ability to detect change. In practice, the best methods often combine a mechanism for retaining knowledge with a mechanism for detecting when retention is no longer appropriate.
Continual Adaptation Without Unsafe Drift
Suppose you accept that the world changes and decide the model should keep learning online. You set up a replay buffer, a modest learning rate, and a periodic update schedule. What could go wrong?
Quite a lot. Online adaptation in a closed loop is a feedback system, and feedback systems have failure modes that open-loop training does not.
Model exploitation and the optimizer's curse
The policy is an optimizer over the model's predictions. Optimizers are adversarial to the objects they optimize. If the model has a region where it over-predicts return, the policy will find that region, regardless of how small it is.
This is the optimizer's curse (Smith and Winkler, 2006): selecting the best of many options according to noisy estimates creates an expected optimism bias in the selected estimate. Larger search sets can intensify that selection pressure, but a realized gap need not grow monotonically with every added candidate. In a world model, "many options" means many candidate action sequences, and modern planning methods may consider thousands.
The consequence for online learning can be severe. Data collection concentrates where the model predicts high return. Training on those transitions can correct the error when real outcomes are recorded and weighted adequately. If updates instead rely on model-generated targets, sparse feedback, or a buffer that underrepresents failures, the loop can reinforce an optimistic error.
It is worth distinguishing two sources of error. The first is ordinary approximation error: the model is not a perfect representation of the environment. The second is selection error: the policy chooses actions based on the model's predictions, and selection error amplifies approximation error in the regions where the model is most optimistic. The optimizer's curse is about selection error, not approximation error. Even a model with small average approximation error can have large selection error if its errors are concentrated in the regions the policy prefers.
Unsafe drift
We use unsafe drift to describe the slow, cumulative movement of a model into a regime where it is confidently wrong and the policy acts on that confidence. It differs from an ordinary performance regression in three ways.
- It is silent. Open-loop prediction error on the training distribution may look fine, because the agent has stopped visiting the region where the model is wrong.
- It is self-reinforcing. Errors steer the policy, and the policy's data confirms the errors.
- It is non-monotonic in the obvious metrics. A model can improve on average loss while becoming less safe, because the average is dominated by easy regions.
Unsafe drift is not merely hypothetical; it is a plausible failure mode for an agent that adapts its model online without adequate external checks. A concrete example appears in the code below: a planner searching over a wider action range than the model was trained on can select extrapolative actions whose model-predicted return exceeds their true return.
The word "drift" suggests slow motion, but the underlying mechanism can be fast. Once the policy discovers a region of model optimism, it will return there repeatedly, and the data from that region will dominate the training signal. The model becomes more confident about its error, which makes the policy more likely to exploit it, which generates more data from the error region. The process can accelerate rather than stabilize.
Guardrails
There is no single technique that eliminates unsafe drift, but there is a well-established set of guardrails that together make it manageable. They fall into four categories.
Constraint-based. Limit how far the model or policy can move per update. Trust-region methods constrain the KL divergence between successive policies; the same idea applies to models through a bound on the change in predicted transition distributions. A small learning rate with a bounded number of updates per unit of new data is the simplest version of this.
Uncertainty-based. Refuse to act on predictions the model is unsure about. Ensembles can disagree where the data is thin, making disagreement a useful heuristic signal, but they can also agree confidently out of distribution. This connects to Stochasticity and Uncertainty: a well-calibrated epistemic uncertainty estimate should reflect lack of knowledge under relevant shifts. Penalizing high estimated uncertainty can deter some unsupported actions.
Verification-based. Require prespecified evidence before a candidate update takes effect. Shadow deployment runs the new model in parallel with the incumbent and compares task, calibration, and safety metrics on the same live inputs without letting the new model act. A mismatch alone is not a reason to reject it; degradation on the chosen criteria is. Rollback checkpoints improve recoverability when monitoring detects degradation, but cannot guarantee that every harmful change will be detected.
Monitoring-based. Track whether live data lies inside the training distribution. Density models, reconstruction error, ensemble disagreement, and simple feature-space distances all provide signals. An out-of-distribution alarm does not fix anything by itself, but it converts a silent failure into a visible one, which is the precondition for any response.
These categories are complementary rather than alternative. Constraint-based methods can limit the size of a change. Uncertainty-based methods can deter actions in poorly supported regions. Verification-based methods can catch some regressions before promotion, while monitoring can reveal failures after deployment. High-consequence systems often layer all four, and the layers are most effective when designed together.
Adaptation as a control problem
There is a useful reframing that ties these ideas together. Online adaptation is itself a control problem, with the learning process as the plant. The setpoint is stable performance across the conditions the agent encounters. The control inputs are the learning rate, the replay fraction, the update-to-data ratio, and the decision of whether to accept an update at all. The feedback signal is a monitored metric, ideally one that combines open-loop accuracy with closed-loop task performance.
Seen this way, the online learning rate need not be a hyperparameter tuned only once. A practical heuristic is to let monitored surprise influence it: if recent real-outcome prediction error is high relative to a baseline, cautiously raise the learning rate and lower the old-data replay fraction so fresh data has more weight; if error is low and stable, reverse those changes. This is feedback-driven adaptation. It becomes dual control only when the agent also chooses actions for both their control value and the information they reveal, a connection we will examine in Active Perception, Dual Control, and Exploration.
The control view also clarifies why fixed hyperparameters are often a bad fit for continual learning. A fixed learning rate is like a controller with no feedback. It may be tuned for an average rate of change, but it cannot respond to a sudden shift or a long period of stability. A feedback-driven learning rate can. The cost is that the feedback signal must be chosen carefully, because a noisy or misleading signal can cause the controller to oscillate or to adapt in the wrong direction.
Safe online adaptation is an operational goal: update a deployed model while controlling exposure to harmful outcomes. Bounded changes, shift and degradation monitors, staged promotion, and rollback can reduce risk, but a formal probability bound requires an explicit statistical or control-theoretic guarantee beyond these mechanisms alone.
What "safe" cannot mean
It is worth being explicit about what these guardrails do not provide. They do not give formal guarantees that an arbitrary neural world model will remain accurate. They do not detect shift that produces no observable signature. They do not help if the monitoring metric itself is gamed by the same optimization pressure that drives the policy.
What they aim to provide is a reduction in the expected severity of failure and, more importantly, a reduction in the time to detection. In safety-critical deployment, the second is often worth more than the first, because a system that fails visibly and reverts is generally less dangerous than one that fails silently. We return to these questions in depth in Part XII: Reliable World Models.
There is also a deeper limitation: guardrails are designed against known failure modes. Unsafe drift is a known failure mode, so it can be monitored. But an adaptive system can fail in ways that were not anticipated, and those failures may not trigger any of the monitors. The best defense is a combination of principled design, conservative defaults, and human oversight at the points where the system's behavior changes most.
Worked Example: Tracking a Drifting Coefficient
Let us make the tradeoffs quantitative with a scalar example we can solve on paper. Suppose the true relationship is
where:
- : the observed target at step
- : the true coefficient in the drifting-coefficient example
- : the scalar input at step
- : zero-mean observation noise at step
- : the variance of the observation noise
with and , and suppose changes at some point from one value to another. We want to know how fast SGD tracks the change and how precisely it can localize the new value.
From the derivation above, the bias decays geometrically:
where:
- : the expected deviation of the estimate from the true parameter after steps
- : the parameter estimate after steps
- : the initial parameter value
- : the true parameter
- : the fixed learning rate
- : the variance of the inputs
- : the number of steps elapsed, so is the per-step contraction factor
With and , the decay rate is per step. To reduce the initial error by a factor of takes about steps. Here is where that number comes from. We want the smallest with . Taking logarithms,
where:
- : the number of steps
- : the learning rate
- : the variance of the inputs
- : a small positive quantity, here
With this gives steps. That is the adaptation time.
The adaptation time is the first half of the tradeoff. It tells us how long the estimator takes to forget an old value after the world changes. The second half is the noise ball, which tells us how precisely the estimator can settle on the new value once it has arrived.
Now the noise. At stationarity, the variance satisfies
where:
- : the stationary variance of the estimate around the true parameter
- : the stationary parameter estimate around which the variance is measured
- : the learning rate
- : the variance of the inputs
- : the scalar input at step
- : the variance of the observation noise
- : the expected squared contraction factor, which appears in the denominator
Replacing the random contraction by its mean gives the moment-closure approximation . Under that approximation,
where:
- : the stationary variance of the estimate around the true parameter
- : the stationary parameter estimate around which the variance is measured
- : the learning rate
- : the variance of the inputs
- : the variance of the observation noise
This is the noise ball: the residual fluctuation of the estimate around the true value. Its radius is
where:
- : the standard deviation of the stationary estimate fluctuation, also called the noise ball radius
- : the stationary variance of the estimate around the true parameter
- : the stationary parameter estimate around which the variance is measured
- : the learning rate
- : the observation noise variance
With and , the approximate stationary standard deviation is about . That is the scale of an instantaneous stationary fluctuation, not a hard detection limit: averaging or sequential tests can detect smaller persistent shifts. A change of is much larger, and the roughly 50-step e-folding time means the estimate moves substantially toward it over tens of steps rather than settling immediately.
The tradeoff is now explicit. Increasing shortens the adaptation time and enlarges the noise ball. Decreasing does the reverse. There is no setting that makes both small; you are choosing where on the curve to sit. This is the same tradeoff that a replay buffer expresses in sample units, and the same tradeoff that a forgetting factor expresses as a discount rate. All three are parametrizations of a single decision about how much history to retain.
The figure below makes that frontier visible. Each point on the curve corresponds to one learning rate, with the adaptation time on the horizontal axis and the noise ball radius on the vertical axis.
import numpy as np
sigma_x_sq = 1.0
sigma_noise = 0.05
eta_grid = np.linspace(0.002, 0.2, 200)
adaptation_time = -1.0 / np.log1p(-eta_grid * sigma_x_sq)
noise_ball_radius = np.sqrt(eta_grid * sigma_noise**2 / 2.0)
marked_eta = np.array([0.005, 0.02, 0.05, 0.1])
marked_time = -1.0 / np.log1p(-marked_eta * sigma_x_sq)
marked_radius = np.sqrt(marked_eta * sigma_noise**2 / 2.0)
marked_labels = [rf"$\eta={e}$" for e in marked_eta]
One more observation from the variance formula. The noise ball shrinks only as , so halving the residual fluctuation requires quartering the learning rate, which quadruples the adaptation time. The returns to precision are poor. If you need a precise estimate, gradient descent with a fixed learning rate is the wrong tool; you want a method that reduces its effective step size as evidence accumulates, which is exactly what RLS does until it is given a forgetting factor.
The worked example also shows why the choice of learning rate depends on the scale of the change you expect. If the true coefficient changes by 0.3, a learning rate of 0.02 tracks it quickly. If the true coefficient changes by 0.003, that same learning rate cannot distinguish the change from noise. A practical system should therefore relate its learning rate to the smallest change it needs to detect and the fastest change it needs to track. Those two requirements pull in opposite directions, and the resolution is usually to use a larger learning rate for adaptation and a smaller one for fine-tuning, or to use a method that adapts the learning rate itself.
Code Implementation
We will now build three small experiments that isolate the mechanisms discussed above. The first trains a small neural dynamics model on two environments in sequence, comparing naive fine-tuning against replay and against Fisher-weighted regularization. The second tracks a drifting coefficient with and without a replay buffer. The third demonstrates model exploitation in a planner. Each experiment precomputes its results from variables and is followed by a discussion of what the numbers mean.
The experiments are deliberately small. The goal is not to achieve state-of-the-art performance but to make the mechanisms visible. The first experiment uses a two-environment sequence so that forgetting and retention can be measured directly. The second uses a scalar drifting coefficient so that the adaptation and noise tradeoff can be seen in a single trace. The third uses a planner with a widening search budget so that the gap between predicted and true return can be measured. Each experiment isolates one part of the problem.
We start with imports and a seeded random generator. Everything downstream uses this generator so results are reproducible.
from collections import deque
import numpy as np
import torch
import torch.nn as nn
torch.manual_seed(0)
np.random.seed(0)
rng = np.random.default_rng(0)Next we define two environments that share a state-action space but have different dynamics. Both are linear in state and action, differing in the state coefficient and the action gain. The difference is large enough that a single shared model cannot serve both without being told which one it is in.
ENV_PARAMS = {0: (0.85, 0.40), 1: (0.55, 0.70)}
def simulate(env_id, n_steps, rng):
a, b = ENV_PARAMS[env_id]
s = rng.normal()
states, actions, next_states = [], [], []
for _ in range(n_steps):
u = rng.uniform(-1.0, 1.0)
s_next = a * s + b * u + 0.05 * rng.normal()
states.append(s)
actions.append(u)
next_states.append(s_next)
s = s_next
return np.array(states), np.array(actions), np.array(next_states)Each transition is packaged as a model input where is a one-hot indicator of the environment. Giving the model the environment identity isolates forgetting from the harder problem of inferring which environment it is in.
def make_dataset(env_id, n_steps, rng):
s, u, s_next = simulate(env_id, n_steps, rng)
onehot = np.zeros((n_steps, 2), dtype=np.float32)
onehot[:, env_id] = 1.0
X = np.concatenate([s[:, None], u[:, None], onehot], axis=1).astype(
np.float32
)
y = s_next[:, None].astype(np.float32)
return X, y
X_A, y_A = make_dataset(0, 3000, rng)
X_B, y_B = make_dataset(1, 3000, rng)
X_A_test, y_A_test = make_dataset(0, 500, rng)
X_B_test, y_B_test = make_dataset(1, 500, rng)The model is a small multilayer perceptron. It is deliberately modest so that forgetting appears quickly and the comparison between methods is visible within a short training run.
class DynamicsMLP(nn.Module):
def __init__(self, in_dim=4, hidden=32):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, hidden),
nn.ReLU(),
nn.Linear(hidden, hidden),
nn.ReLU(),
nn.Linear(hidden, 1),
)
def forward(self, x):
return self.net(x)We need a held-out evaluation helper. This computes mean squared error on a given dataset without altering the model's parameters.
def mse(model, X, y):
model.eval()
with torch.no_grad():
pred = model(torch.from_numpy(X))
value = float(((pred - torch.from_numpy(y)) ** 2).mean())
model.train()
return value
def rollout_mse(model, X, y, horizon=8):
"""Mean squared error over recursive one-step-ahead rollouts."""
model.eval()
with torch.no_grad():
s = float(X[0, 0])
total = 0.0
for t in range(min(horizon, len(X))):
inp = torch.tensor([[s, X[t, 1], *X[t, 2:]]], dtype=torch.float32)
pred = model(inp).item()
total += (pred - y[t, 0]) ** 2
s = torch.tensor(pred)
value = total / min(horizon, len(X))
model.train()
return valueFor the regularization baseline we need a diagonal Fisher estimate. We approximate the Fisher by summing squared gradients of the squared-error loss over a sample of task-A transitions, then normalize so that the regularization strength is comparable across parameters. We compute it once, at the moment of the task switch, and hold it fixed while training on environment B.
def compute_fisher(model, X, y, n_samples=400):
fisher = {n: torch.zeros_like(p) for n, p in model.named_parameters()}
idx = np.random.choice(len(X), size=min(n_samples, len(X)), replace=False)
for i in idx:
model.zero_grad()
out = model(torch.from_numpy(X[i : i + 1]))
target = torch.from_numpy(y[i : i + 1])
loss = ((out - target) ** 2).sum()
loss.backward()
for n, p in model.named_parameters():
fisher[n] += p.grad.detach() ** 2
for n in fisher:
fisher[n] = fisher[n] / len(idx)
scale = sum(f.mean() for f in fisher.values()) / len(fisher)
for n in fisher:
fisher[n] = fisher[n] / (scale + 1e-8)
return fisher
def ewc_penalty(model, fisher, anchor, lam):
penalty = torch.zeros(())
for name, param in model.named_parameters():
penalty = penalty + (fisher[name] * (param - anchor[name]) ** 2).sum()
return 0.5 * lam * penaltyThe training loop below is the core of the experiment. It runs a fixed number of steps on environment A, then the same number on environment B, logging held-out error on both environments throughout. Three methods share the loop: naive uses only the current task's data, replay adds half as many task-A samples as current-task samples (so old data is one third of the combined batch), and ewc adds the Fisher-weighted penalty computed at the moment of the switch.
STEPS_PER_TASK = 800
def train_continual(
method,
X_A,
y_A,
X_B,
y_B,
X_A_test,
y_A_test,
X_B_test,
y_B_test,
steps_per_task=STEPS_PER_TASK,
batch=64,
lr=1e-3,
lam=5.0,
log_every=25,
):
model = DynamicsMLP()
opt = torch.optim.Adam(model.parameters(), lr=lr)
XA, yA = torch.from_numpy(X_A), torch.from_numpy(y_A)
XB, yB = torch.from_numpy(X_B), torch.from_numpy(y_B)
nA, nB = len(XA), len(XB)
fisher, anchor = None, None
log = {"step": [], "taskA": [], "taskB": []}
for step in range(2 * steps_per_task):
on_task_b = step >= steps_per_task
if not on_task_b:
idx = torch.randint(0, nA, (batch,))
X, y = XA[idx], yA[idx]
else:
idx = torch.randint(0, nB, (batch,))
X, y = XB[idx], yB[idx]
if method == "replay":
k = batch // 2
ia = torch.randint(0, nA, (k,))
X = torch.cat([X, XA[ia]])
y = torch.cat([y, yA[ia]])
opt.zero_grad()
loss = ((model(X) - y) ** 2).mean()
if method == "ewc" and on_task_b:
loss = loss + ewc_penalty(model, fisher, anchor, lam)
loss.backward()
opt.step()
if method == "ewc" and step == steps_per_task - 1:
fisher = compute_fisher(model, X_A, y_A)
anchor = {
n: p.detach().clone() for n, p in model.named_parameters()
}
if (
step % log_every == 0
or step == steps_per_task - 1
or step == 2 * steps_per_task - 1
):
log["step"].append(step)
log["taskA"].append(mse(model, X_A_test, y_A_test))
log["taskB"].append(mse(model, X_B_test, y_B_test))
return model, logWe now run all three methods with the same seed so that the comparison is as paired as possible. This cell only computes the results; the next cell displays them and the figure cell below plots them from the precomputed logs.
results = {}
models = {}
for method in ["naive", "replay", "ewc"]:
torch.manual_seed(0)
np.random.seed(0)
model, log = train_continual(
method, X_A, y_A, X_B, y_B, X_A_test, y_A_test, X_B_test, y_B_test
)
results[method] = log
models[method] = modelrollout_stats = {}
for method, model in models.items():
rollout_stats[method] = {
"taskA": rollout_mse(model, X_A_test, y_A_test),
"taskB": rollout_mse(model, X_B_test, y_B_test),
}The printed summary reports held-out error on each environment at the end of training. The interesting comparison is task A: a method that has forgotten environment A will show a much higher error there than a method that has retained it.
naive | final task-A MSE: 0.0189 | final task-B MSE: 0.0029 | task-A rollout MSE: 0.0630 | task-B rollout MSE: 0.0027 replay | final task-A MSE: 0.0025 | final task-B MSE: 0.0028 | task-A rollout MSE: 0.0018 | task-B rollout MSE: 0.0037 ewc | final task-A MSE: 0.0034 | final task-B MSE: 0.0029 | task-A rollout MSE: 0.0114 | task-B rollout MSE: 0.0023
The final one-step and rollout MSE values show the stability-plasticity tradeoff. Naive fine-tuning achieves the lowest task-B error but the largest task-A error, while replay and EWC retain task-A performance at some cost on task B. Rollout error is higher for all methods because prediction errors compound over the horizon, but the ranking between methods is preserved, which indicates that the models learned dynamics rather than merely memorizing one-step transitions.


Read the two panels together. In the right panel, naive training reaches the lowest error on environment B. It pays for that with the largest regression in the left panel. Replay and EWC sit higher on task B and much lower on task A. This is the stability-plasticity tradeoff made visible: the method that is most plastic is the one that forgets most.
The comparison also shows that replay and EWC are not identical. Replay directly reintroduces old data, so it retains task A by continuing to train on it. EWC does not reintroduce data; it constrains parameters that were important for task A. Replay can be seen as changing the data distribution, while EWC can be seen as changing the loss landscape. Both reduce forgetting, but they do so through different mechanisms, and their relative advantage depends on the buffer size, the regularization strength, and the overlap between tasks.
The next experiment isolates streaming estimation. A single scalar coefficient in the true dynamics changes abruptly halfway through a long stream. We estimate it with plain SGD and with SGD over a replay buffer, and we record the state coefficient over time.
def stream_parameters(
n_steps=4000, switch_at=2000, eta=0.02, buffer_size=400, batch=16
):
a_true = np.where(np.arange(n_steps) < switch_at, 0.85, 0.55)
b_true = np.where(np.arange(n_steps) < switch_at, 0.40, 0.70)
s = 0.0
theta_sgd = np.zeros(2)
theta_replay = np.zeros(2)
buf_s = deque(maxlen=buffer_size)
buf_u = deque(maxlen=buffer_size)
buf_y = deque(maxlen=buffer_size)
trace = {"t": [], "a_true": [], "a_sgd": [], "a_replay": []}
for t in range(n_steps):
u = rng.uniform(-1.0, 1.0)
y = a_true[t] * s + b_true[t] * u + 0.05 * rng.normal()
# Plain streaming SGD on the newest transition only.
pred_sgd = theta_sgd[0] * s + theta_sgd[1] * u
theta_sgd = theta_sgd - eta * (pred_sgd - y) * np.array([s, u])
# Streaming SGD over a mini-batch drawn from the replay buffer.
buf_s.append(s)
buf_u.append(u)
buf_y.append(y)
idx = rng.integers(0, len(buf_s), size=min(batch, len(buf_s)))
bs = np.array(buf_s)[idx]
bu = np.array(buf_u)[idx]
by = np.array(buf_y)[idx]
residual = theta_replay[0] * bs + theta_replay[1] * bu - by
grad = (residual[:, None] * np.stack([bs, bu], axis=1)).mean(axis=0)
theta_replay = theta_replay - eta * grad
s = y
if t % 20 == 0:
trace["t"].append(t)
trace["a_true"].append(a_true[t])
trace["a_sgd"].append(theta_sgd[0])
trace["a_replay"].append(theta_replay[0])
return tracetrace = stream_parameters()
The plot shows both effects at once. The plain SGD curve reacts almost immediately at the switch, but it never settles: it wobbles around the new value with the noise ball predicted by the analysis. The replay curve is visibly smoother, because each update averages over sixteen transitions, but it takes longer to arrive at the new value because the buffer still contains old-regime data. Neither curve is strictly better. The right choice depends on whether you care more about responsiveness or variance.
The experiment also illustrates the role of the buffer as a memory horizon. When the true coefficient changes, the replay estimate continues to be pulled toward the old value until the old transitions have been overwritten in the buffer. The plain SGD estimate has no such inertia, but it pays for its responsiveness with variance. If the buffer were larger, the replay curve would lag even more. If it were smaller, the replay curve would track more quickly but would retain less protection against forgetting.
The final experiment demonstrates model exploitation. We train a dynamics model on transitions whose actions are restricted to , then plan over a much wider action range . The true dynamics saturate because of a hyperbolic tangent; a model trained on the narrow range has no way to know that.
def true_step(s, u):
return 0.9 * s + 0.4 * np.tanh(u)
def true_rollout(s0, actions):
s = s0
total = 0.0
for u in actions:
s = true_step(s, u)
total += -((s - 0.8) ** 2)
return total
n_train = 3000
u_train = rng.uniform(-1.0, 1.0, size=n_train)
s_train = np.zeros(n_train)
y_train = np.zeros(n_train)
s_cur = rng.normal()
for i in range(n_train):
y_train[i] = true_step(s_cur, u_train[i]) + 0.02 * rng.normal()
s_train[i] = s_cur
s_cur = y_train[i]
X_ex = np.stack([s_train, u_train], axis=1).astype(np.float32)
y_ex = y_train[:, None].astype(np.float32)torch.manual_seed(1)
exploit_model = DynamicsMLP(in_dim=2)
opt = torch.optim.Adam(exploit_model.parameters(), lr=1e-2)
Xe, ye = torch.from_numpy(X_ex), torch.from_numpy(y_ex)
for _ in range(1500):
idx = torch.randint(0, len(Xe), (128,))
opt.zero_grad()
loss = ((exploit_model(Xe[idx]) - ye[idx]) ** 2).mean()
loss.backward()
opt.step()Now we plan by random shooting. For each search budget we sample that many random action sequences, score them with the learned model, keep the best, and evaluate its true return. As the budget grows, the optimizer has more chances to find a sequence the model is optimistic about.
def model_rollout_return(model, s0, U):
n = U.shape[0]
s = torch.full((n, 1), s0)
total = torch.zeros(n)
for t in range(U.shape[1]):
inp = torch.cat([s, U[:, t : t + 1]], dim=1)
s = model(inp)
total = total - (s.squeeze(1) - 0.8) ** 2
return total
horizon = 6
s0 = 0.0
budgets = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]
pred_returns, true_returns, chosen_actions = [], [], []
exploit_model.eval()
with torch.no_grad():
for n in budgets:
U = torch.empty(n, horizon).uniform_(-3.0, 3.0)
predicted = model_rollout_return(exploit_model, s0, U)
best = int(predicted.argmax())
pred_returns.append(float(predicted[best]))
true_returns.append(true_rollout(s0, U[best].numpy()))
chosen_actions.append(float(U[best].abs().max()))candidates= 1 | predicted= -3.998 | true= -4.002 | max|u|=0.84 candidates= 2 | predicted= -2.537 | true= -1.936 | max|u|=2.61 candidates= 5 | predicted= -0.880 | true= -0.835 | max|u|=2.31 candidates= 10 | predicted= -0.711 | true= -1.084 | max|u|=2.60 candidates= 25 | predicted= -0.477 | true= -0.406 | max|u|=2.14 candidates= 50 | predicted= -0.585 | true= -0.854 | max|u|=2.21 candidates= 100 | predicted= -0.561 | true= -0.469 | max|u|=2.88 candidates= 250 | predicted= -0.371 | true= -0.488 | max|u|=2.81 candidates= 500 | predicted= -0.261 | true= -0.354 | max|u|=2.92 candidates= 1000 | predicted= -0.191 | true= -0.269 | max|u|=2.76 candidates= 2500 | predicted= -0.187 | true= -0.435 | max|u|=2.95 candidates= 5000 | predicted= -0.180 | true= -0.358 | max|u|=2.70 candidates= 10000 | predicted= -0.165 | true= -0.378 | max|u|=2.89
The table illustrates the optimizer's curse. Across these independently drawn candidate sets, predicted and true returns fluctuate rather than changing monotonically, but larger searches tend to locate sequences with optimistic model estimates. Selected actions can also approach the edge of the search range, where the model was never trained and extrapolates most aggressively.

The gap is the point, not monotonicity. Because each budget draws a fresh candidate set, either curve can reverse locally. In this seeded run the broader searches more often find optimistic extrapolations, and their selected model return tends to exceed the measured true return. This single experiment illustrates the selection mechanism; it does not establish that every larger budget is worse or that a small budget is safe.
This is the mechanism behind unsafe drift. It is not that the model is bad on the data it was trained on. It is that the planner is an optimizer, and optimizers search until they find something, including the model's mistakes.
The experiment also shows why uncertainty penalties are helpful. If the planner were penalized for actions where the model is uncertain, the edge of the search range would be less attractive. The model was never trained on actions outside , so a well-calibrated uncertainty estimate would be large there. Without such a penalty, the planner has no reason to avoid the edge. With it, the planner can still explore but is discouraged from exploiting the model's most extreme extrapolations.
Key Parameters
The key parameters for online and continual learning are:
- Learning rate (): Controls the memory horizon of streaming updates. Larger values adapt faster but enlarge the stationary noise ball, which shrinks only as .
- Forgetting factor (): Discounts older observations in recursive least squares. Smaller values shorten the effective window and inflate covariance to preserve plasticity.
- Buffer size: Sets how many past transitions replay retains. Larger buffers preserve a broad distribution but slow adaptation to real change.
- Replay fraction: The proportion of each batch drawn from the buffer rather than fresh data. Higher values stabilize learning but reduce responsiveness.
- Update-to-data ratio: The number of gradient steps per environment step collected. High ratios extract more from each interaction but risk overfitting to stale data.
- EWC regularization strength (): Controls how strongly the Fisher-weighted penalty anchors important parameters against change during new tasks.
These parameters are not independent. The learning rate and the replay fraction both control how quickly the model responds to new data. The buffer size and the forgetting factor both control how much history is retained. The update-to-data ratio and the EWC strength both control how strongly the model is pushed toward the current task. Tuning one without considering the others can produce surprising results, because the parameters interact. A high replay fraction with a high learning rate may be more adaptive than a low replay fraction with a low learning rate, even though both changes push in the same direction.
Limitations and Impact
The techniques in this chapter are effective but they are not solutions in the sense that an optimizer's convergence proof is a solution. Each one trades one failure mode for another, and the tradeoff has to be managed rather than eliminated.
Offline learning gives you reproducibility at the price of staleness. A frozen model can be audited, versioned, and rolled back without ambiguity. But it cannot notice that the world has changed, and its errors grow silently as the deployment distribution drifts. In domains where the environment is stable, offline training remains the right default, and the machinery of this chapter is unnecessary. In domains where it is not, an offline model is a liability with a known expiration date that nobody has measured.
Online learning gives you adaptivity at the price of stability. Every update changes the policy, every policy change changes the data, and the resulting feedback loop has no natural equilibrium. The three experiments above illustrate the components of the problem: forgetting in the sequential training curves, variance in the streaming trace, and exploitation in the planning gap. None of them is fixed by a single technique. Replay reduces forgetting but slows adaptation. Regularization protects important parameters but can prevent necessary change. Uncertainty penalties avoid exploitation but require calibrated uncertainty, which is itself hard to obtain.
Many continual-learning methods are validated on benchmarks that simplify deployment. A common evaluation protocol presents tasks sequentially with clean boundaries and held-out test sets per task. Real deployments may lack task boundaries, clean test sets, or immediate ground truth for current dynamics. A method that achieves near-zero forgetting on Split CIFAR may still be ineffective when tasks are unlabeled and the distribution shifts continuously rather than in discrete jumps. This benchmark-to-deployment gap remains an active research problem, and we will return to evaluation methodology in Part XI: Evaluation and Understanding.
Memory and privacy are real costs. Replay buffers store raw transitions, which can be large, can contain sensitive data, and can create licensing and compliance obligations that offline training does not. In domains with data-protection requirements, the ability to retain and reuse past experience is constrained by law, not just by memory. Generative replay, which trains a generative model of past data and samples from it instead of storing the data itself, is one response to this constraint, though it introduces its own failure mode: the generative model forgets too, and its samples become a distorted echo of the original data.
Safety claims require care. It is tempting to describe a system with uncertainty gating, shadow deployment, and rollback as "safe." That language overstates what the mechanisms provide. They can limit exposure and shorten the time to detection. They do not guarantee that a neural network will remain accurate, and they cannot detect a shift that leaves no observable trace. The honest claim is that these guardrails can make failure more visible and recoverable, which is a meaningful improvement but not a guarantee.
Sequential adaptation has always faced interference between old and new behavior; replay and continual-learning methods make that tradeoff more explicit and manageable. Replay buffers, Fisher-weighted regularization, and architectural isolation each address it differently, and in combination they can help agents accumulate competence over time instead of cycling through it. That capability supports the lifelong-learning systems that the rest of Part VI and Part VII are working toward.
The limitations are not reasons to abandon the techniques. They are reasons to use them with clear expectations. An online learning system is not a system that has solved the problem of change; it is a system that has made a bet about the rate and form of change and has built mechanisms to manage the consequences when that bet is wrong. The quality of the system depends on how well those mechanisms are matched to the deployment context.
Summary
- Batch, streaming, and continual learning are regimes distinguished by how data reaches the optimizer, not by differences in the optimizer itself. Batch training is reproducible but stale; streaming training is adaptive but unstable; continual learning must serve a sequence of regimes without losing earlier ones.
- The learning rate is a memory knob. For a scalar linear model, the bias decays at rate and the stationary noise ball has radius approximately . Larger learning rates adapt faster and fluctuate more; the returns to precision are poor because the noise ball shrinks only as .
- Recursive least squares and the Kalman filter give exact streaming estimators for linear models, and exponential forgetting discounts old information. With persistent excitation and no forgetting, shrinking covariance makes adaptation progressively slower.
- Distribution shift has several useful taxonomies. In the three-part taxonomy used here, a changing policy can induce covariate shift, changed transition dynamics are a form of concept shift, and changes in task or goal frequencies can resemble prior-probability shift.
- Replay is the standard remedy, converting a streaming problem into an approximate batch problem by sampling mini-batches from a stored history. Buffer size and sampling strategy control the memory horizon, and the replay fraction controls the stability-plasticity balance.
- Catastrophic forgetting is gradient interference. Parameters that encode one task are overwritten by gradients that encode another, and the phenomenon is severe because gradient descent has no notion of parameter importance.
- Three families of methods mitigate it: regularization such as EWC, which anchors important parameters using the Fisher information; replay, which reintroduces old data; and architectural isolation, which allocates separate parameters per task.
- Metrics matter. Average accuracy, backward transfer, and forward transfer measure different things, and all three must be computed on held-out data. A method that reduces training loss while degrading held-out performance has not avoided forgetting.
- Unsafe drift is a closed-loop failure mode of online adaptation. The policy optimizes model predictions, so selection can amplify optimistic model errors. The planning experiment illustrates this expected selection bias without claiming a monotonic guarantee for every candidate set.
- Guardrails reduce risk but do not eliminate it. Constraint-based, uncertainty-based, verification-based, and monitoring-based mechanisms together make failure more visible and more recoverable. They do not make it impossible.
- Adaptation is a control problem. Learning rate, replay fraction, update-to-data ratio, and update acceptance are control signals that should respond to detected change rather than being fixed hyperparameters. We will see this reframing again when we discuss exploration and dual control in Part VII.
The next chapter, Pretraining, Post-Training, Scaling, and Adaptation, takes these mechanisms and asks how they compose at the scale of modern foundation models, where the same questions about staleness, forgetting, and drift appear in a different guise: what to freeze, what to fine-tune, and how to adapt a very large model to a new domain without destroying what it already knows.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about online, offline, and continual learning for world models.
Online, Offline, and Continual Learning
Reference
Citation details
Cite or share this article.
Continue with the full handbook
This chapter is part of World Models Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.
Explore World Models HandbookStay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.

Comments
No comments yet. Be the first to share your thoughts!