AI Wiki中文/EN

SAC:把随机策略也写进价值目标

Soft actor-critic

追踪重参数化、tanh密度、双Q和温度,区分2018版与后续实现。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

演员为何要主动保留一点随机性?

在一个教学控制任务里,几个相近动作都能得高分。确定性演员每个状态只给一个动作;SAC训练一个分布,让演员权衡高价值动作与保留选择的熵。评论家不只预测未来奖励,也要考虑未来策略的熵项。随机性因此进入训练目标,而不只是训练时临时加上的探索噪声。

Soft Actor-Critic通常译为软演员—评论家。它结合离策略回放、随机演员、重参数化梯度与软价值备份。不要把所有年份的算法图混在一起:ICML2018版有独立V和目标V网络;后续Algorithms and Applications版本直接使用目标Q,省去独立V,并讨论自动温度;本篇参考的Spinning Up实现使用后一种价值结构,但固定温度。2018版 后续版 固定实现

本文主讲无独立V、两个Q的连续动作版本。小程序固定温度;自动温度的推导与数值检查另列,不声称程序已训练自适应温度或复现机器人实验。

动作密度需要Jacobian修正。温度梯度与固定温度训练是两个例子;种子表显示三位有效数字。
动作密度需要Jacobian修正。温度梯度与固定温度训练是两个例子;种子表显示三位有效数字。

先明确谁产生动作,谁评价动作

从回放取 (s,a,r,s′,d)(s,a,r,s',d)。dd 是真实终止,ϕˉ1,ϕˉ2\bar\phi_1,\bar\phi_2 是目标评论家参数,θ\theta 是当前演员参数。重新从当前演员在下一状态采样动作,并以相同样本计算其log密度:

a′∼πθ(⋅∣s′),y=r+γ(1−d)[min⁡j=1,2Qϕˉj(s′,a′)−αlog⁡πθ(a′∣s′)],Li=EB[(Qϕi(s,a)−stopgrad⁡(y))2].a'\sim\pi_\theta(\cdot\mid s'),\qquad y=r+\gamma(1-d)\left[\min_{j=1,2}Q_{\bar\phi_j}(s',a')-\alpha\log\pi_\theta(a'\mid s')\right],\qquad L_i=\mathbb E_B\left[(Q_{\phi_i}(s,a)-\operatorname{stopgrad}(y))^2\right].

回放提供转移,下一动作不是回放里旧演员留下的动作,也不是TD3目标演员加平滑噪声。这里没有必需的目标演员;目标Q慢变,产生动作的演员是当前版本。真实终止移除整个继续项,包括下一熵;外部截断仍按未终止处理,除非任务本身已结束。无V备份 实际实现

更新评论家后,演员最小化:

Lπ(θ)=Es∼B,ϵ∼N(0,I)[αlog⁡πθ(fθ(s,ϵ)∣s)−min⁡i=1,2Qϕi(s,fθ(s,ϵ))].L_\pi(\theta)=\mathbb E_{s\sim B,\epsilon\sim\mathcal N(0,I)}\left[\alpha\log\pi_\theta(f_\theta(s,\epsilon)\mid s)-\min_{i=1,2}Q_{\phi_i}(s,f_\theta(s,\epsilon))\right].

这里双Q最小值也参与演员学习;经典TD3演员只用Q1。固定评论家权重,却保留动作路径的导数。两Q相等处最小值可能不可微,实现选择一个分支给出次梯度。单次采样给的是固定回放代理损失的随机梯度,不能据此声称精确优化了所有状态的原始回报。演员目标

为让动作可采样又可求导,先取与参数无关的高斯噪声,再变换为有界动作。对每维允许不同的正尺度 cjc_j 和中心 bjb_j:

