Module contents
Lesson 14 of 28Core 105 min

Energy-based models

Define energy-based distributions and derive maximum-likelihood gradients as positive and negative phases. Approximate the negative phase with contrastive divergence, persistent chains and Langevin dynamics, study RBMs and short-run sampling, and reinterpret a classifier as a joint energy model.

After this lesson you can

  • Derive the EBM log-likelihood gradient and explain contrastive-divergence bias.
  • Implement an RBM with CD-k and PCD and compare both against exact likelihood in a tiny model.
  • Train a convolutional EBM with Langevin dynamics and a restart buffer on the GPU.
  • Distinguish equilibrium EBM samples from an implicit short-run-chain generator.
  • Reinterpret a classifier as a joint EBM and explain the benefits.

Before you start

Learning a landscape rather than a direct sampling recipe

Imagine observations as points on terrain. Low energy marks favored regions and high energy makes it harder for a chain to remain there. The terrain can be evaluated at a point without knowing its probability: that requires summing or integrating contributions across the entire space. In a complex model, that sum is the price avoided when drawing the landscape.

An arbitrary scalar function on RD\mathbb R^D does not guarantee a distribution: if energy is zero everywhere, the integral is infinite. On a compact region, continuous energy is bounded and its exponential integrable; an open bounded domain alone is insufficient if energy diverges toward negative infinity at its boundary. On the whole space a term growing sufficiently in the tails can be added. Adding a constant to all energies multiplies ZZ by the corresponding factor and leaves pθp_\theta unchanged. An isolated energy value is therefore not a probability and cannot directly compare models with different normalizations.

Two forces in the likelihood gradient

If differentiation under the integral is valid and support does not depend on θ\theta, then

∇θlog⁡Zθ=1Zθ∫−∇θEθ(x)e−Eθ(x) dx=−Epθ[∇θEθ(X)].\nabla_\theta\log Z_\theta =\frac{1}{Z_\theta}\int -\nabla_\theta E_\theta(x)e^{-E_\theta(x)}\,dx =-\mathbb E_{p_\theta}[\nabla_\theta E_\theta(X)].

Thus, for an observation xx,

∇θlog⁡pθ(x)=−∇θEθ(x)+Epθ[∇θEθ(X)].\nabla_\theta\log p_\theta(x) =-\nabla_\theta E_\theta(x)+\mathbb E_{p_\theta}[\nabla_\theta E_\theta(X)].

In likelihood ascent, the first term encourages lower energy on data. The second compensates through model samples; without it, lowering every energy together does not identify a distribution. These contributions are the positive and negative phases. The second is difficult precisely because it depends on the normalized distribution being learned.

InteractiveSculpting an energy landscape

The points in the minibatch are projected onto the model’s energy surface. Height represents E(x)/2 and the color scale adjusts to each surface.

  • Positive data points
  • Negative samples

This EBM uses 25 Gaussian radial basis functions and the quadratic term 0.15‖x‖². It was trained for 400 steps on 4096 examples from a known mixture. The positive phase adds the feature gradient for the data. The negative phase subtracts the gradient for the persistent particles and includes weight decay. The three snapshots show a single update with the negative particles held fixed. The plot shows 32 points from each 256-example minibatch, and the mean energies use the full batch. The negative samples use 16 Langevin steps with random restart probability 0.05. See train_ebm2d.py and ebm-trained.json. Seeds: 1411, 1412 and 1413.

50
Update phase
Mean data energy in the positive phase
−0.8399 → −0.8827
Mean negative-sample energy in the negative phase
0.4280 → 0.4413
Update
50 / 400
Follow the experiment and separate contributions of data and samples. The figure describes states and the origin of each step.

A gradient vector’s direction depends on all shared parameters; a joint update does not guarantee every data point’s energy falls and every negative sample’s rises at every step. The figure can separate contributions for interpretation, but a real step combines them and an optimizer may modify them. Inspect the objective on held-out data and the chains, not only a pretty surface.

Langevin: moving particles across the landscape

A common overdamped Langevin discretization is

xt+1=xt−η∇xEθ(xt)+2η ξt,ξt∼N(0,I).x_{t+1}=x_t-\eta\nabla_xE_\theta(x_t)+\sqrt{2\eta}\,\xi_t, \qquad \xi_t\sim\Normal(0,I).

Descent follows energy and noise enables exploration. The continuous equation has pθ∝e−Eθp_\theta\propto e^{-E_\theta} as its invariant distribution under suitable assumptions; the discrete update without Metropolis correction can be biased for finite η\eta. Many steps do not ensure mixing, and reducing noise does not preserve the same distribution.

A Gaussian case makes bias calculable. For E(x)=x2/2E(x)=x^2/2,

xt+1=(1−η)xt+2η ξt.x_{t+1}=(1-\eta)x_t+\sqrt{2\eta}\,\xi_t.

If 0<η<20<\eta<2, this autoregressive process has stationary variance 2η/[1−(1−η)2]=1/(1−η/2)2\eta/[1-(1-\eta)^2]=1/(1-\eta/2), above the target variance of one. Replacing 2η\sqrt{2\eta} with arbitrary standard deviation σ\sigma changes stationary variance to σ2/(2η−η2)\sigma^2/(2\eta-\eta^2) under the same stability condition. Changing step and noise independently, clipping states or restarting them changes the kernel and must be interpreted as a different procedure.

InteractiveShort chains, long chains

