Part I · Foundations · Chapter 2

Bandits: exploration vs. exploitation

The one-state RL problem. ε-greedy, UCB, Thompson sampling, and regret.

~120 minBefore this: What is RL?

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 KK slot machines. Each one pays out according to its own fixed probability distribution, which you don’t know. At each step t=1,2,…,Tt = 1, 2, \dots, T you choose one machine (one arm) ata_t, pull it, and receive a reward rtr_t. Your goal is to collect as much total reward as possible over the TT pulls.

The quantity that matters about each arm is its mean payout, the action value

q∗(a)=E[ rt∣at=a ].q_*(a) = \mathbb{E}[\, r_t \mid a_t = a \,].

If you knew q∗q_*, the problem would be solved: pull arg⁡max⁡aq∗(a)\arg\max_a q_*(a) every time. You don’t, so you keep an estimate Qt(a)Q_t(a) 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

Arm1234
q∗(a)q_*(a)0.300.550.700.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 TT steps is

RegretT=T max⁡aq∗(a)  −  ∑t=1Tq∗(at).\text{Regret}_T = T\, \max_a q_*(a) \;-\; \sum_{t=1}^{T} q_*(a_t).

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 Δa=max⁡bq∗(b)−q∗(a)\Delta_a = \max_b q_*(b) - q_*(a) for the gap of arm aa: how much worse it is than the best arm. Each pull of arm aa costs exactly Δa\Delta_a, so

RegretT=∑aΔa NT+1(a),\text{Regret}_T = \sum_a \Delta_a \, N_{T+1}(a),

where NT+1(a)N_{T+1}(a) is the number of times arm aa was pulled in the whole game. Say you pulled our four arms 2, 3, 4 and 1 times in 10 steps. The gaps are (0.40,0.15,0,0.25)(0.40, 0.15, 0, 0.25), so

Regret10=2(0.40)+3(0.15)+4(0)+1(0.25)=1.5.\text{Regret}_{10} = 2(0.40) + 3(0.15) + 4(0) + 1(0.25) = 1.5 .

The first form gives the same answer: 10×0.70−(2×0.30+3×0.55+4×0.70+1×0.45)=7−5.5=1.510 \times 0.70 - (2 \times 0.30 + 3 \times 0.55 + 4 \times 0.70 + 1 \times 0.45) = 7 - 5.5 = 1.5. 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.

Interactive Five slot machines
Who plays:

Pull 0 of 50Total reward 0Regret ?

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 q∗(a)q_*(a) is the sample average of the rewards arm aa has produced:

Qt(a)=sum of rewards from a before step tNt(a),Q_t(a) = \frac{\text{sum of rewards from } a \text{ before step } t}{N_t(a)},

where Nt(a)N_t(a) counts the pulls of aa before step tt. By the law of large numbers, Qt(a)→q∗(a)Q_t(a) \to q_*(a) as Nt(a)→∞N_t(a) \to \infty. The question is only how to compute it cheaply.

Focus on one arm and drop the aa. Let r1,…,rnr_1, \dots, r_n be its first nn rewards and Qn+1=1n∑i=1nriQ_{n+1} = \frac{1}{n}\sum_{i=1}^{n} r_i the average after them. You don’t need to store all the rewards. Each new reward moves the average a fraction 1n\frac{1}{n} of the way toward itself:

Qn+1=Qn+1n(rn−Qn).Q_{n+1} = Q_n + \frac{1}{n}\big(r_n - Q_n\big).

You’ll derive this in Exercise 2.1 (it takes three lines). A worked example: arm 3 pays 1,0,0,1,11, 0, 0, 1, 1 on its first five pulls.

nnrnr_nupdateQn+1Q_{n+1}
11Q1+11(1−Q1)Q_1 + \frac{1}{1}(1 - Q_1)1.000
201+12(0−1)1 + \frac{1}{2}(0 - 1)0.500
300.5+13(0−0.5)0.5 + \frac{1}{3}(0 - 0.5)0.333
410.333+14(1−0.333)0.333 + \frac{1}{4}(1 - 0.333)0.500
510.5+15(1−0.5)0.5 + \frac{1}{5}(1 - 0.5)0.600

The final value is 3/53/5, the plain average. Notice that the first step has step size 1, so whatever Q1Q_1 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?

Greedy, and how it gets stuck

The simplest strategy uses the estimates directly: always pull the arm that currently looks best,

at=arg⁡max⁡aQt(a),a_t = \arg\max_a Q_t(a),

breaking ties at random. This is the greedy policy. It never explores on purpose, and that is fatal.

