Skip to content

TorchEBM Examples

This section contains practical examples that demonstrate how to use TorchEBM for energy-based modeling. Each example is fully tested and focuses on a specific use case or feature.

  • Energy Landscape Visualization


    Visualize energy functions to understand their landscapes and characteristics.

    Energy Visualization

  • Langevin Dynamics Sampling


    Sample from various distributions using Langevin dynamics.

    Langevin Dynamics

  • Hamiltonian Monte Carlo


    Learn to use Hamiltonian Monte Carlo for efficient sampling.

    Hamiltonian Monte Carlo

  • Langevin Sampler Trajectory


    Visualize sampling trajectories on multimodal energy landscapes.

    Langevin Trajectory

Example Structure

Example Format

Each example follows a consistent structure to help you understand and apply the concepts:

  1. Overview: Brief explanation of the example and its purpose
  2. Code: Complete, runnable code for the example
  3. Explanation: Detailed explanation of key concepts and code sections
  4. Extensions: Suggestions for extending or modifying the example

Running the Examples

All examples can be run directly from the command line:

# Clone the repository
git clone https://github.com/soran-ghaderi/torchebm.git
cd torchebm

# Set up your environment
pip install -e .

# Run an example
python examples/energy_fn_visualization.py

Prerequisites

To run these examples, you'll need:

  • Python 3.7+
  • PyTorch 1.9+
  • NumPy
  • Matplotlib

If you haven't installed TorchEBM yet, see the Installation guide.

GPU Acceleration

Most examples support GPU acceleration and will automatically use CUDA if available:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
energy_fn = GaussianEnergy(mean, cov).to(device)

Example Files

You can find all example files in the examples directory of the TorchEBM repository:

File Description
energy_fn_visualization.py Visualizes various energy function landscapes
langevin_dynamics_sampling.py Demonstrates Langevin dynamics sampling
hmc_examples.py Shows usage of Hamiltonian Monte Carlo
lagevin_sampler_trajectory.py Visualizes sampling trajectories

Additional Resources

For more in-depth information about the concepts demonstrated in these examples, see:

What's Next?

After exploring these examples, you might want to:

  1. Check out the API Reference for detailed documentation
  2. Read the Developer Guide to learn about contributing
  3. Look at the roadmap for upcoming features