The contours show the final energy from the same training run. The traces follow a fixed subset of chains from their initial states.

  • Current particles
  • Eight chain trajectories
  • Energy contours

Each chain follows x′ = x − h∇E(x) + q√(2h)ξ, where ξ is standard normal and q is the noise factor. The transition noise uses seed 1414, and random starts use 1415, so settings share the same noise draws. The 64 chains use the same final energy field and 400 precomputed steps per setting. “Data” uses the first training examples. “Persistent buffer” uses the first stored persistent particles from the end of training. Changing h, q or the initialization regenerates the trajectory. Changing the displayed length steps through that trajectory. The chains have no restarts in this visualization.

At q = 1, the continuous-time stochastic differential equation has stationary density proportional to exp(−E). Finite step sizes introduce bias, and 400 steps by themselves do not establish convergence. Changing q changes the dynamics. At q = 0 the dynamics reduce to deterministic descent. The plot clips points outside its axes and the mean includes every chain. Differences between short and long runs here do not establish asymptotic behavior or how another EBM would behave.

Initialization
20
0.04
1.0
Mean chain energy
−2.972
Noise standard deviation per step
0.2828
Particles
64
Change length, step, noise and initialization. Distinguish this chain’s behavior from a claim of equilibrium.

A persistent buffer stores states for future chain initialization. Du and Mordatch report a configuration reusing the buffer with probability 95% and restarting with uniform noise for the remaining 5%; they also regularize energy magnitudes and stop gradients through negative samples. That percentage is their procedural choice, not an equilibrium guarantee. Numerical regularization also does not replace a proof that ZθZ_\theta is finite on the chosen domain.

Contrastive divergence and persistence

A short-chain state is generally not a sample from pθp_\theta. Moreover, the distribution after kk transitions depends on θ\theta; the practical update ignoring that dependence is generally not the full gradient of the formal contrastive-divergence objective. Therefore kk and initialization affect bias. Sutskever and Tieleman study this distinction.

Persistence and partial restart are related but distinct choices: restarting adds another transition and may aid exploration while changing the particle distribution. Tieleman studies persistence for training restricted Boltzmann machines.

An RBM updates whole blocks

Fixing vv makes the energy a sum of terms depending on individual hjh_j. Hidden units are therefore conditionally independent and

p(hj=1∣v)=sigmoid⁡ ⁣(bj+∑iWijvi).p(h_j=1\mid v)=\operatorname{sigmoid}\!\left(b_j+\sum_i W_{ij}v_i\right).

Similarly, p(vi=1∣h)=sigmoid⁡(ai+∑jWijhj)p(v_i=1\mid h)=\operatorname{sigmoid}(a_i+\sum_jW_{ij}h_j). All hidden units can be sampled in parallel given vv, followed by all visible units given hh: block Gibbs sampling. They are not marginally independent; interactions appear when summing variables in the other block.

InteractiveBlock Gibbs sampling in an RBM

Initial visible state. The initial state is test example 71, with label 5. The label identifies the starting example.

Visible units: 8 × 8
Hidden units: 4 × 8
0 / 80 cycles
  • Active visible unit
  • Active hidden unit

The binary RBM has 64 visible and 32 hidden units. It was trained with PCD for 10 epochs, batch size 64 and learning rate 0.08. The 8 × 8 digits were binarized at threshold ≥ 8 and split into 1437 training and 360 test examples using seed 1411. The initialization, minibatch order and persistent chain use seeds 1420, 1421 and 1422. The selected trajectory uses seed 1430. The weights and 80 cycles per initialization come from the recorded Pyodide lab run.

Each block factors conditionally on the other: p(hⱼ = 1 | v) = σ(bⱼ + ΣᵢvᵢWᵢⱼ) and p(vᵢ = 1 | h) = σ(aᵢ + ΣⱼWᵢⱼhⱼ). The readout shows the mean of individual conditional probabilities in the block just sampled. At initialization it previews the hidden-unit probabilities. The joint energy can rise or fall during Gibbs sampling. These few trajectories cannot establish mixing or convergence to equilibrium.

Chain initialization
Current stage
Initial visible state
Mean conditional probability
0.657
Joint energy E(v,h)
Waiting for hidden units
Active hidden units
Awaiting sampling
Alternate visible and hidden samples and observe a chain of the stated model. A short chain does not prove all modes were visited.

The free energy of a visible state is

F(v)=−a⊤v−∑j=1Hlog⁡ ⁣(1+ebj+W:j⊤v),p(v)=e−F(v)/Z.F(v)=-a^\top v-\sum_{j=1}^{H}\log\!\left(1+e^{b_j+W_{:j}^\top v}\right), \qquad p(v)=e^{-F(v)}/Z.

Hidden units have been summed analytically; use a stable softplus implementation. For a small RBM, enumerating every visible state calculates Z=∑ve−F(v)Z=\sum_v e^{-F(v)} and checks exact likelihood and gradient. Cost grows exponentially with enumerated units: the small verification does not make calculation tractable in a large network.

A short chain also defines a generator

Nijkamp and colleagues study short nonpersistent chains initialized from noise. Their figures show CelebA samples obtained with 100 steps; analysis distinguishes that generator from a convergent energy sampler. This does not mean every long chain degenerates or a persistent buffer reproduces the same experiment. To investigate a case, freeze weights, preserve initialization and compare trajectories and lengths; an observed difference alone proves neither its cause nor equilibrium.

A classifier can be part of a joint model

