How Gradient Variance Shapes Policy Optimization¶
In this article, we’ll investigate how reward baselines affect the learning dynamics of policy-gradient algorithms using a simple multi-armed bandit problem. Unlike value-based methods, which estimate the expected reward associated with each action, policy-gradient methods directly optimize the probabilities with which actions are selected.
Our objective is to maximize the expected reward under a parameterized policy:
Here, \(\theta\) denotes the policy parameters. We can optimize this objective using gradient ascent:
where \(\alpha\) is the learning rate. However, since the reward distributions are unknown, we cannot calculate this gradient directly. Instead, we can use the log-derivative identity to estimate it from sampled actions and rewards.
For a multi-armed bandit, we can write the objective as:
where \(q_*(a)\) is the true expected reward for action \(a\). Taking the gradient:
This gives us an unbiased estimate of the policy gradient using a single sampled action and reward. The resulting update is:
Gradient Bandits¶
For our experiments, we’ll use a gradient-bandit agent. It maintains a preference \(H_t(a)\) for each action rather than an estimate of its expected reward. These preferences determine the action probabilities through a softmax policy:
The derivative of the log-probability of the selected action with respect to each preference is:
where \(\mathbb{1}[a=A_t]\) is 1 if \(a\) was selected and 0 otherwise. Substituting this into our gradient update gives:
A positive reward increases the preference for the selected action and decreases the preferences for the others. A negative reward has the opposite effect.
Let’s begin by implementing a \(k\)-armed bandit environment. Each action produces rewards with unit variance and a fixed expected value \(q_*(a)\), sampled independently from:
We’ll vary \(\mu\) to shift all the expected rewards by the same amount. Since this does not change the differences between action values or which action is optimal, it gives us a useful way to investigate whether the absolute magnitude of rewards affects learning.
from typing import NamedTuple
import jax
import jax.numpy as jnp
class KArmedBandit:
def __init__(self, k=10, mean=0.0):
self.k = k
self.mean = mean
def reset(self, key):
q_star = self.mean + jax.random.normal(key, shape=(self.k,))
observation = 0
env_state = q_star
return env_state, observation
def step(self, key, env_state, action):
reward = env_state[action] + jax.random.normal(key)
observation = 0
terminated = False
info = {}
return env_state, observation, reward, terminated, info
Next, we’ll implement the gradient-bandit agent using the softmax policy and preference update derived above.
class GradientBanditState(NamedTuple):
H: jax.Array
N: jax.Array
class GradientBanditAgent:
def __init__(self, k=10, alpha=0.1):
self.k = k
self.alpha = alpha
def init(self):
# Initialize action preferences H to zeros
return GradientBanditState(
H=jnp.zeros(self.k),
N=jnp.array(0, dtype=jnp.int32)
)
def select_action(self, key, agent_state: GradientBanditState):
# Sample an action from softmax(H)
H, _ = agent_state
probs = jax.nn.softmax(H)
action = jax.random.choice(key, a=self.k, p=probs)
return action
def update(self, agent_state, action, reward):
H, N = agent_state
probs = jax.nn.softmax(H)
mask = jnp.zeros(self.k).at[action].set(1)
H = H + self.alpha * (reward) * (mask - probs)
return GradientBanditState(
H=H,
N=N+1
)
Let’s train the agent with reward offsets of \(0\), \(2\), \(4\), and \(8\). For each offset, we’ll run 2,000 independent bandit problems for 1,000 training steps each.
k = 10
num_runs = 2000
num_steps = 1000
means = [0.0, 2.0, 4.0, 8.0]
agent = GradientBanditAgent(
k=k,
alpha=0.1,
)
env = KArmedBandit(k=k, mean=0.0)
def run_experiment(key, reward_offset):
key, env_key = jax.random.split(key)
env_state, _ = env.reset(env_key)
agent_state = agent.init()
optimal_action = jnp.argmax(env_state)
def training_step(carry, _):
key, agent_state, env_state = carry
log_probs = jax.nn.log_softmax(agent_state.H)
probs = jnp.exp(log_probs)
entropy = -jnp.sum(probs * log_probs)
key, action_key, reward_key = jax.random.split(key, 3)
action = agent.select_action(action_key, agent_state)
env_state, _, reward, _, _ = env.step(
reward_key, env_state, action
)
reward = reward + reward_offset
agent_state = agent.update(
agent_state, action, reward
)
is_optimal = action == optimal_action
return (
key, agent_state, env_state
), (is_optimal, entropy)
initial_carry = (key, agent_state, env_state)
_, (optimal_actions, entropies) = jax.lax.scan(
training_step,
initial_carry,
xs=None,
length=num_steps,
)
return optimal_actions, entropies
key = jax.random.key(42)
keys = jax.random.split(key, num_runs)
means = jnp.array([0.0, 2.0, 4.0, 8.0])
batched_experiment = jax.jit(
jax.vmap(
jax.vmap(run_experiment, in_axes=(0, None)),
in_axes=(None, 0),
)
)
optimal_actions, entropies = batched_experiment(keys, means)
mean_optimal = 100 * jnp.mean(optimal_actions, axis=1)
mean_entropy = jnp.mean(entropies, axis=1)
First, let’s plot how often the agent selects the optimal action at each training step, averaged across the 2,000 runs.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/696917459.py:34: UserWarning: The figure layout has changed to tight
plt.tight_layout()
We can observe that performance deteriorates as the reward offset increases. This is surprising because shifting every action’s expected reward by the same constant does not change the optimal action or the expected policy gradient. Let’s examine the distribution of optimal-action frequencies across individual runs to see where this difference comes from.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/1135208797.py:42: UserWarning: The figure layout has changed to tight
plt.tight_layout()
The distributions are strongly bimodal. Most runs either select the optimal action almost all the time or rarely select it at all. As the reward offset increases, a larger proportion of runs end up in the second group.
One possible explanation is that large preference updates cause the policy to concentrate on an action too early, sometimes before it has identified the optimal one. We can investigate this by measuring policy entropy.
Measuring Policy Entropy¶
Policy entropy measures how spread out the action-selection probabilities are. For a policy \(\pi_t\), it is defined as:
Entropy is highest when all actions are equally likely. For our 10-armed bandit, the maximum is:
As the policy concentrates on a single action, its entropy approaches zero. Note that low entropy does not necessarily mean the policy has learned the optimal action. It only tells us that the policy strongly favors a particular action.
We’ll calculate entropy from the softmax probabilities at every training step and average it across runs.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/2075688572.py:24: UserWarning: The figure layout has changed to tight
plt.tight_layout()
We can observe that entropy decreases much faster for larger reward offsets. The agent is becoming increasingly confident in one action, even though its probability of selecting the optimal action is falling.
A possible explanation is that larger rewards increase the variance of the stochastic gradient estimates. Let’s measure this directly.
Measuring Gradient Variance¶
Recall the preference update:
The stochastic gradient estimate for preference \(H_t(a)\) is therefore:
Since the gradient has one component for every action, we’ll measure its total variance by summing the variance of each component:
For this experiment, we’ll hold the policy fixed at the uniform distribution and sample independent actions and rewards. Unlike the previous experiments, the agent will not update its preferences. This allows us to isolate the effect of the reward offset without introducing changes in the policy itself.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/132038405.py:15: UserWarning: The figure layout has changed to tight
plt.tight_layout()
We can see that gradient variance increases rapidly as the reward offset grows. The relationship is approximately quadratic, even though the expected gradient and the differences between action values remain unchanged.
This helps explain our earlier results. Large reward offsets produce noisier preference updates, which may cause the policy to concentrate on an action before it has explored the alternatives sufficiently. Can we reduce this variance without changing the expected policy gradient?
A simple way to do this is to subtract a reward baseline.
Introducing a Reward Baseline¶
Our current preference update is:
When rewards are large and positive, even a suboptimal action can receive a large positive preference update whenever it is selected. Instead of using the absolute reward, we can subtract a reference value \(b_t\):
We’ll use the average reward observed before the current step as our baseline:
For the first step, we’ll initialize the baseline to zero. We can then update the running average incrementally:
Notice that the preference update uses the previous average, before incorporating the current reward. This means an action’s preference changes according to whether its reward is above or below the historical average, rather than according to the absolute reward.
Why Doesn’t a Baseline Change the Expected Policy Gradient?¶
Recall that our objective is:
Using the log-derivative identity, we obtained:
Now consider subtracting a baseline \(b\) that does not depend on the sampled action:
Expanding this expression gives:
The second term is zero. To see why, recall that:
Therefore:
Consequently, subtracting an action-independent baseline leaves the expected gradient unchanged. This also applies to our running-average baseline because it only uses rewards observed before the current action is sampled.
The two estimators therefore have the same expected value at a fixed policy, although their variances can be very different.
Does the Baseline Help?¶
Let’s modify our gradient-bandit agent to maintain a running average reward and use it as a baseline in the preference update.
class GradientBanditState(NamedTuple):
H: jax.Array
avg_reward: jax.Array
N: jax.Array
class GradientBanditAgent:
def __init__(self, k=10, alpha=0.1, use_baseline=True):
self.k = k
self.alpha = alpha
self.use_baseline = use_baseline
def init(self):
# Initialize action preferences H to zeros
return GradientBanditState(
H=jnp.zeros(self.k),
avg_reward=jnp.array(0.0),
N=jnp.array(0, dtype=jnp.int32)
)
def select_action(self, key, agent_state: GradientBanditState):
# Sample an action from softmax(H)
H, _, _ = agent_state
probs = jax.nn.softmax(H)
action = jax.random.choice(key, a=self.k, p=probs)
return action
def update(self, agent_state, action, reward):
H, avg_reward, N = agent_state
probs = jax.nn.softmax(H)
mask = jnp.zeros(self.k).at[action].set(1)
baseline = avg_reward if self.use_baseline else 0.0
H = H + self.alpha * (reward - avg_reward) * (mask - probs)
avg_reward = avg_reward + (reward - baseline) / (N + 1)
return GradientBanditState(
H=H,
avg_reward=avg_reward,
N=N+1
)
We’ll compare agents with and without a baseline on bandit problems with a reward offset of \(4\). As before, we’ll measure the frequency with which each agent selects the optimal action during training.
plt.figure(figsize=(10, 5))
steps = jnp.arange(1, num_steps + 1)
for name, percentages in results.items():
plt.plot(steps, percentages, label=name)
plt.axhline(
100 / k,
color="gray",
linestyle="--",
label="Uniform random policy",
)
plt.xlabel("Training steps")
plt.ylabel("% Optimal actions")
plt.title("Effect of Reward Baselines on Gradient Bandits")
plt.ylim(0, 100)
plt.legend()
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/772520547.py:21: UserWarning: The figure layout has changed to tight
plt.tight_layout()
The agent using a reward baseline selects the optimal action considerably more often. Let’s check whether this improvement persists across different reward offsets.
Looking Across Reward Offsets¶
We’ll repeat the comparison with offsets of \(0\), \(2\), \(4\), and \(8\), keeping the training configuration unchanged.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/74129231.py:34: UserWarning: The figure layout has changed to tight
plt.tight_layout()
The baseline agent maintains fairly consistent performance as the reward offset increases. In contrast, the agent without a baseline becomes progressively worse. Let’s examine the final optimal-action frequencies across individual runs rather than looking only at their averages.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/1593458216.py:43: UserWarning: The figure layout has changed to tight
plt.tight_layout()
The distribution of optimal-action frequencies remains relatively stable with a baseline. Without one, it shifts sharply toward zero as the reward offset increases. At \(\mu=8\), most runs rarely select the optimal action during the final 100 steps.
Next, let’s compare the variance of the gradient estimates with and without a baseline, using the same reward offsets.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/673521976.py:17: UserWarning: The figure layout has changed to tight
plt.tight_layout()
We can observe that the gradient variance remains relatively low with a baseline, while the variance without a baseline increases sharply with the reward offset. This is consistent with the differences we observed in learning performance.
Finally, let’s compare policy entropy across reward offsets, including how entropy differs between successful and unsuccessful runs.
/var/folders/x4/85_9sn3d1ng9q48ff6t3fw340000gn/T/ipykernel_35241/3825232308.py:80: UserWarning: The figure layout has changed to tight
plt.tight_layout()
The left plot shows that policy entropy falls much faster without a baseline, while the baseline agent maintains a more spread-out policy for longer. The right plot shows a similar pattern in both successful and unsuccessful runs. The no-baseline agent concentrates its policy quickly, regardless of whether it has selected the optimal action.
Premature Policy Concentration and Recovery¶
A low-entropy policy is not necessarily a problem. In fact, if the agent has identified the best arm, we want it to select that arm most of the time. The problem occurs when the policy becomes highly concentrated on a suboptimal action early in training.
How Softmax Concentration Affects Exploration¶
Recall that the softmax policy converts action preferences into probabilities:
For any two actions \(a_1\) and \(a_2\), their probability ratio is:
This means small differences in preferences can produce large differences in selection probabilities. If one action’s preference is greater than another’s by \(5\), it is about 148 times as likely to be selected. If the difference is \(10\), it is about 22,026 times as likely.
A few large stochastic updates can therefore make one action dominate the policy. However, the policy has no way of knowing whether that action is actually optimal. It simply reflects the preferences learned so far.
Why Recovery Becomes Slow¶
Recall the preference update with a baseline:
Suppose the policy has become concentrated on a suboptimal action \(a_s\):
There are two reasons why it can take a long time to recover.
First, the alternative actions are rarely sampled. If the probability of selecting the optimal action \(a^*\) is very small, the agent may take many steps before trying it again. For a fixed selection probability \(p\), the expected number of trials before the action is selected is:
For example, if an action has probability \(0.001\), we would expect to wait 1,000 steps before selecting it, assuming that probability remains fixed.
Second, the preference updates themselves become small. When the dominant action is selected, its update is:
As \(\pi_t(a_s)\) approaches \(1\), the factor \(1-\pi_t(a_s)\) approaches zero. For an action \(a\) that was not selected, the update is:
If that action has a very small selection probability, its update will also be small. The agent therefore enters a regime in which it repeatedly selects the dominant action, rarely explores the alternatives, and makes only small preference updates on most steps.
This creates a feedback loop. The current policy determines which actions are sampled, and those samples determine how the policy is updated.
Connecting This to Our Experiments¶
We can now connect our results. Increasing the common reward offset increased gradient variance for the agent without a baseline, despite leaving the expected gradient unchanged. The larger stochastic updates were accompanied by a much faster reduction in policy entropy.
At \(\mu=8\), the no-baseline agent’s entropy fell rapidly within roughly the first 100 steps, both in runs that eventually succeeded and in runs that failed. This tells us that rapid policy concentration is not the same as learning the optimal action. In many runs, the agent became highly confident in an action before it had gathered enough evidence to determine whether that action was optimal.
Once a suboptimal action dominated the policy, the dynamics described above made it difficult to recover within our 1,000-step training horizon. Subtracting the running-average reward reduced the effect of the common offset, leading to more gradual policy concentration and better optimal-action selection in our experiments.
Does Premature Concentration Mean Permanent Failure?¶
Not necessarily. As long as the action preferences are finite, softmax assigns a positive probability to every action. A suboptimal action does not become permanently inaccessible simply because the policy strongly favors another action.
However, the probability of sampling an alternative can become so small that recovery takes much longer than the training horizon. Our experiments therefore demonstrate a finite-horizon learning problem, not permanent convergence to a suboptimal policy.
The broader point is that two gradient estimators with the same expectation can produce very different learning trajectories. In our experiments, subtracting a reward baseline reduced gradient variance, slowed premature policy concentration, and made the agent much more likely to identify and consistently select the optimal action.