所属方向:对齐与强化学习 | 难度:前沿 | 前置知识:GRPO、DDIM 采样
关键词:DiffusionRL、DDPO、去噪轨迹、终点奖励、信用分配、DPOK、DRaFT
先掌握条件高斯分布、期望与梯度、策略梯度和 PPO 的局部裁剪目标。latent 是 VAE 编码后的连续变量,prompt 条件记为 $c$;VAE 解码器和奖励函数在本文推导中固定。$T$ 表示实际执行的去噪转移数,$t=T,\ldots,1$ 是本文重新编号的采样序号,未必等于调度器训练噪声网格的整数索引。后者可能跳步、带 offset,不能把源码里的 timestep - stride 直接读成本文的 $t-1$。
扩散模型通常先学习“像训练数据”,但产品真正关心的目标往往不是训练集似然:文字有没有正确渲染、人物是不是多了一根手指、构图是否讨喜、生成物能不能被某个下游系统识别、视频运动是否自然。这些目标可能来自人工打分、视觉语言模型、OCR、物理模拟器,甚至一段只能返回分数的业务程序。它们大多不可微,也不一定有成对偏好数据,却都能回答同一个问题:这张最终样本值多少分?
直接把最终图片当成一次普通动作,会丢掉扩散模型最重要的结构:本文关注的随机扩散采样从初始噪声出发,经过多次转移得到图片;步数可多可少,也有确定性采样。假设采样有 50 步,最后的文字错了,到底是哪一步需要改?若只保留终点而丢弃采样轨迹,就无法直接重算 DDPO 所需的逐步转移密度;如果硬把 50 个概率相乘成一个轨迹比率,数值又很容易趋近 0 或爆炸。
DiffusionRL 的关键不是发明一种新的扩散网络,而是换一个观察角度:
把一次完整采样视为一条有限时域 MDP 轨迹;当前 latent 是状态,下一 latent 的随机采样是动作,最终图片的评分是终点奖励。
这样,奖励虽然只在最后出现,整条轨迹的 log-prob 仍然可以参与策略梯度。DDPO(Denoising Diffusion Policy Optimization)正是把这个视角变成了可训练算法:它允许我们用 JPEG 可压缩性、目标检测器、审美模型或人工反馈等黑盒奖励微调扩散模型,而不要求对奖励函数求导。
这也是理解视频生成 RL 的统一入口。图片去噪已经有“时间步 × latent”的信用分配;到了视频,还会再叠加帧间运动、时序一致性和长时奖励。先把图像版的轨迹与概率比率看清,后面的算法名字就不再是一堆孤立缩写。