A discriminative architecture can serve a joint model if appropriately trained and normalized; softmax alone does not determine p(x)p(x). Adding the same function c(x)c(x) to every logit leaves p(y∣x)p(y\mid x) unchanged but changes marginal energy and may change normalizability. Grathwohl and colleagues, Table 1, report 92.9% accuracy for JEM versus 95.8% for a discriminative Wide-ResNet on CIFAR-10; these are their protocol’s results, not guaranteed improvement on every problem.

In that CIFAR-10 experiment, the table reports JEM FID 38.4 and Inception Score 8.76. On CIFAR-100, the authors compare calibration with the same architecture without EBM training: JEM obtains 72.2% accuracy versus 74.2% and lower calibration error in Figure 4. They also evaluate bounded perturbations under two norms and find improvements over their reference classifier, although for many magnitudes JEM remains below methods specifically trained for robustness. These results belong to those tests and do not guarantee calibration, robustness or sample quality.

When sampling is costly, alternatives use different assumptions. Noise-contrastive estimation, studied in NCE, turns estimation into discrimination against a known distribution. The next lesson studies score matching, avoiding direct normalization by working with derivatives with respect to xx. For each positive density ptp_t of a diffusion process, write Et(x)=−log⁡pt(x)+ctE_t(x)=-\log p_t(x)+c_t and its score is ∇xlog⁡pt(x)=−∇xEt(x)\nabla_x\log p_t(x)=-\nabla_xE_t(x). This connects the families, but a network trained to approximate score is not automatically the exact gradient of a normalizable energy. Song and Kingma develop these connections.

Lab: an RBM from scratch

Implement block Gibbs sampling and compare CD-1, CD-10 and persistent particles under a fixed protocol. In a tiny model enumerate states for exact likelihood: this checks estimators instead of assuming longer chains always win. For digits, document binarization and retain test data.

A Bernoulli RBM has binary visible and hidden units; block conditionals factorize. Each update estimates positive statistics using hidden probabilities given images and negative statistics with a Gibbs chain. CD-1 and CD-10 restart chains at each batch; PCD keeps particles between updates. All three use equal epochs, but CD-10 performs more transitions.

The first cell verifies a 6-visible, 4-hidden RBM partition function via two independent sums: 1024 joint states or 64 visible states after marginalizing hidden units. Check the exact gradient with finite differences. The second loads sklearn.datasets.load_digits, included in Pyodide’s scikit-learn, and binarizes each pixel at value at least 8 out of 16. A fixed split separates 1437 training images and 360 test images. On six central pixels calculate exact test NLL for CD-1, CD-10 and PCD; one seed does not establish a general ranking.

The following cells train three RBMs with 64 visible and 32 hidden units using equal initialization and update budgets. They print mean-field test reconstruction BCE: a diagnostic, not log-likelihood, which is not enumerated in 64 dimensions. The last shows a learned filter and Gibbs state without hand selection; EXPORT contains weights and chains used in the figure. Run cells in order to share variables.

[ ]RBM and exact verificationBrowser
"""RBM Bernoulli-Bernoulli y métodos exactos para un modelo diminuto."""
import numpy as np


def sigmoid(x):
    return 1 / (1 + np.exp(-np.clip(x, -40, 40)))


def binary_states(d):
    integers = np.arange(2 ** d, dtype=np.uint32)[:, None]
    return ((integers >> np.arange(d, dtype=np.uint32)) & 1).astype(np.float64)


class RBM:
    def __init__(self, visible, hidden, seed=1410):
        rng = np.random.default_rng(seed)
        self.W = rng.normal(0, 0.02, size=(visible, hidden))
        self.visible_bias = np.zeros(visible)
        self.hidden_bias = np.zeros(hidden)

    def hidden_prob(self, v):
        return sigmoid(v @ self.W + self.hidden_bias)

    def visible_prob(self, h):
        return sigmoid(h @ self.W.T + self.visible_bias)

    def gibbs(self, visible, k, rng):
        v = visible.copy()
        for _ in range(k):
            h = (rng.random((len(v), len(self.hidden_bias))) < self.hidden_prob(v)).astype(float)
            v = (rng.random(v.shape) < self.visible_prob(h)).astype(float)
        return v

    def update(self, positive, negative, learning_rate):
        ph, nh = self.hidden_prob(positive), self.hidden_prob(negative)
        self.W += learning_rate * (positive.T @ ph / len(positive) - negative.T @ nh / len(negative))
        self.visible_bias += learning_rate * (positive.mean(axis=0) - negative.mean(axis=0))
        self.hidden_bias += learning_rate * (ph.mean(axis=0) - nh.mean(axis=0))

    def free_energy(self, v):
        return -v @ self.visible_bias - np.logaddexp(0, v @ self.W + self.hidden_bias).sum(axis=1)

    def exact_log_z(self):
        if len(self.visible_bias) > 12:
            raise ValueError('La enumeración está reservada a modelos pequeños')
        return float(np.logaddexp.reduce(-self.free_energy(binary_states(len(self.visible_bias)))))

    def exact_nll(self, v):
        return float(self.free_energy(v).mean() + self.exact_log_z())

    def reconstruction_bce(self, v):
        # Reconstrucción de campo medio, un diagnóstico, no log-verosimilitud.
        p = np.clip(self.visible_prob(self.hidden_prob(v)), 1e-12, 1 - 1e-12)
        return float(-(v * np.log(p) + (1 - v) * np.log1p(-p)).mean())