Take two arms with q∗(1)=0.9q_*(1) = 0.9 and q∗(2)=0.5q_*(2) = 0.5, 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 Q(2)=1Q(2) = 1 and Q(1)=0Q(1) = 0, so greedy pulls arm 2 next time. Can Q(2)Q(2) ever fall back to 0? No: arm 2’s average includes that first win, so Q(2)≥1/n>0Q(2) \geq 1/n > 0 forever. And Q(1)Q(1) 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 Δ=0.4\Delta = 0.4 per step. Its regret grows linearly in TT. 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 ϵ/K\epsilon / K per step), every estimate eventually converges to the truth, and the exploit steps end up on the best arm. With ϵ=0.1\epsilon = 0.1 and K=10K = 10, the agent eventually pulls the best arm 0.9+0.01=91%0.9 + 0.01 = 91\% 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, 1K∑aΔa\frac{1}{K}\sum_a \Delta_a. So the regret of ε-greedy also grows linearly, at a rate of at least ϵK∑aΔa\frac{\epsilon}{K}\sum_a \Delta_a 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?

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, Q1(a)=1Q_1(a) = 1. 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 1/n1/n) 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, Q←Q+α(r−Q)Q \leftarrow Q + \alpha(r - Q) with α=0.1\alpha = 0.1, 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, α=0.1\alpha = 0.1.

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 NN samples has a statistical error of order 1/N1/\sqrt{N}. So add to each estimate a bonus that is large when Nt(a)N_t(a) is small:

at=arg⁡max⁡a[ Qt(a)+c ln⁡tNt(a) ],a_t = \arg\max_a \Big[\, Q_t(a) + c\,\sqrt{\frac{\ln t}{N_t(a)}} \,\Big],

where tt 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 tt; it changes nothing important.) The constant cc sets how wide the “plausible” range is. The version called UCB1 (Auer, Cesa-Bianchi and Fischer, 2002) uses c=2c = \sqrt{2} for rewards in [0,1][0, 1]; the derivation below shows where the 2\sqrt{2} comes from.

Read the bonus term by term:

  • 1/Nt(a)1/\sqrt{N_t(a)}: every pull of arm aa shrinks its own bonus. An arm you have measured carefully gets little benefit of the doubt.
  • ln⁡t\sqrt{\ln t}: while an arm is not being pulled, tt keeps growing, so its bonus slowly rises. No arm is abandoned forever; a neglected arm is eventually re-checked. Because ln⁡t\ln t grows very slowly, the re-checks become rare.
  • Qt(a)Q_t(a): 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 t=20t = 20 pulls, with c=2c = \sqrt{2} and ln⁡20=3.00\ln 20 = 3.00:

ArmWins / pullsQQbonus 2ln⁡t/N\sqrt{2 \ln t / N}score
17 / 120.586.00/12=0.71\sqrt{6.00/12} = 0.711.29
23 / 60.506.00/6=1.00\sqrt{6.00/6} = 1.001.50
30 / 20.006.00/2=1.73\sqrt{6.00/2} = 1.731.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 t=21t = 21, ln⁡21=3.04\ln 21 = 3.04, arm 3 has N=3N = 3, and the scores become 1.301.30, 1.511.51, 1.421.42. 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 X1,…,XnX_1, \dots, X_n are independent with values in [0,1][0, 1] and mean μ\mu, their average Xˉ\bar X satisfies

P(Xˉ≥μ+u)≤e−2nu2,P(Xˉ≤μ−u)≤e−2nu2.P\big(\bar X \geq \mu + u\big) \leq e^{-2 n u^2}, \qquad P\big(\bar X \leq \mu - u\big) \leq e^{-2 n u^2}.

(It is a Chernoff bound: the tail of a bounded average is at least as thin as a Gaussian with variance 1/(4n)1/(4n).) We want the bound q∗(a)≤Qt(a)+uq_*(a) \leq Q_t(a) + u to fail with a probability that shrinks fast as time goes on, say t−4t^{-4}. Setting e−2Nu2=t−4e^{-2 N u^2} = t^{-4} and solving gives

u=2ln⁡tN.u = \sqrt{\frac{2 \ln t}{N}}.

That is UCB1’s bonus. So Qt(a)+2ln⁡t/Nt(a)Q_t(a) + \sqrt{2\ln t / N_t(a)} is an upper confidence bound on q∗(a)q_*(a) that is wrong with probability at most t−4t^{-4}.

Step 2: when can a bad arm be pulled? Let ∗* be the best arm and aa a suboptimal arm with gap Δa\Delta_a. Write bt(a)=2ln⁡t/Nt(a)b_t(a) = \sqrt{2 \ln t / N_t(a)}. If UCB pulls aa at step tt, then Qt(a)+bt(a)≥Qt(∗)+bt(∗)Q_t(a) + b_t(a) \geq Q_t(*) + b_t(*). At least one of three things must be true:

  1. the best arm’s bound is wrong: Qt(∗)+bt(∗)≤q∗(∗)Q_t(*) + b_t(*) \leq q_*(*);
  2. arm aa‘s estimate is too high: Qt(a)≥q∗(a)+bt(a)Q_t(a) \geq q_*(a) + b_t(a);
  3. arm aa‘s bonus is still big: 2 bt(a)>Δa2\, b_t(a) > \Delta_a.

