AI Wiki中文/EN

Maximum entropy RL: put a price on keeping options

最大熵强化学习

Use two routes to calculate entropy rewards, soft Bellman backups and temperature-dependent policies.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Why learn only one route when two work?

Suppose two teaching routes give the same return. Under expected-reward maximization, always going left and randomly choosing either route may both be optimal. Maximum entropy reinforcement learning assigns an explicit price to preserving options: rewards should remain high, while the policy need not commit prematurely among similarly good actions.

This is more than adding arbitrary noise to actions. Policy entropy enters the decision objective, so options available in future states can affect current decisions. Applying softmax exploration to ordinary Q-values does not automatically produce the same soft value function. Soft value framework

We derive an exact version with finite states, finite actions and discount below 1, then discuss continuous actions. SAC is one approximate implementation direction, not a synonym for the maximum entropy objective. Policy iteration and approximation

Exact soft Bellman iteration changes action probabilities and adds entropy to value; higher soft value is not higher environmental reward.
Exact soft Bellman iteration changes action probabilities and adds entropy to value; higher soft value is not higher environmental reward.

How entropy enters the Bellman equation

Let α>0\alpha>0 be temperature and use natural logarithms, measuring entropy in nats. For a finite-action policy, H(π)=−∑aπ(a)log⁡π(a)H(\pi)=-\sum_a\pi(a)\log\pi(a), with zero-probability terms defined as zero. This article uses a discounted objective under a starting distribution:

Jα(π)=Eπ ⁣[∑t=0∞γt(rt−αlog⁡π(at∣st))],0≤γ<1.J_\alpha(\pi)=\mathbb E_\pi\!\left[\sum_{t=0}^{\infty}\gamma^t\left(r_t-\alpha\log\pi(a_t\mid s_t)\right)\right],\qquad 0\le\gamma<1.

Averaging negative log probability over actions gives entropy. Temperature converts nats into a scale compatible with reward. This does not establish a universal nonnegative bonus for every sample, particularly when moving from finite actions to continuous densities.

Define VπV^\pi to include current-state entropy, while Qπ(s,a)Q^\pi(s,a) fixes the current action and accumulates entropy starting at the next state:

Qπ(s,a)=r(s,a)+γEs′∣s,aVπ(s′),Vπ(s)=∑aπ(a∣s)[Qπ(s,a)−αlog⁡π(a∣s)].Q^\pi(s,a)=r(s,a)+\gamma\mathbb E_{s'\mid s,a}V^\pi(s'),\qquad V^\pi(s)=\sum_a\pi(a\mid s)\left[Q^\pi(s,a)-\alpha\log\pi(a\mid s)\right].

Changing this convention without changing the backup can omit or double-count current entropy. Here r(s,a)r(s,a) is conditional expected reward; sample-based algorithms substitute observed rewards. The soft Q and SAC papers use corresponding soft Q/V relationships, but an actor trained on replay states should not automatically be described as taking the exact gradient of the start-state objective above. Soft Q definitions SAC definitions

Now fix one state’s action scores qq and choose a distribution pp maximizing expected score plus entropy. Introduce a Lagrange multiplier for ∑apa=1\sum_a p_a=1. Differentiating positive-probability terms gives qa−α(log⁡pa+1)+λ=0q_a-\alpha(\log p_a+1)+\lambda=0. Rearrange, exponentiate and normalize:

pa∗=exp⁡(qa/α)∑bexp⁡(qb/α),Vα(q)=αlog⁡∑bexp⁡(qb/α).p_a^*=\frac{\exp(q_a/\alpha)}{\sum_b\exp(q_b/\alpha)},\qquad V_\alpha(q)=\alpha\log\sum_b\exp(q_b/\alpha).

These are the Boltzmann distribution and log-sum-exp. Finite scores and positive temperature give positive probability to every action. To avoid overflow, the program subtracts the largest score before exponentiation and adds it back to the resulting value. This is a numerical rearrangement, not a different distribution.

