Lower bounds, KL-UCB and Thompson sampling
Study minimax and Lai–Robbins lower bounds, KL-UCB, Thompson sampling, Gittins indices, and pure exploration for best-arm identification.
After this lesson you can
- Prove a minimax lower bound via change of measure and Bretagnolle–Huber.
- Explain Lai–Robbins and calculate its Bernoulli instance constant.
- Implement KL-UCB and Thompson sampling for Bernoulli and Gaussian rewards.
- Calculate truncated Gittins indices using calibration and dynamic programming.
- Design best-arm experiments with successive elimination and halving.
Before you start
How much must learning cost?
UCB1 supplies an upper regret bound. Is there a policy that always needs much less? The answer depends on what is held fixed: in an easy instance some arms are clearly worse; in the worst case means can be so close that identifying them consumes much of the horizon. Lower bounds compare environments producing similar observations but different optimal actions.
Two environments, hard-to-distinguish histories
Let and be full-history distributions induced by the same policy in two environments. For any event , the Bretagnolle–Huber lemma states
If the algorithm behaves very differently in the two environments, this sum can be small only when history KL is sufficiently large. KL order matters. The bound concerns a sum of two error probabilities in distinct environments, not error probability in one alone.
If environments differ only in arm ’s distribution, the chain rule and past-based selection give
Each observation of that arm provides information; actions of one policy add no independent divergence term once conditioned on history. Small KL does not prove distributions equal: it limits how far decisions based on those data can separate.
Preparing both environments.
A minimax lower bound
The minimax lower bound says that for every policy a hard instance exists. We construct a Bernoulli family and make constants explicit. Let , and . In , arm 1 has mean and others . Since expected counts sum to at most , some satisfies . In only that arm changes: its mean becomes and it is now best.
Take . In , pulling arm costs gap ; in , not pulling it costs at least each round. Therefore,
Also , because . The chain rule gives . Applying Bretagnolle–Huber to the sum above, then using gives
We construct alternatives to find an underexplored arm, though ultimately only two environments are compared. Two fixed environments without that argument do not explain factor . For horizons below arm count, per-round regret is bounded and the overall scale must saturate at . This is a worst-case conclusion: it does not say all instances are hard or the bound applies to a policy informed of the instance in advance.
An instance-specific constant
For Bernoulli, write
with the continuity convention for zero-mass terms and infinite value when assigns zero probability to an outcome possible under . If and the policy is uniformly efficient in the considered family, the Lai–Robbins lower bound implies
Uniform consistency requires subpolynomial regret on every family instance, not only the selected instance. Thus it does not contradict a policy knowing the best arm in advance for one instance. This is asymptotic, not a bound that must attain that value at every horizon. Statistical separation appears as KL: similar-mean arms need more samples to distinguish. See Lai and Robbins and KL-UCB analysis.
KL-UCB: distribution-aware optimism
For observed mean after pulls and budget , the Bernoulli KL-UCB index is
The set is an interval because KL increases in for . Calculate it by bisection, handling and separately and prioritizing untried arms. For , one analyzed choice is . Under their assumptions Garivier and Cappé show KL-UCB attains the asymptotic lower constant in the Bernoulli case. The index adapts to KL geometry; it does not dominate every finite trajectory.
Thompson: sample a hypothesis
In Thompson sampling, maintain a posterior over means, draw a joint sample, and choose an optimal arm for that sample. If the posterior is continuous and ties have zero probability, conditional choice probability for each arm equals its posterior probability of being best. This probability matching does not mean one finite trajectory’s frequency exactly matches that probability.
With independent prior and Bernoulli data, successes and failures yield . For normal observations with known variance and prior , the posterior has precision and mean . Choice probability depends on the joint posterior; independently sampling marginals breaks it when means are correlated.
Preparing the posterior race.
Bayesian regret also averages over an environment prior, while the previous lesson’s frequentist regret fixes the instance and averages histories. These are different questions: a small prior average does not guarantee good performance on each instance. Agrawal and Goyal analyze Thompson for stochastic bandits under specific assumptions; Russo and colleagues present Bayesian interpretation and analyses. A prior with zero support in a region cannot recover it by ordinary Bayesian observation; a very concentrated wrong prior can greatly delay exploration. No robustness result should be extrapolated to every prior.
Agrawal and Goyal’s frequentist argument for two Bernoulli arms with a uniform prior counts suboptimal choices between successive optimal-arm visits. After many suboptimal samples its posterior concentrates; to control time until choosing the optimal arm again, the analysis compares the wait with a geometric variable whose probability depends on a beta tail. It also controls few initial samples and occasions when the suboptimal posterior exceeds a threshold. Under the paper’s assumptions, for positive gap they obtain expected regret of order . This concerns that model, not every prior or reward.
Russo and Van Roy’s information view asks how much expected regret is paid to learn the optimal action . Let be expected round regret and conditional mutual information about that action. If is bounded by in relevant rounds, Cauchy–Schwarz and the information chain rule imply
Entropy is finite for a finite action set. The first inequality expresses accumulated information-acquisition cost; the second uses that learning about cannot reveal more than its initial uncertainty. If a round has , the case must be treated consistently with . The bound depends on model, prior, and algorithm through ; it does not imply Thompson is optimal in every problem.
Gittins: value of continuing to learn
Each arm’s posterior is a belief state. For independent arms frozen when not selected, one choice per round, and geometrically discounted infinite-horizon rewards, the Gittins index makes choosing a maximal-index arm optimal. These assumptions matter: restless arms, coupled constraints, or finite horizons require different analysis.
Calibration compares continuing one arm with retiring for constant reward . In the surplus problem truncated to steps, with posterior , and discount ,
Find the threshold where continuation value vanishes by bisection. With finite this approximates the infinite-horizon index; it does not prove the resulting policy optimal for a joint finite-horizon problem. For rewards and in , the discounted surplus tail is bounded in magnitude by ; also record bisection error. Retirement is absorbing in this auxiliary problem, not proof that a multi-arm policy must abandon an arm forever.
Preparing the bandit trajectories.
Explore to identify, not to earn
In best-arm identification, the final recommendation matters, such as its error probability or gap, instead of accumulated exploration regret. With fixed confidence control error and minimize samples; with fixed budget reduce error using limited samples. These objectives differ and require specifying what happens with several best arms.
Successive elimination keeps candidates and removes an arm when its upper bound falls below another’s lower bound, using bounds controlling errors across arms and times. Successive halving allocates budget in phases, keeps a fraction of empirically best arms, and concentrates resources on survivors. Phase samples, rounding, ties, and observation reuse change the algorithm. In hyperparameter tuning a configuration is an arm and budget may mean steps or data; short evaluation need not rank like full training. Hyperband organizes several resource allocations; it does not automatically make that assumption true.
Compare algorithms across 500 replicates with reward sequences and a shared arm permutation per replicate. Permutation prevents systematic advantage for the best arm from lowest-index ties. The Lai–Robbins constant is an asymptotic reference for algorithms satisfying its assumptions; a finite-horizon ratio need not equal it. KL-UCB is applied only to Bernoulli here. Gaussian Thompson uses known observation variance and independent normal prior.
import numpy as np
REPS, K, T, SEED = 500, 3, 300, 220301
def kl_bernoulli(p, q):
p, q = np.broadcast_arrays(np.asarray(p, dtype=float), np.asarray(q, dtype=float))
if np.any(~np.isfinite(p) | ~np.isfinite(q) | (p < 0) | (p > 1) | (q < 0) | (q > 1)):
raise ValueError('Probabilidades fuera de [0,1]')
with np.errstate(divide='ignore', invalid='ignore'):
first = np.where(p == 0, 0., p * (np.log(p)-np.log(q)))
second = np.where(p == 1, 0., (1-p)*(np.log1p(-p)-np.log1p(-q)))
return first+second
def kl_index(means, counts, t):
means=np.asarray(means,dtype=float)
counts=np.asarray(counts,dtype=float)
if (not np.isfinite(t) or t < 3 or t != int(t)
or np.any(~np.isfinite(means)) or np.any((means<0) | (means>1))
or np.any(~np.isfinite(counts)) or np.any(counts <= 0)
or np.any(counts != np.floor(counts))):
raise ValueError('Visita cada brazo antes de calcular el índice')
budget = (np.log(t)+3*np.log(np.log(t)))/counts
lo = np.array(means,dtype=float,copy=True)
hi = np.ones_like(lo)
for _ in range(32):
mid=(lo+hi)/2
feasible=kl_bernoulli(means,mid)<=budget
lo=np.where(feasible,mid,lo)
hi=np.where(feasible,hi,mid)
return lo
def compare_bernoulli(means, rewards, method, seed=SEED+100):
reps, arms, horizon = rewards.shape
means=np.broadcast_to(np.asarray(means), (reps,arms))
rows=np.arange(reps)
count=np.zeros((reps,arms),dtype=int)
success=np.zeros((reps,arms),dtype=float)
cumulative=np.zeros(reps)
random=np.random.default_rng(seed)
best=np.max(means,axis=1)
for t in range(1,horizon+1):
if method in ('ucb','kl') and t<=arms:
action=np.full(reps,t-1,dtype=int)
elif method=='ts':
action=np.argmax(random.beta(1+success,1+count-success),axis=1)
elif method=='ucb':
action=np.argmax(success/count+np.sqrt(2*np.log(t)/count),axis=1)
elif method=='kl':
action=np.argmax(kl_index(success/count,count,t),axis=1)
else:
raise ValueError('Método desconocido')
sample=rewards[rows,action,count[rows,action]]
count[rows,action]+=1
success[rows,action]+=sample
cumulative+=best-means[rows,action]
return cumulative,count
assert abs(float(kl_bernoulli(0,.8))-np.log(5))<1e-12
assert float(kl_bernoulli(1,1))==0
assert np.isinf(kl_bernoulli(.5,1))
assert kl_index(np.array([1.]),np.array([1]),3)[0]==1.
for invalid in (float('nan'),float('inf')):
try: kl_bernoulli(invalid,.5)
except ValueError: pass
else: raise AssertionError('La KL debe rechazar entradas no finitas')bernoulli_means=np.array([.7,.6,.5])
random=np.random.default_rng(SEED)
bernoulli_rewards=(random.random((REPS,K,T))<bernoulli_means[None,:,None]).astype(float)
reference=sum((bernoulli_means[0]-x)/float(kl_bernoulli(x,bernoulli_means[0])) for x in bernoulli_means[1:])
permutations=np.random.default_rng(SEED+991).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)
permuted_means=bernoulli_means[permutations]
bernoulli_rewards=np.take_along_axis(bernoulli_rewards,permutations[:,:,None],axis=1)
print('Constante asintótica de Lai y Robbins:',round(reference,4))
for method in ('ucb','kl','ts'):
regret, counts=compare_bernoulli(permuted_means,bernoulli_rewards,method)
se=regret.std(ddof=1)/np.sqrt(REPS)
print(method,'pseudo-regret medio:',round(regret.mean(),4),
'± 1,96 EE:',round(1.96*se,4),'regret / ln T:',round(regret.mean()/np.log(T),4))
assert np.allclose(regret,np.sum(counts*(permuted_means.max(axis=1)[:,None]-permuted_means),axis=1),atol=1e-10)
print('La comparación es a T=300 y no prueba convergencia asintótica.')def compare_gaussian(means,rewards,method,seed=SEED+200):
reps,arms,horizon=rewards.shape
means=np.broadcast_to(np.asarray(means),(reps,arms))
rows=np.arange(reps);count=np.zeros((reps,arms),dtype=int);sums=np.zeros((reps,arms))
cumulative=np.zeros(reps);random=np.random.default_rng(seed)
for t in range(1,horizon+1):
if method=='ucb' and t<=arms:
action=np.full(reps,t-1,dtype=int)
elif method=='ts':
precision=1+count
posterior_mean=sums/precision
sample=random.normal(posterior_mean,1/np.sqrt(precision))
action=np.argmax(sample,axis=1)
elif method=='ucb':
action=np.argmax(sums/count+np.sqrt(2*np.log(t)/count),axis=1)
else:
raise ValueError('Método desconocido')
observation=rewards[rows,action,count[rows,action]]
count[rows,action]+=1;sums[rows,action]+=observation
cumulative+=means.max(axis=1)-means[rows,action]
return cumulative,count
gaussian_means=np.array([.5,.3,0.])
random=np.random.default_rng(SEED+1)
gaussian_rewards=random.normal(size=(REPS,K,T))+gaussian_means[None,:,None]
permutations=np.random.default_rng(SEED+992).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)
permuted_means=gaussian_means[permutations]
gaussian_rewards=np.take_along_axis(gaussian_rewards,permutations[:,:,None],axis=1)
for method in ('ucb','ts'):
regret,counts=compare_gaussian(permuted_means,gaussian_rewards,method)
se=regret.std(ddof=1)/np.sqrt(REPS)
print(method,'pseudo-regret medio:',round(regret.mean(),4),'± 1,96 EE:',round(1.96*se,4))
assert np.allclose(regret,np.sum(counts*(permuted_means.max(axis=1)[:,None]-permuted_means),axis=1),atol=1e-10)
print('Prior N(0,1), varianza observacional conocida 1; las recompensas gaussianas no están en [0,1].')Calculate a truncated index for one Beta–Bernoulli arm. The retirement problem allows continuing to collect arm rewards or retiring with constant reward each round. Dynamic programming ends after H decisions, so the result is not presented as the exact infinite-horizon index. The classical Gittins theorem requires independent arms, common geometric discount, and arms frozen when not chosen.
from functools import lru_cache
def continuation(a,b,h,gamma,retirement):
"""Ventaja sobre retirarse ya, con como máximo h tiradas adicionales."""
@lru_cache(None)
def value(alpha,beta,remaining):
if remaining==0: return 0.
p=alpha/(alpha+beta)
play=p-retirement+gamma*(p*value(alpha+1,beta,remaining-1)
+(1-p)*value(alpha,beta+1,remaining-1))
return max(0.,play)
return value(a,b,h)
@lru_cache(None)
def truncated_index(a,b,h,gamma):
if min(a,b,h)<1 or not 0<=gamma<1:
raise ValueError('Parámetros fuera de rango')
low,high=0.,1.
for _ in range(32):
mid=(low+high)/2
if continuation(a,b,h,gamma,mid)>1e-14: low=mid
else: high=mid
return (low+high)/2
@lru_cache(None)
def finite_optimum(a,b,c,d,h,gamma):
"""Valor óptimo exacto de dos brazos independientes en h rondas."""
if h==0: return 0.
p=a/(a+b); q=c/(c+d)
first=p+gamma*(p*finite_optimum(a+1,b,c,d,h-1,gamma)
+(1-p)*finite_optimum(a,b+1,c,d,h-1,gamma))
second=q+gamma*(q*finite_optimum(a,b,c+1,d,h-1,gamma)
+(1-q)*finite_optimum(a,b,c,d+1,h-1,gamma))
return max(first,second)
@lru_cache(None)
def finite_index_policy(a,b,c,d,h,gamma):
if h==0: return 0.
p=a/(a+b); q=c/(c+d)
if truncated_index(a,b,h,gamma)>=truncated_index(c,d,h,gamma):
return p+gamma*(p*finite_index_policy(a+1,b,c,d,h-1,gamma)
+(1-p)*finite_index_policy(a,b+1,c,d,h-1,gamma))
return q+gamma*(q*finite_index_policy(a,b,c+1,d,h-1,gamma)
+(1-q)*finite_index_policy(a,b,c,d+1,h-1,gamma))
gamma=.9
assert abs(truncated_index(2,3,1,gamma)-.4)<1e-8
for h in (1,4,8,12):
print('Beta(1,1), horizonte',h,'índice truncado:',round(truncated_index(1,1,h,gamma),6))
for state in ((1,1,2,1),(1,2,2,2),(2,3,1,1),(3,3,1,2)):
optimum=finite_optimum(*state,5,gamma)
indexed=finite_index_policy(*state,5,gamma)
assert indexed<=optimum+1e-10
print('Priors',state,'valor óptimo de 5 rondas:',round(optimum,6),
'política por índices truncados:',round(indexed,6),'brecha:',round(optimum-indexed,6))
print('La coincidencia o discrepancia en estos casos no prueba optimalidad general a horizonte finito.')Compare two best-arm identification rules on the same Bernoulli sequences and random arm permutation per replicate. Both receive at most 240 pulls; successive halving may leave some unused through rounding, and successive elimination may stop early if one arm remains. If budget runs out before all but one are eliminated, breaking ties by observed mean is a forced recommendation: it is not assigned the δ error guarantee of the procedure waiting for complete elimination. Metrics are specific to this simulation, not a superiority promise.
import math
import numpy as np
K, BUDGET, REPS, SEED = 8, 240, 200, 220303
means=np.array([.70,.60,.55,.50,.45,.40,.35,.30])
random=np.random.default_rng(SEED)
rewards=(random.random((REPS,K,BUDGET))<means[None,:,None])
permutations=np.random.default_rng(SEED+991).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)
def successive_halving(table,budget):
k=len(table); rounds=math.ceil(math.log2(k)); active=list(range(k))
count=[0]*k; sums=[0]*k; used=0
for phase in range(rounds):
each=budget//(rounds*len(active))
if each==0: raise ValueError('Presupuesto insuficiente para una fase')
for arm in active:
for _ in range(each):
sums[arm]+=int(table[arm,count[arm]])
count[arm]+=1; used+=1
# Empates por índice menor; se usan todas las muestras acumuladas.
active.sort(key=lambda a:(-sums[a]/count[a],a))
active=active[:math.ceil(len(active)/2)]
return active[0],used,len(active)
def successive_elimination(table,budget,delta=.05):
k=len(table);active=list(range(k));count=[0]*k;sums=[0]*k;used=0
while len(active)>1 and used+len(active)<=budget:
for arm in active:
sums[arm]+=int(table[arm,count[arm]])
count[arm]+=1;used+=1
# Unión conservadora sobre brazos, tamaños de muestra y ambas colas.
radii={a:math.sqrt(math.log(4*k*budget**2/delta)/(2*count[a])) for a in active}
best_lower=max(sums[a]/count[a]-radii[a] for a in active)
active=[a for a in active if sums[a]/count[a]+radii[a]>=best_lower]
if not active or any(count[a]==0 for a in active):
raise ValueError('Presupuesto insuficiente')
recommendation=min(active,key=lambda a:(-sums[a]/count[a],a))
return recommendation,used,len(active)
for method in (successive_halving,successive_elimination):
outcomes=[method(rewards[i,permutations[i]],BUDGET) for i in range(REPS)]
best_positions=np.argmax(means[permutations],axis=1)
successes=sum(chosen==best_positions[i] for i,(chosen,_,_) in enumerate(outcomes))
fraction=successes/REPS
se=math.sqrt(fraction*(1-fraction)/REPS)
used=np.array([n for _,n,_ in outcomes])
remaining=np.array([n for _,_,n in outcomes])
assert np.all(used<=BUDGET)
print(method.__name__,'identifica el mejor:',successes,'/',REPS,
'frecuencia:',round(fraction,4),'error estándar:',round(se,4),
'tiradas medias:',round(float(used.mean()),2),
'brazos restantes medios:',round(float(remaining.mean()),2))
print('200 réplicas con recompensas y permutaciones comunes; el mejor brazo único tiene media 0,70.')
print('Un resultado finito no demuestra una cota asintótica ni garantiza una clasificación en cada ejecución.')Exercises
Step 1 of 4. How do you choose a hard alternative for that policy?
def kl_ucb_index(mean, n, t):
pass
import math
def kl_bernoulli_exercise(p,q):
return p*math.log(p/q)+(1-p)*math.log((1-p)/(1-q))
kl_08=kl_bernoulli_exercise(.8,.9)
kl_05=kl_bernoulli_exercise(.5,.9)
constant=.1/kl_08+.4/kl_05
tail=sum(math.comb(11,j)*.8**j*.2**(11-j) for j in range(8))
print('KL(0,8 || 0,9):',kl_08,'KL(0,5 || 0,9):',kl_05)
print('Constante de Lai y Robbins:',constant,'cola de Beta(8,4) sobre 0,8:',tail)