Bellman optimality and value iteration
Derive Bellman optimality, value iteration and policy-loss bounds, then solve finite-horizon decisions by backward induction.
After this lesson you can
- Prove contraction of the discounted Bellman optimality operator.
- Use value iteration and residuals to certify value accuracy.
- Bound the loss of a policy greedy with respect to an approximate value.
- Solve finite-horizon and stopping problems by backward induction.
- Compare synchronous, asynchronous and prioritized updates.
Before you start
From evaluating a policy to choosing one
In a finite MDP with states and actions available in each state there are stationary deterministic policies. You could evaluate each and compare their values, but enumeration grows quickly. The optimality principle lets us reuse solutions to subproblems: after choosing an action, the optimal continuation value again depends only on the next state.
We work with finite states and actions, bounded expected rewards and . These assumptions matter: in a continuing task with , sums can diverge and the operator need not be a contraction. An undiscounted episodic task can be solved under other conditions, but needs a specific argument.
Equations for the best continuation
Let and be the transition. Optimal value is the supremum of expected return from over admissible policies; forces the first action and optimizes afterward. The Bellman optimality equations are
A greedy policy with respect to value chooses an action maximizing the expression in brackets. With respect to , any tie-breaking choice among maxima is optimal under the above assumptions. With respect to an approximation, that policy may be suboptimal. Nor should you confuse vector used for selection with the actual value of the resulting policy.
The operator contracts distances
Define . If componentwise, nonnegative transitions imply . For a constant , : the translation is discounted once.
To prove the Bellman contraction, use and that each transition row is a distribution:
Taking the maximum over , . This is an upper bound: the observed ratio can be smaller, even zero. If , the operator forgets the previous value in one application.
Preparing the contraction.
By Banach’s theorem, has a unique fixed point . Choose a deterministic policy greedy with respect to : then , and uniqueness of evaluation implies . For any other stationary policy, ; by monotonicity and evaluation convergence, . For history-dependent policies the same domination follows by comparing finite horizons and letting the discounted tail tend to zero. Thus and a stationary deterministic optimal policy exists in this finite discounted model. The proof does not automatically extend that conclusion to arbitrary continuous spaces or undiscounted criteria.
Sweeps and residual
Value iteration applies from an initial vector. By contraction,
If rewards lie in and , then . For , requiring that bound to be at most gives a sufficient number of sweeps via logarithms; if the quotient is negative, zero suffice. With handle the case separately: one sweep computes the immediate optimal value.
Preparing the sweeps.
An observable stopping rule uses residual . From the triangle inequality and contraction,
Thus, if you return that same , guarantees value error at most . If you stop when comparing with , state which of the two you return and which residual you checked. Visual stabilization of the policy alone does not bound value error; a policy can also already be optimal while value error remains.
How costly is acting on an approximate value?
Suppose and choose greedy with respect to , so . The greedy policy loss bound follows by writing
Rearranging yields . If you only know the residual of , you can substitute ; this gives a sufficient policy guarantee, which may be loose. For , the greedy immediate reward choice is optimal and the factor is zero.
Preparing the stopping-criteria comparison.
When remaining time matters
For finite horizon and terminal reward , define and solve backward
Backward induction produces a potentially different policy for each remaining time. In optimal stopping, one action terminates with a known payoff and another continues with an expected value. The classical secretary problem assumes random order, a known number of candidates, only relative ranks, no recall and the goal of choosing the best. The rule of rejecting approximately a fraction is an asymptotic limit under those assumptions, not the exact threshold for every finite size.
In an American option on a binomial tree, each node compares exercise value with discounted continuation computed under the model’s valuation probabilities. Exercise depends on remaining time and the underlying asset price; parameters must satisfy the chosen tree’s assumptions. The lab implements both problems without presenting the asymptotic rule as a measured result.
A synchronous sweep uses previous iteration values for all states. Gauss–Seidel reuses updates already made during the sweep. An asynchronous update changes only some states; convergence guarantees require update coverage conditions. Prioritized sweeping concentrates work on states with significant residuals and their predecessors, but queue and maintenance costs matter. In all cases the number of states and transitions can make a full tabular representation impractical: this is one form of the curse of dimensionality.
First we solve our own 2×3 grid with deterministic moves, a step cost and two terminals. Then we reconstruct the classic 4×4 FrozenLake map and its slippery transitions: the intended action and its two neighbors are executed with probability 1/3. Goal and holes are absorbing with no subsequent reward; reaching the goal pays 1. The gambler’s problem uses capital 0 to 20, positive stakes up to the allowed limit, heads probability 0,4 and reward 1 on reaching 20. It uses γ=1 for this episodic problem: here the residual is diagnostic and cannot use the contraction bound for .
import heapq
import numpy as np
def backups(P,R,V,gamma,legal):
q=R+gamma*np.einsum('san,n->sa',P,V)
return np.where(legal,q,-np.inf)
def value_iteration(P,R,gamma,legal,tol=1e-8,method='sync',limit=20000):
S=len(R); V=np.zeros(S); updates=0
if method in ('sync','gs'):
for sweeps in range(1,limit+1):
if method=='sync':
V=backups(P,R,V,gamma,legal).max(axis=1)
updates+=S
else:
for s in range(S):
q=R[s]+gamma*P[s]@V
V[s]=np.max(np.where(legal[s],q,-np.inf))
updates+=1
residual=float(np.max(np.abs(backups(P,R,V,gamma,legal).max(axis=1)-V)))
if residual<=tol: break
elif method=='priority':
# Predecesores del estado modificado, para actualizar solo prioridades afectadas.
predecessors=[set(np.where(P[:,:,s].any(axis=1))[0]) | {s} for s in range(S)]
versions=np.zeros(S,dtype=int); queue=[]
def enqueue(s):
q=R[s]+gamma*P[s]@V
error=abs(np.max(np.where(legal[s],q,-np.inf))-V[s])
versions[s]+=1
heapq.heappush(queue,(-error,int(versions[s]),s))
for s in range(S): enqueue(s)
while queue and updates<limit*S:
_,version,s=heapq.heappop(queue)
if version!=versions[s]: continue
q=R[s]+gamma*P[s]@V
new=float(np.max(np.where(legal[s],q,-np.inf)))
if abs(new-V[s])<=tol: continue
V[s]=new; updates+=1
for pred in predecessors[s]: enqueue(pred)
residual=float(np.max(np.abs(backups(P,R,V,gamma,legal).max(axis=1)-V)))
else:
raise ValueError('Método desconocido')
q=backups(P,R,V,gamma,legal)
return V,np.argmax(q,axis=1),residual,updates
def small_grid():
# Tablero 2×3: terminal negativo en 2, meta en 5; sin resbalamiento.
S,A=6,4
P=np.zeros((S,A,S)); R=np.zeros((S,A)); legal=np.ones((S,A),dtype=bool)
moves=((0,-1),(1,0),(0,1),(-1,0))
for s in range(S):
row,col=divmod(s,3)
for a,(dr,dc) in enumerate(moves):
if s in (2,5):
P[s,a,s]=1
continue
nr=min(1,max(0,row+dr)); nc=min(2,max(0,col+dc)); dest=3*nr+nc
P[s,a,dest]=1
R[s,a]=1.0 if dest==5 else (-1.0 if dest==2 else -.02)
return P,R,legal
def frozenlake():
grid=('SFFF','FHFH','FFFH','HFFG'); S=16; A=4
P=np.zeros((S,A,S)); R=np.zeros((S,A)); legal=np.ones((S,A),dtype=bool)
# Orden Gymnasium: izquierda, abajo, derecha, arriba.
moves=((0,-1),(1,0),(0,1),(-1,0))
for s in range(S):
row,col=divmod(s,4)
for a in range(A):
if grid[row][col] in 'HG':
P[s,a,s]=1
continue
for move in ((a-1)%4,a,(a+1)%4):
dr,dc=moves[move]; nr=min(3,max(0,row+dr)); nc=min(3,max(0,col+dc))
dest=4*nr+nc
P[s,a,dest]+=1/3
R[s,a]+=(grid[nr][nc]=='G')/3
return P,R,legal
def gambler(goal=20,p_head=.4):
P=np.zeros((goal+1,goal//2+1,goal+1)); R=np.zeros((goal+1,goal//2+1))
legal=np.zeros_like(R,dtype=bool)
for s in range(goal+1):
if s in (0,goal):
P[s,0,s]=1; legal[s,0]=True
else:
for stake in range(1,min(s,goal-s)+1):
legal[s,stake]=True
P[s,stake,s+stake]=p_head; P[s,stake,s-stake]=1-p_head
R[s,stake]=p_head*float(s+stake==goal)
return P,R,legal
P,R,legal=small_grid()
assert np.allclose(P.sum(axis=2),1) and np.allclose(R[[2,5]],0)
results={m:value_iteration(P,R,.9,legal,method=m) for m in ('sync','gs','priority')}
reference=results['sync'][0]
for method,(v,policy,residual,updates) in results.items():
print('Cuadrícula 2×3',method,'actualizaciones de valor',updates,'residuo',round(residual,10),
'cota error',round(residual/.1,8),'diferencia con síncrona',round(float(np.max(np.abs(v-reference))),8),
'valor inicial',round(float(v[0]),6))
P,R,legal=frozenlake()
assert np.allclose(P.sum(axis=2),1) and np.allclose(R[[5,7,11,12,15]],0)
for gamma in (.9,.99):
results={m:value_iteration(P,R,gamma,legal,method=m) for m in ('sync','gs','priority')}
reference=results['sync'][0]
for method,(v,policy,residual,updates) in results.items():
# El residuo de la última tabla certifica error máximo ≤ residuo/(1−γ).
print('FrozenLake',gamma,method,'actualizaciones de valor',updates,'residuo',round(residual,10),
'cota error',round(residual/(1-gamma),8),'diferencia con síncrona',round(float(np.max(np.abs(v-reference))),8),
'valor inicial',round(float(v[0]),6))
P,R,legal=gambler()
v,policy,residual,updates=value_iteration(P,R,1.0,legal,method='sync',tol=1e-9)
print('Jugador episódico γ=1: actualizaciones de valor',updates,'residuo',round(residual,10),
'valor capital 10',round(float(v[10]),6),'apuesta voraz',int(policy[10]))
if residual>1e-9:
print('Se agotó el límite antes de alcanzar la tolerancia')The counter measures state-value updates, not total work: residual checks and priority updates also recompute values and are not included. The three variants are compared here by residual and updates; this does not prove which is faster. Ties are resolved by the first valid index and another tied policy may be equally optimal. The gambler’s terminal state has value zero because reward is paid on entering the goal.
In the secretary problem we assume uniformly random arrival order, observation of relative ranks only, one irrevocable choice and reward 1 only for choosing the absolute best person. For the American option we use a dividend-free CRR binomial tree and compare the right to exercise at each node with continuation. These are different stopping problems: the 1/e rule is only asymptotic for the first.
import math
def secretary(n):
if not isinstance(n,int) or isinstance(n,bool) or n<1:
raise ValueError('n debe ser entero positivo')
# V[t]: probabilidad óptima antes de observar el candidato t.
V=[0.0]*(n+2); stop=[False]*(n+1)
for t in range(n,0,-1):
continuation=V[t+1]
stop[t]=t/n>=continuation
V[t]=(max(t/n,continuation)+(t-1)*continuation)/t
return V[1],stop
def cutoff_probability(n,skip):
if not isinstance(n,int) or isinstance(n,bool) or n<1 or not isinstance(skip,int) or isinstance(skip,bool) or not 0<=skip<n:
raise ValueError('Corte fuera de rango')
if skip==0:
return 1/n
return (skip/n)*sum(1/j for j in range(skip,n))
def american_put(spot,strike,rate,volatility,maturity,steps):
if not all(math.isfinite(x) for x in (spot,strike,rate,volatility,maturity)) or min(spot,strike,volatility,maturity)<=0 or not isinstance(steps,int) or isinstance(steps,bool) or steps<1:
raise ValueError('Parámetros inválidos')
dt=maturity/steps
try:
up=math.exp(volatility*math.sqrt(dt)); down=1/up
p=(math.exp(rate*dt)-down)/(up-down)
except (OverflowError,ZeroDivisionError) as exc:
raise ValueError('Árbol no representable numéricamente') from exc
if not 0<p<1:
raise ValueError('Se requiere d < exp(r·dt) < u para ausencia de arbitraje')
discount=math.exp(-rate*dt)
european=[max(strike-spot*up**j*down**(steps-j),0) for j in range(steps+1)]
american=european.copy()
early=0
for t in range(steps-1,-1,-1):
next_e=[]; next_a=[]
for j in range(t+1):
e=discount*((1-p)*european[j]+p*european[j+1])
continuation=discount*((1-p)*american[j]+p*american[j+1])
intrinsic=max(strike-spot*up**j*down**(t-j),0)
next_e.append(e); next_a.append(max(intrinsic,continuation))
if intrinsic>continuation: early+=1
european=next_e; american=next_a
return american[0],european[0],early,p
n=50
optimal,stop=secretary(n)
cutoffs=[cutoff_probability(n,m) for m in range(n)]
best=max(range(n),key=lambda m:cutoffs[m])
asymptotic=int(n/math.e)
assert abs(optimal-cutoffs[best])<1e-12
assert abs(secretary(1)[0]-1)<1e-12
print('Secretaria: n',n,'corte exacto',best,'probabilidad',round(optimal,6),
'corte floor(n/e)',asymptotic,'probabilidad',round(cutoffs[asymptotic],6))
american,european,nodes,p=american_put(100,100,.05,.2,1,50)
assert american+1e-12>=european
print('Put americano',round(american,6),'europeo',round(european,6),
'nodos con ejercicio estrictamente preferido',nodes,'probabilidad neutral',round(p,6))In the secretary problem the cutoff is the number of people rejected before accepting the next who exceeds all previous candidates. If none appears, the attempt fails; no final choice is forced. The tree requires the strict no-arbitrage condition . The American and European comparison shares parameters and exercise dates; the difference is the early-exercise premium for this discretization, not an observed quote.
Exercises
Step 1 of 3. How do you bound the difference between maxima at one state?
Step 1 of 3. How do you compare V* and Vπ?
import numpy as np
def value_iteration(P,R,gamma,tol):
pass
import math
k=math.ceil(math.log(1e-8)/math.log(.99))
print('Barridos garantizados:',k,'cota',.99**k/(1-.99),'cota anterior',.99**(k-1)/(1-.99))