Why is this globally optimal? Substituting log⁡pa∗=qa/α−log⁡Z\log p_a^*=q_a/\alpha-\log Z into KL divergence yields an identity useful for checking an answer:

Vα(q)−(∑apaqa+αH(p))=αDKL(p∥p∗)≥0.V_\alpha(q)-\left(\sum_a p_aq_a+\alpha H(p)\right)=\alpha D_{\rm KL}(p\Vert p^*)\ge0.

The left side is the gap between any distribution and the optimal soft value. Nonnegative KL establishes optimality; for this finite, positive target distribution equality holds exactly when p=p∗p=p^*. With two zero-valued actions and temperature 0.5, the uniform policy has soft value 0.5log⁡2≈0.3465740.5\log2\approx0.346574. Plain reward is still zero.

Let m=max⁡qm=\max q. The shifted exponential sum lies between 1 and action count nn, giving:

max⁡aqa≤Vα(q)≤max⁡aqa+αlog⁡n.\max_aq_a\le V_\alpha(q)\le\max_aq_a+\alpha\log n.

As temperature approaches zero, soft value approaches the maximum score. For fixed scores with tied maxima, the Boltzmann limit splits probability equally among those maximizers. Adding the same constant to every score leaves the policy unchanged. Multiplying every reward and temperature by the same positive factor also preserves the corresponding optimal policy; scaling reward alone changes the tradeoff.

Replace qq by reward plus expected next-state value to obtain the optimal soft Bellman operator TαT_\alpha. With finite states and actions, bounded rewards and discount below 1, log-sum-exp is 1-Lipschitz in maximum norm. Transition probabilities add an averaging step, so:

