Download src/score_matching.py from At1uri/energy-based-model-vault: direct link, hf CLI and curl.
- Browser
- Download file 2.23 kB
-
https://huggingface.co/At1uri/energy-based-model-vault/resolve/main/src/score_matching.py
- Command line
-
hf download hf://At1uri/energy-based-model-vault/src/score_matching.py
-
curl -L -o score_matching.py https://huggingface.co/At1uri/energy-based-model-vault/resolve/main/src/score_matching.py
2.23 kB
| """ | |
| Score Matching Objective Formulations | |
| Vault: At1uri/energy-based-model-vault | |
| Author: Ramprasad Atluri (At1uri) | |
| Theory: | |
| 1. Implicit Score Matching (Hyvärinen, 2005): | |
| Bypasses intractable partition function Z_theta by evaluating: | |
| L_ISM = E_{p_data} [ 1/2 * ||s_theta(x)||^2 + Tr(grad_x s_theta(x)) ] | |
| 2. Sliced Score Matching (Song et al., 2020): | |
| Projects score vectors onto random unit vectors v ~ N(0, I): | |
| L_SSM = E_{p_data, v} [ v^T grad_x s_theta(x) v + 1/2 * (v^T s_theta(x))^2 ] | |
| """ | |
| import numpy as np | |
| class ScoreMatchingLoss: | |
| """Implementations of partition-free score matching losses.""" | |
| def implicit_score_matching(model, x_batch): | |
| """ | |
| Computes sample average of Implicit Score Matching loss: | |
| L = (1/N) * sum_i [ 0.5 * ||s(x_i)||^2 - Tr(H_E(x_i)) ] | |
| """ | |
| N = len(x_batch) | |
| total_loss = 0.0 | |
| for i in range(N): | |
| x = x_batch[i] | |
| s = model.score(x, temp=1.0) | |
| score_norm_sq = np.sum(s**2) | |
| tr_hessian = model.hessian_trace(x) | |
| # Loss: 0.5 * ||s||^2 - Tr(grad s) where s = -grad E => Tr(grad s) = -Tr(H_E) | |
| loss_i = 0.5 * score_norm_sq - tr_hessian | |
| total_loss += loss_i | |
| return float(total_loss / N) | |
| def sliced_score_matching(model, x_batch, n_slices=1, eps=1e-4): | |
| """ | |
| Sliced Score Matching with Hutchinson random projection: | |
| L_SSM = E_v [ v^T (s(x+eps v) - s(x-eps v))/(2 eps) + 0.5 * (v^T s(x))^2 ] | |
| """ | |
| N = len(x_batch) | |
| total_loss = 0.0 | |
| d = x_batch.shape[1] | |
| for i in range(N): | |
| x = x_batch[i] | |
| s_x = model.score(x, temp=1.0) | |
| for _ in range(n_slices): | |
| v = np.random.randn(d) | |
| v = v / np.linalg.norm(v) | |
| s_plus = model.score(x + eps * v, temp=1.0) | |
| s_minus = model.score(x - eps * v, temp=1.0) | |
| div_v = np.dot(v, (s_plus - s_minus) / (2.0 * eps)) | |
| loss_v = div_v + 0.5 * (np.dot(v, s_x)**2) | |
| total_loss += loss_v | |
| return float(total_loss / (N * n_slices)) | |