Exploration: multi-armed bandits
Choose among options one request at a time, shifting traffic toward the winners as evidence arrives, so you learn which is best while losing as little reward (regret) as possible.
Analogy: In a new city you mostly eat at the best place you've found, but now and then try a new one. Too loyal and you miss the gem; too curious and you eat badly.
How it works
- The core tension is explore vs exploit: only exploiting may miss a better arm, over-exploring wastes traffic.
- A fixed-ε greedy policy has linear regret; UCB adds an optimism bonus to rarely tried arms for ~log T.
- Thompson sampling plays each arm with the probability it is best, so exploration fades on its own.
- Contextual bandits add features like user and device, so the best arm can differ per request.
- A/B tests hold a fixed split to learn an effect; bandits shift traffic to earn, losing clean inference.
Check yourself
Answer to mark it learned; your answers aren't scored.
A Thompson-sampling bandit has picked promo banners for six months. This month banner A's real CTR fell sharply, yet A still gets ~90% of traffic over banners that now convert better. Most likely cause and fix?
Go deeper
Full explanation
A multi-armed bandit picks one of K options (arms: headlines, ads, prompts, models) per request and observes a reward (click, thumbs-up). The tension is explore vs exploit: always play the current best and you may never find a better arm; explore too much and you waste traffic on losers. The cost is regret: reward lost versus always playing the best arm.
- ε-greedy: play the best arm, a random one with probability ε. Simple, but a fixed ε wastes traffic forever: regret grows linearly.
- UCB: play the highest optimistic estimate, mean + √(2 ln t / nᵢ). Rarely tried arms get a bonus. Regret grows ~log T.
- Thompson sampling: keep a posterior per arm (Beta for clicks), draw one sample from each, play the max. Each arm is played with the probability it is the best; exploration fades on its own. My default.
Contextual bandits (LinUCB, Vowpal Wabbit) add features (user, device, query type), so the best arm can differ per request: one-step RL with no state.
vs A/B testing LLM features: an A/B test holds a fixed split to learn an unbiased effect; a bandit shifts traffic to earn during the test, at the cost of clean inference.
Code Thompson sampling for 4 headlines (Beta-Bernoulli)
import numpy as np
rng = np.random.default_rng(0)
true_ctr = np.array([0.040, 0.045, 0.050, 0.060]) # unknown in real life
K, T = len(true_ctr), 50_000
alpha, beta = np.ones(K), np.ones(K) # Beta(1,1) prior = "no idea yet"
pulls = np.zeros(K, dtype=int)
for t in range(T):
# Sample a plausible CTR per arm, play the best sample. Uncertain arms
# have wide posteriors, sometimes sample high, and so keep being explored.
theta = rng.beta(alpha, beta)
arm = int(np.argmax(theta))
click = int(rng.random() < true_ctr[arm]) # observe the reward
alpha[arm] += click # successes
beta[arm] += 1 - click # failures
pulls[arm] += 1
lost = T * true_ctr.max() - pulls @ true_ctr # expected regret, in clicks
uniform = T * (true_ctr.max() - true_ctr.mean()) # regret of a fixed 4-way split
print("traffic share:", (pulls / T).round(2)) # [0.03 0.05 0.13 0.79]
print(f"clicks lost: {lost:.0f} vs {uniform:.0f}") # 129 vs 562Real example
A news site has 4 headlines for a story that stays hot for ~6 hours, with CTRs of 4.0, 4.5, 5.0 and 6.0% (unknown to you). A fixed 4-way A/B split would still be sending 75% of readers to worse headlines when the story goes cold. In a 50,000-impression simulation (the code above, 6 seeds), Thompson sampling sent ~80–93% of traffic to the best headline and lost ~45–130 clicks versus 562 for the fixed split. The same loop picks among prompt variants or models, with thumbs-up minus a cost penalty as the reward.
Trade-offs +4 · −3
+ You gain
- Less regret: traffic moves to winners during the experiment, not after it.
- Fits many arms and short-lived options (headlines, creatives, promos) where a test would end too late.
- Contextual versions personalize: the best arm per user or query, not one global winner.
- Runs continuously and absorbs new arms without restarting an experiment.
− You pay
- Adaptive allocation biases naive effect estimates and p-values: weak for launch decisions.
- Optimizes one short-term reward; guardrails and long-term effects are invisible unless you build them in.
- Assumes fast feedback and roughly stable rewards; delayed conversions and drift break it.
Use it when
Many or short-lived options with fast, clear feedback: headlines, ad creatives, promotions, cold-start items, or routing among prompts and models by a cost-adjusted reward.
Avoid it when
When you need a clean causal estimate for a launch, the outcome is delayed (retention, revenue), several guardrail metrics matter, or traffic is tiny. Run an A/B test.
Numbers to know 4
- UCB1 bonus √(2 ln t / nᵢ) gives regret O(log T) (Auer et al., 2002); a fixed-ε greedy policy has linear regret.
- Lai & Robbins (1985): no policy beats ~log T regret growth; UCB and Thompson sampling match that order.
- LinUCB on Yahoo!'s front page: 12.5% click lift over a context-free bandit (Li et al., 2010).
- Rule of thumb: ε = 5–10% for ε-greedy; Beta(1,1) prior for Thompson sampling on clicks.
Common pitfalls 4
- Not logging the propensity (probability of the chosen arm): no unbiased off-policy evaluation later.
- Rewarding clicks when the goal is a purchase days later: the bandit races to clickbait.
- Posteriors that never forget lock onto last month's winner; add decay or a sliding window.
- Reading the bandit's traffic split as an A/B result: adaptive sampling biases the comparison.
Interview questions 3
Answer out loud first, then reveal.
When would you use a bandit instead of an A/B test?Show answer
It depends on whether I need to learn or to earn. For a launch decision like a new ranking model, I want an A/B test: a fixed split gives an unbiased effect, a confidence interval and guardrail readouts. When options are many or short-lived, like headlines or ad creatives, a bandit loses far less reward by shifting traffic as evidence arrives. The price is biased estimates, a single reward and the assumption of fast, stable feedback. Often I combine them: the bandit optimizes inside a surface, and an A/B test validates the bandit policy against the old one.
Explain Thompson sampling. Why does it explore?Show answer
Each arm keeps a posterior over its reward; for clicks, Beta(successes + 1, failures + 1). Per request I draw one sample from each posterior and play the highest. An arm with little data has a wide posterior, so it sometimes draws high and gets tried; as data accumulates the posteriors narrow and the best arm wins almost every draw. So each arm is played with the probability that it is the best, and exploration fades automatically. In practice it matches or beats UCB, and it tolerates batched or delayed updates.
How would you use a bandit to choose among LLMs or prompts?Show answer
Each (model, prompt) pair is an arm, and the reward combines quality and cost: task success or thumbs-up minus a penalty per dollar. A contextual bandit uses query type, language and length, so cheap models win easy queries. I log the propensity of every choice to evaluate new policies offline with inverse propensity scoring. Safety and latency stay outside as hard constraints, not reward terms. And since thumbs-up is sparse and biased, I check the reward against an offline eval set so the bandit doesn't optimize a broken signal.