AI Wiki中文/EN

Value iteration: stable actions do not mean converged values

价值迭代

Apply optimality backups, extract a greedy policy and check both value error and policy-loss bounds.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The recommended action can settle before its value does

In the synthetic arcade game, start every state value at zero. After two value updates, the vector for entry, room and terminal is [3.6, 4, 0]. The greedy recommendation is already “advance at entry, spin in the room.” After another update, the vector is [3.6, 4.336, 0], with the same recommendation.

Should the algorithm stop? The entry value is still almost one point below its optimum of approximately 4.556962. An unchanged action need not mean a converged value. There can be a wide range of inaccurate values that preserve the same action ordering.

Value iteration repeatedly applies the Bellman optimality operator instead of fully evaluating each intermediate policy. Sutton and Barto, Section 4.4 connects this update to the optimality equation. Bertsekas’s discounted-DP lectures supply the contraction framework. We will use a residual-based stopping rule and distinguish the approximate vector from the exact value of its extracted policy.

The extracted actions stabilize before the values do; changing discount changes both the objective and the observed iteration count.
The extracted actions stabilize before the values do; changing discount changes both the objective and the observed iteration count.

Take the maximum inside each backup

Assume a finite, known MDP, bounded rewards and discount 0 ≤ gamma < 1. For a candidate continuation vector v, define the optimality operator:

