Energy-based 模型Energy-Based Models
Energy-based 模型(EBM)只学一个打分函数:能量越低,输入越“合理”。它不要求网络输出一个归一化的概率,所以结构完全自由,多峰、跳变、几个约束相加都不在话下;代价是那个算不出来的归一化常数 Z。本节先用一条可以亲手塑形的能量曲线看清能量、温度和 Z 的关系,再用 Langevin 动力学从能量里采样,在浏览器里用对比散度实时训练一个二维 EBM,把几个能量相加来组合约束,最后看隐式行为克隆(Implicit BC)怎样把机器人策略写成“能量最低的动作”。 An energy-based model (EBM) learns just a scoring function: the lower the energy, the more "plausible" the input. It never asks the network to output a normalized probability, so its architecture is completely free, and multiple modes, jumps and sums of constraints are all easy; the price is the normalizing constant Z, which cannot be computed. This lesson first uses an energy curve you sculpt by hand to see how energy, temperature and Z relate, then samples from an energy with Langevin dynamics, trains a 2D EBM live in your browser with contrastive divergence, adds energies together to combine constraints, and finally shows how implicit behaviour cloning (Implicit BC) writes a robot policy as "the action of lowest energy".
1为什么机器人需要它Why robots need this
很多机器人问题天然是“打分”问题,而不是“给出答案”的问题。一个抓取好不好、一个动作和当前观测配不配、一段轨迹有没有撞上东西,判断起来都比直接写出“最好的那个”容易得多。Energy-based 模型就把这种判断本身当作模型:一个网络 \(E_\theta(x)\) 给每个候选 \(x\) 打一个实数分,分数越低越好(沿用物理里“能量越低越稳定”的说法)。要用它的时候,要么找能量最低的 \(x\)(优化),要么按 \(e^{-E}\) 的比例去采样(生成)。
这种写法有三个对机器人特别有用的性质。第一,多峰与跳变:同一个杯子可以从左边抓也可以从右边抓,能量地形上就是两个谷,不会像均方误差那样把两种答案平均成抓在空气里(19.2 节的开头讲过这个问题);观测稍有变化、最佳动作就从左跳到右,能量函数本身仍然是光滑的,只是谷底换了一个。第二,可组合:“抓得稳”的能量加上“够得着”的能量再加上“不撞桌子”的能量,就是同时满足三个条件的能量,每一项可以分开学、分开换。第三,结构自由:网络只需要输出一个数,不需要像 normalizing flow(19.3 节)那样可逆,也不需要像自回归模型(19.4 节)那样按顺序分解。
自由是有代价的。把能量变成概率要除以一个积分 \(Z=\int e^{-E(x)}dx\),在高维空间里没人算得出它;训练和采样都得绕开它,而绕开它的工具就是 4.9 节的 MCMC,以及本节的 Langevin 动力学。理解这一点,也就理解了为什么扩散模型(19.6 节)要转而学能量的梯度。2021 年的隐式行为克隆(Implicit BC,Florence 等)正是用 EBM 作为机器人策略,第 7 节会实际训练一个。
Many robot problems are naturally "scoring" problems rather than "produce the answer" problems. Whether a grasp is good, whether an action fits the current observation, whether a trajectory hits something: judging these is much easier than writing down "the best one" directly. An energy-based model takes that judgement itself as the model: a network \(E_\theta(x)\) gives each candidate \(x\) a real-valued score, and lower is better (borrowing the physics phrase "lower energy is more stable"). To use it, you either look for the \(x\) of lowest energy (optimization), or sample in proportion to \(e^{-E}\) (generation).
This formulation has three properties that are especially useful for robots. First, multiple modes and jumps: the same mug can be grasped from the left or from the right, which in the energy landscape is simply two valleys, and nothing averages the two answers into a grasp in mid-air the way mean squared error does (the problem at the start of Lesson 19.2); when a small change in the observation makes the best action jump from left to right, the energy function itself stays smooth, only the lowest valley changes. Second, composability: the energy for "stable grasp" plus the energy for "reachable" plus the energy for "does not hit the table" is the energy for satisfying all three, and each term can be learned and swapped separately. Third, free architecture: the network outputs a single number; it need not be invertible like a normalizing flow (Lesson 19.3) or factorize in order like an autoregressive model (Lesson 19.4).
The freedom has a price. Turning energy into probability means dividing by an integral \(Z=\int e^{-E(x)}dx\), which nobody can compute in high dimensions; both training and sampling must work around it, and the tools for that are the MCMC of Lesson 4.9 and the Langevin dynamics of this lesson. Understanding this also explains why diffusion models (Lesson 19.6) learn the gradient of the energy instead. Implicit behavioural cloning (Implicit BC; Florence et al., 2021) uses an EBM as a robot policy, and Section 7 trains one.
2直觉:能量是地形,概率是积水Intuition: energy is terrain, probability is where the water collects
把能量 \(\hl{E}{E(x)}\) 想成一片地形,把概率想成下雨后积在低处的水。能量和概率之间的换算是 Boltzmann 分布(也叫 Gibbs 分布):
Think of the energy \(\hl{E}{E(x)}\) as a terrain, and of probability as the water that collects in the low places after rain. The conversion between energy and probability is the Boltzmann distribution (also called the Gibbs distribution):
指数保证概率为正,再低的谷也不会变成负概率;除以 \(Z\) 让总概率为 1。温度 \(T\) 决定地形有多“陡”:\(T\) 小,水几乎全挤进最低的那个谷;\(T\) 大,水漫开,各处差不多。两点的概率比只取决于能量差,\(p(x_1)/p(x_2)=e^{-(E(x_1)-E(x_2))/T}\),与 \(Z\) 无关;整片地形一起抬高一个常数,概率一点也不变,只有 \(Z\) 跟着变。6.11 节的 MPPI 给每条采样轨迹的权重 \(\exp(-f/\lambda)\) 就是这个分布,\(\lambda\) 就是温度。
下图的横轴是夹爪绕竖直轴的偏航角 \(x\),被关节限位限制在 \([-3,3]\) rad 内(区间有界,所以 \(Z\) 总是有限的)。两个谷是两种都能抓牢的朝向。拖动琥珀色的控制点重塑地形,滑块改温度。
The exponential keeps probabilities positive, however deep a valley is; dividing by \(Z\) makes the total probability 1. The temperature \(T\) sets how "steep" the terrain is: at small \(T\) nearly all the water squeezes into the lowest valley; at large \(T\) it spreads out and every place gets about the same. The probability ratio of two points depends only on the energy difference, \(p(x_1)/p(x_2)=e^{-(E(x_1)-E(x_2))/T}\), independent of \(Z\); raise the whole terrain by a constant and the probabilities do not change at all, only \(Z\) does. The weight \(\exp(-f/\lambda)\) that MPPI in Lesson 6.11 gives each sampled trajectory is exactly this distribution, with \(\lambda\) as the temperature.
In the figure below the horizontal axis is the gripper's yaw angle \(x\) about the vertical axis, limited by the joint to \([-3,3]\) rad (the interval is bounded, so \(Z\) is always finite). The two valleys are two orientations that both give a firm grasp. Drag the amber control points to reshape the terrain; the slider sets the temperature.
- 保持 \(T=1\)(0.95 到 1.05 之间),把一个谷的最低点拖得比另一个谷低 1(差在 0.9 到 1.1 之间)。读数里两个谷底的密度比约为 \(e\approx2.72\)(若加深的是左谷,则约为 \(1/e\)),可两半的质量比却不是:只拖一个控制点,谷底变低的同时也变窄了,而质量还要乘上谷的宽度。Keep \(T=1\) (between 0.95 and 1.05) and drag the bottom of one valley 1 lower than the other (a difference between 0.9 and 1.1). In the readout the density ratio of the two valley bottoms is about \(e\approx2.72\) (about \(1/e\) if you deepened the left one), but the mass ratio of the two halves is not: dragging a single control point makes the valley narrower as well as deeper, and mass is density times width.
- 让两个谷底相差至少 0.5,再把温度降到 0.5 以下,直到较深那一半的质量超过 95%(相差 0.5 时大约要 \(T\approx0.15\))。再把温度升到 3:两半的质量又回到接近一半一半。Make the two valley bottoms differ by at least 0.5, then lower the temperature below 0.5 until the deeper half holds more than 95% of the mass (with a difference of 0.5 that takes about \(T\approx0.15\)). Then raise the temperature to 3: the two halves are back near fifty-fifty.
能量只有相对意义:比较两个点只需要它们的能量差,所以“哪个动作更好”“从哪里往哪里走”都不需要 \(Z\)。需要 \(Z\) 的是“这个 \(x\) 的概率到底是多少”和“整体的质量怎么分配”:一个谷的质量既看它有多深,也看它有多宽(第一个任务),而宽度信息藏在积分里。这正是后面训练 EBM 时最难的地方。
Energy has only relative meaning: comparing two points needs only their energy difference, so "which action is better" and "which way to move" never need \(Z\). What needs \(Z\) is "what exactly is the probability of this \(x\)" and "how is the total mass shared out": a valley's mass depends on how wide it is as well as how deep (the first task), and the width information lives inside the integral. That is exactly the hard part of training an EBM later on.
3动手:沿着能量下山,再加一点噪声Play: roll downhill on the energy, plus a little noise
一维时可以把整条曲线算出来再积分;二维以上,网格的格子数随维数指数增长,只能采样。4.9 节的 Metropolis 算法只用到能量差,可以直接用在 EBM 上,但它的提议是盲目的随机步。能量有梯度(3.2 节),梯度指向能量升高最快的方向,所以更聪明的做法是先朝 \(-\nabla E\) 走一小步,再加一点高斯噪声。这就是 Langevin 动力学(未校正的 Langevin 算法,ULA):
In 1D the whole curve can be computed and integrated; from 2D on, the number of grid cells grows exponentially with dimension, and we have to sample. The Metropolis algorithm of Lesson 4.9 uses only energy differences and works directly on an EBM, but its proposals are blind random steps. The energy has a gradient (Lesson 3.2), which points where the energy rises fastest, so a smarter move is a small step along \(-\nabla E\) followed by a little Gaussian noise. That is Langevin dynamics (the unadjusted Langevin algorithm, ULA):
只有前一项就是 6.3 节的梯度下降,所有点都滚进最近的谷底停下来;只有后一项就是随机游走,到处乱跑。两项按这个比例(噪声方差是步长的 2 倍)放在一起,步长 \(\eta\to0\) 时,点的长期分布恰好是 \(p\propto e^{-E}\)(第 6 节说明原因)。注意 \(\nabla_xE\) 里没有 \(Z\):常数的梯度是零。下图的能量都是已知的解析函数,所以“真实答案”可以用网格精确算出来,用来检验采样器。
The first term alone is the gradient descent of Lesson 6.3: every point rolls into the nearest valley and stops. The second alone is a random walk that wanders everywhere. Put together in this proportion (noise variance twice the step size), the long-run distribution of the points is exactly \(p\propto e^{-E}\) as the step \(\eta\to0\) (Section 6 explains why). Note that \(\nabla_xE\) contains no \(Z\): the gradient of a constant is zero. The energies in the figure below are known analytic functions, so the "true answer" can be computed exactly on a grid and used to check the sampler.
- “两个谷”,把噪声关掉,按“重置”后运行:所有链滚进谷底,平均梯度 \(|\nabla E|\) 降到 0.05 以下,紫色箭头消失。读数里左谷的比例停在约 0.53,而不是 0.70:没有噪声时,比例由“吸引域”的面积决定,与概率无关。On "two wells", switch the noise off, press "Reset" and run: every chain rolls into a valley bottom, the mean gradient \(|\nabla E|\) drops below 0.05 and the purple arrows vanish. The readout's left-well fraction stops at about 0.53, not 0.70: without noise the fractions are set by the areas of the basins of attraction, not by probability.
- “两个谷”,噪声打开、均匀初始化、\(\eta=0.01\),重置后运行至少 1000 步:左谷的比例(最近 200 步的平均)落在 0.70 ± 0.04 之内。把 \(\eta\) 降到 0.002 再试:同样的步数后比例只到约 0.60,明显不够:链要靠噪声慢慢翻过两谷之间的坡。On "two wells" with noise on, uniform init and \(\eta=0.01\), reset and run for at least 1000 steps: the left-well fraction (averaged over the last 200 steps) lands within 0.70 ± 0.04. Try again with \(\eta=0.002\): after the same number of steps the fraction is only about 0.60, clearly short, because the chains need the noise to carry them slowly over the ridge between the wells.
- “圆环”,把 \(\eta\) 调到 0.03 以上并运行 300 步:链的半径标准差超过精确值(0.149)的 1.6 倍,步子太大让分布被“抹宽”了。再打开 MALA(同样的 \(\eta\)),继续运行 300 步:标准差回到精确值的 ±15% 之内,代价是一部分提议被拒绝(看接受率)。On "ring", set \(\eta\) above 0.03 and run 300 steps: the standard deviation of the chains' radii exceeds 1.6 times the exact value (0.149); steps that are too big smear the distribution out. Then switch MALA on (same \(\eta\)) and run another 300 steps: the standard deviation returns to within ±15% of the exact value, at the cost of rejecting some proposals (see the acceptance rate).
- “高势垒”,初始化选“全在左谷”,\(\eta\le0.01\),重置后运行至少 2000 步:精确答案是一半一半,可左谷里仍有 95% 以上的链。梯度把链困在谷里,噪声又太小,翻不过 \(e^{-E}\) 只有峰值的几万分之一的势垒。On "high barrier", choose init "all in left well", keep \(\eta\le0.01\), reset and run at least 2000 steps: the exact answer is fifty-fifty, yet more than 95% of the chains are still in the left well. The gradient keeps them in the valley and the noise is too small to carry them over a barrier where \(e^{-E}\) is only a few times \(10^{-5}\) of its peak.
(1) 噪声不是瑕疵,是采样的一半:没有它,Langevin 就退化成梯度下降,只找谷底,而且落在哪个谷由起点决定(第一个任务)。(2) 每一步噪声都比漂移大:漂移 \(\propto\eta\),噪声 \(\propto\sqrt\eta\),步长小时噪声占主导;但漂移是累加的、方向一致,噪声会互相抵消,所以 10 步之后蓝色箭头才和紫色箭头可比。(3) 步长有偏:有限的 \(\eta\) 下 ULA 的平稳分布并不是 \(p\);在曲率为 \(c\) 的二次谷里,它的方差是精确值的 \(1/(1-\eta c/2)\) 倍(第 6 节),所以默认的 \(\eta=0.01\) 在圆环上已经宽了约 15%。MALA 在每一步后加一次 Metropolis 检验(4.9 节),把偏差完全去掉。(4) 混合:谷与谷之间的势垒越高,链越难翻过去;高维的 EBM 里这是常态,也是 19.6 节扩散模型先加噪声再逐步去噪的动机之一。
(1) The noise is not a flaw, it is half of sampling: without it Langevin degenerates into gradient descent, which only finds valley bottoms, and which valley depends on the starting point (the first task). (2) Each step's noise is larger than its drift: the drift is \(\propto\eta\) and the noise \(\propto\sqrt\eta\), so at small steps the noise dominates; but the drift accumulates in a consistent direction while the noise partly cancels, which is why after 10 steps the blue arrows are comparable to the purple ones. (3) The step size biases the result: at finite \(\eta\) the stationary distribution of ULA is not \(p\); in a quadratic valley of curvature \(c\) its variance is \(1/(1-\eta c/2)\) times the exact one (Section 6), so the default \(\eta=0.01\) is already about 15% too wide on the ring. MALA adds a Metropolis test (Lesson 4.9) after each step and removes the bias completely. (4) Mixing: the higher the barrier between valleys, the harder it is for chains to cross; in high-dimensional EBMs this is the normal situation, and it is one motivation for the diffusion models of Lesson 19.6, which add noise first and then remove it step by step.
4训练:把数据处压低,把模型样本处抬高Training: push down on the data, push up on the model's samples
现在能量不再是给定的,而是一个网络 \(E_\theta(x)\),要从数据里学。最自然的目标是 4.6 节的最大似然:让数据的 \(\log p_\theta(x)=-E_\theta(x)-\log Z(\theta)\) 尽量大。第一项好办,第二项里的 \(Z\) 算不出来,但它的梯度可以写成一个期望(第 6 节推导):
Now the energy is no longer given: it is a network \(E_\theta(x)\) to be learned from data. The most natural objective is the maximum likelihood of Lesson 4.6: make the data's \(\log p_\theta(x)=-E_\theta(x)-\log Z(\theta)\) as large as possible. The first term is easy; the \(Z\) in the second cannot be computed, but its gradient can be written as an expectation (derived in Section 6):
读法很直白:在数据点上把能量压低,在模型自己的样本上把能量抬高。两者一样多的时候,也就是模型的样本分布和数据分布一致时,梯度为零。第一项叫“正相”,用一批数据就能估计;第二项叫“负相”,需要从当前模型里采样,而这正是上一节的 Langevin。每走一步参数就做一次长链 MCMC 太贵了,Hinton(2002)的对比散度(CD)只跑 \(K\) 步短链;Tieleman(2008)的持续对比散度(PCD)让链在参数更新之间不重置,接着上一轮的位置继续走,因为参数每步只变一点,上一轮的样本已经接近当前模型的分布。下图用 PCD 训练一个 2→32→32→1 的 MLP(GELU 激活):一个容量 1024 的样本缓冲区,每次取 32 条链跑 \(K\) 步 Langevin(\(\eta=0.006\)),其中 5% 从均匀噪声重新开始;损失再加一项 \(0.1\,(E^2_{\text{data}}+E^2_{\text{neg}})\),防止能量整体漂移(Du 与 Mordatch,2019 的做法)。
It reads plainly: push the energy down on data points, push it up on the model's own samples. When the two balance, that is when the model's samples are distributed like the data, the gradient is zero. The first term is the "positive phase", estimated with a batch of data; the second is the "negative phase", which needs samples from the current model, and that is exactly the Langevin of the previous section. Running a long MCMC chain for every parameter update is too expensive, so the contrastive divergence (CD) of Hinton (2002) runs only \(K\) short steps; the persistent contrastive divergence (PCD) of Tieleman (2008) does not reset the chains between parameter updates but continues from where they were, because the parameters change only a little per step and the old samples are already close to the current model's distribution. The figure trains a 2→32→32→1 MLP (GELU activations) with PCD: a buffer of 1024 samples, from which each step takes 32 chains and runs \(K\) Langevin steps (\(\eta=0.006\)), 5% of them restarted from uniform noise; the loss also has a term \(0.1\,(E^2_{\text{data}}+E^2_{\text{neg}})\) that stops the energies drifting as a whole (the recipe of Du and Mordatch, 2019).
- 选“圆环”,按“训练”:开始时琥珀点散在各处,青色的低能量区先缩到数据附近,琥珀点随后被吸到环上。训练到测试 NLL 低于 1.10(真实分布是 0.92;默认种子约 500 步)。Choose "ring" and press "Train": at first the amber dots are scattered everywhere, the cyan low-energy region shrinks onto the data, and the amber dots are then drawn onto the ring. Train until the test NLL is below 1.10 (the true distribution has 0.92; about 500 steps with the default seed).
- 换成“两簇”,训练至少 200 步,直到 NLL 低于 0.60 且读数里大簇所占的概率质量在 0.65 到 0.85 之间(真实值 0.75)。两个簇都被覆盖,比例也大致对,不会像 19.2 节的 GAN 那样坍缩到一个簇上。Switch to "two clusters" and train for at least 200 steps, until the NLL is below 0.60 and the readout's probability mass of the big cluster is between 0.65 and 0.85 (the true value is 0.75). Both clusters are covered with roughly the right proportions; nothing collapses onto one cluster as a GAN can (Lesson 19.2).
继续训练下去,大簇的质量会在 0.75 上下摆动(默认种子在 1000 到 2000 步之间约为 0.74 到 0.92),NLL 也在 0.5 到 0.6 之间起伏:负相只用了 32 个样本,PCD 的梯度噪声很大,实际训练会逐渐减小学习率。也请看右侧读数里的 \(\bar E_{\text{data}}\) 与 \(\bar E_{\text{neg}}\):它们是损失的两项,差值时正时负,不是进度条,真正的进度要看 NLL(这里是因为二维才能精确算出 \(\log Z\);高维时只能看样本)。“链”切到“每次从噪声重来”就是不持续的短链 CD:在这个二维例子里它也能学到还不错的能量(默认种子下,800 到 1200 步之间 NLL 在 1.05 上下,持续链在 1.0 上下),但只有约一半的负样本到达圆环附近(持续链超过 90%),其余停在半路;Nijkamp 等(2019)研究过这种“不收敛的短链”学到的到底是什么。
Train on and the big cluster's mass swings around 0.75 (about 0.74 to 0.92 between steps 1000 and 2000 with the default seed) while the NLL wanders between 0.5 and 0.6: the negative phase uses only 32 samples, so the PCD gradient is very noisy, and real training gradually lowers the learning rate. Look too at \(\bar E_{\text{data}}\) and \(\bar E_{\text{neg}}\) in the readout: they are the two terms of the loss, their difference flips sign, and they are not a progress bar; real progress is the NLL (available here only because \(\log Z\) can be computed exactly in 2D; in high dimensions you can only look at samples). Switching "chains" to "restart from noise" gives non-persistent short-run CD: in this 2D example it also learns a fairly decent energy (with the default seed, between steps 800 and 1200 its NLL hovers around 1.05, against about 1.0 for persistent chains), but only about half of the negatives get near the ring (over 90% with persistent chains), the rest stopping halfway; Nijkamp et al. (2019) studied what such "non-convergent short-run" chains actually learn.
5另一个视角:能量可以相加Another view: energies add up
两个能量相加,对应的概率相乘:\(e^{-(E_1+E_2)}=e^{-E_1}e^{-E_2}\)。概率相乘就是“与”:只有两个模型都认为合理的地方,乘积才大。Hinton 把这叫作专家乘积(product of experts)。反过来,对两个概率求和是“或”,在能量上就是 \(-\log(e^{-E_1}+e^{-E_2})\)。显式的采样器(GAN 的生成器、VAE 的解码器)很难这样拼装:两个生成器的样本没法“相乘”;可两个能量相加之后,同一个 Langevin 采样器照样能用,因为它只需要总能量的梯度。
下图是一个抓取的例子:\(\hl{ring}{E_{\text{grasp}}}\) 是绕杯子一圈的抓取位置(圆环能量,半径 0.7),\(\hl{reach}{E_{\text{box}}}\) 说的是杯子右侧有个箱子挡着,\(x_1>-0.55\) 的位置会撞上(一个光滑的“台阶”:\(\operatorname{softplus}(8(x_1+0.55))\))。总能量是 \(E=E_{\text{grasp}}+\lambda E_{\text{box}}\),两者从没一起训练过。
Adding two energies multiplies the corresponding probabilities: \(e^{-(E_1+E_2)}=e^{-E_1}e^{-E_2}\). Multiplying probabilities is an "AND": the product is large only where both models find things plausible. Hinton called this a product of experts. Conversely, summing two probabilities is an "OR", which in energies is \(-\log(e^{-E_1}+e^{-E_2})\). Explicit samplers (a GAN's generator, a VAE's decoder) are hard to assemble like this: there is no way to "multiply" the samples of two generators; but once two energies are added, the same Langevin sampler still works, because it only needs the gradient of the total energy.
The figure is a grasping example: \(\hl{ring}{E_{\text{grasp}}}\) is the grasp positions around a mug (a ring energy of radius 0.7), and \(\hl{reach}{E_{\text{box}}}\) says that a box stands to the right of the mug, so positions with \(x_1>-0.55\) collide with it (a smooth "step": \(\operatorname{softplus}(8(x_1+0.55))\)). The total energy is \(E=E_{\text{grasp}}+\lambda E_{\text{box}}\); the two terms were never trained together.
- 在“与”模式下按“运行”,\(\lambda=0\) 时约一半的链落在红色区域里。把 \(\lambda\) 提高到 3 左右,运行 300 步以上:撞箱子的比例低于 2%,同时 90% 以上的链仍在环上,它们都挤到了环的左半边。In "AND" mode press "Run": at \(\lambda=0\) about half the chains sit in the red region. Raise \(\lambda\) to about 3 and run for 300 steps or more: fewer than 2% collide with the box while more than 90% are still on the ring, all crowded onto its left half.
- 切到“或”模式,运行 500 步以上:两个杯子的圆环上各有至少 35% 的链。Switch to "OR" mode and run for 500 steps or more: each mug's ring holds at least 35% of the chains.
概率:EBM 是一个没有归一化的密度,\(p\propto e^{-E}\)。 优化:能量是代价函数,取 \(T\to0\) 时分布塌到 \(\arg\min E\) 上,“采样”退化为“优化”;14.3 节的 CHOMP 和 6.13 节的轨迹优化都在最小化一个轨迹的能量。 物理:Langevin 动力学原本描述的是在势能 \(E\) 中受摩擦和热噪声作用的粒子,平衡时它的位置正服从 Boltzmann 分布。 分类:任何一个分类器的 logit 都可以读成能量,\(p(y|x)\propto e^{-E(x,y)}\) 里的 \(Z(x)\) 只是对有限个类别求和,所以分类器是最容易归一化的 EBM(Grathwohl 等,2020,把这一点用到了极致)。 score:\(-\nabla_xE=\nabla_x\log p\),叫作 score,与 \(Z\) 无关;19.6 节的扩散模型直接学 score,绕开了能量本身。
Probability: an EBM is an unnormalized density, \(p\propto e^{-E}\). Optimization: the energy is a cost function, and as \(T\to0\) the distribution collapses onto \(\arg\min E\) and "sampling" degenerates into "optimization"; CHOMP in Lesson 14.3 and the trajectory optimization of Lesson 6.13 both minimize an energy over trajectories. Physics: Langevin dynamics originally describes a particle in a potential \(E\) subject to friction and thermal noise, whose position at equilibrium follows exactly the Boltzmann distribution. Classification: the logits of any classifier can be read as energies; in \(p(y|x)\propto e^{-E(x,y)}\) the \(Z(x)\) is only a sum over finitely many classes, so a classifier is the easiest EBM to normalize (Grathwohl et al., 2020, took this idea a long way). Score: \(-\nabla_xE=\nabla_x\log p\) is called the score and does not involve \(Z\); the diffusion models of Lesson 19.6 learn the score directly and bypass the energy itself.
6再看数学The math
提示:把鼠标悬停在公式中带底色的符号上,图中对应的元素会被高亮(FIG 1 的能量曲线和 \(Z\) 的面积,FIG 2 的蓝色与紫色箭头,FIG 3 的数据点和负样本,FIG 4 的圆环和红色区域,FIG 5 的能量最低动作)。Tip: hover the highlighted symbols in the formulas; the matching elements light up in the figures (FIG 1's energy curve and the area \(Z\), FIG 2's blue and purple arrows, FIG 3's data points and negatives, FIG 4's ring and red region, FIG 5's lowest-energy actions).
模型与配分函数The model and the partition function
EBM 由一个参数化的能量 \(E_\theta:\mathcal X\to\mathbb R\) 定义:
An EBM is defined by a parametrized energy \(E_\theta:\mathcal X\to\mathbb R\):
\(Z\) 在统计物理里叫配分函数。只要积分有限(例如 \(\mathcal X\) 有界、\(E_\theta\) 连续,或者 \(E_\theta\) 在远处增长得够快),这就是一个合法的密度。温度只是把能量除以 \(T\),可以吸收进 \(E_\theta\) 里,所以学习时通常取 \(T=1\)。离散的 \(x\)(类别、token)积分换成求和;类别少时 \(Z\) 直接算得出来,这就是 softmax(16.1 节)。
In statistical physics \(Z\) is called the partition function. As long as the integral is finite (for example \(\mathcal X\) bounded and \(E_\theta\) continuous, or \(E_\theta\) growing fast enough far away), this is a valid density. Temperature merely divides the energy by \(T\) and can be absorbed into \(E_\theta\), so for learning one usually takes \(T=1\). For discrete \(x\) (classes, tokens) the integral becomes a sum; with few classes \(Z\) can be computed outright, and that is the softmax (Lesson 16.1).
最大似然的梯度The maximum-likelihood gradient
对 \(\log Z\) 求导,把导数移进积分(2.2 节的链式法则):
Differentiate \(\log Z\) and move the derivative inside the integral (the chain rule of Lesson 2.2):
代入 \(-\log p_\theta(x)=E_\theta(x)+\log Z(\theta)\) 并对数据取平均,就得到第 4 节的 \(\hl{pos}{\mathbb E_{p_{\text{data}}}[\nabla_\theta E_\theta]}-\hl{neg}{\mathbb E_{p_\theta}[\nabla_\theta E_\theta]}\)。两点值得记住。第一,整个困难被集中到“从 \(p_\theta\) 采样”这一件事上;样本越不准,负相的估计偏差越大。第二,实现上常写一个“替身损失” \(\frac1B\sum_i E_\theta(x_i)-\frac1B\sum_i E_\theta(x'_i)\),其中负样本 \(x'_i\) 被当作常数(不对它反向传播),它对 \(\theta\) 的梯度就是上式的估计。这个替身损失的数值没有意义:它可以是任何正负数,FIG 3 的读数显示了这一点。
Substituting \(-\log p_\theta(x)=E_\theta(x)+\log Z(\theta)\) and averaging over the data gives Section 4's \(\hl{pos}{\mathbb E_{p_{\text{data}}}[\nabla_\theta E_\theta]}-\hl{neg}{\mathbb E_{p_\theta}[\nabla_\theta E_\theta]}\). Two things are worth remembering. First, the entire difficulty is concentrated in one task: "sample from \(p_\theta\)"; the worse the samples, the more biased the negative phase. Second, implementations usually write a "surrogate loss" \(\frac1B\sum_i E_\theta(x_i)-\frac1B\sum_i E_\theta(x'_i)\) in which the negatives \(x'_i\) are treated as constants (no backpropagation through them); its gradient with respect to \(\theta\) is an estimate of the expression above. The value of this surrogate loss means nothing: it can be any positive or negative number, as FIG 3's readout shows.
Langevin 动力学为什么采到 \(p\)Why Langevin dynamics samples \(p\)
离散更新 \(x_{k+1}=x_k-\eta\nabla E+\sqrt{2\eta}\,\boldsymbol\xi\) 是随机微分方程 \(dx=-\nabla E(x)\,dt+\sqrt2\,dW\) 的欧拉–丸山离散化(时间步 \(\eta\),对照 2.5 节的欧拉法)。这个方程的密度 \(\rho(x,t)\) 服从 Fokker–Planck 方程
The discrete update \(x_{k+1}=x_k-\eta\nabla E+\sqrt{2\eta}\,\boldsymbol\xi\) is the Euler–Maruyama discretization (time step \(\eta\); compare Euler's method in Lesson 2.5) of the stochastic differential equation \(dx=-\nabla E(x)\,dt+\sqrt2\,dW\). Its density \(\rho(x,t)\) obeys the Fokker–Planck equation
当 \(\rho\propto e^{-E}\) 时 \(E+\log\rho\) 是常数,右边为零,所以 \(p\) 是平稳分布:漂移把概率往谷底推,扩散把它往外摊,两者恰好平衡。噪声系数必须是 \(\sqrt{2\eta}\):换成别的倍数,平稳分布就变成别的温度下的 \(e^{-E/T}\)。很多 EBM 实现(包括 Du 与 Mordatch 2019)把步长和噪声分开调,噪声远小于 \(\sqrt{2\eta}\),那就已经不是在 \(T=1\) 下采样了,更像是带一点抖动的梯度下降。
有限步长的偏差:在一维二次谷 \(E=\tfrac c2x^2\) 里,更新是 \(x_{k+1}=(1-\eta c)x_k+\sqrt{2\eta}\,\xi\),平稳方差 \(v\) 满足 \(v=(1-\eta c)^2v+2\eta\),解得 \(v=\frac1c\cdot\frac{1}{1-\eta c/2}\),而精确值是 \(1/c\)。\(\eta c\to2\) 时方差发散(6.3 节梯度下降的稳定界)。FIG 2 的圆环曲率 \(c=1/0.15^2\approx44\):\(\eta=0.035\) 时 \(\eta c\approx1.56\),标准差约是精确值的 2.1 倍,图中测得约 2 倍。
MALA(Metropolis 校正的 Langevin,Roberts 与 Tweedie,1996)把 Langevin 的一步当作 4.9 节 Metropolis–Hastings 的提议 \(q(x'|x)=\mathcal N\big(x'; x-\eta\nabla E(x),\,2\eta I\big)\),以概率
When \(\rho\propto e^{-E}\), \(E+\log\rho\) is constant and the right-hand side vanishes, so \(p\) is the stationary distribution: the drift pushes probability towards the valley bottoms, the diffusion spreads it out, and the two balance exactly. The noise coefficient must be \(\sqrt{2\eta}\): with another multiple, the stationary distribution becomes \(e^{-E/T}\) at some other temperature. Many EBM implementations (including Du and Mordatch 2019) tune the step and the noise separately, with noise far below \(\sqrt{2\eta}\); that is no longer sampling at \(T=1\), but closer to gradient descent with a little jitter.
Finite-step bias: in a 1D quadratic valley \(E=\tfrac c2x^2\) the update is \(x_{k+1}=(1-\eta c)x_k+\sqrt{2\eta}\,\xi\), and the stationary variance \(v\) satisfies \(v=(1-\eta c)^2v+2\eta\), so \(v=\frac1c\cdot\frac{1}{1-\eta c/2}\), whereas the exact value is \(1/c\). As \(\eta c\to2\) the variance blows up (the stability limit of gradient descent in Lesson 6.3). FIG 2's ring has curvature \(c=1/0.15^2\approx44\): at \(\eta=0.035\), \(\eta c\approx1.56\) and the standard deviation should be about 2.1 times the exact one; the figure measures about 2.
MALA (the Metropolis-adjusted Langevin algorithm; Roberts and Tweedie, 1996) treats a Langevin step as the proposal \(q(x'|x)=\mathcal N\big(x'; x-\eta\nabla E(x),\,2\eta I\big)\) of the Metropolis–Hastings algorithm of Lesson 4.9 and accepts it with probability
满足细致平衡,所以对任何步长都没有偏差;\(Z\) 在比值里消掉了。步长大了接受率下降,链走得慢;FIG 2 的圆环在 \(\eta=0.035\) 时接受率约 0.6。
This satisfies detailed balance, so there is no bias at any step size; \(Z\) cancels in the ratio. Larger steps lower the acceptance rate and slow the chain; on FIG 2's ring at \(\eta=0.035\) the acceptance rate is about 0.6.
不需要采样的训练方法Training methods that avoid sampling
Score matching(Hyvärinen,2005)比较的是梯度而不是密度:最小化 \(\tfrac12\mathbb E_{p_{\text{data}}}\|\nabla_x\log p_\theta-\nabla_x\log p_{\text{data}}\|^2\),\(\nabla_x\log p_\theta=-\nabla_xE_\theta\) 与 \(Z\) 无关;分部积分后未知的 \(\nabla_x\log p_{\text{data}}\) 也能消掉。它的去噪版本是 19.6 节扩散模型的训练目标。噪声对比估计(NCE,Gutmann 与 Hyvärinen,2010)训练一个分类器区分数据和一个已知的噪声分布 \(q\),把 \(\log Z\) 当作一个可学的参数;数据与噪声样本一样多时,分类器的最优 logit 恰是 \(\log p_{\text{data}}-\log q\)(19.2 节的密度比技巧)。第 7 节的 IBC 用的是它的多类版本 InfoNCE(18.3 节的对比学习也用它):对每个数据对 \((o,a)\) 采 \(N\) 个反例动作 \(\tilde a_j\),
Score matching (Hyvärinen, 2005) compares gradients instead of densities: minimize \(\tfrac12\mathbb E_{p_{\text{data}}}\|\nabla_x\log p_\theta-\nabla_x\log p_{\text{data}}\|^2\), where \(\nabla_x\log p_\theta=-\nabla_xE_\theta\) does not involve \(Z\); integrating by parts also removes the unknown \(\nabla_x\log p_{\text{data}}\). Its denoising version is the training objective of the diffusion models of Lesson 19.6. Noise-contrastive estimation (NCE; Gutmann and Hyvärinen, 2010) trains a classifier to tell data from a known noise distribution \(q\), treating \(\log Z\) as a learnable parameter; with equal numbers of data and noise samples, the optimal logit of the classifier is exactly \(\log p_{\text{data}}-\log q\) (the density-ratio trick of Lesson 19.2). Section 7's IBC uses its multi-class version InfoNCE (also used by the contrastive learning of Lesson 18.3): for each data pair \((o,a)\), draw \(N\) counter-example actions \(\tilde a_j\) and minimize
这就是一个 \(N+1\) 类的 softmax 交叉熵,正确答案是示教动作。反例从动作范围内均匀采样时,分母是对 \(Z(o)=\int e^{-E_\theta(o,a)}da\) 的蒙特卡洛估计(差一个常数因子),\(N\) 越大越准。动作维数高时,均匀反例绝大多数落在显然很差的地方,提供的信息很少,需要的 \(N\) 随维数急剧增长。
This is just an \((N+1)\)-way softmax cross-entropy whose correct answer is the demonstrated action. With counter-examples drawn uniformly over the action range, the denominator is a Monte Carlo estimate of \(Z(o)=\int e^{-E_\theta(o,a)}da\) (up to a constant factor), more accurate for larger \(N\). When the action has many dimensions, nearly all uniform counter-examples land in obviously bad places and carry little information, so the \(N\) required grows steeply with dimension.
组合Composition
乘积 \(p_1(x)p_2(x)/Z_{12}\) 的能量是 \(\hl{ring}{E_1}+\hl{reach}{E_2}\)(常数不计);混合 \(\pi_1p_1+\pi_2p_2\) 的能量是 \(-\log\big(\pi_1e^{-E_1}/Z_1+\pi_2e^{-E_2}/Z_2\big)\)。注意“或”需要知道每个分量的 \(Z_i\)(或者接受由它们决定的比例):FIG 4 的两个圆环按周长归一化,正是为了让两个杯子各得一半。“与”则不需要任何 \(Z\),这是 EBM 组合最常用的形式。条件模型 \(E_\theta(o,a)\) 也是同一个思路:观测 \(o\) 固定时,它是动作上的一个能量。
The product \(p_1(x)p_2(x)/Z_{12}\) has energy \(\hl{ring}{E_1}+\hl{reach}{E_2}\) (up to a constant); the mixture \(\pi_1p_1+\pi_2p_2\) has energy \(-\log\big(\pi_1e^{-E_1}/Z_1+\pi_2e^{-E_2}/Z_2\big)\). Note that the OR needs each component's \(Z_i\) (or accepts the proportions they imply): FIG 4 normalizes its two rings by their circumferences precisely so that each mug gets half. The AND needs no \(Z\) at all, which is why it is the most common way to compose EBMs. A conditional model \(E_\theta(o,a)\) follows the same idea: with the observation \(o\) fixed, it is an energy over actions.
与其他生成模型对比Compared with other generative models
| 模型Model | 采样Sampling | 密度Density | 网络限制Network constraint |
|---|---|---|---|
| EBM | MCMC,慢MCMC, slow | 只到一个常数(\(Z\) 未知)only up to a constant (\(Z\) unknown) | 无,输出一个数none: outputs one number |
| GAN(19.2)GAN (19.2) | 一次前向one forward pass | 无none | 需要一个对抗的判别器needs an adversarial discriminator |
| VAE(19.1)VAE (19.1) | 一次前向one forward pass | 下界(ELBO)a lower bound (ELBO) | 编码器加解码器encoder plus decoder |
| Flow(19.3)Flow (19.3) | 一次前向one forward pass | 精确exact | 可逆,雅可比行列式易算invertible, cheap Jacobian determinant |
| 扩散(19.6)Diffusion (19.6) | 多步去噪many denoising steps | 可经 ODE 计算,较贵via an ODE, expensive | 输出与输入同维的 scoreoutputs a score of the input's size |
7机器人中的它:隐式行为克隆In robotics: implicit behavioural cloning
普通的行为克隆(22.1 节)学一个显式策略 \(\hat a=\pi_\theta(o)\),用均方误差回归示教动作。Florence 等(CoRL 2021)的隐式行为克隆(Implicit BC,IBC)改学一个能量 \(E_\theta(o,a)\),策略是
Ordinary behavioural cloning (Lesson 22.1) learns an explicit policy \(\hat a=\pi_\theta(o)\) by regressing the demonstrated actions with mean squared error. The implicit behavioural cloning (Implicit BC, IBC) of Florence et al. (CoRL 2021) learns an energy \(E_\theta(o,a)\) instead, and the policy is
用上一节的 InfoNCE 训练,反例在动作范围内采样。推理时没有梯度下降可以“一步到位”,原文给了几种做法:无梯度优化(DFO:撒一批动作,按 \(\operatorname{softmax}(-E)\) 重采样,加上逐步缩小的噪声,重复几轮,与 6.11 节的 CEM 同一路数)、维数更高时逐维进行的自回归版本,以及 Langevin MCMC。下面是一个推冰球的例子:观测 \(o\) 是冰球相对前方立柱的横向偏移,动作 \(a\) 是推杆经过立柱时的横向位置。冰球明显偏左(\(o<-0.2\))时示教者总从左边绕,\(a=-0.55+0.25\,o\);明显偏右(\(o>0.2\))时总从右边绕,\(a=0.55+0.25\,o\);中间那一段左右各一半。这既有多峰(中间段),又有跳变(\(o=\pm0.2\) 处)。同时训练两个模型:显式的 1→32→32→1 MLP(MSE),和隐式的 \(E_\theta(o,a)\),一个 2→32→32→1 MLP(InfoNCE,每个示教 16 个均匀反例)。
It is trained with the InfoNCE of the previous section, with counter-examples sampled over the action range. At inference there is no single gradient step that "gets there", and the paper gives several options: derivative-free optimization (DFO: scatter a batch of actions, resample them according to \(\operatorname{softmax}(-E)\), add noise that shrinks every round, and repeat a few times, in the same spirit as the CEM of Lesson 6.11), an autoregressive version that goes one dimension at a time for higher-dimensional actions, and Langevin MCMC. Below is a puck-pushing example: the observation \(o\) is the puck's lateral offset from a post ahead of it, and the action \(a\) is the pusher's lateral position as it passes the post. When the puck is clearly to the left (\(o<-0.2\)) the demonstrator always passes on the left, \(a=-0.55+0.25\,o\); clearly to the right (\(o>0.2\)), always on the right, \(a=0.55+0.25\,o\); in the middle band, half and half. That has both multiple modes (the middle band) and jumps (at \(o=\pm0.2\)). Two models train side by side: an explicit 1→32→32→1 MLP (MSE) and an implicit \(E_\theta(o,a)\), a 2→32→32→1 MLP (InfoNCE, 16 uniform counter-examples per demonstration).
- 按“训练”,至少 200 步,直到隐式策略的无效动作率不超过 2%,而 MSE 的仍在 20% 以上(默认种子下两者很快分别稳定在约 0% 和 25%)。看左图:红线在中间段穿过两簇示教之间的空白,琥珀点则在中间段里的某处从一簇跳到另一簇。Press "Train" and run at least 200 steps, until the implicit policy's invalid-action rate is at most 2% while MSE's is still above 20% (with the default seed they soon settle at about 0% and 25%). Look at the left plot: in the middle band the red line runs through the empty gap between the two clusters of demonstrations, while the amber dots jump from one cluster to the other somewhere inside the middle band.
- 训练 200 步以上后,把 \(o\) 拖进中间段(\(|o|\le0.2\)),找一个位置让右图的 \(p(a|o)\) 有两个峰、两个模式各占至少 25% 的概率。再按“运行 DFO”:到第 3 轮时通常大部分候选动作(常常 80% 以上)挤在同一个峰上,最后只选出一个动作:DFO 做的是优化,不是采样。After 200 or more training steps, drag \(o\) into the middle band (\(|o|\le0.2\)) and find a spot where the right plot's \(p(a|o)\) has two peaks, each mode holding at least 25% of the probability. Then press "Run DFO": by round 3 most candidates (often 80% or more) usually crowd onto one peak, and a single action is chosen; DFO optimizes, it does not sample.
为什么 \(\arg\min\) 能跳变?能量 \(E_\theta(o,a)\) 是光滑的,但“哪个谷更低”可以随 \(o\) 突然换边:两个谷的深度连续地此消彼长,交叉的那一刻最低点从一个谷跳到另一个谷。显式网络要表示跳变,只能把一个连续函数掰得很陡;而在多峰的中间段,MSE 的最优解是条件均值,正好落在两个模式之间的空地(这里就是撞上立柱)。IBC 论文把这一点作为主要论据,并在它的实验里报告:隐式策略总体上优于 MSE 和混合密度网络(MDN)这类常见的显式策略。
Why can the \(\arg\min\) jump? The energy \(E_\theta(o,a)\) is smooth, but "which valley is lower" can switch sides abruptly as \(o\) changes: the depths of the two valleys trade off continuously, and at the moment they cross the minimum jumps from one valley to the other. An explicit network can represent a jump only by bending a continuous function very steeply; and in the multimodal middle band the MSE optimum is the conditional mean, which lands exactly in the empty space between the two modes (here: straight into the post). The IBC paper makes this its central argument, and in its experiments reports that implicit policies generally outperform common explicit ones such as MSE and mixture density networks (MDN).
Implicit BC(Florence、Lynch、Zeng、Ramirez、Wahid、Downs、Wong、Lee、Mordatch、Tompson,CoRL 2021)在仿真的推方块等任务、D4RL 的人类示教任务和真实机器人上做了实验;真实机器人从人类示教中学会了接触丰富的操作,包括组合复杂度很高的任务和要求约 1 mm 精度的插入。 它的继承者:Diffusion Policy(Chi 等,RSS 2023,22.2 节)把 IBC 当作主要的比较对象之一,指出 InfoNCE 需要用反例估计 \(Z\),训练不稳定;扩散模型学的是 score \(\nabla_a\log p(a|o)\),与 \(Z\) 无关,从而保留了多峰表达能力又避开了这个问题。这条“从能量到 score”的路线就是 19.6 节的内容。 “对动作打分再优化”早有先例:Levine 等(2018)的抓取网络预测“给定图像和一个运动指令,抓取会成功”的概率,再用 CEM 挑选指令(这个网络在 16.1 节提到过);QT-Opt(Kalashnikov 等,CoRL 2018)用 CEM 求 \(\arg\max_aQ(s,a)\)。把 \(-Q\) 或负的成功概率看作能量,它们都是隐式策略。 轨迹的能量:CHOMP(14.3 节)把轨迹的代价当作能量做梯度下降,MPPI(6.11 节、13.4 节)按 \(\exp(-\text{代价}/\lambda)\) 给采样轨迹加权,就是在一个 Boltzmann 分布下求平均。
Implicit BC (Florence, Lynch, Zeng, Ramirez, Wahid, Downs, Wong, Lee, Mordatch and Tompson, CoRL 2021) ran experiments on simulated tasks such as block pushing, on the human-demonstration tasks of D4RL, and on real robots, which learned contact-rich manipulation from human demonstrations, including tasks of high combinatorial complexity and an insertion requiring about 1 mm precision. Its successors: Diffusion Policy (Chi et al., RSS 2023; Lesson 22.2) takes IBC as one of its main baselines and points out that InfoNCE has to estimate \(Z\) with counter-examples, which makes training unstable; a diffusion model learns the score \(\nabla_a\log p(a|o)\), which does not involve \(Z\), and so keeps the multimodal expressiveness while avoiding that problem. This "from energy to score" route is the subject of Lesson 19.6. "Score the actions, then optimize" has precedents: the grasping network of Levine et al. (2018) predicts the probability that "given the image and a motor command, the grasp succeeds" and picks commands with CEM (the network is mentioned in Lesson 16.1); QT-Opt (Kalashnikov et al., CoRL 2018) uses CEM to find \(\arg\max_aQ(s,a)\). Read \(-Q\) or the negative success probability as an energy, and both are implicit policies. Energies over trajectories: CHOMP (Lesson 14.3) runs gradient descent on a trajectory cost treated as an energy, and MPPI (Lessons 6.11 and 13.4) weights sampled trajectories by \(\exp(-\text{cost}/\lambda)\), which is averaging under a Boltzmann distribution.
8常见误区Common pitfalls
能量整体加一个常数,分布不变(FIG 1 的“全部 +0.5”),所以“这个动作的能量是 −3”本身不说明任何事;只有同一个模型、同一个条件下的能量差有意义。条件模型尤其要小心:\(E_\theta(o_1,a)\) 和 \(E_\theta(o_2,a')\) 的 \(Z(o)\) 不同,直接比较两个不同观测下的能量,并不能说明哪个情形下动作更“有把握”。要做异常检测或置信度判断,需要先归一化或另行校准。
Adding a constant to the whole energy leaves the distribution unchanged (FIG 1's "all +0.5"), so "this action has energy −3" says nothing on its own; only energy differences within the same model and the same condition mean something. Conditional models need special care: \(E_\theta(o_1,a)\) and \(E_\theta(o_2,a')\) have different \(Z(o)\), so comparing energies under two different observations does not tell you in which situation the action is more "certain". For anomaly detection or confidence you must normalize or calibrate first.
对比散度的替身损失 \(\bar E_{\text{data}}-\bar E_{\text{neg}}\) 可正可负,接近零既可能是模型已经很好,也可能是负样本根本没采好、两边一起错(FIG 3 的读数)。要看的是样本本身:用长一点的链从模型里采样,看它们像不像数据;低维时还可以像 FIG 3 一样直接算似然。另外,没有正则项时能量的尺度可能一路漂走,数值溢出。
The contrastive-divergence surrogate loss \(\bar E_{\text{data}}-\bar E_{\text{neg}}\) can be positive or negative, and a value near zero may mean the model is good or that the negatives were sampled badly and both sides are wrong together (FIG 3's readout). Look at the samples themselves: draw from the model with somewhat longer chains and see whether they look like data; in low dimensions you can also compute the likelihood directly, as FIG 3 does. Also, without a regularizer the energy scale can drift away and overflow.
三种情况下都不是:步长有限时分布被抹宽(FIG 2 的圆环,MALA 可修正);噪声被调得比 \(\sqrt{2\eta}\) 小时采的是低温分布;链太短或势垒太高时,比例由起点决定(FIG 2 的高势垒)。这些偏差会直接进入训练:负相的样本错了,梯度就错了。
In three situations they are not: at a finite step the distribution is smeared out (FIG 2's ring; MALA fixes this); with noise set below \(\sqrt{2\eta}\) you sample a colder distribution; with chains too short or barriers too high, the proportions are set by the starting points (FIG 2's high barrier). These errors flow straight into training: wrong negative-phase samples mean a wrong gradient.
隐式策略取的是能量最低的动作,而训练只在示教和反例处约束了能量。数据覆盖不到的地方,网络可能恰好给出很低的能量,优化器会准确地找到这些“假谷”,输出离谱的动作。限制动作范围、让反例覆盖整个范围(IBC 的做法)、或者在线收集失败数据补成反例,都是对策。显式策略不会这样“钻空子”,但它只能平均。
An implicit policy takes the lowest-energy action, and training constrains the energy only at the demonstrations and the counter-examples. Where the data does not reach, the network may happen to give very low energy, and the optimizer will find exactly these "spurious valleys" and output absurd actions. Bounding the action range, letting the counter-examples cover the whole range (IBC's approach), or collecting failures online as extra counter-examples are the remedies. An explicit policy cannot "exploit loopholes" like this, but it can only average.
本节的每个图都是一维或二维,网格积分、均匀反例、16 个反例就够了。动作是 7 维关节角加夹爪、还要预测一段动作序列时,均匀反例几乎全在无关的地方,InfoNCE 需要非常多的反例;DFO 的候选也要指数级地增多;Langevin 要在许多谷之间混合。这正是 Diffusion Policy 报告 IBC 训练不稳定的背景,也是扩散和 flow matching(19.6、19.7 节)成为主流动作生成器的原因之一。
Every figure in this lesson is 1D or 2D, where grid integration, uniform counter-examples and 16 of them suffice. When the action is 7 joint angles plus a gripper, and a whole sequence of them is predicted, uniform counter-examples land almost entirely in irrelevant places and InfoNCE needs a great many of them; DFO's candidates must grow exponentially too; Langevin must mix between many valleys. That is the background to Diffusion Policy reporting unstable IBC training, and one reason diffusion and flow matching (Lessons 19.6 and 19.7) became the mainstream action generators.
9小练习Check yourself
10延伸阅读Further reading
- Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato & F. J. Huang, A Tutorial on Energy-Based Learning, in Predicting Structured Data, MIT Press, 2006 — 把能量当作“兼容性打分”的经典综述,涵盖各种损失函数the classic survey of energies as "compatibility scores", covering many loss functions
- G. E. Hinton, Training Products of Experts by Minimizing Contrastive Divergence, Neural Computation, 2002 — 专家乘积与对比散度products of experts and contrastive divergence
- T. Tieleman, Training Restricted Boltzmann Machines using Approximations to the Likelihood Gradient, ICML 2008 — 持续对比散度(PCD)persistent contrastive divergence (PCD)
- G. O. Roberts & R. L. Tweedie, Exponential Convergence of Langevin Distributions and Their Discrete Approximations, Bernoulli, 1996 — Langevin 算法的收敛性与 MALAconvergence of Langevin algorithms, and MALA
- M. Welling & Y. W. Teh, Bayesian Learning via Stochastic Gradient Langevin Dynamics, ICML 2011 — 把 Langevin 噪声加进 SGDadding Langevin noise to SGD
- A. Hyvärinen, Estimation of Non-Normalized Statistical Models by Score Matching, JMLR, 2005; M. Gutmann & A. Hyvärinen, Noise-Contrastive Estimation: A New Estimation Principle for Unnormalized Statistical Models, AISTATS 2010 — 两种绕开 \(Z\) 的训练方法two training methods that avoid \(Z\)
- Y. Du & I. Mordatch, Implicit Generation and Modeling with Energy Based Models, NeurIPS 2019 — 用 Langevin 与样本缓冲区训练深度 EBMtraining deep EBMs with Langevin and a replay buffer
- E. Nijkamp, M. Hill, S.-C. Zhu & Y. N. Wu, Learning Non-Convergent Non-Persistent Short-Run MCMC Toward Energy-Based Model, NeurIPS 2019 — 短链 MCMC 训练出来的到底是什么what short-run MCMC training actually learns
- W. Grathwohl, K.-C. Wang, J.-H. Jacobsen, D. Duvenaud, M. Norouzi & K. Swersky, Your Classifier is Secretly an Energy Based Model and You Should Treat it Like One, ICLR 2020 — 把分类器读成 EBMreading a classifier as an EBM
- Y. Song & D. P. Kingma, How to Train Your Energy-Based Models, arXiv:2101.03288, 2021 — MCMC、score matching 与 NCE 三类训练方法的综述,通向扩散模型a survey of MCMC, score-matching and NCE training, leading to diffusion models
- Y. Du, S. Li & I. Mordatch, Compositional Visual Generation with Energy Based Models, NeurIPS 2020 — 用能量相加组合概念composing concepts by adding energies
- P. Florence, C. Lynch, A. Zeng, O. Ramirez, A. Wahid, L. Downs, A. Wong, J. Lee, I. Mordatch & J. Tompson, Implicit Behavioral Cloning, CoRL 2021 — EBM 作为机器人策略EBMs as robot policies
- C. Chi, S. Feng, Y. Du, Z. Xu, E. Cousineau, B. Burchfiel & S. Song, Diffusion Policy: Visuomotor Policy Learning via Action Diffusion, RSS 2023 — 与 IBC 的对比,以及从能量到 score 的转向the comparison with IBC, and the turn from energies to scores