(TαV)(s)=αlog⁡∑aexp⁡ ⁣(r(s,a)+γE[V(s′)∣s,a]α),∥TαV−TαW∥∞≤γ∥V−W∥∞,∥V−Vα∗∥∞≤∥TαV−V∥∞1−γ.(T_\alpha V)(s)=\alpha\log\sum_a\exp\!\left(\frac{r(s,a)+\gamma\mathbb E[V(s')\mid s,a]}{\alpha}\right),\quad \|T_\alpha V-T_\alpha W\|_\infty\le\gamma\|V-W\|_\infty,\quad \|V-V_\alpha^*\|_\infty\le\frac{\|T_\alpha V-V\|_\infty}{1-\gamma}.

This explains the unique fixed point and a residual-based stopping criterion for exact iteration. Neural fitting, finite data and incomplete policy updates no longer apply this exact operator. A finite-table result is not a guarantee of deep-training convergence. Theory and approximation scope

Higher soft value need not mean higher environmental reward

This original two-state task continues indefinitely. At state 0, stay and earn 0.2 or enter state 1 for reward zero. Either state 1 action earns 0.4 and returns to state 0. Discount is 0.9. Without entropy, staying at state 0 gives value 2 and state 1 has value 2.2. Entering state 1 from state 0 gives only 0.9×2.2=1.98, so the reward-optimal action is to stay.

The program uses this known transition table directly rather than estimating a model. It checks value changes at each iteration, then computes a fresh Bellman residual. An independent two-variable linear policy-evaluation system checks the resulting values. Only the Python standard library is needed.

"""Exact finite-action soft control; all rewards and transitions are synthetic."""
import json
import math


def soft_value(q, alpha):
    if not q or not math.isfinite(alpha) or alpha <= 0 or not all(math.isfinite(v) for v in q):
        raise ValueError('nonempty finite Q and positive finite temperature required')
    m = max(q)
    return m + alpha*math.log(sum(math.exp((v-m)/alpha) for v in q))


def policy(q, alpha):
    soft_value(q, alpha)  # Validate the same contract.
    m = max(q)
    weights = [math.exp((v-m)/alpha) for v in q]
    return [v/sum(weights) for v in weights]


def entropy(p):
    if not p or any(not math.isfinite(x) or x < 0 for x in p) or not math.isclose(sum(p), 1.0, abs_tol=1e-12):
        raise ValueError('probabilities must be finite, nonnegative and sum to one')
    return -sum(x*math.log(x) for x in p if x > 0)


# State 0: stay for reward .2, or enter state 1 for reward 0.
# State 1: either action gives .4 and returns to state 0.
REWARDS = ((0.2, 0.0), (0.4, 0.4))
NEXT = ((0, 1), (0, 0))


def backup(v, alpha, gamma=0.9):
    if len(v) != 2 or not 0 <= gamma < 1:
        raise ValueError('two states and discount in [0,1) required')
    q = [[REWARDS[s][a]+gamma*v[NEXT[s][a]] for a in range(2)] for s in range(2)]
    return [soft_value(row, alpha) for row in q], q


def solve(alpha, gamma=0.9, tolerance=1e-11):
    if not 0 <= gamma < 1 or not math.isfinite(tolerance) or tolerance <= 0:
        raise ValueError('invalid discount/tolerance')
    v = [0.0, 0.0]
    for iterations in range(1, 100001):
        nv, _ = backup(v, alpha, gamma)
        residual = max(abs(a-b) for a, b in zip(v, nv))
        v = nv
        if residual <= tolerance:
            break
    else:
        raise RuntimeError('iteration limit')
    nv, q = backup(v, alpha, gamma)
    return {'alpha':alpha, 'value':v, 'policy':[policy(row, alpha) for row in q],
            'residual':max(abs(a-b) for a,b in zip(v,nv)), 'iterations':iterations}


if __name__ == '__main__':
    print(json.dumps([solve(a) for a in (0.01, 0.1, 0.5, 1.0)], sort_keys=True))
Inspect the complete recorded output
[{"alpha": 0.01, "iterations": 227, "policy": [[0.8248384046293907, 0.17516159537060924], [0.5, 0.5]], "residual": 8.291589637110519e-12, "value": [2.0192567784180473, 2.2242625723735507]}, {"alpha": 0.1, "iterations": 229, "policy": [[0.534803209786206, 0.465196790213794], [0.5, 0.5]], "residual": 8.842704346534447e-12, "value": [2.6258564318398716, 2.8325855067030368]}, {"alpha": 0.5, "iterations": 236, "policy": [[0.506910935379839, 0.493089064620161], [0.5, 0.5]], "residual": 8.673950446791423e-12, "value": [5.397099803338071, 5.6039634132755625]}, {"alpha": 1.0, "iterations": 241, "policy": [[0.5034519190956785, 0.4965480809043215], [0.5, 0.5]], "residual": 8.379075211450981e-12, "value": [8.862670647300805, 9.06955076312229]}]

For temperatures 0.01, 0.1, 0.5 and 1, probabilities of staying at state 0 are approximately 0.824838, 0.534803, 0.506911 and 0.503452. Corresponding soft values are about 2.019257, 2.625856, 5.397100 and 8.862671. The increase includes entropy; it does not mean the environment became more generous. All final residuals are below 9×10−129\times10^{-12}. At discount 0.9, the maximum-norm error bound is ten times the residual, apart from additional floating-point rounding error.

Each action here has one next state, so one sweep costs state count times action count. A general dense transition table requires summing over next states, costing O(∣S∣2∣A∣)O(|S|^2|A|) per sweep and the same order of transition storage. The value table alone uses O(∣S∣)O(|S|) space. Large unknown environments require learning or approximation rather than exhaustive use of this table.

Discrete entropy bounds do not transfer directly to continuous actions

Continuous actions use probability densities and differential entropy. A density can exceed 1 and entropy can be negative; changing action units also changes entropy. Scaling a one-dimensional action by positive cc adds log⁡c\log c to differential entropy, so learned-temperature entropy targets need a coordinate convention. The discrete upper bound log⁡n\log n does not apply to an infinite action set.

A continuous Boltzmann expression also needs a finite partition integral. A constant Q over the entire real line does not define a uniform probability density. The original soft Q paper specifies integrability and boundedness conditions; approximate sampling adds further error. Continuous conditions

Estimating an integral and then taking its logarithm has another trap. A positive estimator taking 1 or 3 with equal probability has mean 2, yet its mean logarithm is 12log⁡3\tfrac12\log3, less than log⁡2\log2. An unbiased integral estimate does not imply an unbiased log estimate. This is an independent arithmetic counterexample, not a reproduction of the paper’s sampler.

Entropy encourages randomness among covered actions but cannot guarantee discovery of rare rewards. High-entropy bad actions can still perform poorly. If action randomness itself is constrained by a task, state that constraint in the task and evaluation instead of merely increasing temperature.

Predict the probabilities first

  1. Both actions have Q=0. When temperature rises from 0.5 to 1, how do the optimal policy and soft value change?

Answer: Each action still receives half the probability. Soft value rises from 0.5log⁡20.5\log2 to log⁡2\log2. The entropy price increases, not the environmental reward.

  1. Does adding 100 to every action score change probabilities at fixed temperature? What can go wrong with direct exponentiation?

Answer: Probabilities stay unchanged because normalization cancels the common factor; soft value rises by 100. Direct exponentiation can overflow. Subtracting the largest score gives a more stable log-sum-exp calculation.

  1. Discount is 0.9 and the exact-operator residual is 0.001. What is the maximum-norm value-error bound?

Answer: It is 0.001/(1−0.9)=0.01 under the current finite, exact contraction assumptions. A random minibatch residual does not automatically supply the same deterministic bound.

  1. Is a continuous-action density greater than 1 invalid? What happens when action units are enlarged by a factor of 10?

Answer: It is valid: integrating density over an interval gives probability. Scaling units by 10 adds log⁡10\log10 to one-dimensional differential entropy. Transform densities and entropy targets consistently instead of importing discrete nonnegative-entropy intuition.

From an exact objective to approximate algorithms

The soft Q paper connects maximum entropy objectives, energy models and soft Bellman equations. This article reads PDF 2–4 without claiming a complete SVGD implementation or experiment audit. Soft Q source SAC 2018 connects policy evaluation and improvement while distinguishing exact finite-action theory from continuous function approximation. The reading covers PDF 3–5; our example implements finite-table computation only. SAC theory scope

Make a prediction, then check

Two actions both have Q=0 and alpha=0.5. What is the soft value?

Choose one answer

Learning objectives

  • Derive a finite-action Boltzmann policy and log-sum-exp through a KL identity.
  • Check soft Bellman residuals and distinguish soft value, plain reward and differential entropy.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning with Deep Energy-Based Policies — scoped soft Bellman equations
    Tuomas Haarnoja; Haoran Tang; Pieter Abbeel; Sergey Levine · 2017
  2. Soft Actor-Critic — ICML2018 scoped methods
    Tuomas Haarnoja; Aurick Zhou; Pieter Abbeel; Sergey Levine · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PMLR70:1352–1361. Read PDF2–4: soft Q/V, partition function and boundedness conditions. No complete SVGD implementation or experiment audit; finite-action teaching and independent log-estimation checks are separately labeled. PMLR80:1861–1870. Read PDF3–5: exact finite-action theory versus approximate training, explicit V/target V, twin Q and reparameterization. Full appendices and benchmark replication excluded. 6 paired equations and four explained exercises. Finite-action soft Bellman iteration, KL variational identity, log-sum-exp bounds, reward shifts and residual contraction checked, with an independent two-state linear solve. Soft value includes entropy; finite table guarantees do not transfer automatically to neural or continuous-density settings.

  • Finite-action soft Bellman iteration, KL variational identity, log-sum-exp bounds, reward shifts and residual contraction checked, with an independent two-state linear solve. Soft value includes entropy; finite table guarantees do not transfer automatically to neural or continuous-density settings.
  • Four computed SVG variants per topic;10 numeric/geometry tests and24 current responsive cases passed. All eight selected current captures directly viewed; all four groups use the checked initial captures. Actual assets and manuscripts are SHA bound. 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.