def train_rbm(train, test, method, epochs, batch_size, learning_rate, init_seed, order_seed, chain_seed):
    if method not in ('CD-1', 'CD-10', 'PCD'):
        raise ValueError('Método no reconocido')
    model = RBM(train.shape[1], 4 if train.shape[1] == 6 else 32, init_seed)
    order = np.random.default_rng(order_seed)
    rng = np.random.default_rng(chain_seed)
    persistent = (rng.random((batch_size, train.shape[1])) < 0.5).astype(float)
    initial = model.exact_nll(test) if train.shape[1] == 6 else model.reconstruction_bce(test)
    trace = [initial]
    for epoch in range(epochs):
        for start in range(0, len(train), batch_size):
            # La permutación se genera una vez al principio de cada época.
            if start == 0:
                permutation = order.permutation(len(train))
            pos = train[permutation[start:start + batch_size]]
            if method == 'PCD':
                persistent = model.gibbs(persistent, 1, rng)
                neg = persistent
            else:
                neg = model.gibbs(pos, 1 if method == 'CD-1' else 10, rng)
            model.update(pos, neg, learning_rate)
        trace.append(model.exact_nll(test) if train.shape[1] == 6 else model.reconstruction_bce(test))
    return model, persistent, trace


# Un modelo de 6 visibles y 4 ocultas admite 2**10 estados conjuntos.
tiny = RBM(6, 4, seed=1401)
tiny.W[:] = np.arange(24).reshape(6, 4) / 100 - 0.12
tiny.visible_bias[:] = np.linspace(-0.2, 0.2, 6)
tiny.hidden_bias[:] = np.linspace(-0.1, 0.1, 4)
v_all, h_all = binary_states(6), binary_states(4)
joint_log = ((v_all @ tiny.W) @ h_all.T + v_all @ tiny.visible_bias[:, None] +
             (h_all @ tiny.hidden_bias)[None, :])
joint_log_z = float(np.logaddexp.reduce(joint_log.flatten()))
assert abs(tiny.exact_log_z() - joint_log_z) < 1e-12
assert np.allclose(np.exp(-tiny.free_energy(v_all) - tiny.exact_log_z()).sum(), 1, atol=1e-12, rtol=0)

# El gradiente exacto de la NLL se contrasta con diferencias finitas.
training_tiny = v_all[[3, 7, 11, 19, 29, 34, 42, 59]]
model_prob = np.exp(-tiny.free_energy(v_all) - tiny.exact_log_z())
ph_data, ph_model = tiny.hidden_prob(training_tiny), tiny.hidden_prob(v_all)
exact_grad = {
    'W': v_all.T @ (model_prob[:, None] * ph_model) - training_tiny.T @ ph_data / len(training_tiny),
    'visible_bias': model_prob @ v_all - training_tiny.mean(axis=0),
    'hidden_bias': model_prob @ ph_model - ph_data.mean(axis=0),
}
largest_error, eps = 0.0, 1e-5
for key, expected in exact_grad.items():
    parameter = getattr(tiny, key)
    for index in np.ndindex(parameter.shape):
        saved = parameter[index]
        parameter[index] = saved + eps
        plus = tiny.exact_nll(training_tiny)
        parameter[index] = saved - eps
        minus = tiny.exact_nll(training_tiny)
        parameter[index] = saved
        largest_error = max(largest_error, abs((plus - minus) / (2 * eps) - expected[index]))
assert largest_error < 1e-8
print(f'RBM 6+4: {2 ** 10} estados conjuntos; Z por dos sumas coincide; error de gradiente {largest_error:.2e}')
[ ]Digits and comparison with exact ZBrowser
"""Carga dígitos y compara CD y PCD con NLL exacta en 6 visibles."""
from sklearn.datasets import load_digits

digits = load_digits()
binary_digits = (digits.data >= 8).astype(float)
split = np.random.default_rng(1411).permutation(len(binary_digits))
train_ids, test_ids = split[:1437], split[1437:]
digit_train, digit_test = binary_digits[train_ids], binary_digits[test_ids]
print(f'Dígitos binarios: {len(digit_train)} train y {len(digit_test)} test; umbral ≥8 de 16')

# Seis píxeles centrales, modelo exactamente normalizable y test separado.
six_pixels = np.array([18, 19, 20, 26, 27, 28])
small_train = digit_train[:512, six_pixels]
small_test = digit_test[:256, six_pixels]
small_results = {}
for method in ('CD-1', 'CD-10', 'PCD'):
    small_model, _, small_trace = train_rbm(small_train, small_test, method,
        epochs=20, batch_size=64, learning_rate=0.08, init_seed=1412, order_seed=1413, chain_seed=1414)
    small_results[method] = {'test_nll_initial': small_trace[0], 'test_nll_final': small_trace[-1],
                             'test_nll_epochs': small_trace}
    print(f'{method}, 6 visibles: NLL exacta test {small_trace[0]:.5f} → {small_trace[-1]:.5f} nats')

digit_results = {}
digit_models = {}
digit_buffers = {}


def run_digit(method):
    model, buffer, trace = train_rbm(digit_train, digit_test, method,
        epochs=10, batch_size=64, learning_rate=0.08, init_seed=1420, order_seed=1421, chain_seed=1422)
    digit_models[method], digit_buffers[method] = model, buffer
    digit_results[method] = {'test_reconstruction_bce_initial': trace[0],
                             'test_reconstruction_bce_final': trace[-1],
                             'test_reconstruction_bce_epochs': trace}
    print(f'{method}, 64 visibles: BCE de reconstrucción de campo medio en test '
          f'{trace[0]:.5f} → {trace[-1]:.5f} por píxel')
