HamiltonianMonteCarlo
Methods and Attributes¶
Bases: BaseSampler
Hamiltonian Monte Carlo sampler for efficient exploration of complex probability distributions.
This class implements the Hamiltonian Monte Carlo algorithm, which uses concepts from Hamiltonian mechanics to generate more efficient proposals than traditional random-walk methods. By introducing an auxiliary momentum variable and simulating Hamiltonian dynamics, HMC can make distant proposals with high acceptance probability, particularly in high-dimensional spaces.
The method works by: 1. Augmenting the state space with momentum variables 2. Simulating Hamiltonian dynamics using leapfrog integration 3. Accepting or rejecting proposals using a Metropolis-Hastings criterion
Algorithm Summary
- If
x
is not provided, initialize it with Gaussian noise. - For each step:
a. Sample momentum from Gaussian distribution.
b. Perform leapfrog integration for
n_leapfrog_steps
steps. c. Accept or reject the proposal based on Metropolis-Hastings criterion. - Optionally track trajectory and diagnostics.
Key Advantages
- Efficiency: Performs well in high dimensions by avoiding random walk behavior
- Exploration: Can efficiently traverse complex probability landscapes
- Energy Conservation: Uses symplectic integrators that approximately preserve energy
- Adaptability: Can be adjusted through mass matrices to handle varying scales
Parameters:
Name | Type | Description | Default |
---|---|---|---|
energy_function
|
BaseEnergyFunction
|
Energy function to sample from. |
required |
step_size
|
float
|
Step size for leapfrog updates. |
0.1
|
n_leapfrog_steps
|
int
|
Number of leapfrog steps per proposal. |
10
|
mass
|
Optional[Tuple[float, Tensor]]
|
Optional mass matrix or scalar for momentum sampling. |
None
|
dtype
|
dtype
|
Data type to use for computations. |
float32
|
device
|
Optional[Union[Tuple[str, device]]]
|
Device to run computations on. |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
For invalid parameter ranges |
Methods:
Name | Description |
---|---|
_initialize_momentum |
Generate initial momentum from Gaussian distribution. |
_compute_kinetic_energy |
Compute the kinetic energy of the momentum. |
_leapfrog_step |
Perform a single leapfrog step. |
_leapfrog_integration |
Perform full leapfrog integration. |
hmc_step |
Perform one HMC step with Metropolis-Hastings acceptance. |
sample_chain |
Run the sampling process. |
_setup_diagnostics |
Initialize the diagnostics. |
Basic Usage
# Define energy function for a 2D Gaussian
energy_fn = GaussianEnergy(mean=torch.zeros(2), cov=torch.eye(2))
# Initialize HMC sampler
sampler = HamiltonianMonteCarlo(
energy_function=energy_fn,
step_size=0.1,
n_leapfrog_steps=10
)
# Sample 100 points from 5 parallel chains
samples = sampler.sample_chain(
dim=2,
k_steps=100,
n_samples=5
)
Parameter Relationships
- Decreasing
step_size
improves stability but may reduce mixing. - Increasing
n_leapfrog_steps
allows exploring more distant regions but increases computation. - The
mass
parameter can be tuned to match the geometry of the target distribution.
Source code in torchebm/samplers/hmc.py
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 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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 |
|
_initialize_momentum
¶
Initialize momentum variables from Gaussian distribution.
For HMC, momentum variables are sampled from a multivariate Gaussian distribution determined by the mass matrix. The kinetic energy is then: K(p) = p^T M^(-1) p / 2
Parameters:
Name | Type | Description | Default |
---|---|---|---|
shape
|
Size
|
Size of the momentum tensor to generate. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Momentum tensor drawn from appropriate Gaussian distribution. |
Note
When using a mass matrix M, we sample from N(0, M) rather than transforming samples from N(0, I).
Source code in torchebm/samplers/hmc.py
_compute_kinetic_energy
¶
Compute the kinetic energy given momentum.
The kinetic energy is defined as: $$ K(p) = p^T M^(-1) p / 2 $$
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p
|
Tensor
|
Momentum tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Kinetic energy for each sample in the batch. |
Source code in torchebm/samplers/hmc.py
_leapfrog_step
¶
_leapfrog_step(position: Tensor, momentum: Tensor, gradient_fn: Callable) -> Tuple[torch.Tensor, torch.Tensor]
Perform a single leapfrog integration step.
Implements the symplectic leapfrog integrator for Hamiltonian dynamics:
- Half-step momentum update: \(p(t+ε/2) = p(t) - (ε/2)∇U(q(t))\)
- Full-step position update: \(q(t+ε) = q(t) + εM^(-1)p(t+ε/2)\)
- Half-step momentum update: \(p(t+ε) = p(t+ε/2) - (ε/2)∇U(q(t+ε))\)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
position
|
Tensor
|
Current position tensor. |
required |
momentum
|
Tensor
|
Current momentum tensor. |
required |
gradient_fn
|
Callable
|
Function to compute gradient of potential energy. |
required |
Returns:
Type | Description |
---|---|
Tuple[Tensor, Tensor]
|
Tuple of (new_position, new_momentum). |
Source code in torchebm/samplers/hmc.py
_leapfrog_integration
¶
Perform a full leapfrog integration for n_leapfrog_steps.
Applies multiple leapfrog steps to simulate Hamiltonian dynamics for a trajectory of specified length. This is the energy_functions of the HMC proposal generation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
position
|
Tensor
|
Initial position tensor. |
required |
momentum
|
Tensor
|
Initial momentum tensor. |
required |
Returns:
Type | Description |
---|---|
Tuple[Tensor, Tensor]
|
Tuple of (final_position, final_momentum) after integration. |
Source code in torchebm/samplers/hmc.py
hmc_step
¶
Perform a single HMC step with Metropolis-Hastings acceptance.
This implements the energy_functions HMC algorithm:
- Sample initial momentum
- Compute initial Hamiltonian
- Perform leapfrog integration to propose new state
- Compute final Hamiltonian
- Accept/reject based on Metropolis-Hastings criterion
Parameters:
Name | Type | Description | Default |
---|---|---|---|
current_position
|
Tensor
|
Current position tensor of batch_shape (batch_size, dim). |
required |
Returns:
Name | Type | Description |
---|---|---|
new_position |
Tensor
|
Updated position tensor |
acceptance_prob |
Tensor
|
Probability of accepting each proposal |
accepted |
Tensor
|
Boolean mask indicating which proposals were accepted |
Source code in torchebm/samplers/hmc.py
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 |
|
sample
¶
sample(x: Optional[Tensor] = None, dim: int = None, n_steps: int = 100, n_samples: int = 1, return_trajectory: bool = False, return_diagnostics: bool = False) -> Tuple[torch.Tensor, torch.Tensor]
Generate samples using Hamiltonian Monte Carlo.
Runs an HMC chain for a specified number of steps, optionally returning the entire trajectory and/or diagnostics. The HMC algorithm uses Hamiltonian dynamics with leapfrog integration to propose samples efficiently, particularly in high-dimensional spaces.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Initial state to start sampling from. If None, random initialization is used. |
None
|
dim
|
int
|
Dimension of the state space when x is None. If None, will attempt to infer from the energy function. |
None
|
n_steps
|
int
|
Number of HMC steps to perform. |
100
|
n_samples
|
int
|
Number of parallel chains to run. |
1
|
return_trajectory
|
bool
|
If True, return the entire trajectory of samples. |
False
|
return_diagnostics
|
bool
|
If True, return diagnostics about the sampling process. |
False
|
Returns:
Type | Description |
---|---|
Tuple[Tensor, Tensor]
|
Final samples:
|
Note
This method uses automatic mixed precision when available on CUDA devices to improve performance while maintaining numerical stability for the Hamiltonian dynamics simulation.
Example
# Run 10 parallel chains for 1000 steps
samples, diagnostics = hmc.sample_chain(
dim=10,
k_steps=1000,
n_samples=10,
return_diagnostics=True
)
# Plot acceptance rates
import matplotlib.pyplot as plt
plt.plot(diagnostics[:-1, 3, 0, 0].cpu().numpy())
plt.ylabel('Acceptance Rate')
plt.xlabel('Step')
plt.show()
Source code in torchebm/samplers/hmc.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
|
_setup_diagnostics
¶
Initialize diagnostics tensor to track HMC sampling metrics.
Creates a tensor to store diagnostics information during sampling, including:
- Mean of samples (dimension 0)
- Variance of samples (dimension 1)
- Energy values (dimension 2)
- Acceptance rates (dimension 3)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dim
|
int
|
Dimensionality of the state space. |
required |
n_steps
|
int
|
Number of sampling steps. |
required |
n_samples
|
int
|
Number of parallel chains (if None, assumed to be 1). |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Empty tensor of batch_shape (k_steps, 4, n_samples, dim) to store diagnostics. |