# swyoon/pytorch-energy-based-model architecture

> Architecture diagram of the GitHub repository swyoon/pytorch-energy-based-model, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/swyoon/pytorch-energy-based-model
- Repository: https://github.com/swyoon/pytorch-energy-based-model

## Overview

This is a **Python/PyTorch educational/research repo** (not a deployed service) demonstrating **Energy-Based Models (EBMs)** and **Langevin dynamics sampling** on **toy 2D distributions**. The “system” is therefore best represented as **execution pipelines + module dependencies**, rather than the usual web-app components (LB/API/DB).

- “What are the runnable entry points?”
- “How do toy datasets flow into sampling/training?”
- “Where does Langevin dynamics fit (standalone sampling vs training inner-loop)?”
- “What artifacts are produced (plots/images/gifs, checkpoints)?”
- “Which files/modules own which responsibilities?”

##### File structure (map files to architectural roles)
Top-level files imply a “flat module” research layout:

##### Primary modules (core logic)
- `data.py`
**Toy distribution generation** (e.g., “8gaussians”). Produces tensors/samples for training or for “ground truth” visualization.
- `models.py`
**Neural network energy function** definitions (e.g., MLP returning scalar energy). Likely includes initialization/config helpers.
- `langevin.py`
**Langevin dynamics / MCMC sampler**. Takes an energy function (model) and performs iterative updates; returns sampled points.

##### Entry points / orchestration scripts (runtime)
- `train_energy_based_model.py`
The **training pipeline orchestrator**. Expected responsibilities:
- load/generate toy dataset via `data.py`
- instantiate model(s) via `models.py`
- run optimization loop (Torch optimizer)
- periodically call `langevin.py` for negative samples (typical EBM training pattern)
- write outputs (plots, checkpoints, logs)
- `make_langevin_gif.py`
**Visualization pipeline**. Likely:
- run Langevin sampling at intervals or load saved sample frames
- compile frames into a GIF

##### Supporting
- `tests.py`
- `imgs/`
Output artifacts: sample plots, training curves, generated GIF frames, etc.
- `README.md`, `LICENSE`, `.gitignore`

##### EBM training flow (with negative sampling loop)

This is what explains the actual algorithmic system.

- **Toy Data Generator** (`data.py`)
- **Energy Model / NN** (`models.py`)
- **Langevin Sampler** (`langevin.py`)
- **Training Orchestrator** (`train_energy_based_model.py`)
- **Visualization / GIF Builder** (`make_langevin_gif.py`)
- **Tests** (`tests.py`)
- **Artifacts Store** (`imgs/` directory)
- **External Library Layer** (PyTorch; optionally NumPy/Matplotlib/imageio if used)

##### Langevin sampling runtime
1. “Select toy distribution config” → `data.py` (for target distribution/initialization/plotting grid)
##### “Write frames/plots” → `imgs/`
6. Optionally `make_langevin_gif.py` reads frames from `imgs/` → writes `*.gif` back to `imgs/`

##### EBM training runtime
1. `train_energy_based_model.py` calls `data.py` → provides **positive samples** (real data from toy distribution)
##### Training loop
- Compute **positive phase**: `E(x_real)`
- Compute **negative phase**:
- Call `langevin.py` with current model to generate `x_neg` (MCMC)
- Compute `E(x_neg)`
- Compute loss (contrastive / score matching variant) and backprop via **PyTorch autograd**
- Optimizer step updates parameters
4. Periodically: save plots/checkpoints → `imgs/` (and maybe local checkpoint files if present)

##### Architectural patterns/design principles to highlight
- **Pipeline orchestration pattern**: “scripts” orchestrate reusable modules.
- **Separation of concerns**:
- `data.py` = data generation (domain)
- `models.py` = parameterized energy function (learning)
- `langevin.py` = inference/sampling method (MCMC)
- scripts = experiments + IO
- **Core algorithmic feedback loop** in EBMs:
- model parameters affect sampler
- sampler produces negatives used to update model

##### Technologies / libraries to label explicitly
- **PyTorch**: tensors, autograd, `nn.Module`, optimizers
- Any plotting/IO libs if used (commonly matplotlib, imageio/PIL) as “Visualization/Export dependencies”
- Python runtime environment requirement (python>=3.6 per README; torch>=1.2)

## Diagram (Mermaid)