[ ]Train CD-1Browser
run_digit('CD-1')
[ ]Train CD-10Browser
run_digit('CD-10')
[ ]Train PCD and generate chainsBrowser
run_digit('PCD')
"""Tras entrenar PCD, construye cadenas Gibbs reproducibles para la figura."""
model = digit_models['PCD']
persistent = digit_buffers['PCD']
random_start = (np.random.default_rng(1423).random(64) < 0.5).astype(float)
initials = [('test', digit_test[0], int(test_ids[0]), int(digits.target[test_ids[0]])),
            ('persistente', persistent[0], None, None),
            ('ruido binario', random_start, None, None)]
chains = []
for chain_index, (name, initial, test_index, label) in enumerate(initials):
    seed = 1430 + chain_index
    chain_rng = np.random.default_rng(seed)
    v = initial.copy()
    visible_states = [v.astype(int).tolist()]
    hidden_states = []
    for _ in range(80):
        h = (chain_rng.random(32) < model.hidden_prob(v[None])[0]).astype(float)
        v = (chain_rng.random(64) < model.visible_prob(h[None])[0]).astype(float)
        hidden_states.append(h.astype(int).tolist())
        visible_states.append(v.astype(int).tolist())
    chains.append({'name': name, 'seed': seed, 'test_index': test_index, 'label': label,
                   'initial_visible': visible_states[0], 'visible': visible_states,
                   'hidden': hidden_states})

print('Filtro de la primera unidad oculta: + peso positivo, − negativo')
for row in model.W[:, 0].reshape(8, 8):
    print(''.join('+' if value >= 0 else '-' for value in row))
print('Último estado de la cadena inicializada en test:')
for row in np.array(chains[0]['visible'][-1]).reshape(8, 8):
    print(''.join('#' if value else '.' for value in row))

EXPORT = {'schema': 1, 'source': 'sklearn.datasets.load_digits', 'pixels': '8×8, 0 a 16',
          'binarization': 'valor >= 8', 'train_count': len(digit_train), 'test_count': len(digit_test),
          'split_seed': 1411, 'visible_count': 64, 'hidden_count': 32,
          'method': 'PCD', 'epochs': 10, 'batch_size': 64, 'learning_rate': 0.08,
          'init_seed': 1420, 'order_seed': 1421, 'chain_seed': 1422,
          'W': model.W.tolist(), 'visible_bias': model.visible_bias.tolist(),
          'hidden_bias': model.hidden_bias.tolist(), 'chains': chains,
          'small_results': small_results, 'digit_results': digit_results}

Exercises

ProofFrom the partition function to two phases
Prove: Derive the EBM log-likelihood gradient and explain why CD-k can give a biased estimator.
0
Assume finite Z, fixed support and conditions permitting differentiation under the integral.

Step 1 of 3. What appears when differentiating Z?

ProofWhy Gibbs parallelizes by block
Prove: Derive an RBM’s binary conditionals and prove their factorization.
0
First fix v and group terms depending on each h_j.

Step 1 of 3. How does energy depend on hidden units when v is fixed?

NumericCounting states
An RBM has 6 binary visible and 4 binary hidden units. How many joint states appear in the direct partition-function sum?
CodeA chain with input gradients
Implement langevin_sample(energy_fn, x0, n_steps, step_size, noise_scale, generator=None). energy_fn returns one energy per example. At each step use x ← x − step_size ∇E(x) + noise_scale ξ without modifying x0 or accumulating model-parameter gradients. Return a tensor detached from the graph and use generator if supplied. For standard ULA, noise_scale is sqrt(2·step_size).
import torch

def langevin_sample(energy_fn, x0, n_steps, step_size, noise_scale, generator=None):
  pass
Shift+Enter to run

The Gaussian test compares against the discretized chain’s variance, not the continuous target variance of one. Test tolerance allows sampling variation; it does not demonstrate mixing for a multimodal energy.

QuizDiagnosing long chains
An EBM produces convincing images after few transitions from noise, but longer chains produce different results. Which conclusion is justified?

Lab: convolutional energy and a buffer

Train an image energy with Langevin chains and a persistent buffer. Detach negative states from the graph before parameter updates and record step size, noise, initialization and length. To compare horizons, freeze the checkpoint and continue from the same particles; do not call a chain equilibrium merely because it is longer.

Train a convolutional energy with a positive phase and approximate negative phase. The network ends in a scalar output; bounded activations are complemented by a positive quadratic term. Energy therefore grows quadratically far from the origin and defines an integrable density on continuous space. This does not make its partition function accessible or turn the upcoming loss into exact log-likelihood.

Negatives initialize from the persistent buffer or, with probability 0.05, new uniform noise. Each Langevin step uses displacement proportional to half the step size and noise with standard deviation equal to its square root. The chain is detached each step and its outputs treated as constants when updating the network. The optimizer minimizes mean data energy minus mean negative energy plus weak quadratic regularization of both; parameter gradient norms are also clipped. This follows the buffer and regularization idea of Du and Mordatch, but architecture and figures differ.