u=μθ(s)+σθ(s)⊙ϵ,a=b+c⊙tanh⁡u,log⁡πθ(a∣s)=log⁡N(u;μθ,diag⁡σθ2)−∑jlog⁡(1−tanh⁡2uj)−∑jlog⁡cj.u=\mu_\theta(s)+\sigma_\theta(s)\odot\epsilon,\qquad a=b+c\odot\tanh u,\qquad \log\pi_\theta(a\mid s)=\log\mathcal N(u;\mu_\theta,\operatorname{diag}\sigma_\theta^2)-\sum_j\log(1-\tanh^2u_j)-\sum_j\log c_j.

减去Jacobian的log绝对行列式,是因为压缩后同样一块概率质量占据了不同宽度的动作区间。变换后的分布已不是高斯。直接把高斯log密度用于压缩动作,会让熵项和演员导数出错。变量变换

大 ∣u∣|u| 时,浮点tanh可能舍入到 ±1,直接算 log⁡(1−tanh⁡2u)\log(1-\tanh^2u) 会出问题。保留压缩前的 uu,使用稳定等价式:

log⁡(1−tanh⁡2u)=2(log⁡2−u−softplus⁡(−2u)),softplus⁡(v)=max⁡(v,0)+log⁡(1+e−∣v∣).\log(1-\tanh^2u)=2\left(\log2-u-\operatorname{softplus}(-2u)\right),\qquad \operatorname{softplus}(v)=\max(v,0)+\log(1+e^{-|v|}).

程序从同一个 uu 计算动作和log密度,不从舍入到边界的动作反求atanh。数学支持是开区间,浮点返回值却可能落在端点;有限log密度来自保留的前像数值,不表示端点存在概率原子。稳定实现

一维、尺度1、ℓ=log⁡σ\ell=\log\sigma、δ=eℓϵ\delta=e^\ell\epsilon、z=tanh⁡uz=\tanh u 时,可以手推路径导数。令 qaq_a 是当前较小评论家的动作导数,保持噪声与评论家参数不变:

dLπdμ=2αz−qa(1−z2),dLπdℓ=−α+[2αz−qa(1−z2)]δ.\frac{dL_\pi}{d\mu}=2\alpha z-q_a(1-z^2),\qquad \frac{dL_\pi}{d\ell}=-\alpha+\left[2\alpha z-q_a(1-z^2)\right]\delta.

第一项的 2z2z 来自tanh密度修正;−α-\alpha 来自高斯log密度中的 −ℓ-\ell。再乘状态特征即可更新均值和log标准差参数。小程序把log标准差裁到[−3,1],区间外其裁剪路径导数为0;边界不可微点不用于中心差分一致性检查。

自动温度换了一个问题:希望平均熵不低于目标 Hˉ\bar H。冻结本次策略样本,把估计熵记为 H^\widehat H,用非负拉格朗日乘子 α=eβ\alpha=e^\beta:

E[−log⁡π(a∣s)]≥Hˉ,Lα(β)=eβ(H^−Hˉ),∂Lα∂β=α(H^−Hˉ).\mathbb E[-\log\pi(a\mid s)]\ge\bar H,\qquad L_\alpha(\beta)=e^\beta(\widehat H-\bar H),\qquad \frac{\partial L_\alpha}{\partial\beta}=\alpha(\widehat H-\bar H).

熵不足时梯度为负,下降步增大 β\beta 和温度,从而加重演员损失中的熵权重。常见的 −β(log⁡π+Hˉ)-\beta(\log\pi+\bar H) 更新有相同符号,却少了 α\alpha 因子,不能称为同一参数化下完全相同的梯度。固定版本Spinning Up没有这个自动调节步骤。温度双目标 固定温度实现

训练结果要分开看三种量

原创环境与DDPG/TD3篇相同:初始位置均匀采样于 [−1,1][-1,1],每步奖励 1−(a−x/2)21-(a-x/2)^2,下一位置 (x+a)/2(x+a)/2,两步后终止,折扣0.9。两个评论家各使用六个二次特征;演员每阶段有均值与log标准差各两个线性参数,再作tanh压缩。标准差可以随位置改变。