```mermaid
flowchart TD

%% =======================
%% High-level: Repo Layout
%% =======================

U["User / Researcher"]:::external

subgraph "Runnable Entry Points (scripts)"
direction TB
Train["train_energy_based_model.py\n(EBM training orchestrator)"]:::entry
Gif["make_langevin_gif.py\n(Visualization / GIF builder)"]:::entry
Tests["tests.py\n(Sanity checks)"]:::entry
end

subgraph "Core Reusable Modules"
direction TB
Data["data.py\n(Toy 2D distributions)"]:::module
Model["models.py\n(EnergyModel: NN energy function)"]:::module
Sampler["langevin.py\n(Langevin dynamics sampler)"]:::module
end

subgraph "Artifacts / Outputs"
direction TB
Imgs[("imgs/\n(plots, frames, gifs, checkpoints)")]:::artifact
end

subgraph "External Dependencies"
direction TB
Torch["PyTorch\n(tensors, autograd, nn.Module, optimizers)"]:::external
Viz["Visualization / Export libs\n(matplotlib, imageio/PIL etc.)"]:::external
Python["Python runtime\n(python>=3.6)"]:::external
end

Readme["README.md\n(Project overview; legacy entrypoint names note)"]:::doc

%% =======================
%% Static dependencies
%% =======================

U -->|"runs"| Train
U -->|"runs"| Gif
U -->|"runs"| Tests
U -->|"reads"| Readme

Train -->|"imports/uses"| Data
Train -->|"imports/uses"| Model
Train -->|"imports/uses"| Sampler
Train -->|"writes"| Imgs
Train -->|"uses"| Torch
Train -->|"uses"| Viz

Gif -->|"imports/uses"| Sampler
Gif -->|"reads/writes"| Imgs
Gif -->|"uses"| Viz

Tests -->|"imports/uses"| Data
Tests -->|"imports/uses"| Model
Tests -->|"imports/uses"| Sampler
Tests -->|"uses"| Torch

Readme -.->|"mentions legacy names\n(run_langevin.py/run_ebm.py/model.py)\n(actual file tree differs)"| Train
Readme -.->|"mentions legacy names\n(run_langevin.py etc.)"| Gif

Python -.->|"runtime for"| Train
Python -.->|"runtime for"| Gif
Python -.->|"runtime for"| Tests

%% =======================
%% Dynamic view: Sampling-only flow
%% =======================
subgraph "Runtime Dataflow A: Langevin sampling (standalone demo)"
direction TB
A0["Select toy distribution config"]:::flow
A1["Generate target samples / grid (optional)"]:::flow
A2["Initialize particles x0"]:::flow
A3["Iterate Langevin steps\nx_{t+1} = x_t - step*∇xE(x_t) + noise"]:::flow
A4["Samples x_T + frames/plots"]:::flow

A0 -->|"params"| A1
A1 -->|"target distribution info"| Data
A0 -->|"x0 spec"| A2
A2 -->|"x0 tensors"| Sampler
Sampler -->|"calls E(x), ∇xE(x)"| Model
Model -->|"autograd gradients"| Torch
Sampler -->|"samples x_t"| A3
A3 -->|"frames/plots"| A4
A4 -->|"write frames/plots"| Imgs
Imgs -->|"read frames"| Gif
Gif -->|"compile *.gif"| Imgs
end

%% =======================
%% Dynamic view: Training flow with negative sampling loop
%% =======================
subgraph "Runtime Dataflow B: EBM training (positive vs negative phase)"
direction TB

B0["Generate positive samples x_real"]:::flow
B1["Instantiate EnergyModel"]:::flow
B2["Training loop (epochs/steps)"]:::flow

Bpos["Positive phase:\ncompute E(x_real)"]:::flow
Bneg0["Negative phase:\ncall Langevin to sample x_neg"]:::flow
Bneg1["Compute E(x_neg)"]:::flow
Bloss["Loss + backprop\n(contrastive / score-matching variant)"]:::flow
Bopt["Optimizer step\n(update model params)"]:::flow
Bsave["Periodic saves:\nplots/checkpoints/logs"]:::flow

Train -->|"requests"| B0
B0 -->|"x_real tensors"| Data
Data -->|"x_real"| Train

Train -->|"creates"| B1
B1 -->|"EnergyModel"| Model
Model -->|"nn.Module params"| Torch

Train -->|"runs"| B2
B2 -->|"x_real"| Bpos
Bpos -->|"E(x_real)"| Model

B2 -->|"invoke sampler"| Bneg0
Bneg0 -->|"x_init / replay buffer (optional)"| Sampler
Sampler -->|"needs E(x), ∇xE(x)"| Model
Bneg0 -->|"x_neg"| Bneg1
Bneg1 -->|"E(x_neg)"| Model

Bpos -->|"energies"| Bloss
Bneg1 -->|"energies"| Bloss
Bloss -->|"autograd backward"| Torch
Torch -->|"grads"| Bopt
Bopt -->|"optimizer (Adam/SGD)"| Torch
Bopt -->|"updates"| Model

B2 -->|"periodically"| Bsave
Bsave -->|"plots/ckpts"| Imgs
end

%% =======================
%% Click events (component mapping)
%% =======================
click Data "https://github.com/swyoon/pytorch-energy-based-model/blob/master/data.py"
click Model "https://github.com/swyoon/pytorch-energy-based-model/blob/master/models.py"
click Sampler "https://github.com/swyoon/pytorch-energy-based-model/blob/master/langevin.py"
click Train "https://github.com/swyoon/pytorch-energy-based-model/blob/master/train_energy_based_model.py"
click Gif "https://github.com/swyoon/pytorch-energy-based-model/blob/master/make_langevin_gif.py"
click Tests "https://github.com/swyoon/pytorch-energy-based-model/blob/master/tests.py"
click Imgs "https://github.com/swyoon/pytorch-energy-based-model/tree/master/imgs/"
click Readme "https://github.com/swyoon/pytorch-energy-based-model/blob/master/README.md"

%% =======================
%% Styles
%% =======================
classDef entry fill:#2ecc71,stroke:#1e8449,color:#0b2e13,stroke-width:2px;
classDef module fill:#3498db,stroke:#1f618d,color:#0b1f33,stroke-width:2px;
classDef artifact fill:#95a5a6,stroke:#5d6d7e,color:#1b2631,stroke-width:2px;
classDef external fill:#f4d03f,stroke:#b7950b,color:#2a1f00,stroke-width:2px,stroke-dasharray: 4 3;
classDef doc fill:#e8daef,stroke:#7d3c98,color:#2a1233,stroke-width:2px;
classDef flow fill:#f8f9f9,stroke:#7b7d7d,color:#1c1c1c,stroke-width:1.5px;
```