Install torch, torchvision, numpy and pillow. MNIST is default; ORYON_DATASET accepts mnist, cifar10 or both. ORYON_DATA_ROOT selects where to find or download data and ORYON_OUTPUT_DIR the results folder. Full mode uses all training images, five epochs, batch 64, 30 Langevin steps per update and a buffer of 10,000 images. Official test data do not participate in optimization; they only study chain initialization from held-out data.

ORYON_QUICK=1 limits the run to 128 training images, 32 test images, a batch of 8, small network, one epoch and four chain steps per update. It checks code and does not demonstrate generation quality. Only in that mode, ORYON_CIFAR_PARQUET can reuse a folder containing CIFAR-10 train-*.parquet and test-*.parquet; it needs pyarrow. The test takes the first available images in each split and is not representative evaluation.

Before training, check one network derivative with finite differences, a Langevin step with identical noise, absence of accumulated parameter gradients during sampling, resets and buffer updates. Also simulate a one-dimensional Gaussian and compare its variance with ULA’s finite-step stationary variance. That variance is not exactly the target Gaussian’s: the discrete method is biased even in this simple case.

After saving and reloading the checkpoint, freeze parameters and compare 0-, 30- and 300-step chains initialized from noise, test images and buffer samples. Within each comparison, the 300-step state extends the same 30-step trajectory. Record energy, mean square and fraction of components outside [−1,1]. Only displayed images are clipped to that interval; chains and metrics use original values. More steps do not prove equilibrium or a particular cause of visual differences.

Save weights, optimizer, buffer and noise-generator state with metrics and grids; the example checks loading but does not implement automatic training resumption. Energy metrics must be compared with the same model and are not likelihood values. For a maximum-likelihood approximation, negative samples should represent the model distribution; short chains and a changing buffer do not guarantee that condition.

[ ]Convolutional EBM with Langevin and bufferLocal GPU
"""EBM convolucional con Langevin y reinicios de búfer en MNIST o CIFAR-10.

ORYON_DATASET=mnist|cifar10|both; ORYON_DATA_ROOT y ORYON_OUTPUT_DIR;
ORYON_QUICK=1 limita el trabajo para verificarlo. Solo en quick,
ORYON_CIFAR_PARQUET puede apuntar a la caché parquet de CIFAR-10.
"""
import copy
import csv
import io
import math
import os
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torch import nn
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image

torch.set_num_threads(2)


