AI Wiki中文/EN

Neural energy models: lowering data energy is only half the job

能量模型的神经参数化

Train an exact four-state neural energy distribution and expose the normalization term through a constant-shift counterexample.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

An energy network assigns a scalar score to a configuration. Lower energy means greater compatibility under a chosen convention. To turn those scores into probabilities, every allowed configuration must compete through a normalizing constant. A network can make all data energies smaller without improving the distribution at all.

The Deep Learning chapter on partition functions derives the normalization gradient. Du and Mordatch study neural energies with approximate sampling on large continuous spaces. We use only four discrete states, so normalization and both gradient expectations can be computed exactly; sampling error cannot obscure the lesson.

Definitions and derivation

The state space contains the four pairs of signs. A two-hidden-unit tanh network has a 2×2 input matrix, two hidden biases, two output weights and one output bias: nine parameters in total.

Eθ(x)=v⊤tanh⁡(W⊤x+b)+c,pθ(x)=e−Eθ(x)Zθ,Zθ=∑x∈Xe−Eθ(x).E_\theta(x)=v^\top\tanh(W^\top x+b)+c,\qquad p_\theta(x)=\frac{e^{-E_\theta(x)}}{Z_\theta},\quad Z_\theta=\sum_{x\in\mathcal X}e^{-E_\theta(x)}.

The program uses row vectors, computing XW; the equation uses the equivalent column-vector convention. Finite energies over this finite nonempty state space guarantee a positive finite Z. For an unbounded continuous domain, a bounded tanh network alone generally does not give an integrable density: exp(−E) fails to decay sufficiently at infinity. One must specify a bounded domain, a suitable base measure or coercive energy. Our finite-state model avoids that separate issue explicitly.

Let q assign probabilities (0.4,0.1,0.1,0.4) in the order (−1,−1),(−1,+1),(+1,−1),(+1,+1). The mean negative log-likelihood and its gradient are:

L(θ)=Eq[Eθ(x)]+log⁡Zθ,∇θL=Eq[∇θEθ(x)]−Epθ[∇θEθ(x)].L(\theta)=\mathbb E_q[E_\theta(x)]+\log Z_\theta,\qquad \nabla_\theta L=\mathbb E_q[\nabla_\theta E_\theta(x)]- \mathbb E_{p_\theta}[\nabla_\theta E_\theta(x)].

For gradient descent, the data term tends to lower energies at data states, while the model expectation pushes back where the current model places probability. Both expectations depend on the same energy derivatives. The model distribution is used as the weighting in the exact gradient; there is no extra derivative through a separately sampled expectation in this formula.

The Jacobian follows the chain rule through tanh: output-weight derivatives are hidden activations; hidden-bias derivatives multiply output weights by 1−tanh²; input-weight derivatives additionally multiply the input coordinate. The program enumerates all four states and forms the weighted difference of Jacobians. Nine independent finite differences check the signs and parameter order.

A common energy shift is unidentifiable from probabilities:

Eθ′(x)=Eθ(x)+C,Zθ′=e−CZθ,pθ′=pθ,L′=L,L=H(q)+DKL(q∥pθ).E'_\theta(x)=E_\theta(x)+C,\quad Z'_\theta=e^{-C}Z_\theta, \quad p'_\theta=p_\theta,\quad L'=L,\qquad L=H(q)+D_{\rm KL}(q\|p_\theta).

The output bias c therefore has zero likelihood gradient, up to rounding. The entropy identity gives a second independent check: loss cannot be below H(q), and equality holds when the model matches q. Reducing the data-energy term alone can instead drive c toward negative infinity without changing probabilities.

Run the calculation

Run the complete Python 3.12 / NumPy 1.26.4 program:

import numpy as np

STATES=np.array([[-1.,-1],[-1,1],[1,-1],[1,1]])
TARGET=np.array([.4,.1,.1,.4])


def initial():return np.array([.7,-.4,.3,.6,.2,-.3,.5,-.7,.1])


def energy_jac(theta):
    t=np.asarray(theta,dtype=float)
    if t.shape!=(9,) or not np.isfinite(t).all():raise ValueError('Use nine finite neural energy parameters.')
    w=t[:4].reshape(2,2);b=t[4:6];v=t[6:8];hidden=np.tanh(STATES@w+b);energy=hidden@v+t[8];slope=(1-hidden**2)*v
    jac=np.concatenate([(STATES[:,:,None]*slope[:,None,:]).reshape(4,4),slope,hidden,np.ones((4,1))],axis=1)
    return energy,jac


