Update a gradient bandit's action preferences
Why it matters The same 'reward minus baseline times grad log pi' pattern is REINFORCE, which powers policy gradient training of LLMs.
A gradient bandit keeps a preference number per arm and picks arms with softmax probabilities. After each pull it nudges preferences up or down depending on whether the reward beat the running average.
Write gradient_bandit(H, history, lr). H is a length K list of starting preferences. history is a list of (arm, reward) pairs in order. For each pair:
1. pi = softmax(H).
2. baseline = mean of all rewards BEFORE this step (0.0 at the first step).
3. H[arm] += lr * (reward - baseline) * (1 - pi[arm]); every other arm b gets H[b] -= lr * (reward - baseline) * pi[b].
Return (H as a numpy array, final baseline) where the final baseline is the mean of all rewards in history (0.0 if empty).
def gradient_bandit(H, history, lr)Example
gradient_bandit([0, 0], [(0, 1.0)], 0.1) gives (array([0.05, -0.05]), 1.0).
Understand the idea
Instead of estimating how good each arm is, a gradient bandit learns preferences and turns them into probabilities with softmax. If an arm pays more than the average so far, its preference goes up; if less, it goes down.
Example: two arms with preferences [0, 0], so pi = [0.5, 0.5]. We pull arm 0 and get reward 1. The baseline (average of earlier rewards) is 0, so the surprise is 1. With lr 0.1: arm 0 rises by 0.1 * 1 * (1 - 0.5) = 0.05 and arm 1 falls by 0.1 * 1 * 0.5 = 0.05.
Rule: H <- H + lr * (r - baseline) * (onehot(a) - pi), with baseline = mean of past rewards.
The baseline does not change the expected direction of the update but cuts its noise a lot. Policy gradient methods for games and RLHF use the same trick with a learned value instead of a running mean.
Shapes and data flow
H: (K,) -> pi: (K,) -> H += g * (onehot - pi)