energy-based-model-vault / src /energy_model.py
At1uri's picture
Deploy Energy-Based Model research vault with MALA & score matching loss suites
505021e verified
Raw History Blame Contribute Delete
3.1 kB
"""
Energy-Based Model (EBM) Architecture & Analytical Score Module
Vault: At1uri/energy-based-model-vault
Author: Ramprasad Atluri (At1uri)
Theory:
Let E_theta: R^d -> R be a smooth parameterized energy function.
The unnormalized density is given by:
p_theta(x) = (1 / Z_theta) * exp(-E_theta(x) / T)
The score function s_theta(x) = grad_x log p_theta(x) eliminates the intractable partition function Z_theta:
s_theta(x) = - (1 / T) * grad_x E_theta(x)
"""
import numpy as np
def silu(z):
return z / (1.0 + np.exp(-np.clip(z, -20.0, 20.0)))
def d_silu(z):
s = 1.0 / (1.0 + np.exp(-np.clip(z, -20.0, 20.0)))
return s * (1.0 + z * (1.0 - s))
class EnergyModel:
"""Deep Energy-Based Model with exact analytical gradient and Hessian trace estimation."""
def __init__(self, in_dim=2, hidden_dim=64):
self.in_dim = in_dim
self.hidden_dim = hidden_dim
rng = np.random.RandomState(42)
scale1 = np.sqrt(2.0 / (in_dim + hidden_dim))
scale2 = np.sqrt(2.0 / (hidden_dim + hidden_dim))
scale3 = np.sqrt(2.0 / (hidden_dim + 1))
self.W1 = rng.randn(hidden_dim, in_dim) * scale1
self.b1 = np.zeros(hidden_dim)
self.W2 = rng.randn(hidden_dim, hidden_dim) * scale2
self.b2 = np.zeros(hidden_dim)
self.W3 = rng.randn(1, hidden_dim) * scale3
self.b3 = np.zeros(1)
def energy(self, x):
"""Evaluates scalar energy E_theta(x)."""
x_vec = np.asarray(x, dtype=np.float64)
single = (x_vec.ndim == 1)
if single:
x_vec = x_vec[None, :]
h1 = silu(x_vec @ self.W1.T + self.b1)
h2 = silu(h1 @ self.W2.T + self.b2)
E = (h2 @ self.W3.T + self.b3)
return float(E[0, 0]) if single else E
def score(self, x, temp=1.0):
"""Computes analytical score vector: s(x) = - (1/T) * grad_x E(x)."""
x_vec = np.asarray(x, dtype=np.float64)
single = (x_vec.ndim == 1)
if single:
x_vec = x_vec[None, :]
a1 = x_vec @ self.W1.T + self.b1
h1 = silu(a1)
a2 = h1 @ self.W2.T + self.b2
h2 = silu(a2)
delta3 = self.W3
delta2 = (delta3 * d_silu(a2)) @ self.W2
grad_x = (delta2 * d_silu(a1)) @ self.W1
score_vec = -(1.0 / temp) * grad_x
return score_vec[0] if single else score_vec
def hessian_trace(self, x, eps=1e-4):
"""
Estimates Laplacian / Trace of Hessian Tr(grad_x^2 E(x)) via Hutchinson's estimator:
Tr(H) = E_{v ~ N(0, I)} [ v^T H v ] ~ v^T (grad(x + eps*v) - grad(x - eps*v)) / (2*eps)
"""
x_vec = np.asarray(x, dtype=np.float64)
d = len(x_vec)
v = np.random.randn(d)
v = v / np.linalg.norm(v)
# Numerical directional gradient difference
s_plus = -self.score(x_vec + eps * v, temp=1.0) # grad E(x + eps v)
s_minus = -self.score(x_vec - eps * v, temp=1.0) # grad E(x - eps v)
h_v = (s_plus - s_minus) / (2.0 * eps)
trace_est = float(d * np.dot(v, h_v))
return trace_est