def loss_grad(theta,target=TARGET):
    q=np.asarray(target,dtype=float)
    if q.shape!=(4,) or np.any(q<0) or not np.isclose(q.sum(),1):raise ValueError('Target must be a probability over the four states.')
    e,jac=energy_jac(theta);logits=-e;shift=float(logits.max());logz=shift+np.log(np.exp(logits-shift).sum());p=np.exp(logits-logz)
    return float(q@e+logz),(q-p)@jac,p


def train(steps=1200):
    t=initial();start=loss_grad(t)[0]
    for _ in range(steps):loss,g,p=loss_grad(t);t-=.1*g
    return t,start,loss_grad(t)


if __name__ == '__main__':
    t,start,(end,g,p)=train();print('NLL before/after',round(start,9),round(end,9),'target entropy',round(float(-TARGET@np.log(TARGET)),9));print('probabilities',p.round(9).tolist(),'target',TARGET.tolist())
    shifted=t.copy();shifted[-1]-=100;print('constant energy shift probability error',float(np.max(np.abs(loss_grad(shifted)[2]-p))),'offset gradient',round(float(g[-1]),12))
    e,_=energy_jac(t);se,_=energy_jac(shifted);print('data-only energy decreases',round(float(TARGET@e),9),round(float(TARGET@se),9),'NLL unchanged',round(loss_grad(shifted)[0]-end,12))

Actual output:

NLL before/after 1.541686468 1.193549604 target entropy 1.193549604
probabilities [0.4, 0.1, 0.1, 0.4] target [0.4, 0.1, 0.1, 0.4]
constant energy shift probability error 1.5543122344752192e-15 offset gradient 0.0
data-only energy decreases 0.70356347 -99.29643653 NLL unchanged -0.0

After 1,200 updates at step size 0.1, probabilities match the specified target to the displayed precision. NLL falls from 1.541686468 to 1.193549604, matching target entropy at nine decimals. Subtracting 100 from the common output bias lowers mean data energy by 100 but leaves NLL and probabilities unchanged to rounding. This is an exact-enumeration teaching model, not MCMC training.

For S finite states and P parameters, explicitly storing all Jacobians costs O(SP), with network-dependent evaluation work. Binary vectors of dimension d have 2ᵈ states, making enumeration quickly impractical. Continuous domains replace the sum with an integral. Sampling, noise-contrastive objectives and score-based alternatives address different parts of that difficulty; they have assumptions and errors absent from this four-state calculation.

When the method fails

Low energy alone is not a calibrated likelihood, because both the domain and normalization matter. Comparing raw energies from independently trained models is generally meaningless under the free additive offset. Even within one model, an out-of-distribution scoring claim needs direct evaluation rather than inference from an attractive energy landscape.

Du and Mordatch use finite Langevin chains and a replay buffer in a much larger setting. A finite chain is not automatically an exact model sample; mixing and discretization matter. Our successful exact fit gives no evidence about large-scale sample quality, mode coverage or computational efficiency.

Exercises with answers

  1. What happens after subtracting the same constant from every energy?

Answer 1: All unnormalized weights scale equally; normalized probabilities and NLL remain unchanged.

  1. Which expectation is missing in data-energy-only training?

Answer 2: The model-distribution expectation arising from log Z.

  1. Why is the output bias gradient zero?

Answer 3: Both data and model expectations of its derivative one equal one, so they cancel.

  1. Can this bounded tanh energy be normalized unchanged over all of R²?

Answer 4: Generally no. A bounded energy leaves exp(−E) bounded away from zero, so its integral over an infinite-volume domain diverges.

Sources and next steps

Deep Learning Chapter 18 opening and Section 18.1, Equations 18.1–18.15, supply the partition-gradient derivation and continuous-domain qualifications. Du–Mordatch physical page 3 defines neural energies and approximate likelihood gradients through Langevin samples; page 2 explains the replay-buffer setting. Our finite enumeration, gauge counterexample and gradient tests are original. See softmax for stable normalization and maximum likelihood for the fitting objective.

Make a prediction, then check

Why can lowering all data energies fail to improve likelihood?

Choose one answer

Learning objectives

  • Compute both likelihood-gradient expectations exactly.
  • Explain additive energy ambiguity and normalizability.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 18: Confronting the Partition Function
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. Implicit Generation and Modeling with Energy-Based Models — arXiv v2
    Yilun Du; Igor Mordatch · 2019

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

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.