To check: if none of them holds, then Qt(∗)+bt(∗)>q∗(∗)=q∗(a)+Δa≥q∗(a)+2bt(a)>Qt(a)+bt(a)Q_t(*) + b_t(*) > q_*(*) = q_*(a) + \Delta_a \geq q_*(a) + 2b_t(a) > Q_t(a) + b_t(a), which contradicts pulling aa.

Step 3: count. Condition 3 says Nt(a)<8ln⁡t/Δa2N_t(a) < 8 \ln t / \Delta_a^2, so it can only hold for the first ⌈8ln⁡T/Δa2⌉≤8ln⁡T/Δa2+1\lceil 8 \ln T / \Delta_a^2 \rceil \leq 8 \ln T / \Delta_a^2 + 1 pulls of aa (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 t−4t^{-4} 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 tt for each of the two counts. That costs a factor t2t^2, leaving 2t−22t^{-2} per step, and ∑t2t−2=π2/3\sum_t 2 t^{-2} = \pi^2/3 is finite. Altogether

E[NT+1(a)]≤8ln⁡TΔa2+1+π23.\mathbb{E}\big[N_{T+1}(a)\big] \leq \frac{8 \ln T}{\Delta_a^2} + 1 + \frac{\pi^2}{3}.

Step 4: regret. Plug into the regret decomposition E[RegretT]=∑aΔa E[NT+1(a)]\mathbb{E}[\text{Regret}_T] = \sum_a \Delta_a\, \mathbb{E}[N_{T+1}(a)]:

E[RegretT]≤∑a: Δa>08ln⁡TΔa+(1+π23)∑aΔa.\mathbb{E}[\text{Regret}_T] \leq \sum_{a:\,\Delta_a > 0} \frac{8 \ln T}{\Delta_a} + \Big(1 + \frac{\pi^2}{3}\Big)\sum_a \Delta_a .

This is Theorem 1 of Auer, Cesa-Bianchi and Fischer (2002). The regret grows like ln⁡T\ln T, not TT: a bad arm is pulled about ln⁡T/Δa2\ln T / \Delta_a^2 times, and each pull costs Δa\Delta_a. Arms that are nearly as good as the best are hard to rule out (many pulls) but cheap to pull by mistake (small Δa\Delta_a).

The 2\sqrt{2} comes from demanding that the bound fail with probability only t−4t^{-4}, for any rewards in [0,1][0, 1], so it is conservative. In practice cc is a tuning knob, and it should scale with how noisy the rewards are. For 0/1 rewards (standard deviation at most 0.5), c≈0.5c \approx 0.5 usually works much better than 2\sqrt{2}, and both demos in this chapter start there. For Gaussian rewards with standard deviation 1, the race demo switches to c=1c = 1.

Quick check Under UCB, an arm has not been pulled for a long time while the others were. What happens to its score?

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 θ=q∗(a)\theta = q_*(a). Before any pulls, a reasonable belief is “any θ\theta in [0,1][0, 1] is equally likely”: the uniform distribution, which is the Beta distribution Beta(1,1)\text{Beta}(1, 1). In general Beta(α,β)\text{Beta}(\alpha, \beta) has density

p(θ)∝θα−1(1−θ)β−1,mean αα+β.p(\theta) \propto \theta^{\alpha - 1}(1 - \theta)^{\beta - 1}, \qquad \text{mean } \frac{\alpha}{\alpha + \beta}.

(Here α\alpha and β\beta are just the two shape parameters of the Beta distribution. They are unrelated to the step size α\alpha later in this chapter and to the KL coefficient β\beta 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 θ\theta: the posterior is ∝θα(1−θ)β−1\propto \theta^{\alpha}(1-\theta)^{\beta - 1}, that is, Beta(α+1,β)\text{Beta}(\alpha + 1, \beta). A loss multiplies by 1−θ1 - \theta and gives Beta(α,β+1)\text{Beta}(\alpha, \beta + 1). So the whole belief is two counters:

after S wins and F losses from a Beta(1,1) prior:θ∼Beta(1+S,  1+F).\text{after } S \text{ wins and } F \text{ losses from a Beta}(1,1) \text{ prior:} \qquad \theta \sim \text{Beta}(1 + S,\; 1 + F).

(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 Beta(4,2)\text{Beta}(4, 2), mean 4/6=0.674/6 = 0.67, a little below the raw average 0.750.75. As data accumulates the posterior narrows around the true θ\theta; its standard deviation shrinks like 1/N1/\sqrt{N}, 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:

ArmWins / lossesPosteriorMeanP(pulled)
A3 / 1Beta(4, 2)0.670.56
B0 / 0Beta(1, 1)0.500.30
C6 / 6Beta(7, 7)0.500.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 θB>0.67\theta_B > 0.67 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?

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 TT), each suboptimal arm must be pulled at least

NT+1(a)≳ln⁡TKL(q∗(a) ∥ q∗(∗))N_{T+1}(a) \gtrsim \frac{\ln T}{\mathrm{KL}\big(q_*(a) \,\Vert\, q_*(*)\big)}

times as T→∞T \to \infty, where KL\mathrm{KL} is the Kullback–Leibler divergence between the arm’s reward distribution and the best arm’s (for Bernoulli arms, KL(p∥q)=pln⁡pq+(1−p)ln⁡1−p1−q\mathrm{KL}(p \Vert q) = p \ln\frac{p}{q} + (1-p)\ln\frac{1-p}{1-q}). Multiplying by Δa\Delta_a and summing gives the Lai–Robbins lower bound: regret must grow at least like ln⁡T\ln T, with a constant set by how hard the arms are to tell apart.

So the target is logarithmic regret. Here is the scorecard:

StrategyRegret growthWhy
Greedylinearcan lock onto a bad arm forever
ε-greedy (fixed ε)linearexplores at rate ε forever
Optimistic greedylinear in the worst caseexploration stops once the optimism wears off
UCB1O(ln⁡T)O(\ln T)proved above; the right rate, but a larger constant than the lower bound (Exercise 2.7)
Thompson samplingO(ln⁡T)O(\ln T)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 TT, and constants matter. Over 1,000 pulls, ε-greedy with ε = 0.1 beats UCB1 with its textbook c=2c = \sqrt{2}; set cc to 1.41 in the race below to see it. Second, ln⁡T/Δ\ln T / \Delta blows up when gaps are tiny; for the worst-case problem at a given TT, no algorithm can guarantee regret smaller than order KT\sqrt{KT} (UCB1 achieves that up to a log factor). Lattimore and Szepesvári’s book covers both kinds of bound carefully.

Interactive The race: five strategies on 200 bandits
ShowRegret% best arm (recent)
Where the pulls wentarms ranked best → worst

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 c=0.5c = 0.5 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 c=1c = 1 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 q∗(a)q_*(a) 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 1/10001/1000, so it would take hundreds of new rewards to move it. The fix is to stop shrinking the step: use a constant α∈(0,1]\alpha \in (0, 1],

Qn+1=Qn+α (rn−Qn).Q_{n+1} = Q_n + \alpha\,(r_n - Q_n).

Unrolling this recursion (Exercise 2.6) shows what it computes:

Qn+1=(1−α)nQ1+∑i=1nα(1−α)n−i ri.Q_{n+1} = (1 - \alpha)^n Q_1 + \sum_{i=1}^{n} \alpha (1 - \alpha)^{n - i}\, r_i .

This is an exponential recency-weighted average: the newest reward gets weight α\alpha, the one before it α(1−α)\alpha(1-\alpha), then α(1−α)2\alpha(1-\alpha)^2, and so on; the weights (including the one on Q1Q_1) sum to 1. With α=0.1\alpha = 0.1 a reward’s weight halves about every 7 steps, so the estimate “remembers” roughly the last 1/α=101/\alpha = 10 rewards. Physicists will recognize a discrete low-pass filter, the response of an RC circuit with time constant 1/α1/\alpha steps.

The price of tracking is noise. The sample average converges to q∗(a)q_*(a); the constant-α average never settles but keeps jittering, with variance α2−ασ2\frac{\alpha}{2 - \alpha}\sigma^2 for rewards of variance σ2\sigma^2 (Exercise 2.6). Small α means less jitter but slower tracking. The classical conditions for a step-size sequence αn\alpha_n to converge to the true mean (the Robbins–Monro conditions) are

∑nαn=∞(steps big enough to overcome any start),∑nαn2<∞(steps small enough that noise dies out).\sum_n \alpha_n = \infty \quad \text{(steps big enough to overcome any start)}, \qquad \sum_n \alpha_n^2 < \infty \quad \text{(steps small enough that noise dies out)}.

αn=1/n\alpha_n = 1/n 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 Q1=0Q_1 = 0 would leave weight (1−α)n(1-\alpha)^n 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

  1. the environment shows you a context xtx_t (drawn from some distribution, not caused by you),
  2. you choose an action ata_t using a policy π(a∣xt)\pi(a \mid x_t),
  3. you receive a reward rtr_t with mean q∗(xt,at)q_*(x_t, a_t), 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 Q(x,a)Q(x, a) 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 q∗(a)q_*(a) by its sample average, computed incrementally as Q←Q+1n(r−Q)Q \leftarrow Q + \frac{1}{n}(r - Q). The pattern “estimate ← estimate + step × (target − estimate)” runs through all of RL.
  • Regret =∑aΔaNT+1(a)= \sum_a \Delta_a N_{T+1}(a) 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, Q+cln⁡t/NQ + c\sqrt{\ln t / N}: optimism in the face of uncertainty. UCB1’s regret is O(ln⁡T)O(\ln T), 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 1/α1/\alpha.
  • 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

Exercise 2.1The incremental meanPen & paper●○○

Let Qn+1=1n∑i=1nriQ_{n+1} = \frac{1}{n}\sum_{i=1}^{n} r_i be the average of the first nn rewards from an arm.

(a) Show that Qn+1=Qn+1n(rn−Qn)Q_{n+1} = Q_n + \frac{1}{n}(r_n - Q_n).

(b) An arm pays 2,4,92, 4, 9. Starting from Q1=100Q_1 = 100, apply the update three times. What happened to the 100?

Solution

(a) Split off the last reward and use ∑i=1n−1ri=(n−1)Qn\sum_{i=1}^{n-1} r_i = (n-1)Q_n:

Qn+1=1n(rn+∑i=1n−1ri)=1n(rn+(n−1)Qn)=Qn+1n(rn−Qn).Q_{n+1} = \frac{1}{n}\Big(r_n + \sum_{i=1}^{n-1} r_i\Big) = \frac{1}{n}\big(r_n + (n-1)Q_n\big) = Q_n + \frac{1}{n}\big(r_n - Q_n\big).

(b) Q2=100+11(2−100)=2Q_2 = 100 + \frac{1}{1}(2 - 100) = 2. Q3=2+12(4−2)=3Q_3 = 2 + \frac12(4 - 2) = 3. Q4=3+13(9−3)=5Q_4 = 3 + \frac13(9 - 3) = 5. That is the average (2+4+9)/3=5(2 + 4 + 9)/3 = 5. The initial 100 was erased by the first update, because its step size is 1/1=11/1 = 1. This is why optimistic initial values need a constant step size to have a lasting effect.

Exercise 2.2Greedy locks inPen & paper●●○

Two Bernoulli arms with q∗(1)=0.9q_*(1) = 0.9 and q∗(2)=0.5q_*(2) = 0.5. Greedy starts with Q(1)=Q(2)=0Q(1) = Q(2) = 0, uses sample averages, and breaks ties uniformly at random.

(a) Show that once Q(2)>0Q(2) > 0 while Q(1)=0Q(1) = 0, 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 T→∞T \to \infty?

(d) Would ε-greedy with ε = 0.1 fix this? Would starting both estimates at 1 (still with sample averages) fix it completely?

Hint
As long as both estimates are 0, the situation is the same as at the start. Each step, something either ends the “tie” state for good or leaves it unchanged. Compute the probability of each outcome per step.
Solution

(a) Arm 2’s sample average includes at least one reward of 1 and rewards are never negative, so after nn pulls Q(2)≥1/n>0Q(2) \geq 1/n > 0. 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 12\frac12), win (0.9): Q(1)>0=Q(2)Q(1) > 0 = Q(2), locked onto arm 1 (by the argument in (a) with the arms swapped). Probability 0.450.45.
  • pick arm 1, lose (0.1): both still 0. Back to the tie state. Probability 0.050.05.
  • pick arm 2, win (0.5): locked onto arm 2. Probability 0.250.25.
  • pick arm 2, lose: back to the tie state. Probability 0.250.25.

Each step in the tie state ends with “locked on arm 1” or “locked on arm 2” in the ratio 0.45:0.250.45 : 0.25, and the tie state ends eventually with probability 1. So

P(locked on arm 2)=0.250.25+0.45=514≈0.36.P(\text{locked on arm 2}) = \frac{0.25}{0.25 + 0.45} = \frac{5}{14} \approx 0.36.

(The lab’s last test checks this by simulation.)

(c) With probability 5/145/14, greedy pulls arm 2 forever from some point on, losing Δ=0.4\Delta = 0.4 per step. So E[RegretT]≥514(0.4)(T−a few)≈0.14 T\mathbb{E}[\text{Regret}_T] \geq \frac{5}{14}(0.4)(T - \text{a few}) \approx 0.14\,T: linear.

(d) ε-greedy fixes it: every arm is pulled with probability at least ϵ/K=0.05\epsilon/K = 0.05 per step, so Q(1)Q(1) 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 Q=1Q = 1, 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), Q(1)=0Q(1) = 0, and as soon as arm 2 has a win, greedy is locked onto arm 2 again.