仅用Python标准库训练6000步,前200步均匀探索,回放容量2000、批量32,温度固定0.1。评论家学习率0.04、演员0.02,目标评论家系数0.01。后续环境动作从当前随机演员直接采样,不再叠加DDPG式探索噪声。每次先更新两Q,再更新演员,最后更新目标Q。

"""Original fixed-temperature SAC lesson; quadratic critics, not a deep benchmark."""
import json
import math
import random


def clip(x, low=-1.0, high=1.0):
    return min(high, max(low, x))


def features(x, a):
    return [1.0, x, a, x*x, x*a, a*a]


def value(w, x, a):
    return sum(u*v for u, v in zip(w, features(x, a)))


def action_gradient(w, x, a):
    return w[2] + w[4]*x + 2*w[5]*a


def policy(w, x):
    return math.tanh(w[0]*x + w[1])


def transition(phase, x, a):
    if phase not in (0, 1) or not -1 <= a <= 1:
        raise ValueError('phase must be 0/1 and action in [-1,1]')
    return 1.0-(a-0.5*x)**2, 0.5*(x+a), phase == 1


def bootstrap(reward, future, terminated, truncated=False, gamma=0.9):
    # External collection limits do not erase the continuation value.
    # A real terminal state takes precedence even if both flags are true.
    return reward if terminated else reward + gamma*future


def evaluate(actor):
    returns = []
    for i in range(101):
        x = -1.0 + 2.0*i/100
        total = 0.0
        for h in (0, 1):
            a = policy(actor[h], x)
            r, x, _ = transition(h, x, a)
            total += (0.9**h)*r
        returns.append(total)
    return sum(returns)/len(returns)


def softplus(x):
    return max(0.0, x) + math.log1p(math.exp(-abs(x)))


def sample(actor, x, epsilon, low=-1.0, high=1.0):
    if not low < high or not all(math.isfinite(v) for v in (*actor, x, epsilon, low, high)):
        raise ValueError('finite inputs and ordered action bounds required')
    raw_log_std = actor[2]*x + actor[3]
    log_std = clip(raw_log_std, -3.0, 1.0)
    delta = math.exp(log_std)*epsilon
    u = actor[0]*x + actor[1] + delta
    z = math.tanh(u)
    scale, center = (high-low)/2, (high+low)/2
    log_jacobian = 2*(math.log(2)-u-softplus(-2*u))
    logp = -0.5*epsilon**2 - 0.5*math.log(2*math.pi) - log_std - log_jacobian - math.log(scale)
    return center+scale*z, logp, (z, delta, scale, -3 < raw_log_std < 1)


def actor_loss_gradient(actor, q1, q2, x, epsilon, alpha=0.1):
    a, logp, (z, delta, scale, live_std) = sample(actor, x, epsilon)
    v1, v2 = value(q1, x, a), value(q2, x, a)
    # A deterministic subgradient at ties; finite-difference checks avoid ties.
    chosen = q1 if v1 <= v2 else q2
    path = action_gradient(chosen, x, a)*scale*(1-z*z)
    gm = 2*alpha*z-path
    gl = (-alpha+(2*alpha*z-path)*delta) if live_std else 0.0
    return alpha*logp-min(v1,v2), [gm*x, gm, gl*x, gl], logp


def temperature_step(log_alpha, entropy, target_entropy, learning_rate=0.01):
    # Exact gradient of exp(log_alpha)*(H-H_target), with H detached.
    if learning_rate < 0 or not all(math.isfinite(v) for v in (log_alpha, entropy, target_entropy, learning_rate)):
        raise ValueError('finite temperature arguments and nonnegative learning rate required')
    return log_alpha-learning_rate*math.exp(log_alpha)*(entropy-target_entropy)


