Policy iteration, linear programming and occupancy measures
Study policy improvement and iteration, linear programming, discounted occupancy and constrained Markov decision processes.
After this lesson you can
- Prove policy improvement and explain termination of policy iteration.
- Relate policy iteration to Newton steps and compare it with value iteration.
- Formulate the MDP linear program and interpret its occupancy dual.
- Model expected cost constraints and explain when randomization is necessary.
- Implement exact policy evaluation and stable improvement.
Before you start
- 22Bellman optimality equationBellman operator contractionValue iterationExact policy evaluationGreedy policy and existence of an optimal policy
- 06Linear programmingLagrange dual functionDual problem and weak dualityNewton's methodLocal quadratic convergence of Newton's methodLagrange multipliersDual ascent and dual decomposition
Improving a policy without starting over
Value iteration alternates one optimality backup with the next. When is close to one, contraction guarantees may require many sweeps. If we know the model, another possibility is to evaluate a policy exactly and then change its actions. Each step costs more, but one improvement can change many decisions at once.
We work with a finite MDP, bounded rewards and . The termination conclusions and linear programs below use that framework; infinite undiscounted horizons or general spaces need additional assumptions.
An improvement that worsens no state
Let be a stationary policy and greedy with respect to : in each state it chooses an action maximizing the value of taking that action once and then following . Then componentwise. By monotonicity, repeatedly applying preserves the inequality; by contraction, the iterations converge to . Thus we obtain the policy improvement theorem:
The same proof can be viewed using the evaluation inverse. If , then
The inverse is a sum of nonnegative powers. If any component of is strictly positive, the value strictly improves in at least that state, because the series includes the identity. The comparison is simultaneous for all states, not only one chosen initial distribution.
Evaluation and improvement
Policy iteration (PI) starts from a deterministic policy, solves and improves it by choosing greedy actions. Repeat until no improvement remains. A simple tie-breaking rule keeps the current action if it is still maximal; change only when a strictly better action exists. Each change strictly improves at least one state. Because there are finitely many deterministic policies, infinitely many strict improvements cannot occur. On stopping, , so .
Allowing an arbitrary rule to switch actions among ties can alternate between policies with the same value. Stable tie-breaking avoids mistaking that superficial change for actual improvement. Finite arithmetic adds another decision: a tolerance for declaring ties can stop an implementation near the optimum without proving exact mathematical equality.
The connection to Newton
Define . In a region where each greedy action is unique, for greedy policy and . The Newton step is
That is, improving with respect to and evaluating the chosen policy performs that step. Implementations are also presented starting with evaluation and then improvement; the index shift does not change the relationship. At ties, the maximum may be nondifferentiable and there need not be a unique classical Jacobian. The appropriate interpretation selects a branch and uses generalized or semismooth Newton; see Grand-Clément.
Between one sweep and exact evaluation
In modified policy iteration (MPI), you improve the policy and apply a finite number of evaluation backups before improving again. With more evaluation you approach PI; with very partial evaluation you approach VI dynamics, depending on the precise operation order. Generalized policy iteration describes this interaction between evaluation and improvement, which also appears when both are approximated using samples.
Preparing the method comparison.
A sweep and a linear solve do not cost the same. Comparison depends on sparse structure, implementation, tolerance and hardware; browser times measure that run, not algorithm constants. Ye proves strong polynomiality for Howard policy iteration and a specific simplex rule when the discount factor is fixed. This is not a guarantee for every pivot rule, variable discount as input, or average-reward criterion.
A linear program for values
Let be an initial distribution with for every state. The MDP linear program can be written
A feasible solution satisfies ; by monotonicity and contraction, . Since is feasible, it minimizes the objective. Full support of forces equality in every state. If some weights are zero, an LP solution may differ from in states not penalized by the objective, although the weighted value is correct.
The dual is a flow of visits
The unnormalized discounted occupancy measure is
Its dual interpretation is a flow: mass leaving a state is initial mass plus discounted mass arriving from other states. The dual of the preceding LP is
Summing the equations shows . If you prefer normalized occupancy , its total mass is one, its initial flow is and return is . Mixing the two conventions without adjusting the factor changes the results.
Preparing occupancy flow.
From a feasible occupancy you recover in states with positive mass; in zero-mass states any distribution may be chosen. Complementary slackness connects the formulations: an action with positive occupancy in an optimal solution can use only an active primal constraint. In a problem without cost constraints, this relates the actions used to optimal greedy actions.
Constraining cost
A constrained MDP adds, for example, to the objective of maximizing . This bounds expected discounted cost; alone it does not guarantee that every trajectory respects a safety limit. The occupancy LP incorporates the inequality directly and can detect infeasibility.
For a multiplier , define
The dual function is convex and minimized over . If a policy maximizes the inner problem, is a subgradient of ; projected step is dual descent. When cost exceeds the threshold, the penalty increases. For a feasible finite LP one can use linear duality; iterating multipliers with finite steps does not guarantee that the last policy is feasible or the average converged without conditions on steps and the inner solution.
Preparing the constrained frontier.
The constrained optimum can require randomization. Consider one state that always returns to itself, , a safe action with zero reward and cost, and a risky action with reward and cost one. With , the always-risky policy has discounted cost two and is infeasible; the always-safe policy gets zero. Choosing risky with probability on each visit gives expected cost and return both equal to one. The figures follow from the geometric series and are checked in the lab.
In a finite discounted CMDP with one feasible constraint, an optimal occupancy can be chosen representable as a mixture of at most two deterministic-policy occupancies. This includes the degenerate case where one occupancy suffices, without requiring a nontrivial edge of the region. Mixing is not always needed: the limit may be inactive or a deterministic policy optimal. At a tie in the Lagrangian problem, a maximizing policy chosen by tie-breaking may violate the limit; recovering a primal solution may require mixing occupancies and normalizing by state, not arbitrarily averaging two policies’ action probabilities.
We use normalized occupancies x=(1−γ)d, where d(s,a)=E[Σ γᵗ 1{Sₜ=s,Aₜ=a}]. Thus unnormalized return is Σ x·R/(1−γ). The initial distribution has positive mass in each state so the primal determines all values. The comparison uses the same MDP and, in states without appreciable occupancy, completes the policy with the action greedy for the primal value.
import numpy as np
from scipy.optimize import linprog
def q_values(P,R,V,gamma):
return R+gamma*np.einsum('san,n->sa',P,V)
def evaluate(P,R,policy,gamma):
states=np.arange(len(policy))
return np.linalg.solve(np.eye(len(policy))-gamma*P[states,policy],R[states,policy])
def improve(P,R,V,gamma,policy,tolerance=1e-12):
q=q_values(P,R,V,gamma); best=np.argmax(q,axis=1)
# Mantener la acción actual en empates evita cambiar por cambios de índice.
return np.where(q.max(axis=1)-q[np.arange(len(policy)),policy]<=tolerance,policy,best)
def policy_iteration(P,R,gamma):
policy=np.zeros(len(R),dtype=int)
for iteration in range(1,101):
value=evaluate(P,R,policy,gamma)
new=improve(P,R,value,gamma,policy)
if np.array_equal(new,policy): return value,policy,iteration
policy=new
raise ArithmeticError('No terminó dentro del límite')
def modified_pi(P,R,gamma,steps=3,tol=1e-9):
n=len(R); policy=np.zeros(n,dtype=int); V=np.zeros(n)
for iteration in range(1,10001):
for _ in range(steps):
V=R[np.arange(n),policy]+gamma*np.einsum('sn,n->s',P[np.arange(n),policy],V)
policy=improve(P,R,V,gamma,policy)
residual=float(np.max(np.abs(q_values(P,R,V,gamma).max(axis=1)-V)))
if residual<=tol: return V,policy,iteration,residual
raise ArithmeticError('No alcanzó el residuo pedido')
def primal_dual(P,R,gamma,mu):
S,A=R.shape
# F[s,(u,a)] = 1{s=u} - gamma P(s|u,a).
F=np.zeros((S,S*A))
for s in range(S):
for a in range(A):
F[:,s*A+a]=-gamma*P[s,a]
F[s,s*A+a]+=1
primal=linprog(mu,A_ub=-F.T,b_ub=-R.ravel(),bounds=[(None,None)]*S,method='highs')
dual=linprog(-R.ravel()/(1-gamma),A_eq=F,b_eq=(1-gamma)*mu,
bounds=[(0,None)]*(S*A),method='highs')
if not primal.success or not dual.success:
raise ArithmeticError('Falló la resolución de los programas lineales')
return primal,dual,F
rng=np.random.default_rng(108); S,A=4,2; gamma=.9
P=rng.random((S,A,S)); P/=P.sum(axis=2,keepdims=True)
R=rng.uniform(-1,1,(S,A)); mu=np.full(S,1/S)
V,policy,iterations=policy_iteration(P,R,gamma)
Vm,pm,mi,residual=modified_pi(P,R,gamma)
primal,dual,F=primal_dual(P,R,gamma,mu)
x=dual.x.reshape(S,A)
pi=x/x.sum(axis=1,keepdims=True)
Ppi=np.einsum('sa,san->sn',pi,P); rpi=np.sum(pi*R,axis=1)
Vpi=np.linalg.solve(np.eye(S)-gamma*Ppi,rpi)
assert np.allclose([email protected],(1-gamma)*mu,atol=1e-8,rtol=0)
assert np.allclose(primal.fun,-dual.fun,atol=1e-7,rtol=0)
assert np.allclose(V,primal.x,atol=1e-7,rtol=0)
assert np.allclose(Vpi,V,atol=1e-7,rtol=0)
print('PI evaluaciones',iterations,'política',policy,'valor',np.round(V,6))
print('MPI rondas',mi,'residuo',residual,'cota error',residual/(1-gamma),
'diferencia con PI',float(np.max(abs(Vm-V))))
print('Primal y dual',primal.fun,-dual.fun,'masa ocupación',x.sum(),
'retorno política recuperada',float(mu@Vpi))PI exactly solves the policy system each round; MPI performs three evaluation backups before improving and stops based on the optimal operator residual. Retaining the previous action in ties avoids unnecessary changes: the tolerance used is numerical, not a claim of exact equality. Positive initial mass avoids zero occupancy rows in this example. If a row were zero, occupancy would not determine which action to choose there and it would need separate specification.
The 2×2 grid starts at the top left, with a risk zone at top right, a safe path at bottom left and the goal at bottom right. The first action enters one of the two paths and the next reaches the goal; terminals are absorbing. Entering risk gives reward 3 and cost 2; entering the safe path gives reward 1 and cost 0. The goal and later steps contribute zero. The budget is 0,8 for unnormalized discounted cost. This is an explicit toy model, not a safety measurement.
import numpy as np
from scipy.optimize import linprog
S,A=4,2; gamma=.9; budget=.8
P=np.zeros((S,A,S)); R=np.zeros((S,A)); C=np.zeros((S,A))
# Acción 0: riesgo; acción 1: camino seguro.
P[0,0,1]=1; P[0,1,2]=1; R[0]=[3,1]; C[0]=[2,0]
for s in (1,2): P[s,:,3]=1
P[3,:,3]=1
mu=np.array([1.,0.,0.,0.]); scale=1-gamma
F=np.zeros((S,S*A))
for s in range(S):
for a in range(A):
F[:,s*A+a]=-gamma*P[s,a]
F[s,s*A+a]+=1
def occupancy(policy):
transition=np.einsum('sa,san->sn',policy,P)
state=np.linalg.solve(np.eye(S)-gamma*transition.T,scale*mu)
return state[:,None]*policy
def values(x):
return float(np.sum(x*R)/scale),float(np.sum(x*C)/scale)
result=linprog(-R.ravel()/scale,A_ub=[C.ravel()/scale],b_ub=[budget],
A_eq=F,b_eq=scale*mu,bounds=[(0,None)]*(S*A),method='highs')
if not result.success:
raise ArithmeticError('CMDP no resuelto: '+result.message)
x_lp=result.x.reshape(S,A); mass=x_lp.sum(axis=1)
policy=np.full((S,A),.5)
for s in range(S):
if mass[s]>1e-12: policy[s]=x_lp[s]/mass[s]
assert np.allclose(occupancy(policy),x_lp,atol=1e-8,rtol=0)
assert np.allclose(F@x_lp.ravel(),scale*mu,atol=1e-8,rtol=0)
assert values(x_lp)[1]<=budget+1e-8
risky=np.zeros((S,A)); risky[:,0]=1
safe=np.zeros((S,A)); safe[:,1]=1
x_risk=occupancy(risky); x_safe=occupancy(safe)
reward_risk,cost_risk=values(x_risk); reward_safe,cost_safe=values(x_safe)
# Mezclar medidas, no probabilidades de acción estado por estado.
weight=(budget-cost_safe)/(cost_risk-cost_safe)
x_mix=weight*x_risk+(1-weight)*x_safe
assert 0<=weight<=1 and np.allclose(values(x_mix),values(x_lp),atol=1e-8,rtol=0)
print('LP: retorno, coste',values(x_lp),'probabilidades iniciales',policy[0],
'masa',x_lp.sum())
print('Mezcla por trayectoria: peso riesgo',round(weight,6),
'retorno y coste',values(x_mix))
# Minimización proyectada del dual g(lambda)=max_pi [Jr-lambda(Jc-budget)].
# En este modelo la política mejor responde eligiendo riesgo o camino seguro.
lam=0.; step=.1; accumulated=np.zeros_like(x_lp); best_dual=float('inf')
for _ in range(80):
use_risk=reward_risk-lam*cost_risk >= reward_safe-lam*cost_safe
x=x_risk if use_risk else x_safe
reward,cost=values(x)
best_dual=min(best_dual,reward-lam*(cost-budget))
accumulated+=x
lam=max(0.,lam+step*(cost-budget))
average=accumulated/80
print('Descenso dual: lambda final',round(lam,6),'mejor cota dual',round(best_dual,6),
'retorno y coste de ocupación media',values(average))
print('La media finita puede violar el presupuesto:',values(average)[1]>budget+1e-10)The LP optimizes a measure satisfying flow conservation and the budget; normalizing rows with positive mass recovers a stationary policy. A mixture at the start of trajectories has the average occupancy of its components. Mixing their action probabilities by state with the same weights does not generally have that property. Dual descent can oscillate between deterministic best responses; its last policy can violate the budget and a finite average does not automatically guarantee it either.
The one-state example in the explanation has two actions that preserve the state: the first gives zero reward and cost; the second gives reward and cost one. Normalized occupancy equals the action probabilities. The next cell checks the γ=0,5 case, budget 1 and an equal mixture.
gamma=.5
safe,risky=.5,.5
reward=(safe*0+risky*1)/(1-gamma)
cost=(safe*0+risky*1)/(1-gamma)
budget=1.0
assert safe+risky==1 and reward==1 and cost==budget
print('Ocupaciones normalizadas:',safe,risky,'retorno:',reward,
'coste:',cost,'presupuesto:',budget)Exercises
Step 1 of 3. How is the assumption written using operators?
Step 1 of 3. What form does T have near V?
import numpy as np
def policy_iteration(P,R,gamma):
pass
gamma=.5
occupancy=(1-gamma, gamma)
print('Ocupación normalizada:',occupancy,'retorno:',(occupancy[0]+2*occupancy[1])/(1-gamma))