图里有一个必须说准的细节:网络通常输出噪声、velocity 或转移均值的参数,但在 MDP 记号中,“动作”是实际采样出来的 $x_{t-1}$。也就是说,网络参数化动作分布,采样器从这个分布中抽出动作;不要把“网络输出”和“环境中发生的动作”混成一件事。
为避免被不同预测参数化淹没,先只保留采样器真正需要的形式。对当前 latent $x_t$,模型根据时间步 $t$ 和条件 $c$ 预测噪声,再由调度器算出一个转移均值:
$$\mu_\theta(x_t,t,c).$$
带随机性的 DDIM 步可以统一写成:
$$x_{t-1}=\mu_\theta(x_t,t,c)+\sigma_t z_t,\qquad z_t\sim\mathcal N(0,I).$$
因此条件转移是一个高斯策略:
$$\pi_\theta(a_t\mid s_t)=p_\theta(x_{t-1}\mid x_t,t,c)=\mathcal N\!\left(x_{t-1};\mu_\theta(x_t,t,c),\sigma_t^2 I\right).$$
DDIM 用随机强度 $\eta$ 控制 $\sigma_t$;$I$ 是坐标维度上的单位矩阵,$z_t$ 是逐步独立标准高斯。下文纯 score-function 等式假设所有可训练转移都具有严格正、参数无关的方差,奖励与固定解码器没有显式的参数依赖。$\eta>0$ 本身不保证终步方差为正,必须检查实际网格和边界配置。固定官方函数在先裁剪到非负网格后算方差:本次 CPU 夹具的原网格索引 1→0 得正标准差 0.00866421,而索引 0→0 或 $\eta=0$ 给出非有限 log-prob。它不是自动跳过退化步的实现,不能从默认 timestep_fraction=1.0 推断任何网格都安全。
简单删掉零方差终步不一定保留原目标的梯度。 若终步为 $x_0=f_\theta(x_1)$,即便前面没有随机动作,$R(f_\theta(x_1))$ 仍可能随参数变化;例如 $f_\theta(x_1)=x_1+\theta$、$R(x_0)=x_0$,真梯度为 1,空的 score 求和却为 0。可行处理包括把最后读出固定为与参数无关、为训练转移定义并记录正方差策略,或在可微条件下加入该确定性读出的路径导数。改变方差就改变了策略;只排除该步或加分母 epsilon 是另一个近似目标,不能声称仍严格等价。
把扩散采样改写成 MDP 时,可使用下面的对应关系:
| RL 概念 | 扩散采样中的对象 |
|---|---|
| 状态 $s_t$ | 当前 latent、时间步和条件:$(x_t,t,c)$ |
| 动作 $a_t$ | 从模型给出的分布中采样下一 latent:$x_{t-1}$ |
| 策略 $\pi_\theta$ | 反向去噪转移 $p_\theta(x_{t-1}\mid x_t,t,c)$ |
| 奖励 | 中间步骤通常为 0;解码 $x_0$ 后得到 $R(x_0,c)$ |
这里的“环境”几乎没有额外动力学:动作 $x_{t-1}$ 本身就成为下一状态的一部分,时间步从 $t$ 减到 $t-1$。文本编码器、VAE 解码器和奖励模型通常不属于策略参数;真正更新的是 UNet、DiT 或其 LoRA 适配器。
给定提示词,一条轨迹记作 $\tau=(x_T,x_{T-1},\ldots,x_0)$。因为初始噪声不依赖模型参数,轨迹概率可分解为:
$$p_\theta(\tau\mid c)=p(x_T)\prod_{t=1}^{T}p_\theta(x_{t-1}\mid x_t,t,c).$$
取对数后,乘积变为求和。这里按标准数学写法从 1 到 T 对所有转移求和或相乘;标量项的书写顺序不改变采样仍从 T 向 1 执行:
$$\log p_\theta(\tau\mid c)=\log p(x_T)+\sum_{t=1}^{T}\log p_\theta(x_{t-1}\mid x_t,t,c).$$
目标是最大化期望终点奖励:
$$J(\theta)=\mathbb E_{c,\tau\sim p_\theta}[R(x_0,c)].$$
应用 likelihood-ratio trick:
$$\nabla_\theta J(\theta)=\mathbb E\!\left[R(x_0,c)\nabla_\theta\log p_\theta(\tau\mid c)\right]=\mathbb E\!\left[R(x_0,c)\sum_{t=1}^{T}\nabla_\theta\log p_\theta(x_{t-1}\mid x_t,t,c)\right].$$
这来自 $\nabla p=p\nabla\log p$,在允许交换积分与求导、初始噪声及 prompt 分布固定、转移支持集相容且积分有限时成立。算 score 时保存的状态与动作都视为常数,只对当前转移均值求导;不要同时把状态经采样链反传再加 score,以免混用两种估计器。若奖励或确定性读出还显式依赖参数,要另加相应路径项。实践中会减去不依赖当前动作的基线 $b(c)$,得到优势:
$$A=R(x_0,c)-b(c).$$
对与当前动作条件独立的基线,由 $\mathbb E[\nabla\log\pi\mid s]=0$,减基线不改变期望梯度;基线参数在这项 score 乘积中应停止梯度。它可能降方差,不保证任意基线都降低。若考察标量轨迹 score $S$,常数基线的二阶矩为 $\mathbb E[(R-b)^2S^2]$,对 $b$ 求导可得最小方差常数 $b^*=\mathbb E[RS^2]/\mathbb E[S^2]$(分母非零);奖励均值不一定等于它。若同一个 prompt 一次生成多张图,可以用组内均值和标准差做归一化:
$$A_i=\frac{R_i-\operatorname{mean}(R_{1:G})}{\operatorname{std}(R_{1:G})+\epsilon}.$$
组均值包含自身时,未标准化的中心化 score 估计在独立采样条件下有 $(1-1/G)$ 的缩放;随机标准差还会改变各组权重。因此上面的无偏基线证明不能直接套到组内标准化。独立同分布的 $G$ 条轨迹下,不做 std 归一化时,包含自身的均值给出 $(G-1)/G$ 倍原梯度;leave-one-out 均值可消去这一缩放。本文检查脚本穷举 Bernoulli 的 $G=2,3,4$,真梯度 0.21,组均值分别给出 0.105、0.14、0.1575,LOO 均为 0.21。除以当前组 std 后,奖励与分母相关,不能再只乘 $G/(G-1)$ 修复。不同 prompt 的标准差也会改变它们的相对权重。它与 GRPO 有相似工程动机,但并非通用的无偏定理。
设动作 $x_{t-1}$ 有 $D$ 个独立高斯坐标、固定方差为 $\sigma_t^2>0$。真实联合 log-prob 必须对坐标求和:
$$\ell_\theta=-\frac{\|x_{t-1}-\mu_\theta\|^2}{2\sigma_t^2}-D\log\sigma_t-\frac D2\log(2\pi).$$
真实逐步联合概率比为 $r_t=\exp(\ell_\theta-\ell_{old})$。DDPO 作者实现 则把逐坐标 log-prob 取平均,即 $\bar\ell=\ell/D$,再计算
$$\bar r_t=\exp(\bar\ell_\theta-\bar\ell_{old})=r_t^{1/D}.$$
这是一种控制高维数值尺度的工程替代比率,不再是严格的联合重要性权重;它也改变了 clip 的尺度。本文一维玩具 $D=1$ 时二者相同,多维复现时必须明确采用哪个约定。例如 $D=1024$、联合 log-ratio 为 10,真实比率为 22026.4658,平均坐标比率却只有 1.009813;用 $\epsilon=0.2$ 时后者还在区间内。相同 clip 数值不能在不同归约下解释为同样的策略变化。下式须先明确使用哪一种 $r_t$。
PPO 风格的裁剪目标是:
$$L_t(\theta)=\min\!\left(r_t A,\operatorname{clip}(r_t,1-\epsilon,1+\epsilon)A\right).$$
训练代码通常最小化 $-L_t$。关键是先按转移计算比率再裁剪,不是先把所有 $r_t$ 相乘成一个轨迹比率。对真实联合密度,在旧策略覆盖新策略轨迹时,$J(\theta)=\mathbb E_{\tau\sim p_{\mathrm{old}}}[R\prod_t r_t]$ 才是完整轨迹的重要性重加权;比率在 log 域求和仍可能有高方差。逐步 PPO 把旧轨迹状态分布与旧策略下的优势固定,优化局部 surrogate,并非把完整乘积恒等改成逐步裁剪求和。它在旧参数处有相应的一阶联系,离开旧参数后状态分布与未来回报也会改变;平均坐标比率又额外改变了尺度。clip 只抑制特定优势符号下继续获益的方向,不是 ratio 或 KL 的硬约束,不能保证更新后所有转移都落在区间内。
优势 $A$ 可以广播给每一步,但 score function 不同。对固定方差的高斯策略,有:
$$\nabla_\theta\log p_\theta(x_{t-1}\mid x_t,c)=\frac{x_{t-1}-\mu_\theta}{\sigma_t^2}\nabla_\theta\mu_\theta.$$
时间步的噪声尺度、采样残差、网络 Jacobian 都不同,因此各步的梯度贡献不会相等。终点附近通常对最终结果影响更直接,但并不存在“最后一步天然包办所有学习”的定理;调度器与模型参数化会改变信用在各步之间的分布。
下面的玩具过程只有一个可训练标量 $\theta$,但保留了 DDPO 的核心结构:8 步高斯转移、只在终点计算奖励、保存逐步 log-prob、用 batch 中心化再除以标准差的优势做 score 更新,最后单独诊断新旧策略的 PPO 比率。主训练循环没有优化 clipped PPO loss,也没有 reference KL;它是结构教学过程,没有图像扩散模型的训练噪声日程或预训练权重。
状态转移是:
$$x_{t-1}=0.72x_t+0.18\theta+0.45z_t,\qquad z_t\sim\mathcal N(0,1).$$
终点目标为 1.5,奖励为:
$$R(x_0)=-(x_0-1.5)^2.$$
完整代码见文末。直接运行:
python3 ddpo_minimal.py
真实输出如下:
trajectory_shape= (4096, 9)
transition_log_prob_shape= (4096, 8)
before_terminal_mean= 0.0052
before_reward_mean= -2.6513
after_theta= 2.2677
after_terminal_mean= 1.3577
after_reward_mean= -0.4370
per_step_gradient= [0.0088 0.0085 0.014 0.024 0.0358 0.0435 0.0578 0.0883]
gradient_sample_std_raw_centered= 1.6981 1.3899
ppo_ratio_mean_min_max= 1.0010 0.4051 2.2337
ppo_clip_fraction= 0.3108
history_first= [ 0. -0.0165 -2.7295]
history_last= [ 2.2677 1.3601 -0.4503]
几个 shape 很重要:4096 条轨迹、每条 8 个转移,所以状态数组有 9 个点,而 log-prob 只有 8 个。训练前 $x_0$ 均值约为 0;40 次更新后移到 1.36,接近目标 1.5,平均奖励从 -2.65 提升到约 -0.44。奖励是负平方误差,所以“更大”意味着更接近 0,而不是数值绝对值更大。
中心化前后,单样本梯度估计的标准差从 1.70 降到 1.39。这段方差比较只减去了 batch 均值,没有除以 std;主训练用的则是标准化优势。数字来自 seed=7 最后一次训练批,不能与所有参数设置或训练轮次混为一谈,也不是无偏性的证明。工业实现还会按 prompt 维护统计量,避免一个本来就容易拿高分的 prompt 主导更新。
最后把参数轻微扰动,逐步比率均值仍约为 1,但极端值已经到 0.41 和 2.23,有约 31% 的转移落到裁剪区间之外。这说明“平均比率看起来正常”不足以判断更新是否安全,还要看 clip fraction、KL 和比率分位数。