class EnergyNet(nn.Module):
    """Red acotada más potencial cuadrático: exp(−E) es integrable en ℝ^D."""
    def __init__(self, channels, side, width=32, quadratic=0.05):
        super().__init__()
        if side % 4 or quadratic <= 0:
            raise ValueError('El lado debe ser múltiplo de cuatro y la escala positiva')
        self.channels, self.side, self.width, self.quadratic = channels, side, width, quadratic
        self.net = nn.Sequential(
            nn.Conv2d(channels, width, 3, stride=2, padding=1), nn.Tanh(),
            nn.Conv2d(width, 2 * width, 3, stride=2, padding=1), nn.Tanh(),
            nn.Flatten(), nn.Linear(2 * width * (side // 4) ** 2, 1),
        )

    def forward(self, x):
        neural = self.net(x).squeeze(1)
        confining = 0.5 * self.quadratic * x.flatten(1).square().sum(1)
        return neural + confining


def langevin(energy, x0, steps, step_size, generator, snapshots=()):
    """ULA: x' = x − h∇E/2 + √h ξ, sin proyectar ni crear grafo en θ."""
    if steps < 0 or step_size <= 0 or not math.isfinite(step_size):
        raise ValueError('El número de pasos y el tamaño de paso no son válidos')
    requested = set(snapshots)
    if any(k < 0 or k > steps for k in requested):
        raise ValueError('Los instantes deben estar entre 0 y steps')
    x = x0.detach().clone()
    saved = {0: x.clone()} if 0 in requested else {}
    for k in range(1, steps + 1):
        with torch.enable_grad():
            x = x.detach().requires_grad_(True)
            e = energy(x)
            gradient = torch.autograd.grad(e.sum(), x, create_graph=False)[0]
        with torch.no_grad():
            noise = torch.randn(x.shape, dtype=x.dtype, device=x.device, generator=generator)
            x = (x - 0.5 * step_size * gradient + math.sqrt(step_size) * noise).detach()
            if not torch.isfinite(x).all():
                raise FloatingPointError('La cadena dejó de ser finita')
            if k in requested:
                saved[k] = x.clone()
    return x.detach(), saved


class ReplayBuffer:
    def __init__(self, capacity, shape, device, generator):
        if capacity < 1:
            raise ValueError('El tamaño del búfer debe ser positivo')
        self.values = 2 * torch.rand((capacity, *shape), device=device, generator=generator) - 1

    def initialize(self, batch, generator, restart_probability=0.05):
        if batch > len(self.values) or not 0 <= restart_probability <= 1:
            raise ValueError('Lote o probabilidad de reinicio inválidos')
        indices = torch.randperm(len(self.values), device=self.values.device, generator=generator)[:batch]
        initial = self.values[indices].detach().clone()
        restart = torch.rand(batch, device=self.values.device, generator=generator) < restart_probability
        count = int(restart.sum().item())
        if count:
            fresh = 2 * torch.rand((count, *initial.shape[1:]), device=initial.device, generator=generator) - 1
            initial[restart] = fresh
        return initial, indices, restart

    def update(self, indices, values):
        with torch.no_grad():
            self.values[indices] = values.detach()


def verify(device):
    """Controles pequeños de derivadas, ruido, búfer y checkpoint."""
    torch.manual_seed(1410)
    model = EnergyNet(1, 8, width=4).to(device).double()
    x = torch.randn(2, 1, 8, 8, dtype=torch.float64, device=device, requires_grad=True)
    analytical = torch.autograd.grad(model(x).sum(), x)[0][0, 0, 3, 4]
    plus, minus = x.detach().clone(), x.detach().clone()
    plus[0, 0, 3, 4] += 1e-5
    minus[0, 0, 3, 4] -= 1e-5
    numerical = (model(plus).sum() - model(minus).sum()) / 2e-5
    assert torch.allclose(analytical, numerical, atol=1e-7, rtol=1e-5)
    gen = torch.Generator(device=device).manual_seed(1411)
    out, _ = langevin(model, x, 3, 0.01, gen)
    assert not out.requires_grad and all(parameter.grad is None for parameter in model.parameters())

    # El caso gaussiano permite contrastar cada operación y el sesgo de ULA.
    def quadratic(v):
        return 0.5 * v.flatten(1).square().sum(1)
    start = torch.tensor([[1.0], [-0.5]], device=device)
    h = 0.2
    seed = 1412
    gen_a = torch.Generator(device=device).manual_seed(seed)
    gen_b = torch.Generator(device=device).manual_seed(seed)
    one, _ = langevin(quadratic, start, 1, h, gen_a)
    manual = start - 0.5 * h * start + math.sqrt(h) * torch.randn(start.shape, device=device, generator=gen_b)
    assert torch.allclose(one, manual, atol=1e-7)
    gen = torch.Generator(device=device).manual_seed(1413)
    chain, _ = langevin(quadratic, torch.zeros(8192, 1, device=device), 80, h, gen)
    theoretical_variance = 1.0 / (1.0 - h / 4.0)
    measured_variance = chain.var(unbiased=False).item()
    assert abs(measured_variance - theoretical_variance) < 0.08

    gen = torch.Generator(device=device).manual_seed(1414)
    buf = ReplayBuffer(12, (1, 8, 8), device, gen)
    _, indices, restarted = buf.initialize(5, gen, restart_probability=1.0)
    assert restarted.all() and len(indices.unique()) == len(indices)
    replacement = torch.ones(5, 1, 8, 8, device=device)
    buf.update(indices, replacement)
    assert torch.equal(buf.values[indices], replacement)
    snapshot = {'model': copy.deepcopy(model.state_dict()), 'buffer': buf.values.detach().clone()}
    clone = EnergyNet(1, 8, width=4).to(device).double()
    clone.load_state_dict(snapshot['model'])
    assert all(torch.equal(snapshot['model'][name], value) for name, value in clone.state_dict().items())
    assert torch.equal(snapshot['buffer'], buf.values)
    print(f'Controles correctos: gradiente, paso, ausencia de grafo, búfer y estado; '
          f'varianza ULA {measured_variance:.4f}, teórica {theoretical_variance:.4f}.', flush=True)
    del model, clone, x, plus, minus, out, chain, buf, snapshot
    if device.type == 'cuda':
        torch.cuda.empty_cache()


class ParquetCifar(Dataset):
    def __init__(self, folder, split, start, count):
        import pyarrow.parquet as pq
        rows = []
        for file in sorted(Path(folder).glob(f'{split}-*.parquet')):
            for batch in pq.ParquetFile(file).iter_batches(batch_size=128, columns=['img']):
                rows.extend(batch.to_pylist())
                if len(rows) >= start + count:
                    break
            if len(rows) >= start + count:
                break
        self.rows = rows[start:start + count]
        if len(self.rows) != count:
            raise ValueError('El parquet CIFAR no contiene suficientes imágenes')

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, index):
        with Image.open(io.BytesIO(self.rows[index]['img']['bytes'])) as image:
            return transforms.PILToTensor()(image.convert('RGB')), 0


def get_data(kind, root, quick, parquet):
    if kind == 'cifar10' and quick and parquet:
        return ParquetCifar(parquet, 'train', 0, 128), ParquetCifar(parquet, 'test', 0, 32)
    cls = datasets.MNIST if kind == 'mnist' else datasets.CIFAR10
    train = cls(root, train=True, download=True, transform=transforms.PILToTensor())
    test = cls(root, train=False, download=True, transform=transforms.PILToTensor())
    indices = torch.randperm(len(train), generator=torch.Generator().manual_seed(1420)).tolist()
    return Subset(train, indices[:128] if quick else indices), Subset(test, range(32 if quick else len(test)))


def dequantize(pixels, generator, device):
    # En cada canal: entero 0..255 a una celda uniforme dentro de [−1,1].
    pixels = pixels.to(device=device, dtype=torch.float32)
    u = torch.rand(pixels.shape, dtype=pixels.dtype, device=device, generator=generator)
    return 2.0 * ((pixels + u) / 256.0) - 1.0


def describe(model, points):
    with torch.no_grad():
        energy = model(points).mean().item()
        outside = ((points < -1) | (points > 1)).float().mean().item()
        mean_square = points.square().mean().item()
    return {'energia_media': energy, 'fraccion_componentes_fuera': outside, 'media_cuadrado': mean_square}


def train_one(kind, quick, root, output_root, parquet, device):
    channels, side = (1, 28) if kind == 'mnist' else (3, 32)
    batch, width, capacity, chain_steps = (8, 8, 128, 4) if quick else (64, 32, 10000, 30)
    epochs, h, penalty = (1 if quick else 5), 0.01, 0.0001
    train, test = get_data(kind, root, quick, parquet)
    loader = DataLoader(train, batch_size=batch, shuffle=True, num_workers=0,
                        generator=torch.Generator().manual_seed(1421))
    test_loader = DataLoader(test, batch_size=batch, shuffle=False, num_workers=0)
    output = Path(output_root) / kind
    output.mkdir(parents=True, exist_ok=True)
    torch.manual_seed(1422)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(1422)
    random = torch.Generator(device=device).manual_seed(1423)
    model = EnergyNet(channels, side, width).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)
    replay = ReplayBuffer(capacity, (channels, side, side), device, random)
    history = []
    for epoch in range(1, epochs + 1):
        model.train()
        for batch_index, (pixels, _) in enumerate(loader):
            real = dequantize(pixels, random, device)
            initial, indices, restarted = replay.initialize(len(real), random, restart_probability=0.05)
            negative, _ = langevin(model, initial, chain_steps, h, random)
            replay.update(indices, negative)
            optimizer.zero_grad(set_to_none=True)
            positive_energy, negative_energy = model(real), model(negative.detach())
            loss = (positive_energy.mean() - negative_energy.mean() +
                    penalty * (positive_energy.square().mean() + negative_energy.square().mean()))
            if not torch.isfinite(loss):
                raise FloatingPointError('La pérdida no es finita')
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0, error_if_nonfinite=True)
            optimizer.step()
            history.append((epoch, batch_index, float(loss.detach()), float(positive_energy.detach().mean()),
                            float(negative_energy.detach().mean()), int(restarted.sum())))
        print(f'{kind} época {epoch}: pérdida {history[-1][2]:.4f}, '
              f'E real {history[-1][3]:.4f}, E negativa {history[-1][4]:.4f}', flush=True)
    with (output / 'entrenamiento.csv').open('w', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(('epoca', 'lote', 'perdida', 'energia_real', 'energia_negativa', 'reinicios'))
        writer.writerows(history)
    checkpoint = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(),
                  'buffer': replay.values.detach().cpu(), 'dataset': kind, 'channels': channels, 'side': side,
                  'width': width, 'quadratic': model.quadratic, 'steps': chain_steps, 'step_size': h,
                  'restart_probability': 0.05, 'quick': quick, 'epoch': epochs, 'rng': random.get_state().cpu()}
    torch.save(checkpoint, output / 'ebm.pt')
    restored = torch.load(output / 'ebm.pt', map_location=device, weights_only=True)
    clone = EnergyNet(channels, side, width, restored['quadratic']).to(device)
    clone.load_state_dict(restored['model'])
    assert torch.equal(restored['buffer'].cpu(), replay.values.cpu())
    for key, value in model.state_dict().items():
        assert torch.equal(value, clone.state_dict()[key])
    del clone, restored, checkpoint
    optimizer.zero_grad(set_to_none=True)
    model.eval()
    diagnostic_rng = torch.Generator(device=device).manual_seed(1424)
    test_pixels, _ = next(iter(test_loader))
    starts = {
        'ruido': 2 * torch.rand((len(test_pixels), channels, side, side), device=device, generator=diagnostic_rng) - 1,
        'datos_test': dequantize(test_pixels, diagnostic_rng, device),
        'buffer': replay.values[:len(test_pixels)].detach().clone(),
    }
    diagnostics = []
    for name, initial in starts.items():
        _, snapshots = langevin(model, initial, 300, h, diagnostic_rng, snapshots=(0, 30, 300))
        for steps, values in snapshots.items():
            stats = describe(model, values)
            diagnostics.append({'inicio': name, 'pasos': steps, **stats})
            print(kind, name, steps, stats, flush=True)
            # Solo la visualización recorta al rango; los valores anteriores son los reales.
            save_image(((values + 1) / 2).clamp(0, 1), output / f'{name}-{steps:03d}.png', nrow=4)
    with (output / 'cadenas.csv').open('w', encoding='utf-8', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=list(diagnostics[0]))
        writer.writeheader()
        writer.writerows(diagnostics)
    print('Las cadenas largas no demuestran equilibrio; ULA tiene sesgo de paso finito.', flush=True)
    del model, optimizer, replay, train, test, loader, test_loader, starts, snapshots
    if device.type == 'cuda':
        torch.cuda.empty_cache()


def main():
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    quick = os.environ.get('ORYON_QUICK') == '1'
    kinds = os.environ.get('ORYON_DATASET', 'mnist').lower()
    if kinds not in ('mnist', 'cifar10', 'both'):
        raise ValueError('ORYON_DATASET debe ser mnist, cifar10 o both')
    parquet = os.environ.get('ORYON_CIFAR_PARQUET')
    if parquet and not quick:
        raise ValueError('ORYON_CIFAR_PARQUET solo está disponible en quick')
    root = os.environ.get('ORYON_DATA_ROOT', './data')
    output = os.environ.get('ORYON_OUTPUT_DIR', './ebm-results')
    verify(device)
    for kind in ('mnist', 'cifar10') if kinds == 'both' else (kinds,):
        train_one(kind, quick, root, output, parquet, device)


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

An EBM assigns energy scores and needs a normalizing constant to define probabilities. Training approximates a negative phase dependent on the sampler; a short chain can be a useful generator without representing model equilibrium.