def train(seed=0, steps=6000, alpha=0.1):
    if not math.isfinite(alpha) or alpha <= 0:
        raise ValueError('positive finite alpha required')
    explore, replay_rng = random.Random(seed), random.Random(seed+10000)
    init, target_rng, actor_rng = (random.Random(seed+k) for k in (20000, 30000, 40000))
    actor = [[0.0, 0.0, 0.0, -0.7] for _ in range(2)]
    critics = [[[init.uniform(-0.05,0.05) for _ in range(6)] for _ in range(2)] for _ in range(2)]
    targets = [[w[:] for w in q] for q in critics]
    replay, capacity, tau = [], 2000, 0.01
    initial = evaluate(actor)
    phase, x, updates = 0, explore.uniform(-1, 1), 0
    for t in range(steps):
        a = explore.uniform(-1,1) if t < 200 else sample(actor[phase],x,explore.gauss(0,1))[0]
        r, nx, terminal = transition(phase,x,a)
        item = (phase,x,a,r,nx,terminal)
        if len(replay) < capacity:
            replay.append(item)
        else:
            replay[t % capacity] = item
        phase,x = (0,explore.uniform(-1,1)) if terminal else (1,nx)
        if t < 200:
            continue
        batch = [replay_rng.choice(replay) for _ in range(32)]
        cg = [[[0.0]*6 for _ in range(2)] for _ in range(2)]
        for h,sx,act,reward,next_x,done in batch:
            future = 0.0
            if not done:
                na,lp,_ = sample(actor[1],next_x,target_rng.gauss(0,1))
                future = min(value(q[1],next_x,na) for q in targets)-alpha*lp
            y = bootstrap(reward,future,done)
            for k,q in enumerate(critics):
                error = value(q[h],sx,act)-y
                for j,f in enumerate(features(sx,act)):
                    cg[k][h][j] += 2*error*f/len(batch)
        for k,q in enumerate(critics):
            for h in (0,1):
                q[h] = [w-0.04*g for w,g in zip(q[h],cg[k][h])]
        ag = [[0.0]*4 for _ in range(2)]
        for h,sx,*_ in batch:
            _,gradient,_ = actor_loss_gradient(actor[h],critics[0][h],critics[1][h],sx,actor_rng.gauss(0,1),alpha)
            for j,g in enumerate(gradient):
                ag[h][j] += g/len(batch)
        for h in (0,1):
            actor[h] = [w-0.02*g for w,g in zip(actor[h],ag[h])]
            for qt,q in zip(targets,critics):
                qt[h] = [(1-tau)*v+tau*w for v,w in zip(qt[h],q[h])]
        updates += 1
    evaluation_rng = random.Random(seed+50000)
    rewards, soft_returns, entropies = [], [], []
    for _ in range(1000):
        sx = evaluation_rng.uniform(-1,1)
        reward_return = soft_return = 0.0
        for h in (0,1):
            act,logp,_ = sample(actor[h],sx,evaluation_rng.gauss(0,1))
            reward,sx,_ = transition(h,sx,act)
            reward_return += 0.9**h*reward
            soft_return += 0.9**h*(reward-alpha*logp)
            entropies.append(-logp)
        rewards.append(reward_return)
        soft_returns.append(soft_return)
    return {'seed':seed,'alpha':alpha,'initial':initial,'deterministic_final':evaluate(actor),
            'stochastic_reward':sum(rewards)/len(rewards),'stochastic_soft_return':sum(soft_returns)/len(soft_returns),
            'mean_entropy':sum(entropies)/len(entropies),'reward_optimum':1.9,
            'critic_updates':updates,'actor_updates':updates,'actor':actor,'critics':critics}


if __name__ == '__main__':
    print(json.dumps(train(),sort_keys=True))
