Part I · Foundations · Chapter 2
Bandits: exploration vs. exploitation
The one-state RL problem. ε-greedy, UCB, Thompson sampling, and regret.
You moved to a new neighborhood a month ago. There are five restaurants within walking distance. You have eaten at two of them; one was good. Tonight, do you go back to the good one, or try one of the three you have never been to?
If you always go back, you might eat at the second-best restaurant for the rest of your life and never know it. If you keep trying new places, you will eat a lot of mediocre dinners. Every learning agent faces this same tension between exploitation (doing what currently looks best) and exploration (doing something else to find out whether it is better). In Chapter 1 you met it as one of the core challenges of RL: because your actions choose your data, you only learn about the options you try.
This chapter studies that tension in its purest form, the multi-armed bandit. There are no states and no delayed consequences, just repeated choices and rewards. Everything difficult about bandits comes from exploration, so it is the cleanest place to understand it. You will meet five strategies (greedy, ε-greedy, optimistic initial values, UCB, Thompson sampling), learn how to score them (regret), and see why the problem matters for language models: RLHF on a single response is a bandit with a context.
The K-armed bandit
The name comes from slot machines, which are sometimes called “one-armed bandits”. Picture a row of slot machines. Each one pays out according to its own fixed probability distribution, which you don’t know. At each step you choose one machine (one arm) , pull it, and receive a reward . Your goal is to collect as much total reward as possible over the pulls.
The quantity that matters about each arm is its mean payout, the action value
If you knew , the problem would be solved: pull every time. You don’t, so you keep an estimate built from the rewards you have seen, and you choose arms based on those estimates. The catch is that the estimates are only as good as your data, and your data depends on your choices.
A concrete example, which we’ll reuse. Four machines pay 1 (a win) or 0 (a loss), with hidden win probabilities
| Arm | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0.30 | 0.55 | 0.70 | 0.45 |
Arm 3 is best. Rewards that are 0 or 1 like this are called Bernoulli rewards; they are the natural model for clicks, conversions, and “was the answer correct?”.
In the language of Chapter 1, a bandit is an RL problem with a single state. The environment never changes in response to what you do; pulling arm 2 now does not change what arm 3 will pay later. That removes the credit-assignment problem (every reward is caused by the action just taken) and leaves only the exploration problem. Chapter 3 adds states back in.
Keeping score: regret
How should you judge a strategy? Total reward is natural but hard to compare across problems: 35 wins out of 50 is excellent on one set of machines and poor on another. Instead we compare against an oracle that knows the best arm. The regret after steps is
In words: the expected reward you gave up by not pulling the best arm every time. It uses the true means of the arms you chose, not the rewards you happened to get, so lucky wins on a bad arm don’t hide a bad choice.
Regret has a useful second form. Write for the gap of arm : how much worse it is than the best arm. Each pull of arm costs exactly , so
where is the number of times arm was pulled in the whole game. Say you pulled our four arms 2, 3, 4 and 1 times in 10 steps. The gaps are , so
The first form gives the same answer: . The second form tells you what a good algorithm must do: pull bad arms rarely, and the worse the arm, the more rarely.
Before reading about any algorithm, play the game yourself.
Play a 50-pull game as 'You': tap the machines (or the Pull buttons) and try to win as much as you can. The dot on each machine is your current estimate (wins / pulls). The true odds and your regret are revealed at the end. Then press New machines (the old odds are no longer secret), play again, and notice how hard it is to decide when to stop exploring. Later sections explain the Greedy, ε-greedy, UCB and Thompson buttons; come back and let each one play your machines.
You probably did something sensible: tried each machine a few times, then mostly pulled the one that looked best, with an occasional check on a runner-up. The rest of this chapter turns that instinct into algorithms and asks how good they can be.
Estimating an arm’s value
The obvious estimate of is the sample average of the rewards arm has produced:
where counts the pulls of before step . By the law of large numbers, as . The question is only how to compute it cheaply.
Focus on one arm and drop the . Let be its first rewards and the average after them. You don’t need to store all the rewards. Each new reward moves the average a fraction of the way toward itself:
You’ll derive this in Exercise 2.1 (it takes three lines). A worked example: arm 3 pays on its first five pulls.
| update | |||
|---|---|---|---|
| 1 | 1 | 1.000 | |
| 2 | 0 | 0.500 | |
| 3 | 0 | 0.333 | |
| 4 | 1 | 0.500 | |
| 5 | 1 | 0.600 |
The final value is , the plain average. Notice that the first step has step size 1, so whatever you started from is overwritten immediately.
Quick check An arm's estimate is Q = 0.40 after 4 pulls. The 5th pull pays 1. What is the new sample-average estimate?
Q ← 0.40 + (1/5)(1 − 0.40) = 0.40 + 0.12 = 0.52. Check: 4 pulls averaging 0.40 sum to 1.6; adding 1 gives 2.6, and 2.6/5 = 0.52.
Greedy, and how it gets stuck
The simplest strategy uses the estimates directly: always pull the arm that currently looks best,
breaking ties at random. This is the greedy policy. It never explores on purpose, and that is fatal.
Take two arms with and , both estimates starting at 0. At the start the estimates tie, so greedy picks at random. Suppose it picks arm 2 and arm 2 pays 1. Now and , so greedy pulls arm 2 next time. Can ever fall back to 0? No: arm 2’s average includes that first win, so forever. And stays at exactly 0, because greedy never pulls arm 1 again to learn otherwise. Greedy is now locked onto the worse arm for the rest of time, losing per step. Its regret grows linearly in . Exercise 2.2 asks you to compute the probability of this lock-in (it’s about 36%).
The deeper problem: greedy treats its estimates as facts. An arm with one unlucky pull looks bad, so it is never pulled again, so its estimate never gets corrected. Mistakes that make an arm look too good get fixed (you keep pulling it and the average comes down). Mistakes that make an arm look too bad are permanent. Exploration exists to fix the second kind.
Switch the slot-machine demo above to Greedy and press Play a few times (Restart between games). Some games it finds the best machine; in others it settles on a mediocre machine after one or two lucky pulls and never looks back.
ε-greedy: explore on purpose
The simplest fix is to explore at random some fixed fraction of the time. The ε-greedy policy is:
at each step t:
with probability ε: pick an arm uniformly at random (explore)
otherwise: pick argmax_a Q(a), ties at random (exploit)
pull it, observe r
N(a) ← N(a) + 1
Q(a) ← Q(a) + (1 / N(a)) · (r − Q(a))
Because every arm keeps being pulled (each with probability at least per step), every estimate eventually converges to the truth, and the exploit steps end up on the best arm. With and , the agent eventually pulls the best arm of the time.
That remaining 9% is the price. ε-greedy explores forever at the same rate, even after it has seen thousands of pulls and is sure which arm is best. Each exploration step pulls a random arm and costs, on average, . So the regret of ε-greedy also grows linearly, at a rate of at least per step (Exercise 2.5). It is a much smaller line than greedy’s, but it is still a line. Lowering ε makes the slope smaller but slows down learning at the start; a schedule that decays ε over time can fix this, but only if it is tuned to the problem.
Exploration in ε-greedy is also undirected: when it explores, it is as likely to re-check an arm it has pulled 500 times as one it has pulled twice, and as likely to try an arm that is clearly terrible as one that is nearly tied with the leader. The methods below explore where it is useful.
Quick check ε-greedy with ε = 0.2 on a 4-armed bandit. Its estimates have converged, so the greedy arm is the truly best arm. What fraction of pulls go to the best arm?
Exploit steps (probability 0.8) always pull the best arm. Explore steps (probability 0.2) pick uniformly among all 4 arms, including the best, so they add 0.2 × 1/4 = 0.05. Total 0.85.
Optimistic initial values
Here is a trick that makes even greedy explore. Start every estimate high, above any reward you expect: for 0/1 rewards, . Now every arm looks wonderful until it has been tried. Greedy pulls one, gets a reward below the optimistic guess, and that arm’s estimate drops below the untried ones, so greedy moves on to another. Every arm gets tried, and arms keep being retried until their estimates have been pulled down to their real level. The best arm is the one that disappoints least.
There is a subtlety. With the sample average (step ) the initial value is forgotten after one pull, because the first step size is 1 (look back at the table above). So optimism only guarantees that each arm is tried once. To make it last, Sutton and Barto pair it with a constant step size, with , under which the initial value fades geometrically (we study constant step sizes properly below). The race demo later in the chapter uses that version: initial value 1 for 0/1 rewards, 5 for Gaussian ones, .
Optimistic initialization is cheap and often works well on small stationary problems. But all its exploration happens at the beginning, driven by an arbitrary number you chose; if the world changes later, nothing makes it explore again. The next idea keeps the optimism and makes it principled.
UCB: optimism in the face of uncertainty
Look at what optimistic initialization got right: it treated an arm we know little about as if it might be great. Upper confidence bound (UCB) methods make this precise. For each arm, ask: given the data so far, how good could this arm plausibly be? Then pull the arm with the highest plausible value.
An estimate built from samples has a statistical error of order . So add to each estimate a bonus that is large when is small:
where is the number of pulls so far and untried arms count as having an infinite score, so they are tried first. (Sources differ by one in how they count ; it changes nothing important.) The constant sets how wide the “plausible” range is. The version called UCB1 (Auer, Cesa-Bianchi and Fischer, 2002) uses for rewards in ; the derivation below shows where the comes from.
Read the bonus term by term:
- : every pull of arm shrinks its own bonus. An arm you have measured carefully gets little benefit of the doubt.
- : while an arm is not being pulled, keeps growing, so its bonus slowly rises. No arm is abandoned forever; a neglected arm is eventually re-checked. Because grows very slowly, the re-checks become rare.
- : arms that look good are favored, as in greedy.
An arm gets pulled either because its estimate is high (exploitation) or because its uncertainty is high (exploration). The formula trades the two automatically.
A worked example
Three Bernoulli arms after pulls, with and :
| Arm | Wins / pulls | bonus | score | |
|---|---|---|---|---|
| 1 | 7 / 12 | 0.58 | 1.29 | |
| 2 | 3 / 6 | 0.50 | 1.50 | |
| 3 | 0 / 2 | 0.00 | 1.73 |
UCB pulls arm 3, which has never paid out, because two pulls are too few to rule out that it is the best arm. (Scores above 1 are fine: they are optimistic scores, not probabilities.) Suppose arm 3 loses again. Now , , arm 3 has , and the scores become , , . Arm 2 is next. Arm 1 has the highest estimate but the lowest score, because it is already well measured and an extra pull would teach little.
Switch the slot-machine demo to UCB and step through a game. The blue bars run from each estimate (dot) up to its score; when scores exceed 1, the vertical axis stretches to fit them. Watch the tallest bar get pulled, then shrink.
∂ Where √(2 ln t / N) comes from, and why UCB1's regret is logarithmic
Step 1: a confidence bound. Hoeffding’s inequality says that if are independent with values in and mean , their average satisfies
(It is a Chernoff bound: the tail of a bounded average is at least as thin as a Gaussian with variance .) We want the bound to fail with a probability that shrinks fast as time goes on, say . Setting and solving gives
That is UCB1’s bonus. So is an upper confidence bound on that is wrong with probability at most .
Step 2: when can a bad arm be pulled? Let be the best arm and a suboptimal arm with gap . Write . If UCB pulls at step , then . At least one of three things must be true:
- the best arm’s bound is wrong: ;
- arm ‘s estimate is too high: ;
- arm ‘s bonus is still big: .
To check: if none of them holds, then , which contradicts pulling .
Step 3: count. Condition 3 says , so it can only hold for the first pulls of (that is where the “+1” below comes from). For a fixed number of pulls of each arm, conditions 1 and 2 each have probability at most by Step 1. But the counts are random (they depend on the rewards), so take a union bound over all their possible values, at most for each of the two counts. That costs a factor , leaving per step, and is finite. Altogether
Step 4: regret. Plug into the regret decomposition :
This is Theorem 1 of Auer, Cesa-Bianchi and Fischer (2002). The regret grows like , not : a bad arm is pulled about times, and each pull costs . Arms that are nearly as good as the best are hard to rule out (many pulls) but cheap to pull by mistake (small ).
The comes from demanding that the bound fail with probability only , for any rewards in , so it is conservative. In practice is a tuning knob, and it should scale with how noisy the rewards are. For 0/1 rewards (standard deviation at most 0.5), usually works much better than , and both demos in this chapter start there. For Gaussian rewards with standard deviation 1, the race demo switches to .
Quick check Under UCB, an arm has not been pulled for a long time while the others were. What happens to its score?
Its Q and N are frozen, but t keeps increasing, so the bonus c·√(ln t / N) creeps up. Eventually it overtakes the leader's score and the arm is re-checked. This is why UCB never permanently abandons an arm, yet re-checks become rarer because ln t grows slowly.
Thompson sampling: act on a plausible world
UCB asks “how good could each arm be?” and acts as if the most optimistic answer were true. Thompson sampling asks a different question: “what do I currently believe about each arm?”, keeps that belief as a full probability distribution, and acts on a random draw from it. It is the oldest idea in this chapter (Thompson, 1933) and often the best performer in practice.
Beliefs about a coin
Take one Bernoulli arm with unknown win probability . Before any pulls, a reasonable belief is “any in is equally likely”: the uniform distribution, which is the Beta distribution . In general has density
(Here and are just the two shape parameters of the Beta distribution. They are unrelated to the step size later in this chapter and to the KL coefficient of Part III; the letters are traditional in all three places.)
Now pull the arm and see a win. Bayes’ rule multiplies the prior by the likelihood of a win, which is : the posterior is , that is, . A loss multiplies by and gives . So the whole belief is two counters:
(A prior that stays in the same family after an update is called conjugate; Beta is conjugate to Bernoulli.) The prior acts like one imaginary win and one imaginary loss. An arm with 3 wins and 1 loss has posterior , mean , a little below the raw average . As data accumulates the posterior narrows around the true ; its standard deviation shrinks like , the same rate as UCB’s bonus.
The algorithm
keep α(a) = β(a) = 1 for every arm
at each step t:
for each arm a: draw θ(a) ~ Beta(α(a), β(a)) (one plausible world)
pull a_t = argmax_a θ(a) (the best arm in that world)
observe r ∈ {0, 1}
α(a_t) ← α(a_t) + r ; β(a_t) ← β(a_t) + (1 − r)
That’s all. There is no exploration parameter to tune. Each step imagines one world consistent with the evidence and plays optimally in that world.
Why does this explore well? Each arm is pulled with exactly the posterior probability that it is the best arm. This property is called probability matching. An arm with a wide posterior sometimes produces a high draw, so it gets tried. An arm whose posterior is narrow and clearly below the leader almost never wins the draw, so it is (correctly) ignored. As evidence accumulates, the posteriors sharpen and exploration fades on its own.
A worked example with three arms:
| Arm | Wins / losses | Posterior | Mean | P(pulled) |
|---|---|---|---|---|
| A | 3 / 1 | Beta(4, 2) | 0.67 | 0.56 |
| B | 0 / 0 | Beta(1, 1) | 0.50 | 0.30 |
| C | 6 / 6 | Beta(7, 7) | 0.50 | 0.13 |
(The last column was computed by sampling.) B and C have the same mean, 0.5, but B is pulled more than twice as often, because B’s uniform posterior gives real probability to while C’s twelve pulls have pinned it near 0.5. Exercise 2.4 has you compute a case like this exactly.
Switch the slot-machine demo to Thompson. Each machine shows its Beta posterior as a green violin shape and the value it drew this step as a diamond. Early on the violins are wide and the diamonds jump around; after a few dozen pulls the best machine’s violin is narrow and high, and it wins almost every draw.
Quick check Thompson sampling: arm X has posterior Beta(50, 50) and arm Y has posterior Beta(2, 2). Both have mean 0.5. Which is pulled more often, and why?
Both posteriors are symmetric around 0.5, so P(draw_X > draw_Y) = 1/2 exactly. The wider posterior produces more extreme draws, both high and low, and the two effects cancel here. Wide posteriors are favored only when the leader is above the uncertain arm's mean, as in the worked example where arm B was compared against arm A at 0.67.
How good can a strategy be?
You now have five strategies. Before racing them, what is the best regret any strategy could possibly get?
Not zero. Any strategy has to pull each bad arm a few times to find out it is bad. In 1985, Lai and Robbins made this precise. Informally: for any strategy that does reasonably well on every bandit problem (its regret grows more slowly than any power of ), each suboptimal arm must be pulled at least
times as , where is the Kullback–Leibler divergence between the arm’s reward distribution and the best arm’s (for Bernoulli arms, ). Multiplying by and summing gives the Lai–Robbins lower bound: regret must grow at least like , with a constant set by how hard the arms are to tell apart.
So the target is logarithmic regret. Here is the scorecard:
| Strategy | Regret growth | Why |
|---|---|---|
| Greedy | linear | can lock onto a bad arm forever |
| ε-greedy (fixed ε) | linear | explores at rate ε forever |
| Optimistic greedy | linear in the worst case | exploration stops once the optimism wears off |
| UCB1 | proved above; the right rate, but a larger constant than the lower bound (Exercise 2.7) | |
| Thompson sampling | for Bernoulli arms it matches the Lai–Robbins constant (Kaufmann, Korda & Munos 2012; Agrawal & Goyal 2013) |
Two honest caveats. First, these are statements about large , and constants matter. Over 1,000 pulls, ε-greedy with ε = 0.1 beats UCB1 with its textbook ; set to 1.41 in the race below to see it. Second, blows up when gaps are tiny; for the worst-case problem at a given , no algorithm can guarantee regret smaller than order (UCB1 achieves that up to a log factor). Lattimore and Szepesvári’s book covers both kinds of bound carefully.
| Show | Regret | % best arm (recent) |
|---|
Press Play. Every strategy faces the same 200 random 10-armed bandits with the same reward luck, so differences come from the strategies. Then: (1) tick 'log time axis'. Logarithmic regret shows up as a straight line on this axis, and linear regret bends upward. (2) Set ε to 0: ε-greedy becomes greedy. (3) Move UCB's c to 0, then √2 ≈ 1.41, then 3. (4) Switch to Gaussian rewards and 5,000 steps. (5) 'Where the pulls went' shows each strategy's pulls by arm, best arm on the left: greedy's are smeared over every arm.
Things to notice in the race (default settings, Bernoulli rewards; exact numbers vary with “New bandits”):
- Greedy reaches about 20% best-arm pulls and stays there forever. Its regret is a steep straight line, about 250 after 1,000 steps.
- ε-greedy learns quickly, then its regret keeps growing in a straight line (about 65–70 after 1,000 steps), with a slope set by ε. In “Where the pulls went” it gives 1% of its pulls to every arm, even the worst, by construction.
- Optimistic greedy does surprisingly well on this problem (about 45).
- UCB with and Thompson sampling are best (about 35 and 30), and their regret curves keep flattening. By the end, Thompson puts nearly 90% of its pulls on the best arm.
- With Gaussian rewards the order changes a little: UCB with edges ahead of Thompson, and optimistic greedy ends near ε-greedy’s total. Its initial value of 5 is far above every arm, so it spends its first few hundred pulls wearing that optimism down on every arm; after that its curve is much flatter than ε-greedy’s. “Usually the strongest” is a tendency, not a law.
When the world changes: constant step sizes
Everything so far assumed stationary arms: each is fixed forever. Real problems drift. A restaurant changes chefs; users’ tastes shift; in RL proper, the “arm values” an agent estimates change as its own policy improves (that is how Chapter 5 will use these updates).
The sample average is the wrong tool for a moving target. After 1,000 pulls its step size is , so it would take hundreds of new rewards to move it. The fix is to stop shrinking the step: use a constant ,
Unrolling this recursion (Exercise 2.6) shows what it computes:
This is an exponential recency-weighted average: the newest reward gets weight , the one before it , then , and so on; the weights (including the one on ) sum to 1. With a reward’s weight halves about every 7 steps, so the estimate “remembers” roughly the last rewards. Physicists will recognize a discrete low-pass filter, the response of an RC circuit with time constant steps.
The price of tracking is noise. The sample average converges to ; the constant-α average never settles but keeps jittering, with variance for rewards of variance (Exercise 2.6). Small α means less jitter but slower tracking. The classical conditions for a step-size sequence to converge to the true mean (the Robbins–Monro conditions) are
satisfies both. A constant α fails the second on purpose: in a nonstationary world you want to keep moving.
In the race demo, tick Shuffle the arms halfway: at the midpoint, the arms’ true means are randomly reassigned, so the best arm is suddenly some other arm. Everyone’s ”% best arm” crashes. The sample-average ε-greedy agent barely recovers, because hundreds of old rewards outvote each new one. Now tick ε-greedy forgets (constant α = 0.1): it recovers far faster. (One detail: the demo’s forgetting agent uses the plain average for an arm’s first 10 pulls and α = 0.1 after that. Starting with a constant α from would leave weight on that 0, dragging down the estimates of arms that have been explored only a few times.) Optimistic greedy, which also uses α = 0.1, recovers fastest of all, and UCB recovers well too. Thompson sampling, whose model says the arms never change, is the slowest of the three principled methods to recover (though still faster than sample-average ε-greedy). Exercise 2.8 asks you to explain each curve.
Contextual bandits
In many problems you see some information before choosing. A news site sees who is visiting before picking which article to show; a doctor sees the patient before picking a treatment. A contextual bandit adds this: at each step
- the environment shows you a context (drawn from some distribution, not caused by you),
- you choose an action using a policy ,
- you receive a reward with mean , and the round ends.
Your action affects only the current reward, never the next context. That is the line between contextual bandits and full RL: in an MDP (Chapter 3) your action also changes the next state.
With many contexts you can’t keep a separate table of estimates for each one, so you learn a model that generalizes across contexts, and explore with the same principles as before. LinUCB (Li, Chu, Langford and Schapire, 2010), for example, uses a linear model per article and a UCB-style bonus based on the model’s uncertainty; the paper tests it on news recommendation with real traffic from Yahoo!‘s front page.
Bandits also return in Chapter 7, which learns a softmax policy over a bandit’s arms directly by gradient ascent (the “gradient bandit”), and in Chapter 10, where the UCB formula reappears inside Monte Carlo tree search as UCT, the rule for choosing which moves to explore, and AlphaGo-style search uses a variant of it.
Summary
- A K-armed bandit is RL with one state: choose an arm, get a reward, repeat. Only exploration vs. exploitation remains.
- Estimate each arm’s value by its sample average, computed incrementally as . The pattern “estimate ← estimate + step × (target − estimate)” runs through all of RL.
- Regret measures what exploration costs. Greedy and fixed-ε ε-greedy have linear regret; the best possible is logarithmic (Lai–Robbins), with a constant set by how hard arms are to tell apart.
- Greedy can lock onto a bad arm forever: estimates that are too low never get corrected. Optimistic initial values force early exploration but stop exploring later.
- UCB pulls the arm with the highest plausible value, : optimism in the face of uncertainty. UCB1’s regret is , proved with Hoeffding’s inequality.
- Thompson sampling keeps a posterior (Beta for 0/1 rewards), samples one plausible world, and acts optimally in it. Each arm is pulled with the probability that it is best. It is simple, has no exploration parameter to tune, and is usually the strongest of the five.
- For nonstationary problems, use a constant step size α: an exponential recency-weighted average with memory about .
- A contextual bandit adds a context before each choice. An LLM responding to a prompt and getting a reward is one, which is the view Chapters 11–16 build on.
Exercises
Let be the average of the first rewards from an arm.
(a) Show that .
(b) An arm pays . Starting from , apply the update three times. What happened to the 100?
Solution
(a) Split off the last reward and use :
(b) . . . That is the average . The initial 100 was erased by the first update, because its step size is . This is why optimistic initial values need a constant step size to have a lasting effect.
Two Bernoulli arms with and . Greedy starts with , uses sample averages, and breaks ties uniformly at random.
(a) Show that once while , greedy never pulls arm 1 again.
(b) Compute the probability that greedy ends up locked onto arm 2.
(c) What does this imply about greedy’s expected regret as ?
(d) Would ε-greedy with ε = 0.1 fix this? Would starting both estimates at 1 (still with sample averages) fix it completely?
Hint
Solution
(a) Arm 2’s sample average includes at least one reward of 1 and rewards are never negative, so after pulls . Arm 1’s estimate only changes when it is pulled, so it stays 0. Greedy always picks the larger, arm 2, so arm 1 is never pulled and the situation persists forever.
(b) While both estimates are 0 (the “tie state”), each step greedy picks an arm uniformly. The four outcomes:
- pick arm 1 (prob ), win (0.9): , locked onto arm 1 (by the argument in (a) with the arms swapped). Probability .
- pick arm 1, lose (0.1): both still 0. Back to the tie state. Probability .
- pick arm 2, win (0.5): locked onto arm 2. Probability .
- pick arm 2, lose: back to the tie state. Probability .
Each step in the tie state ends with “locked on arm 1” or “locked on arm 2” in the ratio , and the tie state ends eventually with probability 1. So
(The lab’s last test checks this by simulation.)
(c) With probability , greedy pulls arm 2 forever from some point on, losing per step. So : linear.
(d) ε-greedy fixes it: every arm is pulled with probability at least per step, so eventually converges to 0.9 and the exploit steps move to arm 1. Optimistic starts with sample averages do not fix it completely. Each arm is eventually tried (an untried arm keeps , which no tried arm can beat), but after its first pull the initial value is gone. If arm 1’s first pull loses (probability 0.1), , and as soon as arm 2 has a win, greedy is locked onto arm 2 again.
After pulls, three Bernoulli arms have
| Arm | pulls | estimate |
|---|---|---|
| 1 | 70 | 0.60 |
| 2 | 25 | 0.52 |
| 3 | 5 | 0.40 |
(a) With , compute each arm’s UCB score. Which arm is pulled? (.)
(b) Suppose arm 3 keeps losing. How many losses in a row before UCB stops pulling it? (A short loop in Python, or patient arithmetic.)
(c) Which arm is pulled with ? With ?
Hint
Solution
(a) . Bonuses: , , . Scores: , , . Arm 3 is pulled, despite the lowest estimate, because 5 pulls leave it very uncertain.
(b) After more losses, arm 3’s score is and arm 2’s is :
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| arm 3 | 1.757 | 1.574 | 1.435 | 1.326 | 1.238 | 1.165 | 1.103 |
| arm 2 | 1.127 | 1.128 | 1.128 | 1.129 | 1.130 | 1.130 | 1.131 |
Arm 3 stays on top through and drops below arm 2 at : after 6 losses in a row, UCB moves on to arm 2. Its estimate fell from 0.40 to , and its bonus shrank from 1.36 to 0.92.
(c) With the bonus is : , , , giving scores , , . Arm 3 is still pulled. With : bonuses , , , scores , , . Now arm 1, the greedy choice, wins. As , UCB turns into greedy.
Use a prior for every arm.
(a) Arm A pays win, win, loss, win. What is its posterior? Its posterior mean? Why is that different from the sample average?
(b) Two arms: A has been pulled once and won; B has never been pulled. With what probability does Thompson sampling pick A next? What would greedy (with estimates starting at 0) do?
(c) A is pulled again and loses. Now what is the probability Thompson picks A?
Hint
Solution
(a) 3 wins and 1 loss: , with mean . The sample average is . The prior acts like one extra imaginary win and one imaginary loss, which pulls the estimate toward . The effect fades as real data accumulates.
(b) A’s posterior is , density . B’s is uniform. Using the hint,
So Thompson picks A with probability 2/3 and B with probability 1/3: it leans toward the arm that has paid, but gives the untried arm a real chance. Greedy has and picks A with probability 1. (The lab’s test test_task4_probability_matching checks the 2/3.)
(c) A’s posterior is , density , mean . By the same argument, . One win and one loss is no evidence either way relative to the uniform prior, so Thompson is indifferent between A and B.
(a) Show that for any bandit, ε-greedy with fixed ε satisfies
(b) On the 10-armed Bernoulli testbed (each drawn uniformly from ), estimate the slope of this bound for ε = 0.1. The expected maximum of 10 uniform numbers is . Compare with the race demo.
(c) How could you change ε over time to fix the linear growth? What is the catch?
Hint
Solution
(a) The expected regret at step is . With probability ε the agent explores and picks each arm with probability , giving expected regret . With probability it exploits, and the regret of that is . So at every step, however much has been learned. Summing over steps gives the bound.
(b) . Its expectation is . With ε = 0.1 the slope is at least per step, so at least about 41 regret per 1,000 steps once learning is done. In the race demo, ε-greedy’s regret grows by about that much per 1,000 steps after the first few hundred (a bit more, because exploitation sometimes picks a near-best arm). Its total at 1,000 steps (about 65–70) also includes the learning phase.
(c) Let decrease, so the exploration cost grows slower than . With the total cost is , and Auer et al. (2002) show that gives logarithmic regret when is a lower bound on the smallest gap. The catch: you need to know something like in advance. Decay too fast and you stop exploring before the estimates are right, and you are back to greedy’s lock-in problem. UCB and Thompson sampling get logarithmic regret without this tuning, because their exploration shrinks according to the uncertainty that is actually there.
The constant-step-size update is with .
(a) Show by induction that .
(b) Show that the weights sum to 1.
(c) With α = 0.1, after how many steps has a reward’s weight halved? What does α = 1 do?
(d) Suppose the arm is stationary with mean and reward variance , and is large. Show that has mean close to and variance close to , so it never converges.
Hint
Solution
(a) The update is . For : , which matches the formula. If the formula holds for , then
since the term of the sum is .
(b) With ,
(c) A reward’s weight is multiplied by every step. It halves when , that is steps. In general for small α. With α = 1, : the estimate is just the last reward, with no memory at all.
(d) Mean: as , because and by (b) the reward weights sum to . Variance (independent rewards):
This does not shrink with . For Bernoulli rewards with () and α = 0.1, the standard deviation is : the estimate keeps wandering by about ±0.1. That is the cost of being able to track change. It is also why, in the race demo with stationary arms, the constant-α ε-greedy agent does slightly worse than the sample-average one.
Two Bernoulli arms: the best has , the other .
(a) Compute for Bernoulli distributions.
(b) By the Lai–Robbins bound, roughly how many times must any good algorithm pull the worse arm by ? By ? What is the corresponding regret?
(c) Compare with ε-greedy (ε = 0.1) at the same horizons.
(d) UCB1’s guarantee says the bad arm is pulled at most about times. Evaluate it at . What do you conclude?
Hint
Solution
(a) nats.
(b) Pulls . At (): about 451 pulls, regret about . At (): about 677 pulls, regret about 68. A hundred times longer game costs only 50% more regret.
(c) ε-greedy explores at rate 0.1 and picks the bad arm half of those times, so it pulls the bad arm at least times: regret at least , which is 50 at and 5,000 at . At it is comparable to the lower bound, but at it is about 70 times worse. Linear and logarithmic growth look similar for small and very different for large .
(d) pulls of the bad arm out of 10,000, which is worse than pulling the two arms alternately. The bound is valid but vacuous here: its constant is loose (Pinsker’s inequality, , shows the Lai–Robbins count is at most , sixteen times smaller), and it only becomes meaningful for very long games. Take-aways: “logarithmic regret” describes how regret grows, and constants matter a lot at practical horizons. That is why in UCB is usually tuned, and why refined methods such as KL-UCB, and Thompson sampling, which match the Lai–Robbins constant, are preferred.
(a) In the slot-machine demo, play three 50-pull games yourself, pressing New machines before each one (the end of a game reveals the true odds, so replaying the same machines would be cheating). After each of your games, switch to Thompson and let it play the same machines twice (press Play; the scoreboard records every game). Whose average regret is lower? What did you do differently from Thompson?
(b) In the race, with default settings, tick “log time axis”. Which regret curves look like straight lines in the second half, and which curve upward? Connect this to the table in “How good can a strategy be?”. Then set c = 1.41 and look at UCB again.
(c) Set UCB’s c to 0. What does UCB turn into, and why? Then try c = 3.
(d) Tick “Shuffle the arms halfway”. Describe what happens to each strategy after the shuffle and explain it. Then tick “ε-greedy forgets (constant α = 0.1)” and compare both halves of the ε-greedy curve to before.
Hint
Solution
(a) Answers vary. Most people explore too little (committing after two or three pulls per machine) or keep “checking” long after the evidence is clear. Thompson sampling explores in proportion to how plausible each machine still is: it drops clearly bad machines quickly and keeps testing close competitors. Over 50 pulls its regret is typically between about 4 and 11 (about 7 on average over random machines); human play is often comparable or worse, with more variance. With only 50 pulls, luck matters a lot, which is why you should compare averages over several games.
(b) Thompson’s curve becomes close to a straight line on the log axis (logarithmic regret), and UCB’s (c = 0.5) nearly so. Greedy’s curve bends sharply upward (linear regret), and ε-greedy’s also curves upward, more gently (linear with a smaller slope). Optimistic greedy bends slightly; it has no guarantee. With c = 1.41, UCB’s curve bends upward over 1,000 steps, and even over 5,000 steps it is still bending (its regret, about 275 at 5,000 steps, is still above ε-greedy’s, about 240). Logarithmic regret is an asymptotic statement: with the conservative constant, UCB is still busy separating the near-best arms, and gaps of a few hundredths need thousands of pulls each (Exercise 2.7 (d)). The lab’s run.py --steps 10000 shows UCB1 with c = √2 finally overtaking ε-greedy somewhere between 5,000 and 7,000 steps.
(c) With c = 0 the bonus vanishes. Untried arms still score infinity, so UCB tries every arm once and then acts greedily. That single forced try already makes it much better than plain greedy, but it still locks in: its ”% best arm” stops improving (around 60–75%, depending on the bandits), and its regret grows at a constant rate (a straight line on the ordinary axis, a sharply rising curve on the log axis). Over 1,000 steps that is easy to miss, because its total is not far from c = 0.5’s. Switch to 5,000 steps: c = 0 ends near 170, while c = 0.5 stays near 60. With c = 3 it over-explores: over 1,000 steps its regret is nearly as bad as greedy’s, because it keeps re-checking arms it already knows are bad. The constant matters as much as the shape of the bound.
(d) At the shuffle the best arm becomes a random other arm, so every curve’s ”% best arm” drops sharply and regret slopes jump.
- Sample-average ε-greedy barely recovers: each estimate is an average over hundreds of old rewards, so the new rewards take hundreds of steps to outvote them. The old best arm keeps being exploited long after it stopped being best.
- The forgetting version (α = 0.1) tracks the old best arm’s decline within a few dozen pulls and switches away. It still needs its 10% exploration to find the new best arm, which takes a couple of hundred steps. Before the shuffle it is slightly worse than the sample-average version, because its estimates stay noisy (Exercise 2.6 (d)).
- Optimistic greedy recovers fastest. It uses α = 0.1, so the old leader’s estimate falls within a few dozen pulls. Thanks to the optimistic start, every other arm was abandoned only once its estimate had dropped just below the leader’s, so those estimates are still close behind, and as soon as the leader slips, greedy re-checks them one after another.
- UCB recovers reasonably well: the bonuses of neglected arms have kept growing with , so they get re-checked soon after the old best arm’s estimate starts to fall.
- Thompson sampling is the slowest of the three principled methods (still faster than sample-average ε-greedy): the old best arm’s posterior is very narrow after hundreds of pulls, so it keeps winning the draws until many losses wear it down. With 5,000 steps (2,500 before the shuffle) it is even slower. A Bayesian method is only as good as its model, and this model says the arms never change.
A chatbot is being trained with a reward model: for each prompt, it writes one response, the reward model scores it, and the model is updated.
(a) Name the context, the arm, the reward, and the policy. Why is this a contextual bandit rather than a full MDP?
(b) Why can’t you run UCB1 or Beta–Bernoulli Thompson sampling over responses directly?
(c) In this setting, where does exploration come from? What happens on a prompt for which the model never samples a good response?
(d) Best-of-: sample responses, return the one with the highest reward-model score. In bandit terms, what is this doing, and what is the risk as grows?
Hint
Solution
(a) Context: the prompt . Arm: the entire response . Reward: the reward-model score . Policy: the language model’s distribution . It is a contextual bandit because the episode ends after one response and the next prompt is drawn from the dataset independently of what the model wrote; the action affects only its own reward. (If you zoom in, the response is built token by token, and the token-level view is an MDP with deterministic transitions; Chapter 11 compares both views.)
(b) Both keep separate statistics per arm and need to try every arm at least once. The number of possible responses is astronomically large (vocabulary size to the power of the response length), most are never seen twice, and prompts vary too. You need a model that generalizes across responses and prompts, which the LLM itself provides. Exploration has to come from the policy instead of from per-arm counts.
(c) From the randomness of sampling: the model generates from , often with temperature near 1, so it tries varied responses. If the model never produces a good response to some prompt, every sample gets a low reward and there is nothing better to reinforce. RL can only sharpen behaviors the policy already produces sometimes. This is why reasoning RL starts from a capable base model and why loss of diversity (entropy collapse) is a serious failure mode (Chapters 15 and 19).
(d) It pulls arms once each and picks the highest estimated value, which is greedy selection on noisy estimates, and no learning happens. The risk: the maximum of noisy scores is biased upward (the “winner’s curse”), and as grows the winner is increasingly a response that exploits the reward model’s errors rather than one that is truly better. This is reward over-optimization, studied in Chapter 19.
Download the lab below and complete the four tasks in bandits.py:
- Task 1
argmax_tiebreak: argmax with random tie-breaking. - Task 2
EpsilonGreedy:select_actionand the incrementalupdate(sample average or constant α). One class gives greedy, ε-greedy and optimistic greedy. - Task 3
ucb_scoresandUCB1. The test uses this chapter’s worked example. - Task 4
ThompsonBernoulli: Beta posteriors, one sample per arm, argmax.
Then run python run.py to race them on the 10-armed Bernoulli testbed (200 runs), and python run.py --switch for the nonstationary version.
Hint
python -m pytest -q -k task1. In EpsilonGreedy.update, increment N[a] before computing the step . In ucb_scores, fill the array with np.inf first and then compute scores only where N > 0, so you never divide by zero.Solution
The reference is solutions/bandits.py. The key lines:
argmax_tiebreak:best = np.flatnonzero(values == values.max()); return int(rng.choice(best)).EpsilonGreedy.select_action:if rng.random() < epsilon: return rng.integers(k)elseargmax_tiebreak(Q, rng). Exploration is uniform over all arms, including the greedy one.EpsilonGreedy.update:N[a] += 1; step = 1/N[a] if step_size is None else step_size; Q[a] += step * (r - Q[a]).ucb_scores:scores = np.full_like(Q, np.inf); tried = N > 0; scores[tried] = Q[tried] + c * np.sqrt(np.log(t) / N[tried]).UCB1.update: incrementtandN[a], then the sample-average update.ThompsonBernoulli.select_action:theta = rng.beta(alpha, beta); return argmax_tiebreak(theta, rng);update:alpha[a] += r; beta[a] += 1 - r.
What you should see from run.py (regret after 1,000 steps, averaged over 200 runs): greedy about 250 and growing in a straight line; ε = 0.1 about 70; ε = 0.01 about 135; optimistic greedy about 40; UCB1 with c = √2 about 130 (its conservative constant over-explores at this horizon); Thompson about 27. With --switch, the constant-α ε-greedy agent recovers from the shuffle much faster than the sample-average one.
Files: README.md, bandits.py, envs.py, test_bandits.py, run.py
cd 02-bandits
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, ch. 2. The classic treatment and the source of the 10-armed testbed, optimistic initial values and the gradient bandit. Sections 2.1–2.7 match this chapter.
- Lattimore & Szepesvári (2020), Bandit Algorithms. The reference for the theory, free online: UCB and its analysis, lower bounds (Lai–Robbins and minimax), Thompson sampling, contextual and linear bandits. Read the chapters on UCB and on lower bounds first.
- Russo, Van Roy, Kazerouni, Osband & Wen (2018), A Tutorial on Thompson Sampling. A readable tutorial with many examples, including Thompson sampling beyond Beta–Bernoulli.
- Auer, Cesa-Bianchi & Fischer (2002), Finite-time Analysis of the Multiarmed Bandit Problem. The UCB1 paper; the proof of Theorem 1 is the one sketched in this chapter’s derivation, and it also analyzes the decaying-ε schedule.
- Slivkins (2019), Introduction to Multi-Armed Bandits. A shorter, more lecture-like book than Lattimore & Szepesvári.
- Li, Chu, Langford & Schapire (2010), A Contextual-Bandit Approach to Personalized News Article Recommendation. LinUCB, and a well-known example of contextual bandits running on a real website.
- Kaufmann, Korda & Munos (2012), Thompson Sampling: An Asymptotically Optimal Finite-Time Analysis. Shows Thompson sampling matches the Lai–Robbins lower bound for Bernoulli arms.
Next, the world starts to respond to you: Chapter 3 adds states that change with your actions, and with them the idea of planning ahead.