Exercise 2.3UCB scores by handPen & paper●○○

After t=100t = 100 pulls, three Bernoulli arms have

Armpulls NNestimate QQ
1700.60
2250.52
350.40

(a) With c=2c = \sqrt{2}, compute each arm’s UCB score. Which arm is pulled? (ln⁡100=4.605\ln 100 = 4.605.)

(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 c=0.5c = 0.5? With c=0.2c = 0.2?

Hint
For (b), after kk more losses arm 3 has N=5+kN = 5 + k, two wins (so Q=2/(5+k)Q = 2/(5+k)), and t=100+kt = 100 + k. Arm 2’s score also creeps up a little because tt grows.
Solution

(a) 2ln⁡100=9.212 \ln 100 = 9.21. Bonuses: 9.21/70=0.363\sqrt{9.21/70} = 0.363, 9.21/25=0.607\sqrt{9.21/25} = 0.607, 9.21/5=1.357\sqrt{9.21/5} = 1.357. Scores: 0.9630.963, 1.1271.127, 1.7571.757. Arm 3 is pulled, despite the lowest estimate, because 5 pulls leave it very uncertain.

(b) After kk more losses, arm 3’s score is 25+k+2ln⁡(100+k)5+k\frac{2}{5+k} + \sqrt{\frac{2\ln(100+k)}{5+k}} and arm 2’s is 0.52+2ln⁡(100+k)250.52 + \sqrt{\frac{2\ln(100+k)}{25}}:

kk0123456
arm 31.7571.5741.4351.3261.2381.1651.103
arm 21.1271.1281.1281.1291.1301.1301.131

Arm 3 stays on top through k=5k = 5 and drops below arm 2 at k=6k = 6: after 6 losses in a row, UCB moves on to arm 2. Its estimate fell from 0.40 to 2/11=0.182/11 = 0.18, and its bonus shrank from 1.36 to 0.92.

(c) With c=0.5c = 0.5 the bonus is 0.5ln⁡t/N0.5\sqrt{\ln t / N}: 0.1280.128, 0.2150.215, 0.4800.480, giving scores 0.7280.728, 0.7350.735, 0.8800.880. Arm 3 is still pulled. With c=0.2c = 0.2: bonuses 0.0510.051, 0.0860.086, 0.1920.192, scores 0.6510.651, 0.6060.606, 0.5920.592. Now arm 1, the greedy choice, wins. As c→0c \to 0, UCB turns into greedy.

Exercise 2.4Beta posteriors and Thompson's choicePen & paper●●○

Use a Beta(1,1)\text{Beta}(1, 1) 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
For (b) and (c): if θB\theta_B is uniform on [0,1][0, 1], then P(θB<θA∣θA)=θAP(\theta_B < \theta_A \mid \theta_A) = \theta_A. Average that over A’s posterior.
Solution

(a) 3 wins and 1 loss: Beta(1+3,1+1)=Beta(4,2)\text{Beta}(1 + 3, 1 + 1) = \text{Beta}(4, 2), with mean 4/6≈0.674/6 \approx 0.67. The sample average is 3/4=0.753/4 = 0.75. The prior acts like one extra imaginary win and one imaginary loss, which pulls the estimate toward 1/21/2. The effect fades as real data accumulates.

(b) A’s posterior is Beta(2,1)\text{Beta}(2, 1), density p(θ)=2θp(\theta) = 2\theta. B’s is uniform. Using the hint,

P(θA>θB)=E[θA]=∫01θ⋅2θ dθ=23.P(\theta_A > \theta_B) = \mathbb{E}[\theta_A] = \int_0^1 \theta \cdot 2\theta \, d\theta = \frac{2}{3}.

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 Q(A)=1>0=Q(B)Q(A) = 1 > 0 = Q(B) and picks A with probability 1. (The lab’s test test_task4_probability_matching checks the 2/3.)

(c) A’s posterior is Beta(2,2)\text{Beta}(2, 2), density 6θ(1−θ)6\theta(1 - \theta), mean 1/21/2. By the same argument, P(θA>θB)=E[θA]=1/2P(\theta_A > \theta_B) = \mathbb{E}[\theta_A] = 1/2. One win and one loss is no evidence either way relative to the uniform prior, so Thompson is indifferent between A and B.

Exercise 2.5Why ε-greedy's regret is linearPen & paper●●○

(a) Show that for any bandit, ε-greedy with fixed ε satisfies

E[RegretT]≥ϵK(∑aΔa) T.\mathbb{E}[\text{Regret}_T] \geq \frac{\epsilon}{K}\Big(\sum_a \Delta_a\Big)\, T.

(b) On the 10-armed Bernoulli testbed (each q∗(a)q_*(a) drawn uniformly from [0,1][0, 1]), estimate the slope of this bound for ε = 0.1. The expected maximum of 10 uniform numbers is 10/1110/11. Compare with the race demo.

(c) How could you change ε over time to fix the linear growth? What is the catch?

Hint
Regret per step is Δat\Delta_{a_t}, and it is never negative. Look only at the exploration steps and ignore the rest.
Solution

(a) The expected regret at step tt is E[Δat]\mathbb{E}[\Delta_{a_t}]. With probability ε the agent explores and picks each arm with probability 1/K1/K, giving expected regret 1K∑aΔa\frac{1}{K}\sum_a \Delta_a. With probability 1−ϵ1 - \epsilon it exploits, and the regret of that is ≥0\geq 0. So E[Δat]≥ϵK∑aΔa\mathbb{E}[\Delta_{a_t}] \geq \frac{\epsilon}{K}\sum_a \Delta_a at every step, however much has been learned. Summing over TT steps gives the bound.

(b) 1K∑aΔa=max⁡aq∗(a)−1K∑aq∗(a)\frac{1}{K}\sum_a \Delta_a = \max_a q_*(a) - \frac{1}{K}\sum_a q_*(a). Its expectation is 1011−12≈0.41\frac{10}{11} - \frac12 \approx 0.41. With ε = 0.1 the slope is at least 0.0410.041 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 ϵt\epsilon_t decrease, so the exploration cost ∑tϵt\sum_t \epsilon_t grows slower than TT. With ϵt∝1/t\epsilon_t \propto 1/t the total cost is ∝ln⁡T\propto \ln T, and Auer et al. (2002) show that ϵt=min⁡(1,cKd2t)\epsilon_t = \min\big(1, \frac{cK}{d^2 t}\big) gives logarithmic regret when dd is a lower bound on the smallest gap. The catch: you need to know something like dd 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.

Exercise 2.6Exponential recency weightingPen & paper●●○

The constant-step-size update is Qn+1=Qn+α(rn−Qn)Q_{n+1} = Q_n + \alpha(r_n - Q_n) with 0<α≤10 < \alpha \leq 1.

(a) Show by induction that Qn+1=(1−α)nQ1+∑i=1nα(1−α)n−iriQ_{n+1} = (1-\alpha)^n Q_1 + \sum_{i=1}^{n} \alpha(1-\alpha)^{n-i} r_i.

(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 μ\mu and reward variance σ2\sigma^2, and nn is large. Show that Qn+1Q_{n+1} has mean close to μ\mu and variance close to α2−ασ2\frac{\alpha}{2-\alpha}\sigma^2, so it never converges.

Hint
For (a), rewrite the update as Qn+1=(1−α)Qn+αrnQ_{n+1} = (1-\alpha)Q_n + \alpha r_n. For (b), the weights form a geometric series. For (d), the rewards are independent, so the variance of a weighted sum is the sum of squared weights times σ2\sigma^2.
Solution

(a) The update is Qn+1=(1−α)Qn+αrnQ_{n+1} = (1-\alpha) Q_n + \alpha r_n. For n=1n = 1: Q2=(1−α)Q1+αr1Q_2 = (1-\alpha)Q_1 + \alpha r_1, which matches the formula. If the formula holds for QnQ_n, then

Qn+1=(1−α)[(1−α)n−1Q1+∑i=1n−1α(1−α)n−1−iri]+αrn=(1−α)nQ1+∑i=1nα(1−α)n−iri,Q_{n+1} = (1-\alpha)\Big[(1-\alpha)^{n-1} Q_1 + \sum_{i=1}^{n-1} \alpha(1-\alpha)^{n-1-i} r_i\Big] + \alpha r_n = (1-\alpha)^n Q_1 + \sum_{i=1}^{n} \alpha(1-\alpha)^{n-i} r_i ,

since the i=ni = n term of the sum is α(1−α)0rn=αrn\alpha(1-\alpha)^0 r_n = \alpha r_n.

(b) With k=n−ik = n - i,

(1−α)n+∑k=0n−1α(1−α)k=(1−α)n+α⋅1−(1−α)n1−(1−α)=(1−α)n+1−(1−α)n=1.(1-\alpha)^n + \sum_{k=0}^{n-1} \alpha(1-\alpha)^k = (1-\alpha)^n + \alpha\cdot\frac{1 - (1-\alpha)^n}{1 - (1-\alpha)} = (1-\alpha)^n + 1 - (1-\alpha)^n = 1 .

(c) A reward’s weight is multiplied by 1−α=0.91 - \alpha = 0.9 every step. It halves when 0.9k=1/20.9^k = 1/2, that is k=ln⁡2/ln⁡(1/0.9)≈6.6k = \ln 2 / \ln(1/0.9) \approx 6.6 steps. In general k≈0.69/αk \approx 0.69/\alpha for small α. With α = 1, Qn+1=rnQ_{n+1} = r_n: the estimate is just the last reward, with no memory at all.

(d) Mean: E[Qn+1]=(1−α)nQ1+μ∑iα(1−α)n−i→μ\mathbb{E}[Q_{n+1}] = (1-\alpha)^n Q_1 + \mu \sum_i \alpha(1-\alpha)^{n-i} \to \mu as n→∞n \to \infty, because (1−α)n→0(1-\alpha)^n \to 0 and by (b) the reward weights sum to 1−(1−α)n→11 - (1-\alpha)^n \to 1. Variance (independent rewards):

Var[Qn+1]=σ2∑k=0n−1α2(1−α)2k  →  σ2α21−(1−α)2=σ2α2α(2−α)=α2−ασ2.\mathrm{Var}[Q_{n+1}] = \sigma^2 \sum_{k=0}^{n-1} \alpha^2 (1-\alpha)^{2k} \;\to\; \sigma^2 \frac{\alpha^2}{1 - (1-\alpha)^2} = \sigma^2\frac{\alpha^2}{\alpha(2-\alpha)} = \frac{\alpha}{2-\alpha}\sigma^2 .

This does not shrink with nn. For Bernoulli rewards with μ=0.5\mu = 0.5 (σ2=0.25\sigma^2 = 0.25) and α = 0.1, the standard deviation is 0.0526×0.25≈0.11\sqrt{0.0526 \times 0.25} \approx 0.11: 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.

Exercise 2.7How many pulls does a bad arm need?Pen & paper●●●

Two Bernoulli arms: the best has q∗=0.6q_* = 0.6, the other 0.50.5.

(a) Compute KL(0.5 ∥ 0.6)\mathrm{KL}(0.5 \,\Vert\, 0.6) for Bernoulli distributions.

(b) By the Lai–Robbins bound, roughly how many times must any good algorithm pull the worse arm by T=104T = 10^4? By T=106T = 10^6? 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 8ln⁡T/Δ28\ln T / \Delta^2 times. Evaluate it at T=104T = 10^4. What do you conclude?

Hint
Natural logarithms throughout. Both bounds are asymptotic statements, so treat them as orders of magnitude, not exact predictions.
Solution

(a) KL(0.5∥0.6)=0.5ln⁡0.50.6+0.5ln⁡0.50.4=0.5(−0.1823)+0.5(0.2231)=0.0204\mathrm{KL}(0.5 \Vert 0.6) = 0.5\ln\frac{0.5}{0.6} + 0.5\ln\frac{0.5}{0.4} = 0.5(-0.1823) + 0.5(0.2231) = 0.0204 nats.

(b) Pulls ≳ln⁡T/0.0204=49ln⁡T\gtrsim \ln T / 0.0204 = 49\ln T. At T=104T = 10^4 (ln⁡T=9.21\ln T = 9.21): about 451 pulls, regret about 0.1×451≈450.1 \times 451 \approx 45. At T=106T = 10^6 (ln⁡T=13.8\ln T = 13.8): 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 0.05T0.05T times: regret at least 0.05×0.1×T0.05 \times 0.1 \times T, which is 50 at T=104T = 10^4 and 5,000 at T=106T = 10^6. At 10410^4 it is comparable to the lower bound, but at 10610^6 it is about 70 times worse. Linear and logarithmic growth look similar for small TT and very different for large TT.

(d) 8ln⁡T/Δ2=8×9.21/0.01≈7,4008\ln T/\Delta^2 = 8 \times 9.21 / 0.01 \approx 7{,}400 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, KL≥2Δ2\mathrm{KL} \geq 2\Delta^2, shows the Lai–Robbins count is at most ln⁡T/(2Δ2)\ln T/(2\Delta^2), 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 cc in UCB is usually tuned, and why refined methods such as KL-UCB, and Thompson sampling, which match the Lai–Robbins constant, are preferred.

Exercise 2.8Experiments with the two demosExplore the demo●●○

(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
For (b): if regret ≈aln⁡t\approx a \ln t, then plotted against ln⁡t\ln t it is a straight line. If regret ≈b t\approx b\,t, then against ln⁡t\ln t it grows like eln⁡te^{\ln t}, which curves sharply upward. For (d), ask what each strategy’s estimates “remember” from the first half.
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 ln⁡t\ln t, 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.
Exercise 2.9RLHF as a contextual banditConcept●●○

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-nn: sample nn responses, return the one with the highest reward-model score. In bandit terms, what is this doing, and what is the risk as nn grows?

Hint
For (a), ask whether the next prompt depends on the response just written. For (b), count how many arms there are and how often any one of them gets pulled twice. For (d), recall why greedy’s estimates mislead it: which errors get selected for when you take a maximum?
Solution

(a) Context: the prompt xx. Arm: the entire response yy. Reward: the reward-model score r(x,y)r(x, y). Policy: the language model’s distribution πθ(y∣x)\pi_\theta(y \mid x). 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 πθ\pi_\theta, 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 nn 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 nn noisy scores is biased upward (the “winner’s curse”), and as nn 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.

Exercise 2.10Build the bandit toolkitCode●●○

Download the lab below and complete the four tasks in bandits.py:

  1. Task 1 argmax_tiebreak: argmax with random tie-breaking.
  2. Task 2 EpsilonGreedy: select_action and the incremental update (sample average or constant α). One class gives greedy, ε-greedy and optimistic greedy.
  3. Task 3 ucb_scores and UCB1. The test uses this chapter’s worked example.
  4. 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
Run one task’s tests at a time: python -m pytest -q -k task1. In EpsilonGreedy.update, increment N[a] before computing the step 1/N[a]1/N[a]. 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) else argmax_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: increment t and N[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 pass

First time? See Exercises & setup.

Further reading

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.