查看完整运行结果
{"actor": [[0.5412346442457966, 0.0031440163545796884, 0.0008827443153855828, -1.3717024479653757], [0.5255505201552346, 0.01410547334058794, 0.0007468602712448647, -1.3915726759208558]], "actor_updates": 5800, "alpha": 0.1, "critic_updates": 5800, "critics": [[[1.8467552675914314, 0.00034318610935943556, 0.0003385451321445187, -0.24414118079584754, 0.9727528208668991, -0.9746552795259257], [0.9973626973612275, 0.00026677615664755775, -0.0007388491919690741, -0.23391921500204577, 0.9509034177853424, -0.9585608565256443]], [[1.846750311403298, 0.000344020190230736, 0.00033758649904466905, -0.24412166767225482, 0.9726713244090277, -0.9745633241901841], [0.9974171866234459, 0.0002564365266644398, -0.0007200024926649706, -0.23443336320440183, 0.9520176943830062, -0.959143883142303]]], "deterministic_final": 1.899709453091233, "initial": 1.795875, "mean_entropy": -0.08136317148073031, "reward_optimum": 1.9, "seed": 0, "stochastic_reward": 1.8014228225018432, "stochastic_soft_return": 1.7857204171655978}

程序输出三种不同评价:101点固定网格上的确定性动作回报;1000回合独立随机采样的纯奖励;同一批随机回合的软回报。确定性动作取tanh后的高斯均值,通常不等于变换后动作分布的数学均值。固定网格和随机初始状态的采样方案不同,不能拿极小差值做优势结论。

种子0—7全部保留。确定性评估平均约1.899827;随机纯奖励平均约1.804782;随机软回报平均约1.786261。种子0的平均微分熵约−0.081363,所以软回报可以低于纯奖励。奖励上界1.9是本任务的纯奖励上界,不是所有软目标的上界。结果不证明SAC胜过DDPG或TD3,因为训练目标与评价策略不同。

检查包括演员解析梯度与中心有限差分、独立密度积分约等于1、动作缩放的Jacobian、极端前像下的有限数值、温度调整符号、终止掩码,以及全部种子的真实训练。每次更新的成本随批量和模型计算量增长;固定这组小特征时为批量线性,回放空间为容量线性。神经版本需要另外计网络前后向和优化器状态。

温度、坐标与版本都要讲清楚

改变动作单位会改变微分熵。一维动作作正尺度变换时:

a′=ca+b,c>0,log⁡πa′(a′)=log⁡πa(a)−log⁡c,H(a′)=H(a)+log⁡c.a'=ca+b,\quad c>0,\qquad \log\pi_{a'}(a')=\log\pi_a(a)-\log c,\qquad H(a')=H(a)+\log c.

因此目标熵也须跟着坐标变换。所读Spinning Up代码在动作乘act_limit后,log密度仍按归一化动作坐标计算;本程序的一般采样函数显式保留尺度项,实际训练范围为 [−1,1][-1,1]。固定尺度常数不改变同一状态的局部演员导数,却会影响价值的常数项;可变回合长度或自动温度时,不能不加条件地说坐标变化“完全没影响”。代码坐标约定

SAC的精确软策略迭代论证依赖相应有限动作与精确更新条件。神经评论家、受限策略族、随机梯度与未收敛的交替更新,不自动继承一般最优性保证。tanh高斯还可能难以表达复杂的多峰动作偏好;双Q共享回放,也不是独立的置信估计。理论范围 近似与温度

后续v2原文PDF6的式7把Q参数写成两个状态,同页式9明确为状态与动作;本文按式9和固定实现写正确的动作参数。研究引用的是已核读范围,未把全文可下载或作者机器人演示当作本项目验证。版本核对

追踪密度与更新方向

  1. 非终止奖励1、折扣0.9、两个目标Q为3和2、下一动作log密度为−0.5、温度0.2,备份是多少?

答案:先取2,再减去0.2×(−0.5),得到继续项2.1;目标是1+0.9×2.1=2.89。真实终止则仍为1。

  1. u=0u=0、单位尺度、标准高斯时,tanh的Jacobian修正是多少?把动作范围放大到 [−2,2][-2,2] 呢?

答案:tanh在0处导数为1,log修正为0;乘尺度2再减去 log⁡2\log2。高斯本身在0的log密度仍需计算,不能把“修正为0”读成“密度为1”。

  1. 当前平均熵−0.5,目标−0.2,温度0.2,用正文对数温度的精确梯度,方向和数值是什么?

