This repository contains the code for the numerical experiments in the paper
Chenghao Li, Yuanyuan Lin, Yiqun Xiao, and Xingqiu Zhao. An Error Analysis of Implicit Score Matching-based Diffusion Models. Journal of Machine Learning Research. Accepted.
The environment used for the experiments includes:
- Python 3.12;
- PyTorch 2.7 with CUDA 12.8;
- NumPy, SciPy, Matplotlib, and PyYAML;
- Python Optimal Transport (POT), with
0.9.1 <= POT < 0.10.
The code has been tested on the CUHK High-Performance Computing Cluster and on the Monash M3 cluster with an NVIDIA L40S GPU.
After installing Anaconda, create and activate an environment named albireo:
conda create -n albireo python=3.12 numpy scipy matplotlib pyyaml pip
conda activate albireo
python -m pip install "torch==2.7.*" --index-url https://download.pytorch.org/whl/cu128
python -m pip install "pot>=0.9.1,<0.10"These commands create the environment directly. The PyTorch command follows the official installation instructions for previous versions.
If Conda is not initialized in the current shell, first run the following command with the actual Anaconda installation path:
source /path/to/anaconda3/etc/profile.d/conda.shThe installation above is for a Linux environment with an NVIDIA GPU and a compatible driver. The baseline, varying-dimension, and varying-early-stopping scripts automatically use CUDA when available and otherwise use the CPU. The runtime experiment requires CUDA because it synchronizes the GPU when measuring elapsed time.
The repository root refers to the folder containing ISM_Diffusion.py.
| File or folder | Description |
|---|---|
ISM_Diffusion.py |
Baseline ISM-Diffusion using automatic differentiation or the Hutchinson trace estimator. |
ISM_Diffusion_exactgrad.py |
Baseline ISM-Diffusion using explicit differentiation of the RePU network. |
DSM.py |
Baseline DSM using the ReLU or RePU network implementation. |
models.py |
Target distributions and the true forward-process score for the Gaussian mixture model. |
networks.py |
Score network architectures and explicit network derivatives. |
setup.py |
Forward diffusion, reverse-time sampling, and ISM loss functions. This is a code module, not a package installation script. |
evaluation.py |
Score estimation error, Sinkhorn approximation to Wasserstein-1 distance, and squared MMD. |
utils.py |
Random seeds, configuration handling, and saving results. |
experiment_manager/ |
Configuration and Slurm job generation for the baseline comparison, with example configs and jobs. |
vary_dim/ |
Experiment with varying dimension. |
vary_tlower/ |
Experiment with varying early stopping time. |
runtime/ |
Experiment comparing training time per iteration. |
The Python scripts in the three experiment folders are variants of the baseline scripts. Each folder includes its own supporting modules and configurations. Run these experiments from their corresponding folders, as shown below, because configuration and output paths are relative to the current working directory.
Activate albireo before running the code. Unless otherwise stated, each command block below starts from the repository root. Parentheses in the shell examples keep changes of working directory local to that command block.
All data are generated by the code; no external dataset is required.
The following target distributions are implemented in models.py:
| Model | --distribution |
Implementation |
|---|---|---|
| M1 | polygon_gmm |
Independent two-dimensional polygon Gaussian mixture blocks. Use an even value of dim. |
| M2 | gauss_push |
Gaussian pushforward through an invertible map of the form A tanh(z). |
| M3 | energy_model |
Quartic energy model, with samples generated by Langevin iterations. |
The following methods are included. The method names are also the folder names under experiment_manager/baseline/.
| Method | Tag | Python script | Example configuration ID |
|---|---|---|---|
ISM_AutoGrad |
A |
ISM_Diffusion.py |
baseline_A |
ISM_Hutchinson |
H |
ISM_Diffusion.py |
baseline_H |
ISM_ExactGrad |
E |
ISM_Diffusion_exactgrad.py |
baseline_E |
DSM_ReLU |
DL |
DSM.py |
baseline_DL |
DSM_RePU |
DP |
DSM.py |
baseline_DP |
ISM_AutoGrad computes the divergence using automatic differentiation, ISM_Hutchinson estimates it using the Hutchinson trace estimator, and ISM_ExactGrad computes it using explicit RePU network derivatives. The method named DSM_ReLU uses nn.LeakyReLU in the supplied implementation, with negative slope controlled by net.leak (default 0.1).
The baseline scripts accept two arguments:
--distribution: one ofpolygon_gmm,gauss_push, orenergy_model;--id: the configuration filename without the.yamlextension.
They load configs/<distribution>/<id>.yaml relative to the working directory. For example, run ISM-AutoGrad on M1 using the supplied configuration:
(
cd experiment_manager/baseline/ISM_AutoGrad
python ../../../ISM_Diffusion.py --distribution polygon_gmm --id baseline_A
)This loads experiment_manager/baseline/ISM_AutoGrad/configs/polygon_gmm/baseline_A.yaml. For DSM-RePU on M2:
(
cd experiment_manager/baseline/DSM_RePU
python ../../../DSM.py --distribution gauss_push --id baseline_DP
)Use the corresponding folder, script, and configuration ID in the table to run the other combinations. The supplied baseline configurations use dimension 10, 20 repetitions, and 20,000 training iterations per repetition.
experiment_manager/experiment_manager.py generates one configuration for each method-distribution combination and one Slurm array job per method. The three array tasks correspond to polygon_gmm, gauss_push, and energy_model.
Before running the generator, set CONFIG_ID and BASE_CONFIG as needed, and update work_path, ANACONDA_INIT, and the Slurm resource settings in generate_job_file() for the target cluster. Keep ENV_NAME = "albireo" if using the environment above. The supplied YAML configs can be reused, but the example job files should be regenerated with the actual Conda and working paths.
For example, when running the generator on the cluster and keeping each job in its generated method folder, use:
work_path = os.path.abspath(method_dir)
ANACONDA_INIT = "/path/to/anaconda3/etc/profile.d/conda.sh"
ENV_NAME = "albireo"Then generate the files:
(
cd experiment_manager
python experiment_manager.py
)With CONFIG_ID = "baseline", the files are written under experiment_manager/baseline/<method>/. Regeneration also rewrites the YAML configs, so incorporate any configuration changes into BASE_CONFIG first.
The generator does not copy the Python source files. For the working-directory arrangement above, copy the baseline scripts and their supporting modules into each method folder:
for method in ISM_AutoGrad ISM_Hutchinson ISM_ExactGrad DSM_ReLU DSM_RePU; do
cp ISM_Diffusion.py ISM_Diffusion_exactgrad.py DSM.py \
setup.py models.py networks.py evaluation.py utils.py \
"experiment_manager/baseline/$method/"
doneSubmit the regenerated jobs:
for method in ISM_AutoGrad ISM_Hutchinson ISM_ExactGrad DSM_ReLU DSM_RePU; do
(
cd "experiment_manager/baseline/$method"
sbatch ismd.job
)
doneIf CONFIG_ID is changed, replace baseline in the paths accordingly. Standard output and error are saved as ismd_<job-id>_<task-id>.out and .err in the submission directory.
vary_dim/Diffusion_var_dim.py compares all five methods on M1 for dimensions 8, 12, 16, and 20. It reads configs/var_dim_<dimension>.yaml and loops over the dimensions in DIM_LIST.
(
cd vary_dim
python Diffusion_var_dim.py
)The supplied configurations can be used directly. To change the dimension grid or generate new configurations, edit DIM_LIST, ND_LIST, NW_LIST, LR_LIST, and NITER_LIST in vary_dim/config_generator.py, then run:
(
cd vary_dim
python config_generator.py
)Keep DIM_LIST in the experiment script and plotting script consistent with the generated configs. The default settings are:
| Dimension | Hidden layers | Hidden width | Learning rate | Training iterations |
|---|---|---|---|---|
| 8 | 3 | 128 | 0.001 | 20,000 |
| 12 | 3 | 160 | 0.001 | 24,000 |
| 16 | 3 | 192 | 0.002 | 28,000 |
| 20 | 3 | 224 | 0.004 | 32,000 |
Each method-dimension combination is repeated 20 times. Results are saved in vary_dim/results/polygon_gmm_vardim/, using identifiers such as A_8 and DP_20.
vary_tlower/Diffusion_var_tlower.py compares all five methods on M1 while varying the early stopping time. The default TLOWER_LIST is:
[1e-1, 3e-2, 1e-2, 3e-3, 1e-3, 3e-4, 1e-4]The base configuration is vary_tlower/configs/var_tlower_main.yaml, with dimension 10 and 20 repetitions for each method and early stopping time.
(
cd vary_tlower
python Diffusion_var_tlower.py --id main
)Before running the script, you may modify TLOWER_LIST and METHODS in the Python file, and the remaining parameters in the YAML file. To use another base configuration, save it as configs/var_tlower_<id>.yaml and pass the corresponding --id.
Here, --distribution controls the output subfolder; the target distribution remains M1. Its default value is polygon_gmm_vartlower. Results are saved in vary_tlower/results/polygon_gmm_vartlower/, using identifiers such as main_A_0.01.
runtime/Diffusion_runtime.py compares average training time per iteration for all five methods on M1, using dimensions 8, 12, 16, and 20. Run it on a CUDA-enabled GPU:
(
cd runtime
python Diffusion_runtime.py
)The script reads configs/runtime_<dimension>.yaml. To change the settings, edit these files directly or edit runtime/config_generator_runtime.py and regenerate them:
(
cd runtime
python config_generator_runtime.py
)The default network widths, learning rates, and iteration counts are the same as in the varying-dimension table. Keep DIM_LIST consistent across the generator, experiment script, and plotting script.
The script runs one training procedure per method-dimension combination and divides the elapsed training-loop time by the number of iterations. This includes batch generation, forward diffusion, and optimization, but excludes distribution evaluation and reverse-time sample generation. The runtime script does not loop over experiment.num_repetitions.
Results are saved in runtime/results/polygon_gmm_runtime/evaluation_<tag>_<dimension>.csv. Each file contains the average time per iteration in seconds; the plotting script converts it to milliseconds. The script also prints the PyTorch version, CUDA build version, and GPU model.
The main YAML parameters are summarized below. In the three experiment variants, the script selects the method and network type from METHODS.
| Parameter | Description |
|---|---|
dim |
Data dimension; use an even number for M1. |
method |
autograd or hutchinson for ISM_Diffusion.py. |
experiment.seed |
Random seed. |
experiment.num_repetitions |
Number of training and evaluation repetitions, except in the runtime script. |
diffusion.beta |
Constant coefficient of the Ornstein–Uhlenbeck forward process. |
diffusion.t_lower, diffusion.t_upper |
Early stopping time and terminal time. |
diffusion.t_factor |
Multiplier for the lower training-time endpoint. Training times are sampled uniformly from [t_lower * t_factor, t_upper]. |
net.type |
repu or relu for DSM. |
net.nd, net.nw |
Number of hidden layers and hidden width. |
net.p |
Power of the RePU activation. |
net.leak |
Negative slope of the LeakyReLU activation in DSM_ReLU. |
train.lr, train.bs, train.num_iters |
Initial learning rate, batch size, and number of training iterations. |
train.step, train.gamma |
Step size and multiplicative decay factor for the learning-rate scheduler. |
train.log_step |
Logging interval during the first repetition. |
sampling.sample_step |
Number of Euler–Maruyama steps for reverse-time sampling. |
eva.score_val_size, eva.score_test_size |
Sample sizes for score validation and testing on M1. |
eva.w1_size_true, eva.w1_size_gen |
True and generated sample sizes for the Sinkhorn calculation. |
eva.mmd_size_true, eva.mmd_size_gen |
True and generated sample sizes for squared MMD. |
eva.w1_reg |
Entropic regularization parameter for Sinkhorn. |
eva.mmd_bandwidth |
Gaussian kernel bandwidth; null uses the implemented median heuristic. |
model.simple_matrix |
Whether to use the simpler matrix specification for M2 and M3. |
model.alpha |
Quartic coefficient in M3. |
The supplied configs use 5,000 true and 5,000 generated samples for each distribution discrepancy measure, and 20,000 pairs for score testing on M1. For a short trial run, reduce the training iterations, repetitions, sampling steps, and evaluation sample sizes in a separate configuration.
For the baseline and the two accuracy experiments, results are written to results/<distribution>/ relative to the working directory.
| File | Contents |
|---|---|
evaluation_<id>.csv |
One row per repetition, without a header. Columns are the Sinkhorn approximation to Wasserstein-1 distance, squared MMD, and, for M1, squared L2 score estimation error. M2 and M3 have only the first two columns. |
score_<id>.pth |
Score network state dictionary from the first repetition. |
gen_data_2d_<id>.npz |
First two coordinates of generated samples for M1, under the key gen_data_2d. The file is overwritten each repetition and therefore retains the final repetition. |
2d_visualization.npz |
True two-dimensional marginal density and samples for M1, generated by the baseline scripts for visualization. |
Mean and standard deviation of the evaluation results are also printed. Reusing an output directory and configuration ID overwrites the corresponding result files; use a different ID or directory to retain separate runs.
Run the plotting scripts after the corresponding experiments have finished. If the method list, dimension grid, early stopping grid, or configuration ID was changed, update the settings in the plotting script to match the available results.
experiment_manager/visualization_2d.py plots the true density, true samples, and generated samples from the five methods, using the first two coordinates of M1. It expects results under baseline/<method>/results/polygon_gmm/ and a copy of 2d_visualization.npz in its working directory:
(
cd experiment_manager
cp baseline/ISM_AutoGrad/results/polygon_gmm/2d_visualization.npz .
python visualization_2d.py
)If the experiments were run in separate cluster working folders, first copy their result folders into the corresponding baseline/<method>/ directories. The figures are saved as experiment_manager/baseline/2dim_visualization.png and .pdf. Change CONFIG_ID in the plotting script if using a different configuration group.
(
cd vary_dim
python visualization_var_dim.py
)
(
cd vary_tlower
python visualization_var_tlower.py
)
(
cd runtime
python visualization_runtime_millisecond.py
)The varying-dimension and varying-early-stopping scripts plot mean discrepancy measures over repetitions and the generated two-dimensional samples. The runtime script plots average time per iteration in milliseconds. Figures are saved in each experiment's results/ folder, in PDF format by default.