右图里越靠近终点的转移贡献越大,是这个线性玩具过程的收缩系数 0.72 造成的:早期扰动经过多次收缩后影响变小。这是最后一批的标准化梯度估计,并非无噪声理论曲线。这个玩具还可以闭式验算。令收缩系数 $a=0.72$、参数系数 $b=0.18$、噪声标准差 $\sigma=0.45$,定义 $k=b\sum_{i=0}^{T-1}a^i$。从方差为 1 的初始噪声递推,得到:
$$m=\mathbb E[x_0]=k\theta,\qquad v=\operatorname{Var}(x_0)=a^{2T}+\sigma^2\sum_{i=0}^{T-1}a^{2i}$$
$$J(\theta)=-[(k\theta-1.5)^2+v],\qquad J^{\prime}(\theta)=-2k(k\theta-1.5)$$
第 $j$ 个执行的转移($j=0,\ldots,T-1$)的未标准化期望信用为 $-2ba^{T-1-j}(m-1.5)$,因为这次噪声到终点还要经历 $T-1-j$ 次收缩;各项求和就是上式梯度。默认 $k=0.5964297341$、$v=0.4234961098$,最优 $\theta=2.5149651573$,最优期望奖励仍为 $-v$,不能达到 0:单个均值参数没有消掉随机方差。原 40 轮结果不是已收敛最优值。
diffusion_rl_checks.py 用独立 Gauss–Hermite 数值积分和中心差分验证 $T=1,2,8,16$ 及三个参数值;闭式信用/目标梯度最大差 $2.78\times10^{-11}$,固定动作的 log-prob score 差 $1.90\times10^{-10}$。真实扩散模型一般不满足这个线性收缩模型,不能把信用单调递增外推为普遍规律。
本次于 2026-10-30 核对论文作者仓库,并固定提交 1958463f020112c9a7bc85768d296daacc2e1b4b。以下只描述这一版本的 scripts/train.py、ddim_step_with_logprob 和默认配置,不推断其他版本行为。它们展示的数据流是:
[batch, steps + 1, C, H, W] 的 latents,以及 [batch, steps] 的旧策略 log-prob。这个实现细节解释了为什么训练内存明显大于普通推理:rollout 阶段要保存整条 latent 轨迹和旧 log-prob,更新阶段又要为当前时间步建立反向图。令 $B$ 为全体 rollout 样本数、$T$ 为每条轨迹采样步数。采样处理 $BT$ 个“样本 × 时间步”的网络输入;批大小为 $b_{\mathrm{mb}}$ 时约有 $BT/b_{\mathrm{mb}}$ 次 batch 调用,CFG 若合并双分支会加倍网络 batch,而不是必然加倍 Python 调用数。设更新采样步比例为 $f$、inner epochs 为 $K$,更新约处理 $KB\lfloor fT\rfloor$ 个输入的前向及反向;原默认 $f=1,K=1$。总成本是 rollout 加 update,不能把整个过程简单写成乘 $K$,也不包含奖励与 VAE 成本。梯度累积改变激活驻留、调用和有效 batch,不能消除这些网络输入的总工作量。
该提交的默认值是 LoRA=true、采样 50 步、$\eta=1$、guidance scale=5、训练 CFG=true、advantage clip=5、ratio clip=$10^{-4}$,不是本文教学 ratio 的 0.2。更新时传入保存的 prev_sample,原函数对它 detach,再沿当前均值求导;采样和更新的 CFG/网格/方差配置必须一致。训练里记录的 approx_kl 是平均 log-prob 差平方的一半,并不是高维联合 KL 的实算值。
对原完整 DDIM 函数及两个 helper,本次以 CPU 执行未经改写的 AST:两 dtype、三预测参数化、是否 clip 共 12 组,覆盖采样后动作重放、独立高斯密度与反向梯度;另执行完整 prompt 统计类和 trainer 原五条 loss 赋值。测试用 scheduler 属性与随机数 helper 作夹具,未运行预训练 Stable Diffusion、CUDA、分布式或 LoRA 图像训练。原函数的 $\pi$ 常数以 FP32 构造,即使输入为 FP64 也有约 $10^{-8}$ 归一化误差,证据保留实际精度,不把夹具称为完整工业复现。
工程里最值得先写清的不是 Trainer 类,而是一条样本在两个阶段之间必须携带什么。rollout 结束后,每条样本至少要保存 prompt 或其编码、全部时间步、从初始噪声到终点的 latents、旧策略逐步 log-prob、最终图片、原始奖励和经过标准化的优势。若使用 classifier-free guidance,还必须固定无条件分支、guidance scale 和文本编码方式;否则更新阶段重算出来的均值并不是采样时那条策略的均值。
update 阶段只取保存的当前 latent 和下一 latent,调用当前模型重算同一个已发生动作的 log-prob。这里绝对不能重新抽噪声:PPO 问的是“新策略对旧动作给出多大概率”,不是“新策略这次随机采到了什么”。这个区别在 token PPO 中很直观——不会在更新时重采一句回答——换成连续 latent 后却很容易藏在调度器接口里。
还应给 rollout 批次分配不可变的 sample id,并把 prompt、随机种子、reward 版本、模型 checkpoint 和 scheduler 配置写进元数据。这样一旦某个 batch 的 ratio 或奖励异常,能够重放出同一条轨迹并定位问题。只记录最后的 PNG 不够,因为不同 latent 轨迹可能解码成肉眼相近的图片,而策略梯度依赖的是当时每一步的概率。
若目标是按全局 rollout 统计来标准化,多卡训练必须先聚合所有进程的奖励;固定官方实现正是先 gather 再归一化后分回各卡。每卡分别归一化会定义不同的样本权重,不能冒充同一估计器。否则不同卡的 prompt 难度稍有偏差,就会得到不同的零点和尺度;随后再做梯度平均,相当于混合了多套不一致的目标。相反,若采用 per-prompt 统计器,应明确冷启动策略:某个 prompt 样本太少时回退到全局统计,原统计类在插入本批奖励后判断计数:不足 min_count 时用当前全批均值和 std,否则用 prompt 的有限缓冲区;两者 std 都加 $10^{-6}$。这不是纯历史、与当前动作独立的基线,也不保证小 std 不放大近乎相等的分差;全同奖励才给出零优势。
纯奖励最大化很容易把模型推离预训练分布。DPOK讨论的是参考分布保持。令 $p^0_\theta(x_0\mid c)$ 是终点边缘分布,$P_\theta(\tau\mid c)$ 是完整轨迹分布,二者不能混用。终点正则的目标可写成:
$$J_{\mathrm{end}}(\theta)=\mathbb E[R]-\beta\mathbb E_c D_{\mathrm{KL}}(p^0_\theta(\cdot\mid c)\Vert p^0_{\mathrm{ref}}(\cdot\mid c))$$
终点密度一般不可直接求。两策略共享初始噪声分布时,先把轨迹 log-ratio 展开,再逐步对当前策略动作积分,得到链式恒等式:
$$K_{\mathrm{traj}}=\mathbb E_{c,\tau\sim P_\theta}\sum_t D_{\mathrm{KL}}(\pi_\theta(\cdot\mid s_t)\Vert\pi_{\mathrm{ref}}(\cdot\mid s_t))$$
$$\mathbb E_c D_{\mathrm{KL}}(p^0_\theta\Vert p^0_{\mathrm{ref}})\leq K_{\mathrm{traj}}$$
不等式可由把完整轨迹分解成“终点边缘 × 给定终点的历史条件分布”看出:轨迹 KL 等于终点 KL 加一个非负的条件历史 KL。经同一个固定 VAE 解码后,图像 KL 也不超过 latent 轨迹 KL。这给出可算的上界正则,不是宣称边缘 KL 恰好等于逐步和。若同一状态上两高斯策略的协方差均为固定正的 $\sigma_t^2I$,局部项为:
$$D_{\mathrm{KL}}(\pi_\theta\Vert\pi_{\mathrm{ref}})=\frac{\|\mu_\theta-\mu_{\mathrm{ref}}\|^2}{2\sigma_t^2}$$
此处对所有 latent 坐标求和,不能偷换成均值;方差不同时还要加入方差比与 log 行列式项,确定性不同映射的 KL 可能无穷大。默认玩具中比较 $\theta=0.5$ 与 0,终点 KL=0.10499755、轨迹 KL=0.16,严格不相等。外层状态按当前策略分布积分;若只在固定旧 rollout 上对均值差反传,未计状态分布变化,那是局部代理,不是上式完整梯度。DPOK 使用正则化回报的策略梯度及直接正则项,不能用一个未定义的 KL loss 概括全部更新。
$\beta$ 越大,模型越保守;越小,越容易快速追逐奖励,也越容易丢失多样性或出现奖励投机。PPO clipping 约束的是一次更新相对旧策略的变化,reference KL 约束的是长期相对基座模型的漂移,两者作用并不相同。
如果奖励模型对像素可微,且采样器的整条计算图可以保留,就能把梯度从奖励直接穿过 VAE 与采样步骤反传到扩散模型。DRaFT 是 Direct Reward Fine-Tuning,原论文题名为 Directly Fine-Tuning Diffusion Models on Differentiable Rewards。DRaFT-K 只反传最后 K 步,通常是完整目标梯度的有偏近似:被截断前缀对共享参数的影响丢失。它需要可微奖励、可微解码及可处理的采样路径;参数被冻结的模块仍可能需要向输入传梯度,requires_grad_(False) 不等于把前向包在 no_grad()。DRaFT-LV 则针对 K=1 研究降方差,不能把“可微”直接等同于任意任务都低方差。
两条路线的选择很清楚:
它们可以共享同一个奖励定义,却不能把“对奖励求导”和“用奖励乘 log-prob”混写成一套推导。
不要只看 mean reward。最低限度还应记录:
如果奖励模型本身正在更新,还要给 reward 版本打快照。否则同一条训练曲线纵轴含义会变化,前后 reward 数字不可直接比较。
真实系统几乎不会只用一个分数。以文字生成图片为例,可以同时有提示词一致性、OCR 正确率、审美、人体结构和安全性五类信号。最直接的做法是加权求和:
$$R=w_{\text{prompt}}R_{\text{prompt}}+w_{\text{ocr}}R_{\text{ocr}}+w_{\text{aesthetic}}R_{\text{aesthetic}}-w_{\text{safety}}C_{\text{safety}}.$$
但“都放进来”不等于问题解决了。不同奖励的量纲与波动范围可能差几个数量级:OCR 是 0 或 1,审美模型可能落在 1 到 10,安全惩罚可能只有极少数样本非零。若不先校准,权重看似相近,实际梯度取决于奖励与各步 score 的相关性,而不只由奖励边缘方差决定。稳妥做法是先在固定基座模型上采一批校准集,观察每项分布,再做裁剪、标准化或分位数映射;训练期间同时画出每个子奖励,不能只保存加权总分。
还要区分“软目标”和“硬约束”。图片里文字少一个字,通常是可连续改进的软目标;生成违法内容则不应靠一个可被其他高分抵消的负权重处理。硬约束要有独立验收或可证明满足的机制;过滤、拒绝和约束优化各有失效边界,有限权重的拉格朗日惩罚也不自动保证每张样本满足约束。否则模型可能发现:只要审美分足够高,安全惩罚也值得承受。
多目标之间还会发生真实冲突。把 OCR 权重拉高,模型可能把文字做得巨大而破坏构图;只奖励检测器置信度,可能得到边缘锐利但不自然的目标。应当用 Pareto 视角看结果:同一批 checkpoints 同时比较各子目标和人工偏好,选择没有被某一维明显支配的方案,而不是盯着一条总 reward 曲线挑最高点。
第一,rollout 保存的状态数必须比转移 log-prob 数多 1;若二者相等,通常漏了初始噪声或终点 latent。第二,当新旧模型参数完全相同时,逐步 ratio 应非常接近 1,approximate KL 应接近 0;否则多半是调度器、CFG 分支、时间步索引或 log-prob 归约维度不一致。第三,打乱 batch 顺序不应改变同一个样本的 reward、prompt、latents 与 log-prob 对齐关系。异步奖励最容易在这里悄悄错位:训练仍会运行,均值甚至会上升,但模型学到的是别人的分数。
调试时先用一个可以解析求解的低维过程,就像本文代码;确认梯度方向、ratio 和 baseline 都符合预期,再接入大模型。直接在多卡图像训练里找符号错误,通常会把昂贵计算浪费在最便宜的 bug 上。
这些不变量也适合写进自动化测试:用固定随机种子的十几条轨迹做快速回归,每次升级 diffusers、调度器或混合精度设置后先跑它,再启动昂贵的正式训练。
论文名称很像时,先看梯度从哪里来:若公式里是 $R\nabla\log p_\theta$,属于 score-function 策略梯度;若是 $\nabla_{x_0}R$ 沿采样链反传,则属于可微奖励路线;若训练数据是静态偏好对,通常又是离线偏好优化问题。
噪声预测是策略的参数化中间量。DDPO 的动作通常记为实际采样出的下一 latent $x_{t-1}$,策略概率才是 $p_\theta(x_{t-1}\mid x_t,c)$。只有这样,保存动作、重算 log-prob 和构造新旧比率才是一致的。
轨迹 log-prob 是逐步 log-prob 的和。终点奖励乘的是整条和,因此每个去噪转移都有 score-function 梯度。最后一步可能贡献较大,但不是唯一有梯度的一步。
$\eta=0$ 时 $\sigma_t=0$,普通高斯 log-prob 不再成立。要么使用非零随机性,要么换成适合确定性路径的可微反传或其他估计器,不能简单给分母加一个 epsilon 就宣称理论等价。
轨迹比率在长链上方差巨大。DDPO 实践通常按去噪转移计算和裁剪 ratio;这是局部 surrogate;它能否稳定仍需实测,且真实联合比率与坐标平均比率的解释不同。
优势相同,不等于 score function 相同。噪声方差、预测残差、网络敏感度和调度器权重都随时间步变化,逐步梯度自然不同。
DDPO 只需要采样结果和标量奖励,不需要奖励梯度。不可微带来的问题是估计方差和样本成本,而不是“没有任何梯度”。
模型可能只学会利用 reward 的盲点。必须同时看独立评估、人工盲评、多样性、prompt 遵循和安全指标;最好用不同架构的 holdout reward 检查泛化。
文末代码只依赖 NumPy,建议依次改四个参数,每次固定随机种子并比较输出。
steps 从 8 改为 16预期状态 shape 从 (4096, 9) 变成 (4096, 17),log-prob shape 从 (4096, 8) 变成 (4096, 16)。用 python ddpo_minimal.py --steps 16 实跑;默认学习率/40轮下,10个训练seed的闭式终点奖励均值从8步的 -0.447762 变为16步的 -0.427833。这个收缩过程的均值系数和不可约方差也变了,因此不是只增加估计项的等条件对照,不能据此声称长链必更抖。
noise_std 从 0.45 降到 0.10用 python ddpo_minimal.py --noise-std 0.1 实跑;10 seed的闭式奖励均值为 -0.025906。它改善的一部分来自不可约方差降低,不能称为优化器更好。固定动作残差公式含 $1/\sigma^2$,但 on-policy 残差本身为 $\sigma z$,所以单步 score 的标准差随 $1/\sigma$ 缩放。零噪声不能直接套普通密度,脚本现在明确拒绝。
现在提供真实源码入口 python ddpo_minimal.py --mode raw 和 --mode centered,默认 standardized。无需修改不存在的变量行。10 seed固定40轮,centered与raw的闭式平均奖励分别为 -0.444155、-0.444253;不能由这组近似数值推断raw必更抖。日志里的 gradient_sample_std_raw_centered 仍在同一批上比较原始和仅减均值两种估计,不会因主训练切换mode就自动变成同一种算法。
在 PPO 诊断部分增大 new_theta - old_theta。固定 seed=123,diffusion_rl_checks.py 对差值0、0.1、0.5、1逐项实跑并记录ratio范围及clip fraction;较大差值在这个夹具里给出更高clip比例,但clipping不负责把已发生动作的ratio强行拉回区间。工程上这对应学习率过大、inner epochs 过多或 KL 约束过弱。
进一步可把终点奖励改成离散黑盒:例如 reward = (abs(x0-target) < 0.25)。score-function公式仍适用,但当前脚本内置的是平方奖励;若改奖励,需重新运行并记录命中率、方差与seed。本次没有把未执行的离散奖励训练写成已验证结果,稀疏到全零时归一化优势也为零。这正是从玩具例子走向 OCR 成功率、目标检测命中和人工反馈时遇到的现实问题。
这篇位于“对齐与强化学习”路径的第三段:
如果 DDIM 还不熟,先记住本文真正依赖的最小事实:它把 $x_t$ 和网络预测组合成下一步均值,并可用 $\eta$ 注入高斯随机性。从 DDIM 到高阶采样器 已展开采样公式、ODE/SDE 视角与高阶求解器。
最后用一句话收束:
DiffusionRL 不是把一个 PPO 套在图片外面,而是把每次去噪转移变成可计概率的动作,再让终点奖励沿整条轨迹分配信用。
09 节用到的脚本全文如下(ddpo_minimal.py、diffusion_rl_checks.py、make_figures.py)。复制到本地存成同名文件,按各脚本开头的依赖说明准备环境后即可运行。
"""NumPy-only toy DDPO: treat iterative denoising as a stochastic policy.
This is an algebra demo, not an image generator. A scalar latent follows a
short Gaussian reverse process. One parameter shifts every denoising mean,
and a terminal reward teaches the process to end near a target value.
"""
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True)
class ToyConfig:
steps: int = 8
batch_size: int = 4096
contraction: float = 0.72
action_scale: float = 0.18
noise_std: float = 0.45
target: float = 1.5
def __post_init__(self):
if not isinstance(self.steps, int) or self.steps < 1:
raise ValueError("steps must be a positive integer")
if not isinstance(self.batch_size, int) or self.batch_size < 2:
raise ValueError("batch_size must be at least two")
if not all(np.isfinite(x) for x in
(self.contraction, self.action_scale, self.noise_std, self.target)):
raise ValueError("configuration values must be finite")
if self.noise_std <= 0:
raise ValueError("a Gaussian policy needs strictly positive noise_std")
def gaussian_log_prob(value, mean, std):
"""Elementwise log N(value; mean, std^2)."""
if not np.isfinite(std) or std <= 0:
raise ValueError("std must be finite and positive")
return -0.5 * ((value - mean) / std) ** 2 - np.log(std * np.sqrt(2.0 * np.pi))
def rollout(theta, cfg, rng):
"""Sample x_T -> ... -> x_0 and retain every transition.
Array index 0 stores x_T; index cfg.steps stores x_0. The transition
mean is mu_theta = contraction * x_t + action_scale * theta.
"""
latents = np.empty((cfg.batch_size, cfg.steps + 1), dtype=np.float64)
means = np.empty((cfg.batch_size, cfg.steps), dtype=np.float64)
log_probs = np.empty((cfg.batch_size, cfg.steps), dtype=np.float64)
latents[:, 0] = rng.normal(size=cfg.batch_size)
for j in range(cfg.steps):
mean = cfg.contraction * latents[:, j] + cfg.action_scale * theta
next_latent = mean + cfg.noise_std * rng.normal(size=cfg.batch_size)
latents[:, j + 1] = next_latent
means[:, j] = mean
log_probs[:, j] = gaussian_log_prob(next_latent, mean, cfg.noise_std)
terminal = latents[:, -1]
rewards = -(terminal - cfg.target) ** 2
return latents, means, log_probs, rewards
def score_function(latents, means, cfg):
"""d log pi_theta(x_{t-1}|x_t) / d theta for every transition."""
residual = latents[:, 1:] - means
return residual * cfg.action_scale / (cfg.noise_std**2)
def policy_gradient(rewards, per_step_scores, mode="standardized"):
"""Score estimator; batch-dependent centering/scale are not unbiased baselines."""
centered = rewards - rewards.mean()
if mode == "standardized":
advantages = centered / (rewards.std() + 1e-8)
elif mode == "centered":
advantages = centered
elif mode == "raw":
advantages = rewards
else:
raise ValueError("mode must be standardized, centered or raw")
trajectory_scores = per_step_scores.sum(axis=1)
gradient = np.mean(advantages * trajectory_scores)
per_step_gradient = np.mean(advantages[:, None] * per_step_scores, axis=0)
return gradient, per_step_gradient, advantages
def evaluate(theta, cfg, seed):
rng = np.random.default_rng(seed)
latents, means, log_probs, rewards = rollout(theta, cfg, rng)
return {
"terminal_mean": float(latents[:, -1].mean()),
"reward_mean": float(rewards.mean()),
"latents": latents,
"means": means,
"log_probs": log_probs,
"rewards": rewards,
}
def train(cfg, updates=40, learning_rate=0.08, seed=7, mode="standardized"):
theta = 0.0
history = []
rng = np.random.default_rng(seed)
for update in range(updates + 1):
latents, means, _, rewards = rollout(theta, cfg, rng)
scores = score_function(latents, means, cfg)
gradient, per_step_gradient, advantages = policy_gradient(rewards, scores, mode=mode)
history.append((update, theta, latents[:, -1].mean(), rewards.mean(), gradient))
if update < updates:
theta += learning_rate * gradient
return theta, np.asarray(history), per_step_gradient, advantages, scores, rewards
def ppo_diagnostics(theta_old, theta_new, cfg, seed=123, clip_range=0.2):
"""Re-evaluate old transitions under a candidate new policy."""
rng = np.random.default_rng(seed)
latents, old_means, old_log_probs, rewards = rollout(theta_old, cfg, rng)
new_means = cfg.contraction * latents[:, :-1] + cfg.action_scale * theta_new
new_log_probs = gaussian_log_prob(latents[:, 1:], new_means, cfg.noise_std)
ratios = np.exp(new_log_probs - old_log_probs)
clipped = np.abs(ratios - 1.0) > clip_range
return rewards, ratios, clipped
if __name__ == "__main__":
np.set_printoptions(precision=6, suppress=True)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=["standardized", "centered", "raw"], default="standardized")
parser.add_argument("--steps", type=int, default=8)
parser.add_argument("--noise-std", type=float, default=0.45)
parser.add_argument("--seed", type=int, default=7)
args = parser.parse_args()
cfg = ToyConfig(steps=args.steps, noise_std=args.noise_std)
before = evaluate(theta=0.0, cfg=cfg, seed=2026)
theta, history, per_step_gradient, advantages, scores, rewards = train(cfg, seed=args.seed, mode=args.mode)
after = evaluate(theta=theta, cfg=cfg, seed=2026)
raw_gradient_samples = rewards * scores.sum(axis=1)
centered_gradient_samples = (rewards - rewards.mean()) * scores.sum(axis=1)
ppo_rewards, ratios, clipped = ppo_diagnostics(
theta_old=0.0, theta_new=0.5, cfg=cfg
)
print("trajectory_shape=", before["latents"].shape)
print("transition_log_prob_shape=", before["log_probs"].shape)
print("before_terminal_mean=", f"{before['terminal_mean']:.4f}")
print("before_reward_mean=", f"{before['reward_mean']:.4f}")
print("after_theta=", f"{theta:.4f}")
print("after_terminal_mean=", f"{after['terminal_mean']:.4f}")
print("after_reward_mean=", f"{after['reward_mean']:.4f}")
print("per_step_gradient=", np.round(per_step_gradient, 4))
print(
"gradient_sample_std_raw_centered=",
f"{raw_gradient_samples.std():.4f}",
f"{centered_gradient_samples.std():.4f}",
)
print(
"ppo_ratio_mean_min_max=",
f"{ratios.mean():.4f}",
f"{ratios.min():.4f}",
f"{ratios.max():.4f}",
)
print("ppo_clip_fraction=", f"{clipped.mean():.4f}")
print("history_first=", np.round(history[0, 1:4], 4))
print("history_last=", np.round(history[-1, 1:4], 4))
assert before["latents"].shape == (cfg.batch_size, cfg.steps + 1)
assert before["log_probs"].shape == (cfg.batch_size, cfg.steps)
assert after["reward_mean"] > before["reward_mean"]
assert abs(after["terminal_mean"] - cfg.target) < abs(before["terminal_mean"] - cfg.target)
assert np.all(np.isfinite(ratios))
"""Independent closed-form, quadrature and boundary checks for the scalar RL demo.
Requires NumPy only. This validates algebra, not image generation or GPU speed.
"""
from dataclasses import replace
from itertools import product
from pathlib import Path
import json
import numpy as np
from ddpo_minimal import ToyConfig, rollout, score_function, gaussian_log_prob, train, evaluate, ppo_diagnostics, policy_gradient
def analytic(theta, cfg):
a, b, t = cfg.contraction, cfg.action_scale, cfg.steps
powers = a ** np.arange(t)
k = b * powers.sum()
mean = k * theta
var = a ** (2 * t) + cfg.noise_std**2 * (powers**2).sum()
reward = -((mean - cfg.target)**2 + var)
credit = -2 * (mean - cfg.target) * b * powers[::-1]
return mean, var, reward, credit
def run_checks():
cfg = ToyConfig()
h, weights = np.polynomial.hermite.hermgauss(12)
z = np.sqrt(2) * h
weights = weights / np.sqrt(np.pi)
errors = []
for t, theta in product([1, 2, 8, 16], [0.0, 1.0, 3.0]):
c = replace(cfg, steps=t)
mean, var, reward, credit = analytic(theta, c)
fd = (analytic(theta+1e-5, c)[2]-analytic(theta-1e-5, c)[2])/2e-5
errors.append(abs(fd-credit.sum()))
for j in range(t):
coefficient = c.noise_std * c.contraction ** (t-1-j)
terminal = mean + coefficient*z[:, None] + np.sqrt(max(0, var-coefficient**2))*z[None, :]
score = c.action_scale*z[:, None]/c.noise_std
exact_quadrature = np.sum(weights[:, None]*weights[None, :]*(-(terminal-c.target)**2)*score)
errors.append(abs(exact_quadrature-credit[j]))
assert max(errors) < 1e-9
# Finite differences hold sampled states/actions fixed when differentiating log pi.
latents, means, logs, rewards = rollout(0.4, cfg, np.random.default_rng(17))
eps = 1e-5
fd = (gaussian_log_prob(latents[:, 1:], means+cfg.action_scale*eps, cfg.noise_std)-gaussian_log_prob(latents[:, 1:], means-cfg.action_scale*eps, cfg.noise_std))/(2*eps)
score_error = float(np.max(abs(fd-score_function(latents, means, cfg))))
assert score_error < 1e-8
_, equal_ratio, _ = ppo_diagnostics(0.4, 0.4, cfg)
assert np.array_equal(equal_ratio, np.ones_like(equal_ratio))
# Exact group enumeration shows the (G-1)/G centering factor and LOO equality.
baseline_rows = []
prob = 0.3
true_gradient = prob*(1-prob)
for group_size in [2, 3, 4]:
centered, loo = 0.0, 0.0
for actions in product([0., 1.], repeat=group_size):
r = np.array(actions)
scores = r-prob
mass = np.prod(np.where(r, prob, 1-prob))
centered += mass * np.mean((r-r.mean())*scores)
loo += mass * np.mean((r-(r.sum()-r)/(group_size-1))*scores)
assert abs(centered-(group_size-1)/group_size*true_gradient) < 1e-14
assert abs(loo-true_gradient) < 1e-14
baseline_rows.append(dict(group_size=group_size,true_gradient=true_gradient,centered=centered,loo=loo))
_, _, flat = policy_gradient(np.ones(4), np.ones((4, 2)))
assert np.array_equal(flat, np.zeros(4))
# At D=1024 the geometric ratio can stay inside 0.2 clipping while the joint ratio explodes.
joint_ratio, geometric_ratio = np.exp(10.), np.exp(10./1024)
assert joint_ratio > 20000 and abs(geometric_ratio-1)<0.2
# A deterministic parameter-dependent readout has a path derivative even with no stochastic actions.
deterministic_fd = ((0.7+eps)-(0.7-eps))/(2*eps)
assert abs(deterministic_fd-1)<1e-10
mean,var,_,_=analytic(0.,cfg)
k=cfg.action_scale*(cfg.contraction**np.arange(cfg.steps)).sum()
delta=.5
endpoint_kl=(k*delta)**2/(2*var)
trajectory_kl=cfg.steps*(cfg.action_scale*delta)**2/(2*cfg.noise_std**2)
assert endpoint_kl < trajectory_kl
trials=[]
for steps, noise, mode in [(8,.45,'standardized'),(16,.45,'standardized'),(8,.1,'standardized'),(8,.45,'centered'),(8,.45,'raw')]:
c=replace(cfg,steps=steps,noise_std=noise)
values=[]
for seed in range(10):
theta,history,*_=train(c,seed=seed,mode=mode)
ev=evaluate(theta,c,2026)
values.append(dict(seed=seed,theta=float(theta),sampled_reward=ev['reward_mean'],analytic_reward=analytic(theta,c)[2]))
trials.append(dict(steps=steps,noise_std=noise,mode=mode,runs=values,mean_analytic_reward=float(np.mean([v['analytic_reward']for v in values]))))
ratio_trials=[]
for delta in [.0,.1,.5,1.]:
_,ratios,clipped=ppo_diagnostics(0.,delta,cfg)
ratio_trials.append(dict(delta=delta,min=float(ratios.min()),max=float(ratios.max()),mean=float(ratios.mean()),clip_fraction=float(clipped.mean())))
rejected=[]
for kwargs in [dict(steps=0),dict(batch_size=1),dict(noise_std=0),dict(noise_std=-1),dict(target=float('nan'))]:
try:ToyConfig(**kwargs)
except ValueError:rejected.append(str(kwargs))
else:raise AssertionError(kwargs)
for std in [0.,-1.,float('nan')]:
try:gaussian_log_prob(0.,0.,std)
except ValueError:rejected.append('gaussian std='+str(std))
else:raise AssertionError(std)
return dict(passed=True,closed_form_quadrature_fd_max_error=float(max(errors)),score_fd_max_error=score_error,baseline_enumeration=baseline_rows,ratio_counterexample=dict(D=1024,joint_ratio=joint_ratio,geometric_ratio=geometric_ratio),deterministic_readout_gradient=deterministic_fd,kl_example=dict(endpoint=endpoint_kl,trajectory=trajectory_kl),analytic_default=dict(mean_coefficient=k,variance=var,optimal_theta=cfg.target/k),training_trials=trials,ratio_trials=ratio_trials,rejected_inputs=rejected,errors=[],warnings=[])
if __name__ == '__main__':
result=run_checks()
Path(__file__).with_name('validation_results.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n',encoding='utf8')
print('closed_form_quadrature_fd_max_error=',result['closed_form_quadrature_fd_max_error'])
print('score_fd_max_error=',result['score_fd_max_error'])
print('analytic_default=',result['analytic_default'])
print('kl_example=',result['kl_example'])
print('ratio_counterexample=',result['ratio_counterexample'])
for row in result['training_trials']:
print('training_10_seeds=',row['steps'],row['noise_std'],row['mode'],round(row['mean_analytic_reward'],6))
print('rejected_inputs=',len(result['rejected_inputs']))
print('ALL_CHECKS_PASSED')
"""Generate the explanatory figures for the DiffusionRL article.
Requires NumPy, Matplotlib and Pillow. The numerical chart reuses the exact
toy process from ddpo_minimal.py so the article and figure cannot drift apart.
"""
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from ddpo_minimal import ToyConfig, train
OUT = Path(__file__).resolve().parents[1] / "figures"
OUT.mkdir(exist_ok=True)
def _font(size, bold=False):
candidates = (
"C:/Windows/Fonts/msyhbd.ttc" if bold else "C:/Windows/Fonts/msyh.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/System/Library/Fonts/Hiragino Sans GB.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
)
for path in candidates:
try:
return ImageFont.truetype(path, size)
except OSError:
pass
raise RuntimeError("请安装中文字体后再生成 DiffusionRL 示意图")
def trajectory_mdp():
image = Image.new("RGB", (1800, 980), "#f8fafc")
draw = ImageDraw.Draw(image)
ink, blue, green, orange, muted = "#172033", "#2563eb", "#059669", "#ea580c", "#526078"
draw.text((90, 55), "把多步去噪看成一条 MDP 轨迹", font=_font(70, True), fill=ink)
draw.text((92, 150), "状态是当前 latent,动作是下一 latent 的采样,终点图像只得到一次奖励", font=_font(38), fill=muted)
draw.text((900, 285), "策略 πθ = pθ(next | current, c)", font=_font(32), fill=blue, anchor="mm")
xs = [170, 480, 790, 1100, 1410]
labels = ["xT", "xT−1", "xT−2", "…", "x0"]
subtitles = ["纯噪声", "较粗结构", "结构成形", "继续去噪", "最终样本"]
for i, (x, label, subtitle) in enumerate(zip(xs, labels, subtitles)):
color = blue if i < len(xs) - 1 else green
draw.rounded_rectangle((x - 105, 360, x + 105, 540), radius=36, fill="#ffffff", outline=color, width=6)
draw.text((x, 400), label, font=_font(46, True), fill=color, anchor="mm")
draw.text((x, 485), subtitle, font=_font(28), fill=muted, anchor="mm")
if i < len(xs) - 1:
draw.line((x + 110, 450, xs[i + 1] - 120, 450), fill=ink, width=5)
draw.polygon(
[(xs[i + 1] - 120, 450), (xs[i + 1] - 148, 433), (xs[i + 1] - 148, 467)],
fill=ink,
)
draw.line((1515, 450, 1620, 450), fill=orange, width=5)
draw.rounded_rectangle((1510, 630, 1735, 820), radius=32, fill="#fff7ed", outline=orange, width=5)
draw.text((1622, 675), "R(x0,c)", font=_font(44, True), fill=orange, anchor="mm")
draw.text((1622, 750), "终点奖励", font=_font(31), fill=muted, anchor="mm")
draw.line((1620, 450, 1620, 625), fill=orange, width=5)
draw.polygon([(1620, 625), (1603, 597), (1637, 597)], fill=orange)
draw.rounded_rectangle((90, 650, 1380, 850), radius=30, fill="#eef4ff")
draw.text((130, 685), "同一个优势 A 被广播到每一步:", font=_font(39, True), fill=ink)
draw.text((130, 750), "A · [grad log pθ(xT−1 | xT) + … + grad log pθ(x0 | x1)]", font=_font(39), fill=blue)
draw.text((130, 805), "奖励只在终点出现,但整条轨迹的 log-prob 都参与更新。", font=_font(31), fill=muted)
image.save(OUT / "diffusion_rl_mdp.png", optimize=True)
def cover():
image = Image.new("RGB", (1280, 720), "#081225")
draw = ImageDraw.Draw(image)
# A denoising trajectory that gradually changes from noise-like dots into a
# clean latent. Keeping this code-native makes the cover deterministic.
rng = np.random.default_rng(7)
stages = [190, 400, 610, 820, 1030]
palette = ["#60a5fa", "#38bdf8", "#2dd4bf", "#34d399", "#f59e0b"]
for i, x in enumerate(stages):
radius = 62
draw.ellipse((x - radius, 258 - radius, x + radius, 258 + radius), outline=palette[i], width=5)
spread = 47 - i * 7
for _ in range(38 - i * 4):
px = x + int(rng.normal(0, spread))
py = 258 + int(rng.normal(0, spread))
dot = 2 + i
draw.ellipse((px - dot, py - dot, px + dot, py + dot), fill=palette[i])
if i < len(stages) - 1:
draw.line((x + 72, 258, stages[i + 1] - 75, 258), fill="#94a3b8", width=4)
draw.polygon(
[(stages[i + 1] - 75, 258), (stages[i + 1] - 96, 246), (stages[i + 1] - 96, 270)],
fill="#94a3b8",
)
draw.rounded_rectangle((1068, 190, 1222, 326), radius=26, fill="#431407", outline="#f59e0b", width=4)
draw.text((1145, 258), "+R", font=_font(48, True), fill="#fbbf24", anchor="mm")
draw.text((92, 415), "把 RL 用到扩散模型上", font=_font(64, True), fill="#f8fafc")
draw.text((96, 507), "DiffusionRL · DDPO · 去噪轨迹 · 信用分配", font=_font(34), fill="#93c5fd")
draw.rounded_rectangle((94, 603, 426, 659), radius=25, fill="#1d4ed8")
draw.text((260, 631), "AIGC 基本功", font=_font(28, True), fill="#ffffff", anchor="mm")
image.save(OUT / "wechat_cover_diffusion_rl.png", optimize=True)
def training_and_credit():
cfg = ToyConfig()
_, history, per_step_gradient, _, _, _ = train(cfg)
updates = history[:, 0]
fig, axes = plt.subplots(1, 2, figsize=(11, 4.3))
ax = axes[0]
ax.plot(updates, history[:, 3], color="#2563eb", linewidth=2.5, label="mean terminal reward")
ax.set_xlabel("policy updates")
ax.set_ylabel("reward (higher is better)")
ax.grid(alpha=0.2)
ax2 = ax.twinx()
ax2.plot(updates, history[:, 2], color="#059669", linewidth=2.2, label="mean x0")
ax2.axhline(cfg.target, color="#059669", linestyle="--", alpha=0.45, label="target")
ax2.set_ylabel("terminal latent mean")
lines = ax.get_lines() + ax2.get_lines()
ax.legend(lines, [line.get_label() for line in lines], frameon=False, loc="center right")
ax.set_title("Standardized score update (seed=7)")
ax = axes[1]
steps = np.arange(cfg.steps)
ax.bar(steps, per_step_gradient, color=plt.cm.Blues(np.linspace(0.45, 0.95, cfg.steps)))
ax.set_xticks(steps, [f"{cfg.steps-i}→{cfg.steps-i-1}" for i in steps], rotation=40)
ax.set_xlabel("denoising transition")
ax.set_ylabel("standardized gradient estimate")
ax.grid(axis="y", alpha=0.2)
ax.set_title("Same reward, different credit per step")
fig.suptitle("Terminal reward becomes a trajectory-level policy gradient", fontsize=15, weight="bold")
fig.tight_layout()
fig.savefig(OUT / "diffusion_rl_training_credit.png", dpi=190)
plt.close(fig)
if __name__ == "__main__":
trajectory_mdp()
training_and_credit()
for name in (
"diffusion_rl_mdp.png",
"diffusion_rl_training_credit.png",
):
print(OUT / name)
评论 (0)