torchebm.losses ¶
Loss functions for training energy-based models and generative models.
ContrastiveDivergence ¶
Bases: BaseContrastiveDivergence
Standard Contrastive Divergence (CD-k) loss.
CD approximates the log-likelihood gradient by running an MCMC sampler for k_steps to generate negative samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | The energy-based model to train. | required | |
sampler | The MCMC sampler for generating negative samples. | required | |
k_steps | The number of MCMC steps (k in CD-k). | 10 | |
persistent | If True, uses Persistent CD with a replay buffer. | False | |
buffer_size | Size of the replay buffer for PCD. | 10000 | |
init_steps | Number of MCMC steps to warm up the buffer. | 100 | |
new_sample_ratio | Fraction of new random samples for PCD chains. | 0.05 | |
energy_reg_weight | Weight for energy regularization term. | 0.001 | |
use_temperature_annealing | Whether to use temperature annealing. | False | |
min_temp | Minimum temperature for annealing. | 0.01 | |
max_temp | Maximum temperature for annealing. | 2.0 | |
temp_decay | Decay rate for temperature annealing. | 0.999 | |
dtype | Data type for computations. | float32 | |
device | Device for computations. | device('cpu') |
Example
Source code in torchebm/losses/contrastive_divergence.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
compute_loss(x, pred_x, *args, **kwargs) ¶
Computes the Contrastive Divergence loss from positive and negative samples.
The loss is the difference between the mean energy of positive samples and the mean energy of negative samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Real data samples (positive samples). | required |
pred_x | Tensor | Generated negative samples. | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar loss value. |
Source code in torchebm/losses/contrastive_divergence.py
forward(x, *args, **kwargs) ¶
Computes the Contrastive Divergence loss and generates negative samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | A batch of real data samples (positive samples). | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor] | Tuple[torch.Tensor, torch.Tensor]: - The scalar CD loss value. - The generated negative samples. |
Source code in torchebm/losses/contrastive_divergence.py
DenoisingScoreMatching ¶
Bases: BaseScoreMatching
Denoising Score Matching (DSM) from Vincent (2011).
Avoids computing the Hessian trace by matching the score of noise-perturbed data. More computationally efficient and often more stable than standard Score Matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | BaseModel | The energy-based model to train. | required |
noise_scale | float | Standard deviation of Gaussian noise to add. | 0.01 |
regularization_strength | float | Coefficient for regularization. | 0.0 |
custom_regularization | Optional[Callable] | A custom regularization function. | None |
use_mixed_precision | bool | Whether to use mixed-precision training. | False |
dtype | dtype | Data type for computations. | float32 |
device | Optional[Union[str, device]] | Device for computations. | None |
Example
Source code in torchebm/losses/score_matching.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
compute_loss(x, *args, **kwargs) ¶
Computes the denoising score matching loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar denoising score matching loss. |
Source code in torchebm/losses/score_matching.py
forward(x, *args, **kwargs) ¶
Computes the denoising score matching loss for a batch of data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar denoising score matching loss. |
Source code in torchebm/losses/score_matching.py
EquilibriumMatchingLoss ¶
Bases: BaseLoss
Equilibrium Matching (EqM) training loss.
Implements gradient matching for learning equilibrium energy landscapes. Supports both implicit (vector field) and explicit (energy-based) formulations, with multiple prediction types and loss weighting schemes.
The target is \((\epsilon - x) \cdot c(\gamma)\) where: - \(\epsilon\) is noise (x0), \(x\) is data (x1) - For linear interpolant: target is \((x_0 - x_1) \cdot c(t)\) (noise - data) - \(c(\gamma) = \lambda \cdot \min(1, (1-\gamma)/(1-a))\) is truncated decay
For ODE sampling, use negate_velocity=True in FlowSampler since velocity \(v = -f(x) = x - \epsilon\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | Module | Neural network predicting velocity/score/noise. | required |
prediction | Literal['velocity', 'score', 'noise'] | Network prediction type ('velocity', 'score', or 'noise'). | 'velocity' |
energy_type | Literal['none', 'dot', 'l2', 'mean'] | Energy formulation type: - 'none': Implicit EqM, model predicts gradient directly - 'dot': \(g(x) = x \cdot f(x)\), dot product energy formulation - 'l2': \(g(x) = -\frac{1}{2}\|f(x)\|^2\) (experimental) - 'mean': Same as dot (alias) | 'none' |
interpolant | Union[str, BaseInterpolant] | Interpolant name (e.g. 'linear', 'cosine', 'vp') or BaseInterpolant instance. | 'linear' |
loss_weight | Optional[Literal['velocity', 'likelihood']] | Loss weighting scheme ('velocity', 'likelihood', or None). | None |
train_eps | float | Epsilon for training time interval stability. | 0.0 |
ct_threshold | float | Decay threshold \(a\) for \(c(t)\). Decay starts after \(t > a\). Default: 0.8. | 0.8 |
ct_multiplier | float | Gradient multiplier \(\lambda\) for \(c(t)\). Default: 4.0. | 4.0 |
apply_dispersion | bool | Whether to apply dispersive regularization. | False |
dispersion_weight | float | Weight for dispersive loss term. | 0.5 |
time_invariant | bool | If True, pass zeros for time to model (EqM default). | True |
dtype | dtype | Data type for computations. | float32 |
device | Optional[Union[str, device]] | Device for computations. | None |
use_mixed_precision | bool | Whether to use mixed precision. | False |
clip_value | Optional[float] | Optional value to clamp the loss. | None |
Example
Source code in torchebm/losses/equilibrium_matching.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
compute_loss(x, *args, **kwargs) ¶
Compute the equilibrium matching loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Data samples of shape (batch_size, ...). | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional model arguments passed to the network. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | Scalar loss value. |
Source code in torchebm/losses/equilibrium_matching.py
forward(x, *args, **kwargs) ¶
Compute EqM loss (nn.Module interface).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Data samples of shape (batch_size, ...). | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional model arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | Scalar loss value. |
Source code in torchebm/losses/equilibrium_matching.py
training_losses(x1, model_kwargs=None) ¶
Compute training losses with detailed outputs.
Implements gradient matching with EqM target: - Target: \((\epsilon - x) \cdot c(t) = (x_0 - x_1) \cdot c(t)\) - Time-invariant: zeros out time if time_invariant=True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x1 | Tensor | Data samples of shape (batch_size, ...). | required |
model_kwargs | Optional[Dict[str, Any]] | Additional model arguments. | None |
Returns:
| Type | Description |
|---|---|
Dict[str, Tensor] | Dictionary with 'loss' (per-sample), 'pred', and optionally 'energy'. |
Source code in torchebm/losses/equilibrium_matching.py
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
ScoreMatching ¶
Bases: BaseScoreMatching
Original Score Matching loss from Hyvärinen (2005).
Trains an energy-based model by matching the model's score function \(\nabla_x \log p_\theta(x)\) to the data's score. Avoids MCMC sampling but requires computing the trace of the Hessian.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | BaseModel | The energy-based model to train. | required |
hessian_method | str | Method for Hessian trace ('exact' or 'approx'). | 'exact' |
regularization_strength | float | Coefficient for regularization. | 0.0 |
custom_regularization | Optional[Callable] | A custom regularization function. | None |
use_mixed_precision | bool | Whether to use mixed-precision training. | False |
dtype | dtype | Data type for computations. | float32 |
device | Optional[Union[str, device]] | Device for computations. | None |
Example
Source code in torchebm/losses/score_matching.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
compute_loss(x, *args, **kwargs) ¶
Computes the score matching loss using the specified Hessian computation method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar score matching loss. |
Source code in torchebm/losses/score_matching.py
forward(x, *args, **kwargs) ¶
Computes the score matching loss for a batch of data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar score matching loss. |
Source code in torchebm/losses/score_matching.py
SlicedScoreMatching ¶
Bases: BaseScoreMatching
Sliced Score Matching (SSM) from Song et al. (2019).
A scalable variant that uses random projections to efficiently approximate the score matching objective, avoiding expensive Hessian trace computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | BaseModel | The energy-based model to train. | required |
n_projections | int | Number of random projections to use. | 5 |
projection_type | str | Type of projections ('rademacher', 'sphere', 'gaussian'). | 'rademacher' |
regularization_strength | float | Coefficient for regularization. | 0.0 |
custom_regularization | Optional[Callable] | A custom regularization function. | None |
use_mixed_precision | bool | Whether to use mixed-precision training. | False |
dtype | dtype | Data type for computations. | float32 |
device | Optional[Union[str, device]] | Device for computations. | None |
Example
Source code in torchebm/losses/score_matching.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | |
compute_loss(x, *args, **kwargs) ¶
Computes the sliced score matching loss using random projections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar sliced score matching loss. |
Source code in torchebm/losses/score_matching.py
forward(x, *args, **kwargs) ¶
Computes the sliced score matching loss for a batch of data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x | Tensor | Input data tensor of shape | required |
*args | Additional positional arguments. | () | |
**kwargs | Additional keyword arguments. | {} |
Returns:
| Type | Description |
|---|---|
Tensor | torch.Tensor: The scalar sliced score matching loss. |
Source code in torchebm/losses/score_matching.py
compute_eqm_ct(t, threshold=0.8, multiplier=4.0) ¶
Energy-compatible target scaling c(t) used in EqM.
The scaling function (truncated decay with gradient multiplier) is:
where \(a\) is the threshold and \(\lambda\) is the multiplier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t | Tensor | Time tensor of shape (batch_size,). | required |
threshold | float | Decay threshold \(a\), decay starts after \(t > a\). Default: 0.8. | 0.8 |
multiplier | float | Gradient multiplier \(\lambda\). Default: 4.0. | 4.0 |
Returns:
| Type | Description |
|---|---|
Tensor | Scaling factor c(t) of same shape as t. |
Source code in torchebm/losses/loss_utils.py
dispersive_loss(z) ¶
Dispersive loss (InfoNCE-L2 variant) for regularization.
Encourages diversity in generated samples by penalizing samples that are too close to each other in feature space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z | Tensor | Feature tensor of shape (batch_size, ...). | required |
Returns:
| Type | Description |
|---|---|
Tensor | Scalar dispersive loss. |
Source code in torchebm/losses/loss_utils.py
get_interpolant(interpolant_type) ¶
Get interpolant instance by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interpolant_type | str | One of 'linear', 'cosine', or 'vp'. | required |
Returns:
| Type | Description |
|---|---|
BaseInterpolant | Interpolant instance. |
Raises:
| Type | Description |
|---|---|
ValueError | If interpolant_type is not recognized. |
Source code in torchebm/losses/loss_utils.py
mean_flat(tensor) ¶
Take mean over all non-batch dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor | Tensor | Input tensor of shape (batch_size, ...). | required |
Returns:
| Type | Description |
|---|---|
Tensor | Tensor of shape (batch_size,) with mean over spatial dims. |