(Tv)(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)v(s′)].(Tv)(s)=\max_a\left[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)v(s')\right].

The bracket evaluates one action followed by the supplied continuation estimate. The maximum chooses the best current lookahead. This differs from fixed-policy evaluation, which averages these action values under a specified policy. The source lectures formulate the analogous operation as minimizing costs; replacing costs by negative rewards gives the maximization form here.

Synchronous value iteration uses the entire previous vector for the next update:

v(k+1)=Tv(k).v^{(k+1)}=Tv^{(k)}.

No full policy-evaluation solve lies inside that assignment. A maximizing action may change as the continuation estimates improve. The working draft describes this relation between value iteration and interleaved evaluation/improvement.

Zero initialization gives a finite-horizon interpretation

If the initial vector is zero, the first update chooses the best one-step reward. The second considers two steps, and so on, with zero payoff after the horizon:

v(k)(s)=max⁡πEπ ⁣[∑t=0k−1γtRt+1∣S0=s]when v(0)=0.v^{(k)}(s)=\max_\pi\mathbb E_\pi\!\left[\sum_{t=0}^{k-1}\gamma^tR_{t+1}\mid S_0=s\right] \quad\text{when }v^{(0)}=0.

Here the finite-horizon policy may depend on how much time remains. This interpretation follows by backward induction; it is not a claim that every intermediate vector is the infinite-horizon value of its currently greedy stationary policy. With a different initial vector, the analogous finite-horizon interpretation uses that vector as a terminal payoff.

Our game has two nonterminal states. Leaving at entry earns 2; advancing earns 0 and reaches the room. Leaving in the room earns 4; spinning earns 1.6 and moves to entry, room or terminal with probabilities 0.4, 0.4 and 0.2. Terminal continuation is zero. The first update gives [2, 4, 0]. The next chooses max(2, 0.9 × 4)=3.6 at entry and max(4, 1.6 + 0.36 × (2+4))=4 in the room.

Maximization preserves the contraction bound

For two lists of numbers, the difference between their maxima is no larger than the largest difference between corresponding entries. Combine that fact with probability-weighted averaging:

∥Tv−Tw∥∞≤max⁡s,aγ∣∑s′P(s′∣s,a)(v(s′)−w(s′))∣≤γ∥v−w∥∞.\|Tv-Tw\|_\infty \leq\max_{s,a}\gamma\left|\sum_{s'}P(s'\mid s,a)(v(s')-w(s'))\right| \leq\gamma\|v-w\|_\infty.

Thus the operator has a unique fixed point v*, and repeated updates converge to it from any finite initial vector. Bounded rewards, valid probability rows and discount below one are substantive assumptions. The MIT lectures establish the discounted fixed-point setting; a visually shrinking numerical trace alone would not establish it.

For the current vector, compute residual delta. The same triangle-inequality argument used for fixed-policy evaluation gives:

δ=∥Tv−v∥∞,∥v−v∗∥∞≤δ1−γ.\delta=\|Tv-v\|_\infty,\qquad \|v-v_*\|_\infty\leq\frac{\delta}{1-\gamma}.

The implementation stops only when this bound meets the requested value tolerance. It checks the residual of the vector being returned, not just a policy-ID comparison. After the third update in the opening example, the residual is 0.3024, although the greedy actions have not changed. That is nowhere near the requested 1e-9 value certificate.

Extract a policy, then distinguish its guarantee

A stationary greedy policy chooses a maximizing lookahead at every state. By construction its operator agrees with the optimality operator on the current estimate:

πv(s)∈arg max⁡a[r(s,a)+γ∑s′P(s′∣s,a)v(s′)],Tπvv=Tv.\pi_v(s)\in\operatorname*{arg\,max}_a\left[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)v(s')\right],\qquad T_{\pi_v}v=Tv.

This equality holds at v; it does not say v already equals the policy’s exact value. We can bound the loss of the extracted policy separately. Let epsilon bound ||v−v*|| and let L denote ||v*−v_pi_v||. Insert the equal lookaheads between the two fixed-point equations, then apply the two contraction bounds:

L≤γ∥v∗−v∥∞+γ∥v−vπv∥∞≤2γϵ+γL⟹L≤2γϵ1−γ≤2γδ(1−γ)2.L\leq\gamma\|v_*-v\|_\infty+\gamma\|v-v_{\pi_v}\|_\infty \leq2\gamma\epsilon+\gamma L \quad\Longrightarrow\quad L\leq\frac{2\gamma\epsilon}{1-\gamma} \leq\frac{2\gamma\delta}{(1-\gamma)^2}.

This is a derived sufficient bound, often much larger than the actual policy loss. It uses a policy that is genuinely greedy with respect to v; approximate maximization requires accounting for additional error. A small value error and a small policy loss are related claims, but they are not the same measured quantity.

In this particular game the greedy policy becomes optimal early, while the vector keeps improving. We can verify that using the tiny model’s exact policy values. On a large unknown task, unchanged greedy actions alone would not supply that verification.

Return the residual together with the policy

Save this original program as value_iteration.py, using Python 3.12 and NumPy 1.26.4. It implements synchronous optimality backups, breaks exact ties by the smallest action index, and records the greedy policy and residual for each current vector. The demonstration separately solves the extracted policy’s linear system for comparison; that solve is not used by the value-iteration stopping rule.

"""Original finite-MDP teaching program; Python 3.12 and NumPy 1.26.4."""
import json
import math
import numpy as np


def model():
    # States: entry, room, terminal. Actions: exit, advance/spin.
    P = np.array([[[0,0,1],[0,1,0]], [[0,0,1],[.4,.4,.2]], [[0,0,1],[0,0,1]]], float)
    rewards = np.array([[2,0],[4,1.6],[0,0]], float)
    return P, rewards


def validate(P, rewards, gamma):
    P, rewards = np.asarray(P,float), np.asarray(rewards,float)
    if P.ndim != 3 or P.shape[0] == 0 or P.shape[1] == 0 or P.shape[2] != P.shape[0]:
        raise ValueError('P must have shape (states, actions, states)')
    if rewards.shape != P.shape[:2] or not np.isfinite(P).all() or not np.isfinite(rewards).all():
        raise ValueError('finite P and state-action rewards required')
    if np.any(P < 0) or not np.allclose(P.sum(axis=2),1,rtol=0,atol=1e-12):
        raise ValueError('each transition row must be a probability distribution')
    if not math.isfinite(gamma) or not 0 <= gamma < 1:
        raise ValueError('gamma must be in [0, 1)')
    return P, rewards


def policy_matrix(actions, P):
    actions = np.asarray(actions)
    if actions.shape != (len(P),) or not np.issubdtype(actions.dtype,np.integer):
        raise ValueError('one integer action index per state required')
    if np.any(actions < 0) or np.any(actions >= P.shape[1]):
        raise ValueError('action outside the model')
    return np.eye(P.shape[1])[actions]


def policy_model(P, rewards, policy, gamma):
    P, rewards = validate(P,rewards,gamma)
    policy = np.asarray(policy,float)
    if policy.shape != P.shape[:2] or not np.isfinite(policy).all() or np.any(policy < 0):
        raise ValueError('finite nonnegative action probabilities required')
    if not np.allclose(policy.sum(axis=1),1,rtol=0,atol=1e-12):
        raise ValueError('policy rows must sum to one')
    return np.einsum('sa,san->sn',policy,P), np.sum(policy*rewards,axis=1)


def exact_value(P, rewards, policy, gamma):
    kernel, mean_reward = policy_model(P,rewards,policy,gamma)
    return np.linalg.solve(np.eye(len(P))-gamma*kernel,mean_reward)


def action_values(P, rewards, value, gamma):
    P,rewards = validate(P,rewards,gamma)
    value = np.asarray(value,float)
    if value.shape != (len(P),) or not np.isfinite(value).all():
        raise ValueError('one finite value per state required')
    return rewards+gamma*np.einsum('san,n->sa',P,value)



def value_iteration(P,rewards,gamma=.9,tolerance=1e-9,max_sweeps=10000,initial=None):
    P,rewards=validate(P,rewards,gamma)
    if not math.isfinite(tolerance) or tolerance<=0 or type(max_sweeps) is not int or max_sweeps<1:
        raise ValueError('positive tolerance and integer sweep budget required')
    v=np.zeros(len(P)) if initial is None else np.array(initial,float,copy=True)
    if v.shape!=(len(P),) or not np.isfinite(v).all():raise ValueError('finite initial values required')
    trace=[]
    for sweep in range(max_sweeps+1):
        q=action_values(P,rewards,v,gamma);updated=np.max(q,axis=1)
        residual=float(np.max(np.abs(updated-v)))
        actions=np.argmax(q,axis=1)
        trace.append(dict(sweep=sweep,values=v.tolist(),greedy_actions=actions.tolist(),
                          residual=residual,value_error_bound=residual/(1-gamma)))
        if residual/(1-gamma)<=tolerance:
            return dict(values=v.tolist(),actions=actions.tolist(),trace=trace,
                        value_error_bound=residual/(1-gamma),
                        greedy_policy_loss_bound=2*gamma*residual/(1-gamma)**2)
        if sweep==max_sweeps:raise RuntimeError('sweep budget exhausted before the error certificate')
        v=updated


def demo():
    P,r=model();result=value_iteration(P,r)
    exact=exact_value(P,r,policy_matrix(result['actions'],P),.9)
    trace=result.pop('trace');last=trace[-1]['sweep']
    result.update(sweeps=last,selected_trace=[x for x in trace if x['sweep'] in (0,1,2,3,4,10,20,last)],
                  exact_greedy_policy_value=exact.tolist())
    rows=[]
    for gamma in (0,.5,.9,.99):
        run=value_iteration(P,r,gamma)
        rows.append(dict(gamma=gamma,sweeps=run['trace'][-1]['sweep'],actions=run['actions'],values=run['values']))
    return dict(result=result,discount_comparison=rows)


if __name__ == '__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

At discount 0.9 and requested value tolerance 1e-9, the run performs 88 value updates, followed by the final residual and greedy-action check. The returned values are approximately [4.556962024889, 5.063291138871, 0]. The reported value-error bound is about 9.54e-10, and the sufficient greedy-policy loss bound is about 1.72e-8. The extracted actions are [1,1,0]; their directly solved values are approximately [4.556962025316, 5.063291139241, 0].

The discount comparison also makes the objective change visible. At discount 0, leaving maximizes immediate reward. At discount 0.5, entry’s two actions tie once the room is worth 4, and the fixed tie rule chooses leaving. Both runs require one update from zero. At discount 0.99, advance/spin is selected and the same requested certificate takes 160 updates in this example. The changing count reflects both the model’s dynamics and a tighter residual requirement for a fixed value tolerance.

Each dense sweep costs O(S²A) time, including all successor sums. The dense model occupies O(S²A) space; retaining K trace vectors and policies adds O(KS). The loop performs no environment interaction and learns no transition probabilities. A maximum-sweep limit controls work; failure to reach the certificate raises an error.

A useful stopping rule has a stated scope

The bound is an exact-arithmetic statement for the supplied finite discounted model. Floating-point residuals are numerical estimates, not interval enclosures. Poor model estimates, extreme scaling and discounts close to one can make a small-looking number misleading. The 1/(1−gamma) and 1/(1−gamma)² factors show why a bare residual should not be reported without the discount.

The program rejects discount 1. Certain undiscounted episodic models admit other convergence arguments, but they are not obtained by using the same formulas with a zero denominator. Likewise, replacing full model expectations by samples creates a different algorithm with different conditions; this code is not Q-learning.

A stable extracted policy need not imply converged values, and a changing policy need not imply a large performance loss if actions are almost tied. Consistent tie handling makes runs reproducible, but it does not replace a quantitative certificate. A stopped loop caused by a budget, rather than its error condition, must remain an incomplete computation.

The working draft also discusses in-place and asynchronous updates. This program uses synchronous sweeps so that every iterate and residual has a simple interpretation. Results about other schedules require their own update and coverage conditions; they are not silently included in the recorded 88 updates.

Separate the vector from the policy it suggests

  1. Explain the counterexample. Why can the greedy policy remain unchanged while the value vector is still inaccurate?

    Answer: Action selection depends on relative lookahead ordering. A range of different continuation estimates may produce the same ordering. Keeping the same best action does not establish that its estimated discounted return has reached the fixed point.

  2. Compute the third update. Start from [3.6, 4, 0]. What is the next vector, and why does it still differ from the exact advance/spin value?

    Answer: Entry remains max(2, 0.9 × 4)=3.6. Room becomes max(4, 1.6 + 0.36 × (3.6+4))=4.336. The vector is [3.6,4.336,0]; it has propagated only one more layer of continuation, rather than solving the infinite-horizon fixed point [360/79,400/79,0].

  3. Calculate two bounds. With discount 0.9 and current residual 0.001, what do the displayed value-error and greedy-policy loss bounds give?

    Answer: Value error is bounded by 0.001/0.1 = 0.01. The sufficient greedy-policy loss bound is 2 × 0.9 × 0.001 / 0.1² = 0.18. These are upper bounds under the stated assumptions, not observed errors or proof that the policy actually loses 0.18.

  4. Choose what to report. A program stops after a fixed number of sweeps and returns values plus greedy actions. What additional information lets a reader assess the result?

    Answer: Report the discount, model and reward conventions, update schedule, current residual, derived bound, requested tolerance, actual update count and whether the error condition was met. Distinguish a separate exact or sampled policy evaluation from the approximate vector used to choose actions. A budget stop must not be labeled certified convergence.

The backup defines the algorithm

Sutton and Barto’s 2014–2015 working draft relates value iteration to the Bellman optimality equation and policy extraction. Bertsekas’s Lectures 15–16 provide the discounted contraction framework. The finite-horizon explanation, policy-loss derivation and numerical comparison here are worked through for the declared model rather than presented as reproduced source experiments.

Compare with policy evaluation, which keeps the action distribution fixed, and policy iteration, which completes a policy evaluation before improvement. Then revisit Q-learning to see what changes when exact expectations are replaced by experience. The same decision problem can support several algorithms without giving them the same data requirements or stopping guarantees.

Make a prediction, then check

The greedy actions are unchanged across two value-iteration sweeps. Can you stop and claim the value estimates are accurate?

Choose one answer

Learning objectives

  • Derive the maximum-over-actions backup and its contraction for finite discounted models.
  • Distinguish a stable extracted policy from converged values and calculate residual certificates with their discount dependence.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. MIT 6.231 Fall 2015 — discounted dynamic programming, Lectures 15–16
    Dimitri P. Bertsekas · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF114–115 §4.4/fig4.5 optimality backups, stopping and policy extraction. MIT175 supports contraction certificate; the greedy-policy bound is derived explicitly in the tutorial. Read2026-09-23. Read PDF167–168,173–175,179–180 and182–185; viewed175. Bounded discounted costs, policy/optimality operators, contraction, residual certificate and PI/VI. Diagrams181/184 were only partially legible as text. Tutorial switches cost minimization to reward maximization; affine reward-plus-transition maps are not called linear. 7 paired equations and four explained exercises. Checked full optimality backups, enumerated policy optimum, discount endpoints, unchanged early actions with changing values, every residual certificate, greedy-policy loss bound and budget failure. The policy-loss bound is derived in the article, not attributed to an unread source theorem.

  • Checked full optimality backups, enumerated policy optimum, discount endpoints, unchanged early actions with changing values, every residual certificate, greedy-policy loss bound and budget failure. The policy-loss bound is derived in the article, not attributed to an unread source theorem.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: eight byte-identical to viewed initial images and four reviewed final images; line-wrap revisions retained. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.