Gradient Bandits
Gradient bandits optimize numerical preferences for each action rather than estimating payoff values, shifting probabilities upward for choices that outperform the average reward baseline.
Why Does This Exist?
Most foundational multi-armed bandit algorithms—such as -greedy, Upper Confidence Bound (UCB), and Thompson Sampling—are action-value methods. They maintain numerical estimates of the true expected payoff for each arm, selecting actions based on which estimate is highest.
However, estimating absolute reward values introduces several practical and theoretical challenges:
- Relative order matters, absolute magnitude does not: If arm 1 produces an expected return of and arm 2 produces , an agent does not need to estimate the number to understand that arm 1 is superior. Value estimators waste statistical effort calibrating arbitrary scales and offsets.
- Rigid exploration policies: Action-value methods select actions through discontinuous operations (like ) combined with heuristic random exploration (). They lack a natural, smooth mechanism to continuously adjust the probability of taking actions in proportion to evidence.
- No direct path to policy optimization: In complex or continuous decision problems, estimating values everywhere is intractable. We need methods that directly parameterize and optimize the decision policy itself.
Gradient bandits resolve this by abandoning reward estimation altogether. Instead of tracking expected payouts, the agent assigns an unconstrained numerical preference to each action. These preferences are converted into a probability distribution via a softmax transformation and optimized directly using stochastic gradient ascent on the expected total reward. Gradient bandits serve as the direct conceptual foundation for modern Policy Gradient Methods.
Think of It Like This
A radio DJ tuning genre weights against listener mood
Imagine a radio DJ deciding which genre of music—Pop, Rock, Hip-Hop, or Jazz—to broadcast next. Instead of trying to predict the exact number of phone calls or ratings each individual song will receive, the DJ maintains an internal "preference dial" for each genre.
Whenever it is time to queue a track, the DJ spins a roulette wheel where each genre's slice corresponds to its current preference dial (the softmax distribution). Higher dials get played more often, but every genre retains a chance to hit the airwaves.
After playing a song, the DJ checks listener feedback (the reward ) against the station's recent running average satisfaction score (the baseline ):
- Above-average reaction (): A hip-hop track scores when the station average is . The DJ nudges the hip-hop dial upward. Because all probabilities must sum to , the other genres automatically surrender a fraction of their airtime.
- Below-average reaction (): An indie rock track scores . Even though the rating is positive and listeners did not boycott the station, it scored below the room average. The DJ dials down indie rock, causing the other genres to gain relative probability.
The DJ never needs to define what a "perfect 10" track feels like. They simply boost choices that beat the baseline and suppress choices that lag behind it.
Where the analogy stops: A human DJ must consider listener fatigue, time-of-day dynamics, and smooth transitions between songs. In a gradient bandit, trials are independent, arm payoff distributions are stationary, and there are no sequential state transitions.
How It Actually Works
Action Preferences and Stochastic Gradient Ascent
Rather than estimating expected payoffs , a gradient bandit maintains a numerical preference for each action .
Preferences have no units of reward. Only the relative differences between preferences dictate action selection. If you add an arbitrary constant to every preference, the action probabilities remain completely unchanged:
1. Softmax Action Selection
At time step , the probability of selecting action is determined by the softmax (Boltzmann / Gibbs) distribution:
Every action always has a strictly positive probability (), guaranteeing continuous exploration without requiring an artificial -greedy exploration floor.
2. The Objective Function
The agent seeks to maximize expected reward across trials:
where is the true underlying mean reward of action .
3. Deriving the Gradient
To perform gradient ascent, we take the derivative of expected reward with respect to preference :
Using the derivative of the softmax function , we can introduce an arbitrary baseline that does not depend on the action . Because probabilities sum to 1 (), the gradient of the baseline term vanishes:
Subtracting this zero-valued baseline yields:
Replacing the true expectation with the sampled reward gives an unbiased stochastic gradient sample!
4. The Preference Update Rule
After taking action and observing reward , the preferences are updated via:
Breaking this into the chosen versus unchosen actions:
- For the chosen arm ():
- For all other arms ():
where:
- is the step-size parameter (learning rate).
- is the indicator function ( if , else ).
- is the average reward baseline up to time , tracked incrementally:
5. Role of the Average Reward Baseline
The baseline acts as a comparative anchor. If an arm yields , its preference climbs and all other preferences decline. If , its preference falls even if . While any baseline leaves the expected gradient mathematically unbiased, using the running average dramatically reduces the variance of the gradient estimates, stabilizing learning.
Worked numerical example
Consider a 2-armed bandit () with step-size .
Initial State ()
- Initial preferences: , .
- Initial probabilities:
- Running baseline prior: .
Round 1: Good Outcome on Arm 1
- Action selected: The agent samples Arm ().
- Reward received: .
- Advantage calculation: (performed above baseline).
- Update chosen arm ():
- Update unchosen arm ():
- Update baseline:
- New probabilities for Round 2:
Arm 's probability jumped from to because it outperformed the average baseline.
Round 2: Poor Outcome on Arm 2
- Action selected: The agent explores Arm ().
- Reward received: .
- Advantage calculation: (performed below baseline).
- Update chosen arm ():
- Update unchosen arm ():
- New probabilities for Round 3:
Even though Arm delivered a positive reward of , because it fell short of the baseline, its preference plummeted and Arm 's selection probability climbed to .
Code
Below is a self-contained, type-hinted Python implementation of the Gradient Bandit algorithm with running baseline tracking.
import mathimport randomfrom typing import List
class GradientBandit: """Gradient Bandit algorithm with numerical preferences and baseline tracking.
Optimizes numerical action preferences H(a) via stochastic gradient ascent on expected reward, parameterizing a softmax exploration policy. """
def __init__( self, k_arms: int, alpha: float = 0.1, use_baseline: bool = True, ) -> None: self.k: int = k_arms self.alpha: float = alpha self.use_baseline: bool = use_baseline # Action preferences H_t(a), initialized to 0.0 self.preferences: List[float] = [0.0] * k_arms # Running average reward baseline R_bar self.baseline: float = 0.0 # Time step counter self.step_count: int = 0
def get_probabilities(self) -> List[float]: """Compute action probabilities using numerically stable softmax.""" max_h = max(self.preferences) # Subtract max preference to prevent floating-point exponential overflow exp_h = [math.exp(h - max_h) for h in self.preferences] total_exp = sum(exp_h) return [e / total_exp for e in exp_h]
def select_action(self) -> int: """Sample an action according to softmax probabilities pi_t.""" probs = self.get_probabilities() r = random.random() cumulative = 0.0 for action_idx, p in enumerate(probs): cumulative += p if r < cumulative: return action_idx return self.k - 1
def update(self, action: int, reward: float) -> None: """Update action preferences and baseline following an observed reward.""" self.step_count += 1 probs = self.get_probabilities()
# Update average reward baseline incrementally if enabled if self.use_baseline: self.baseline += (reward - self.baseline) / self.step_count baseline_val = self.baseline else: baseline_val = 0.0
advantage = reward - baseline_val
# Stochastic gradient update rule: # H_{t+1}(a) = H_t(a) + alpha * (R_t - R_bar) * (1_{a=A_t} - pi_t(a)) for a in range(self.k): indicator = 1.0 if a == action else 0.0 self.preferences[a] += self.alpha * advantage * (indicator - probs[a])
# Example demonstration on a 3-armed bandit:if __name__ == "__main__": random.seed(42)
# 3-armed bandit environment with true payout means k = 3 true_means = [2.0, 5.0, 3.0] # Arm index 1 is optimal agent = GradientBandit(k_arms=k, alpha=0.2, use_baseline=True)
print("Initial preferences:", [round(h, 3) for h in agent.preferences]) print("Initial probabilities:", [round(p, 3) for p in agent.get_probabilities()])
# Train for 500 interaction rounds for _ in range(500): a = agent.select_action() # Sample reward with Gaussian noise around true arm mean r = random.gauss(true_means[a], 1.0) agent.update(action=a, reward=r)
probs = agent.get_probabilities() print("Final preferences:", [round(h, 3) for h in agent.preferences]) print("Final probabilities:", [round(p, 3) for p in probs]) print(f"Optimal arm (index 1) probability: {probs[1]:.1%}") print(f"Average baseline reward: {agent.baseline:.2f}")
# -> Expected output:# Initial preferences: [0.0, 0.0, 0.0]# Initial probabilities: [0.333, 0.333, 0.333]# Final preferences: [-2.359, 4.792, -2.433]# Final probabilities: [0.001, 0.998, 0.001]# Optimal arm (index 1) probability: 99.8%# Average baseline reward: 4.90Watch Out For
Omitting the reward baseline in positive-reward environments
A common mistake when implementing gradient bandits is omitting the reward baseline (), assuming that stochastic gradient ascent will still converge because the baseline term has an expected gradient of zero.
The failure mode: If all observed rewards are strictly positive (for example, payouts centered around ), every single action pull produces . As a consequence:
- Every time any arm is pulled, its preference is bumped upward.
- Even severely suboptimal arms receive continuous positive reinforcement simply by being explored.
- Preferences of all actions grow large and positive simultaneously. Suboptimal arms only experience relative decreases through the normalizer , but their probabilities decline at an agonizingly slow rate.
The symptom: The agent exhibits massive gradient variance, takes thousands of extra steps to converge, or prematurely locks onto the first arm tested simply because early rewards boosted its preference ahead of the pack.
The fix: Always maintain a running average reward baseline . The baseline centers the reward signals around zero, ensuring that below-average rewards actively depress preferences () and quickly reallocate exploration budget to promising arms.
The Quick Version
- Preferences, not values: Gradient bandits maintain unbounded numerical preferences rather than estimating expected reward values .
- Softmax exploration: Action selection probabilities naturally balance exploration without requiring hard cutoff thresholds or artificial -greedy coin flips.
- Relative performance drives updates: The update rule rewards actions that beat the running average baseline and penalizes actions that fall below it.
- The baseline is vital: While theoretically unbiased without a baseline, omitting causes preferences to drift upward unboundedly when rewards are positive, resulting in severe variance and crippled convergence.
- Foundation of policy gradients: Gradient bandits are the single-state formulation of the Policy Gradient Theorem, directly inspiring algorithms like REINFORCE and PPO.