答案:梯度为0.2×(−0.3)=−0.06;梯度下降增加对数温度,促使演员更加重视熵。若用省掉温度因子的代理,梯度是−0.3,方向相同、步幅不同。

  1. 确定性测试回报高于随机测试回报,能否说明熵正则失败?

答案:不能。训练的软目标与纯奖励指标不同,确定性评价又改变了策略。应同时报告随机纯奖励、软回报、确定性回报、种子和采样方案,再按任务需求判断;不能只挑一个分数。

先识别算法版本,再对照实现

2018原文解释显式V与软策略迭代,本篇核读PDF3—5。2018方法 后续v2读取PDF4—8及16,核目标Q、温度目标与tanh变量变换;这不是完整证明或机器人实验审计。后续方法 固定Spinning Up提交用于检查当前策略采样、双Q、固定温度、稳定log密度与动作坐标,未执行或复制上游源码。实现阅读

先判断,再看解释

后续无独立V的SAC怎样生成目标中的下一动作?

选择一个答案

学习目标

  • 计算压缩高斯动作的log密度并核对演员路径导数。
  • 区分固定温度、自动温度及动作坐标改变后的熵目标。

先修与延伸

查看知识关联图 →

参考文献

  1. Soft Actor-Critic — ICML2018 scoped methods
    Tuomas Haarnoja; Aurick Zhou; Pieter Abbeel; Sergey Levine · 2018
  2. Soft Actor-Critic Algorithms and Applications — arXiv v2 methods
    Tuomas Haarnoja; Aurick Zhou; Kristian Hartikainen; George Tucker; Sehoon Ha; Jie Tan; Vikash Kumar; Henry Zhu; Abhishek Gupta; Pieter Abbeel; Sergey Levine · 2019
  3. Spinning Up — SAC fixed-commit methods
    OpenAI; Joshua Achiam and contributors · 2020

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: 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. First2018-12-13, v2 dated2019-01-29. Read PDF4–8 and16, viewed6: target Q, current stochastic actor, dual temperature and tanh Jacobian. Eq9 resolves Eq7 Q(s,s) notation; no complete proof audit or robot replication. Docs1–236, main file179–323, all98 core lines; fixed alpha, current policy, stable tanh density and normalized action coordinates. Fixed commit; reference only, no upstream execution or copying. 7 paired equations and four explained exercises. Later no-V SAC uses current-policy next actions, twin critics and fixed alpha in the original teaching program. Pathwise gradients, stable tanh/scaling Jacobians, density quadrature, clipping and temperature-direction examples tested. Eight seeds preserve stochastic reward, soft return and deterministic evaluation separately; automatic temperature was not trained.

  • 后续无V版采用当前策略下一动作和双评论家,原创程序固定alpha;核路径梯度、稳定tanh/缩放Jacobian、密度积分、裁剪和独立温度方向例。八种子分开保存随机奖励/软回报/确定性评价,未训练自动温度。
  • 每题四张计算SVG,10数值/几何与24个当前响应式组合通过;八张当前选定图均直接实看,四组使用已检查的初次捕获,资产与稿件SHA绑定,完整页面验收另记。

核对的来源位置:

  • Soft Actor-Critic — ICML2018 scoped methods · 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.
  • Soft Actor-Critic Algorithms and Applications — arXiv v2 methods · First2018-12-13, v2 dated2019-01-29. Read PDF4–8 and16, viewed6: target Q, current stochastic actor, dual temperature and tanh Jacobian. Eq9 resolves Eq7 Q(s,s) notation; no complete proof audit or robot replication.
  • Spinning Up — SAC fixed-commit methods · Docs1–236, main file179–323, all98 core lines; fixed alpha, current policy, stable tanh density and normalized action coordinates. Fixed commit; reference only, no upstream execution or copying.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。