Interactive explainer
Put an agent in front of a pendulum it has never seen. It does not know the physics, it does not know what its sensors report, and the only signal it gets is a preference for observations in which the pendulum is upright. Hanging at the bottom, every action looks equally bad. To get anywhere, the agent has to try actions that do not pay off yet, learn a model from what happens, and find out where in that model the goal lies.
This page describes an agent that does this by planning with the expected free energy, the objective of active inference. The objective puts the task and the value of learning something new into one quantity, with no weight to tune between them. The agent's world model is a generic neural network with a Bayesian last layer, which makes the value of new information cheap to compute, and the agent minimises the objective by gradient descent through rollouts it imagines with its model. All figures are recorded from this agent.
We ran the agent on three classic control problems: swinging a pendulum upright, driving an underpowered car up a hill, and swinging up a pole on a cart. On all three the motor is too weak to go straight to the goal, so the agent has to build up energy first by swinging or rocking. It starts every run with randomly initialised networks and no data. The only task information it gets is a preference that is flat everywhere except near the goal (pendulum and pole upright, car at the flag), so until the agent has seen the goal once, the preference gives no hint of which way to go. All settings are the same on the three problems except the episode length.
Each row shows episodes 1, 5 and 10 of one run, drawn from the true states of the system. In episode 1 the model is untrained and the behaviour looks random. By episode 10 the agent swings the pendulum and the pole up and holds them there, and it drives the car to the flag. The toggle switches to the same agent with the information-gain terms removed from its objective, so that only the preference is left. That agent stops moving on the pendulum and the car after a few episodes, because nothing in what is left of its objective tells it where the goal is. On the cart-pole it still learns, because the light pole swings through upright even under random actions.
Everything the agent knows about its environment comes in through observations $y_t$, and everything it does goes out through actions $u_t$. Between the two, the agent keeps a model. We give it the most general kind of model that still has some structure: a state-space model. A hidden state $x_t$ summarises whatever about the system matters for the future. It changes when the agent acts, and it produces the observations the agent sees:
The function $f_\theta$ says how the state moves under an action, and $g_\theta$ says what the sensors report in a given state. Over a horizon of $T$ steps, starting from the agent's current belief $p(x_0)$ about the state, the model is
Nothing here is specific to a pendulum. We do not tell the agent what the state means; it only gets a latent space with as many dimensions as its observations, and it has to learn what to put there. The same goes for $f_\theta$ and $g_\theta$: we want one agent that works on many problems, so these functions have to be able to represent whatever dynamics and sensors the agent runs into. That calls for a rich, generic function approximator, and the obvious choice is a neural network. Neural networks can approximate any continuous function (Hornik, Stinchcombe and White, 1989), and they learn useful representations from data on their own.
They have one problem for our purpose. A network trained to a single set of weights gives one prediction with no error bar, and away from the data it was trained on it is often confidently wrong. An agent that has to decide what to explore needs to know where its model is unsure. The next section shows how we add it.
A fully Bayesian neural network would keep a belief over all of its weights, but that is expensive, and the agent has to evaluate its model many thousands of times per action. We make only the last layer Bayesian. A network computes features $\phi(x_{t-1}, u_t)$, and the dynamics are linear in those features with uncertain weights: $f_\theta(x_{t-1}, u_t) = W_x^\top \phi(x_{t-1}, u_t)$. The observation model is built the same way, $g_\theta(x_t) = W_y^\top \psi(x_t)$, and the uncertain parameters are the last-layer weights $\theta = (W_x, W_y)$.
The payoff is that the weights can be integrated out exactly. With a Gaussian belief over $W_x$ (mean $M_x$, row covariance $S_x$), the prediction of the next state, averaged over everything the agent does not know about the weights, is again Gaussian:
The covariance $S_x = (\alpha I + \Phi^\top\Phi)^{-1}$ summarises the data, where $\Phi$ stacks the features of all transitions seen so far. Each new transition adds its features to $\Phi$ and shrinks $S_x$ in the directions those features point. The number $\phi^\top S_x \phi$ is therefore small where the features point in directions the data cover, and large where they do not, and it widens the prediction by exactly that much.
From here it is a short step to the quantity the agent will use to explore: the information gain. It measures how much the agent expects to learn about the weights by seeing the next state. In general it is the spread of the prediction minus the spread that the noise alone would cause. With a Bayesian last layer it has a closed form, one quadratic form per prediction:
The first is the information gain about the dynamics, the second about the observation model. The toy below shows the idea in one dimension. Click the first button a few times: each click observes the hidden function where the information gain is largest, which is also where the predictive band is widest, and the band closes there.
So far the agent has a model and knows where it is uncertain. It still needs a task. In active inference the task is a preference over observations, written as a prior $\hat p(y_t) \propto \exp r(y_t)$. For the pendulum, $r$ is high when the observation says the pendulum is upright and flat everywhere else. There is never a preference on the latent state, because the agent learns those coordinates itself and they have no fixed meaning.
Active inference treats planning as inference: the agent looks for a belief $q$ about the future (observations, states, actions and parameters) that fits both its model and its preferences. It finds that belief by minimising
The first term, $F[q;\hat p]$, is the ordinary variational free energy of the model with the preference attached. Minimising it alone would only steer toward preferred observations. The first sum corrects for the entropy of the action posterior, and the second adds the epistemic part of the expected free energy, the part that values information. We derive both corrections in What Type of Inference Is Active Inference? (UAI 2026).
We restrict $q$ to the family
The beliefs about the current state and the weights come from the agent's filter and from learning, and they stay fixed while it plans. The transitions and observations are copied from the model. Only the action posterior $q(u_t \mid x_{t-1})$ is free, so planning means choosing a distribution over actions, and the actions may depend on the state.
If the transition factor were free, inference would move probability toward the preferred states, and the agent would favour plans in which luck carries it to the goal. Levine (2018), Reinforcement Learning and Control as Probabilistic Inference, discusses this optimism of planning as inference. Transition noise is a property of the environment that planning cannot change, so the agent's belief about transitions has to be its transition model.
In this family the action entropy cancels, and $F_{\text{EFE}}$ becomes a sum of expected costs per step. The two entropy terms that remain are exactly the information gains from the previous section:
preference information gain about the dynamics information gain about the observation model
The cost of a step is low when the predicted observation is preferred, and lower still when the step would teach the model something, about how the system moves or about what the sensors report. When the goal is out of reach, the first term is the same for every plan, and the information gains are the only thing that tells plans apart. That is what makes the agent explore. The information gains have no weight in front of them, so the model's own uncertainty decides how much exploration is worth. As the model learns, they shrink, and the preference takes over.
To see what the information gain does in practice, we can map it over the pendulum's states while the agent learns. There is one complication. The agent plans in a latent space that it learns itself, whose coordinates have no fixed meaning and change every time the model is retrained, so maps drawn in them could not be compared across episodes. We draw the maps over the pendulum's true state instead: its angle $\theta$ and angular velocity $\omega$. (In this section and the next, $\theta$ is the angle, not the model's weights.) For each grid point we take the noise-free observation $y = (\cos\theta, \sin\theta, \omega/8)$, let the agent's encoder map it to a latent state $x$, and evaluate the information gain at that $x$, maximised over the torque for the dynamics. Since $y$ is a one-to-one function of $(\theta, \omega)$, this is the same as a map over observation space.
Move the slider to see how the map changes as the agent collects data. Before any data the information gain is high everywhere. After one episode it is lower on the states the agent has visited (median 0.04 nats) than away from them (median 0.11 nats over the grid). The highest values are at large angular velocities. The agent goes there next, and in doing so pumps energy into the pendulum.
$F_{\text{EFE}}$ is an expectation over futures that the agent imagines with its model. The model is nonlinear, and all steps of one imagined future share the same uncertain parameters, so the expectation has no closed form. The agent estimates it instead: it simulates 16 rollouts with its model, scores them, and lowers the estimate by gradient descent on the parameters of the action posterior. That posterior is a Gaussian squashed into the action limits, whose mean reacts linearly to the state of each rollout,
with parameters $\lambda = \{\mu_t, K_t, \rho_t\}_{t=1}^{T}$ and $\sigma_t = \sigma_{\max}\,\mathrm{sigmoid}(\rho_t)$. To get a gradient through the samples, the agent uses the reparameterisation trick. All randomness is drawn from fixed distributions that do not depend on $\lambda$, and $\lambda$ only transforms it, so every simulated quantity is a differentiable function of $\lambda$ and backpropagation through the rollouts gives an unbiased gradient of $F_{\text{EFE}}$.
The figure steps through planning on the pendulum, recorded from the agent. There are three situations to choose from. Exploring: early in learning, the goal is out of reach and only the information gain shapes the plan. Near the goal: a trained model partway through a swing-up, where the preference dominates. Longer horizon: a plan long enough to reach the goal from rest, where you can watch the preference take over within one planning call.
Draw standard normal noise $\varepsilon_t^{(n)}$ for 16 rollouts and 40 steps. Because the noise does not depend on $\lambda$, the gradient can pass through the samples.
Shift and scale: $\mu_t + \sigma_t \varepsilon_t$, then the feedback term $K_t(x_{t-1} - \bar x_{t-1})$, which depends on each rollout's own state. In the agent this happens step by step inside the rollout; it is drawn here in one go. Black: $\mu_t$, band: $\pm\sigma_t$.
$u_t = u_{\max}\tanh z_t$ keeps every action inside the torque limit $[-2, 2]$ (shaded).
Each rollout draws its own $x_0 \sim q(x_0)$ and one $\theta \sim q(\theta)$ for the whole horizon, then $x_t \sim p(x_t \mid x_{t-1}, u_t, \theta)$ and $y_t \sim p(y_t \mid x_t, \theta)$. Right: the imagined angle and velocity, decoded from the imagined observations $y_t$, drawn over the information gain about the dynamics of this model (the map from the previous figure, in the same true-state coordinates). Orange dot: the true state. Dashed: the goal region.
Each step of each rollout gets its cost $\ell_t$ in closed form. Here no rollout comes near upright, so the preference term is the same for all of them (about 276 nats) and gives no gradient. Rollouts differ only in how much they would teach the model. Thick lines: low cost. Hover the bars to pick out a rollout.
Each step of each rollout gets its cost $\ell_t$ in closed form. Now part of the rollouts pass through the goal region. The preference term differs between rollouts by tens of nats and the information gain by a few nats, so the preference dominates. Thick lines: low cost. Hover the bars to pick out a rollout.
Each step of each rollout gets its cost $\ell_t$ in closed form. With the longer horizon, the plan can reach upright from rest. At first no rollout gets there and the preference is flat, so the information gain shapes the early steps. Once some rollouts enter the goal region, the preference term separates them; after 100 steps 14 of the 16 rollouts reach the goal and the summed $-\log\hat p$ (dashed, bottom right) has fallen.
Backpropagate $\hat F$ through the rollouts and the world model. Arrows: $-\partial \hat F / \partial \mu_t$, the direction in which each step's mean action moves (scaled to the largest).
One Adam step on $\lambda$ (learning rate 0.05). The next iteration draws fresh noise. Use "run all steps" to play the remaining iterations.
Running every Adam step: fresh noise, rollouts, score, gradient, update. Watch the mean action (black) and the rollouts (right) change while the estimate of $F_{\text{EFE}}$ falls (bottom right). Press "next stage" to stop.
The agent executes the mode of $q(u_1 \mid x_0)$ (with the $\tanh$ the mode is not $u_{\max}\tanh\mu_1$; the agent finds it by Newton's method). It then observes, updates its belief about the state, and shifts the plan by one step, appending a fresh factor at the end. The shifted plan is the starting point for the next environment step.
Planning is one half of the agent. The other half learns the model, and the two run on different clocks: planning at every step, learning every 100 steps.
At every environment step the agent updates its belief about the current latent state with an amortised filter, a network that maps the previous state sample, the action and the new observation to a Gaussian over the new state. It then takes 10 Adam steps on the plan (100 at the start of an episode), executes the first action and shifts the plan by one step.
Every 100 steps it stops to learn. It trains the feature networks $\phi$ and $\psi$ and the filter for 250 Adam steps on the evidence lower bound of all data collected so far, cut into sequences of 50 steps. Because the last layer is conjugate, it then sets $q(\theta)$ and the noise covariances to their optimal values for the trained features, in closed form. Finally it re-runs the filter over the current episode, since the encoder has changed. Between these updates the model is fixed.
Separating learning from planning is standard in model-based control and robotics. What makes this loop clunky is how the model learns. The agent keeps every transition it has seen, and every 100 steps it refits all networks and the filter on that whole data set and recomputes $q(\theta)$ over all of it. Nothing is updated from the new observations alone, so each update is a full retraining of the model, and a surprising observation reaches the model only at the next one, up to 100 steps later. The schedule (every 100 steps, 250 gradient steps, sequences of 50) is set by hand.