maurograd-dgm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +135 -0
  3. data/LICENSE +21 -0
  4. data/README.md +442 -0
  5. data/lib/maurograd/dgm/datasets/download.rb +53 -0
  6. data/lib/maurograd/dgm/datasets/idx.rb +39 -0
  7. data/lib/maurograd/dgm/datasets/loader.rb +62 -0
  8. data/lib/maurograd/dgm/datasets/mnist.rb +96 -0
  9. data/lib/maurograd/dgm/datasets/toy_2d.rb +96 -0
  10. data/lib/maurograd/dgm/datasets.rb +19 -0
  11. data/lib/maurograd/dgm/ddim.rb +194 -0
  12. data/lib/maurograd/dgm/ddpm.rb +188 -0
  13. data/lib/maurograd/dgm/distributions/bernoulli.rb +54 -0
  14. data/lib/maurograd/dgm/distributions/categorical.rb +62 -0
  15. data/lib/maurograd/dgm/distributions/mixture_of_gaussians.rb +79 -0
  16. data/lib/maurograd/dgm/distributions/normal.rb +88 -0
  17. data/lib/maurograd/dgm/distributions/standard_normal.rb +42 -0
  18. data/lib/maurograd/dgm/distributions.rb +49 -0
  19. data/lib/maurograd/dgm/ebm.rb +211 -0
  20. data/lib/maurograd/dgm/flow_matching.rb +303 -0
  21. data/lib/maurograd/dgm/flows.rb +245 -0
  22. data/lib/maurograd/dgm/gan.rb +366 -0
  23. data/lib/maurograd/dgm/image_grid.rb +78 -0
  24. data/lib/maurograd/dgm/likelihoods.rb +33 -0
  25. data/lib/maurograd/dgm/linear_vae.rb +140 -0
  26. data/lib/maurograd/dgm/metrics.rb +85 -0
  27. data/lib/maurograd/dgm/networks.rb +151 -0
  28. data/lib/maurograd/dgm/noise_schedule.rb +97 -0
  29. data/lib/maurograd/dgm/normalizing_flow.rb +225 -0
  30. data/lib/maurograd/dgm/ppca.rb +337 -0
  31. data/lib/maurograd/dgm/priors.rb +96 -0
  32. data/lib/maurograd/dgm/slerp.rb +28 -0
  33. data/lib/maurograd/dgm/trainer.rb +158 -0
  34. data/lib/maurograd/dgm/vae.rb +208 -0
  35. data/lib/maurograd/dgm/version.rb +5 -0
  36. data/lib/maurograd/dgm.rb +64 -0
  37. data/lib/maurograd-dgm.rb +3 -0
  38. metadata +143 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4bf93b847999c201f1bbeff7bb2e3bd905c9790b6b728dd17f30ec5f6220a18e
4
+ data.tar.gz: 1b216005c6eb2e1925d2af048f8944f1f9ef97f623b3fa1f39328a89e605820c
5
+ SHA512:
6
+ metadata.gz: a39154959811ff35249dbfe28b026434cbb7ca91e547a4614478057e7c5306daf38b035722199355af96db15cd43802bf294b4db21f4fbca818bc2a3b4ddd292
7
+ data.tar.gz: dab0999dd8e5a1f9466b25ca34b96c3735ecd1adc5a7b12d8dc399f0fc574fa7eb407d33b8a4f9100747ceccdec6a1ef6662944d6faadf67d6741411d955ac65
data/CHANGELOG.md ADDED
@@ -0,0 +1,135 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions
5
+ follow [Semantic Versioning](https://semver.org/): before 1.0, a minor
6
+ release may break things.
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-11-29
11
+
12
+ First public release. Requires Maurograd 0.3.
13
+
14
+ ### Added
15
+
16
+ - Project skeleton: gemspec, `Maurograd::DGM`, CI on Linux and macOS
17
+ (with the MLX backend), and a Gemfile that uses a sibling Maurograd
18
+ checkout when there is one.
19
+ - `Distributions`: `StandardNormal`, `Normal` (diagonal, with
20
+ `rsample` for the reparameterization trick and a closed-form
21
+ `kl_divergence`), `Bernoulli` (on logits), `Categorical` and
22
+ `MixtureOfGaussians`. `log_prob` returns one value per sample, summed
23
+ over every axis but the first.
24
+ - `Datasets`: `MNIST` and `FashionMNIST` (downloaded on first use and
25
+ checked by MD5), `Datasets.binarize`, the 2D sets of `Toy2D` (swiss
26
+ roll, moons, a ring of Gaussians with its true density, a
27
+ checkerboard), and `Loader`, which batches Numo data into Tensors on a
28
+ backend.
29
+ - `Trainer`: the loop for models trained by minimizing `model.call(x)`,
30
+ with validation, early stopping that restores the best weights, and a
31
+ per-epoch block.
32
+ - `ImageGrid.make` and `.save`: batches of images tiled into a grid and
33
+ written as PNG, with no image library needed.
34
+ - `PPCA`, probabilistic PCA: fitted in closed form (`PPCA.closed_form`),
35
+ by EM (`PPCA.em`) or by gradient ascent on its exact log-likelihood
36
+ (`model.call(x)`, with Maurograd's `logdet` and `solve` on M x M
37
+ matrices, through the Woodbury identity); `log_prob`, `posterior`,
38
+ `reconstruct`, `sample`, and `PPCA.subspace_angle` to compare fits.
39
+ - `LinearVAE`: a VAE with linear encoder and decoder, whose ELBO has a
40
+ closed form (`elbo`, checked against `monte_carlo_elbo`); trained, it
41
+ finds PPCA's subspace. `to_ppca` gives its decoder as a `PPCA`.
42
+ - `examples/ppca_mnist.rb`: the four fits on MNIST, compared.
43
+ - `VAE`: a variational autoencoder around your encoder and decoder, with
44
+ the ELBO (`elbo`, `elbo_terms`; the KL exact when the prior allows it,
45
+ Monte Carlo otherwise), β weighting (`beta:`), importance-sampled
46
+ `log_likelihood`, and `sample`, `reconstruct`, `decode`, `interpolate`.
47
+ - `Priors::StandardNormal`, `Priors::MixtureOfGaussians` (learned) and
48
+ `Priors::VampPrior` (pseudo-inputs through the shared encoder).
49
+ - `Likelihoods::Bernoulli` (on logits) and `Likelihoods::Gaussian`
50
+ (fixed or learned variance).
51
+ - `examples/vae_mnist.rb`: MLP and convolutional VAEs on binarized MNIST,
52
+ with any prior, likelihood and β; test NLL by importance sampling, and
53
+ grids of samples, reconstructions and interpolations.
54
+ - `NoiseSchedule`: the forward process's betas, alphas and `alpha_bars`,
55
+ `linear` (Ho et al., 2020) or `cosine` (Nichol and Dhariwal, 2021), with
56
+ `posterior_variances` and `signal_to_noise`.
57
+ - `DDPM`: a denoising diffusion model around a noise-predicting network:
58
+ `q_sample` (the closed-form forward process), the noise-matching loss
59
+ (`call`, and `loss_at` a given step), and ancestral `sample`, with either
60
+ reverse variance, x_0 clipping, and the states along the way.
61
+ - `DDIM`: the deterministic (or, with `eta`, stochastic) sampler for a
62
+ trained `DDPM`, on any subsequence of its steps; `encode`, which inverts
63
+ it, optionally refined by fixed-point iteration so that `decode`
64
+ gives the image back; and spherical `interpolate` through the noises.
65
+ - `Networks`: `SinusoidalEmbedding`, `TimeMLP` and `UNet` (residual
66
+ blocks with GroupNorm and a time embedding), called as
67
+ `network.call(x, t)`.
68
+ - `Trainer`: `max_grad_norm:`, `ema:` and `schedule:`, applied around
69
+ every optimizer step.
70
+ - `examples/diffusion_mnist.rb`: a DDPM on MNIST or Fashion-MNIST, sampled
71
+ with DDPM and DDIM, with grids of the denoising and of interpolations.
72
+ - `NormalizingFlow`: a flow of invertible layers with the exact
73
+ log-likelihood (`log_prob`, `transform`, `inverse`, `encode`, `decode`),
74
+ `sample` with a temperature, and, for discrete data (`levels:`), uniform
75
+ dequantization and `bits_per_dim`. A flow on vectors also works as a
76
+ VAE's prior.
77
+ - `Flows`: `AffineCoupling` (with a tanh-bounded, learned scale),
78
+ `Squeeze`, `Logit`; alternating, checkerboard and channel masks; and
79
+ coupling networks (`Flows.mlp`, `Flows.cnn`) whose last layer starts at
80
+ zero, so that a coupling starts as the identity.
81
+ - `RealNVP.for_vectors` and `RealNVP.for_images`: the usual RealNVP
82
+ architectures, built from those layers.
83
+ - `FlowMatching`: conditional flow matching on straight lines (rectified
84
+ flow) around a velocity network: the regression loss (`call`,
85
+ `loss_at`), `sample` and `decode` with Euler or Heun steps, `encode`
86
+ (the ODE backward), spherical `interpolate`, and `log_prob` by the
87
+ instantaneous change of variables, with the exact divergence or
88
+ Hutchinson's estimate.
89
+ - `DGM.slerp`: the spherical interpolation `DDIM` and `FlowMatching`
90
+ share.
91
+ - `examples/flows_2d.rb`: RealNVP and flow matching on three 2D sets,
92
+ compared by test log-likelihood and by pictures of samples and
93
+ densities.
94
+ - `examples/realnvp_mnist.rb`: RealNVP on dequantized MNIST, in bits per
95
+ dimension, sampled at several temperatures.
96
+ - `examples/flow_matching_mnist.rb`: flow matching with the diffusion
97
+ example's UNet and recipe, compared with DDIM at equal numbers of network
98
+ evaluations, with its test bits per dimension by the ODE.
99
+ - `GAN`: a generator and a discriminator you build, with four losses
100
+ (`:non_saturating`, `:minimax`, `:hinge`, `:least_squares`),
101
+ `discriminator_loss`, `generator_loss`, `sample`, `decode` and
102
+ `interpolate`; `GAN.for_vectors` builds one of MLPs, `GAN.for_images` a
103
+ DCGAN.
104
+ - `GANTrainer`: alternates the discriminator's and the generator's steps,
105
+ each with its own optimizer, optionally with several discriminator steps
106
+ per generator step and an EMA of the generator's weights.
107
+ - `Metrics.frechet_distance`: the Fréchet distance between Gaussians
108
+ fitted to two sets of features (FID's formula), with a matrix square
109
+ root by the Newton-Schulz iteration.
110
+ - `examples/gan_2d.rb`: the four GAN losses on three 2D sets, compared by
111
+ the energy distance to the data, mode coverage and pictures, for the
112
+ averaged and the last generator.
113
+ - `examples/dcgan_mnist.rb`: a DCGAN on MNIST or Fashion-MNIST.
114
+ - `examples/sample_quality.rb`: the MNIST models of the other examples
115
+ compared by the Fréchet distance in the features of an MNIST
116
+ classifier.
117
+ - `EBM`: an energy-based model around any network with a scalar output,
118
+ trained by contrastive divergence with short-run Langevin dynamics from
119
+ a replay buffer (`langevin`, `sample`, `energy`,
120
+ `unnormalized_log_prob`), with optional gradient clamping and noise on
121
+ the data for images.
122
+ - `examples/ebm_2d.rb`: EBMs on three 2D sets, with test log-likelihoods
123
+ from a normalizing constant summed over a grid, and pictures of short
124
+ and long chains.
125
+ - `examples/ebm_mnist.rb`: an EBM on MNIST or Fashion-MNIST, keeping the
126
+ last weights from before training runs away.
127
+ - YARD tags (`@param`, `@return`, `@raise`) on the public methods of the
128
+ models, the trainers, the flow layers' builders and `Metrics`, with the
129
+ types and shapes of arguments and results; `.yardopts`, and YARD as a
130
+ development dependency.
131
+ - `examples/vae_mnist.rb` saves its weights, with its options, and
132
+ `examples/sample_quality.rb` scores the VAEs it finds.
133
+
134
+ [Unreleased]: https://github.com/mtortonesi/maurograd-dgm/compare/v0.1.0...HEAD
135
+ [0.1.0]: https://github.com/mtortonesi/maurograd-dgm/releases/tag/v0.1.0
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mauro Tortonesi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,442 @@
1
+ # maurograd-dgm
2
+
3
+ Deep generative models for Ruby, built on
4
+ [Maurograd](https://github.com/mtortonesi/maurograd), a tensor autograd
5
+ framework written to be read end to end. This library aims to be read as
6
+ well: each model is a short, commented implementation of its method, with
7
+ tests of its math.
8
+
9
+ **Status:** 0.1.0, the first release. Before 1.0, a minor release may
10
+ break things.
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ gem install maurograd-dgm
16
+ ```
17
+
18
+ This installs Maurograd, which compiles a C extension: it needs a C
19
+ compiler, and on Linux the OpenBLAS headers and LAPACKE, e.g. on
20
+ Debian/Ubuntu `sudo apt-get install build-essential libopenblas-dev
21
+ liblapacke-dev` (see [Maurograd's installation
22
+ notes](https://github.com/mtortonesi/maurograd#installation)).
23
+ For the Apple Silicon GPU, also install mlx-c and the `maurograd-mlx` gem,
24
+ then pick the backend with `MAUROGRAD_BACKEND=mlx` or
25
+ `Maurograd.backend = :mlx`:
26
+
27
+ ```sh
28
+ brew install mlx-c
29
+ gem install maurograd-mlx
30
+ ```
31
+
32
+ The examples download MNIST and Fashion-MNIST on first use, into `data/`
33
+ under the working directory, and write their images and weights to `out/`.
34
+
35
+ ## Planned models
36
+
37
+ In the order they will be built:
38
+
39
+ 1. Probabilistic PCA (done: `PPCA`, `LinearVAE`)
40
+ 2. Variational autoencoders: Bernoulli and Gaussian decoders; standard
41
+ normal, mixture-of-Gaussians and VampPrior priors; β-VAE; convolutional
42
+ versions (done: `VAE`, `Priors`, `Likelihoods`)
43
+ 3. DDPM and DDIM (done: `DDPM`, `DDIM`, `NoiseSchedule`, `Networks`)
44
+ 4. Normalizing flows (RealNVP) and flow matching (done: `NormalizingFlow`,
45
+ `Flows`, `RealNVP`, `FlowMatching`)
46
+ 5. GANs: an MLP GAN on 2D data, then DCGAN (done: `GAN`, `GANTrainer`,
47
+ `Metrics`)
48
+ 6. Energy-based models, sampled with Langevin dynamics (done: `EBM`)
49
+
50
+ ## Conventions
51
+
52
+ Models wrap networks you build, so the library supplies the method and you
53
+ choose the architecture:
54
+
55
+ ```ruby
56
+ model = Maurograd::DGM::VAE.new(encoder_net, decoder_net, latent_dim)
57
+ loss = model.call(x) # the training loss, e.g. the negative ELBO
58
+ loss.backward
59
+ samples = model.sample(16) # drawn under Maurograd.no_grad
60
+ model.log_prob(x) # for models with a tractable density
61
+ ```
62
+
63
+ Models are Maurograd `Layers::Module`s, so `parameters`, `train`/`eval`,
64
+ `to(:mlx)` and `state_dict` work on them as on any layer, and every model
65
+ runs on every Maurograd backend.
66
+
67
+ ## Building blocks
68
+
69
+ What the models share, usable on their own:
70
+
71
+ ```ruby
72
+ include Maurograd::DGM
73
+
74
+ x, _ = Datasets::MNIST.load(split: :train) # downloaded into ./data
75
+ x = Datasets.binarize(x.reshape(x.shape[0], 784), seed: 1)
76
+ loader = Datasets::Loader.new(x, batch_size: 128, backend: :mlx, seed: 1)
77
+
78
+ q = Distributions::Normal.new(mean, log_var) # an encoder's output
79
+ z = q.rsample # reparameterized
80
+ kl = q.kl_divergence(Distributions::StandardNormal.new(16))
81
+ log_px = Distributions::Bernoulli.new(logits).log_prob(x_batch)
82
+
83
+ Trainer.new(model, optimizer, max_epochs: 100, patience: 10)
84
+ .fit(loader, validation: validation_loader)
85
+ ImageGrid.save(samples.reshape(64, 1, 28, 28), "samples.png")
86
+ ```
87
+
88
+ - **Distributions**: `StandardNormal`, `Normal` (diagonal), `Bernoulli`,
89
+ `Categorical`, `MixtureOfGaussians`. `log_prob(x)` gives one value per
90
+ sample, summed over every axis but the first.
91
+ - **Datasets**: `MNIST`, `FashionMNIST`, `Datasets.binarize`, and
92
+ `Toy2D`'s swiss roll, moons, ring of Gaussians and checkerboard, where
93
+ what a model learned shows in a scatter plot. `Loader` batches any of
94
+ them into Tensors on a backend.
95
+ - **Trainer**: the training loop for models trained by minimizing
96
+ `model.call(x)`, with early stopping on a validation set, and optional
97
+ gradient clipping, an EMA of the weights and a learning-rate schedule.
98
+ - **Networks**: networks that take a time with the data,
99
+ `network.call(x, t)`, for diffusion and flow matching: `TimeMLP` for
100
+ vectors, `UNet` for images, and their `SinusoidalEmbedding`.
101
+ - **ImageGrid**: tiles samples into a PNG, without an image library.
102
+ - **Metrics**: the Fréchet distance between Gaussians fitted to two sets
103
+ of features, FID's formula, to compare models by their samples.
104
+
105
+ ## Probabilistic PCA
106
+
107
+ `PPCA` is the linear-Gaussian latent variable model x = W z + mu + noise,
108
+ the only model here with an exact maximum-likelihood fit. It can be fitted
109
+ three ways, which agree:
110
+
111
+ ```ruby
112
+ model = Maurograd::DGM::PPCA.closed_form(x, 16) # eigendecomposition
113
+ model = Maurograd::DGM::PPCA.em(x, 16) # expectation-maximization
114
+ model = Maurograd::DGM::PPCA.new(784, 16) # gradient ascent: model.call(x)
115
+ # is the negative log-likelihood
116
+ model.log_likelihood(x_test)
117
+ ```
118
+
119
+ `LinearVAE` fits the same model by its ELBO, with a linear encoder, and
120
+ finds the same subspace (Lucas et al., 2019). `examples/ppca_mnist.rb`
121
+ runs all four on MNIST:
122
+
123
+ ```
124
+ fit train LL test LL sigma^2 angle time
125
+ closed form 265.11 262.44 0.02738 0.00° 0.4s
126
+ EM 265.11 262.44 0.02738 0.00° 1.3s
127
+ gradient 265.05 262.39 0.02739 0.25° 5.5s
128
+ linear VAE 262.73 260.10 0.02790 0.47° 4.9s
129
+ ```
130
+
131
+ (Log-likelihoods in nats per image, of a density on pixel values; angle:
132
+ between each fit's subspace and the closed form's; times on an Apple M5,
133
+ with the gradient fits on MLX.)
134
+
135
+ ## Variational autoencoders
136
+
137
+ `VAE` wraps an encoder (to `[N, 2L]`: the posterior's mean and
138
+ log-variance) and a decoder (to the parameters of p(x | z)), with a prior
139
+ and a likelihood to choose:
140
+
141
+ ```ruby
142
+ vae = Maurograd::DGM::VAE.new(encoder, decoder, 16,
143
+ prior: Maurograd::DGM::Priors::VampPrior.new(encoder, x_train[0...500, true]),
144
+ likelihood: Maurograd::DGM::Likelihoods::Bernoulli.new, # the default
145
+ beta: 1.0)
146
+ loss = vae.call(x) # -ELBO, averaged over the batch
147
+ vae.log_likelihood(x, samples: 100) # importance-sampled log p(x), per sample
148
+ vae.sample(64); vae.reconstruct(x); vae.interpolate(a, b, steps: 10)
149
+ ```
150
+
151
+ Priors: `StandardNormal` (exact KL), `MixtureOfGaussians` and `VampPrior`
152
+ (learned, with a Monte Carlo KL). Likelihoods: `Bernoulli` on logits, and
153
+ `Gaussian`, with a fixed or learned variance. `examples/vae_mnist.rb`
154
+ trains them on binarized MNIST (latent dimension 16, Adam at 1e-3,
155
+ batches of 128, `--epochs 100` with early stopping on 10000 validation
156
+ images, 5 epochs of patience); test NLL, importance-sampled with 100
157
+ samples, and the epochs trained:
158
+
159
+ | encoder and decoder | prior | test -ELBO | test NLL | epochs |
160
+ |---|---|---|---|---|
161
+ | MLP, 2 x 256 hidden | standard normal | 98.74 | 93.41 | 67 |
162
+ | MLP, 2 x 256 hidden | mixture of 16 Gaussians | 96.82 | 91.79 | 61 |
163
+ | MLP, 2 x 256 hidden | VampPrior, 500 pseudo-inputs | 95.17 | 90.64 | 65 |
164
+ | conv / ConvTranspose2D | standard normal | 96.01 | 91.03 | 67 |
165
+
166
+ (In nats; on an Apple M5 with MLX, an MLP epoch takes 0.7 s and a
167
+ convolutional one 2.6 s; on the CPU, 3 s and 9 s.) The order of the priors
168
+ is the one Tomczak and Welling (2018) report; their numbers are lower, with
169
+ larger models, 40 latent dimensions and KL warm-up.
170
+
171
+ A Gaussian likelihood with unit variance (`--likelihood gaussian`) is a
172
+ poor model of binary pixels: the
173
+ reconstruction term is so weak next to the KL that the posterior stays
174
+ close to the prior, and samples are blurry.
175
+
176
+ ## Diffusion models
177
+
178
+ `DDPM` wraps a network that predicts the noise in x_t, called as
179
+ `network.call(x, t)`; `DDIM` samples from the same trained model in fewer
180
+ steps, and maps images back to noise:
181
+
182
+ ```ruby
183
+ unet = Maurograd::DGM::Networks::UNet.new(in_channels: 1, channels: [32, 64, 128])
184
+ model = Maurograd::DGM::DDPM.new(unet, shape: [1, 28, 28]) # data in [-1, 1]
185
+ loss = model.call(x) # the noise's mean squared error
186
+ model.sample(64) # 1000 stochastic steps
187
+ ddim = Maurograd::DGM::DDIM.new(model)
188
+ ddim.sample(64, steps: 50) # 50 deterministic steps (eta: 0)
189
+ noise = ddim.encode(x, iterations: 2) # ddim.decode(noise) gives x back
190
+ ddim.interpolate(a, b, count: 10) # through the noises, spherically
191
+ ```
192
+
193
+ The samplers are tested against the exact noise predictor of Gaussian data,
194
+ which needs no training: DDPM then samples the data's distribution, DDIM
195
+ approaches it as its steps grow, DDIM with eta = 1 on every step is DDPM
196
+ draw for draw, and refined encoding inverts decoding.
197
+
198
+ `examples/diffusion_mnist.rb` trains the UNet above (1.9M parameters) on
199
+ MNIST or Fashion-MNIST: Adam with a peak learning rate of 2e-4, 500 steps
200
+ of warmup and cosine annealing, gradient clipping at 1, and an EMA of the
201
+ weights (decay 0.999), which is what gets sampled. 20 epochs (9380 steps
202
+ of 128 images) take 40 minutes on an Apple M5 with MLX (115 s per epoch;
203
+ about 13 minutes per epoch on the CPU). Sampling 64 images takes 28 s
204
+ with DDPM's 1000 steps and 1.4 s with DDIM's 50. Most samples are clear
205
+ digits after 20 epochs; DDIM's are a little rougher than DDPM's. Training
206
+ longer helps, as does a larger UNet.
207
+
208
+ ## Normalizing flows and flow matching
209
+
210
+ A `NormalizingFlow` is a stack of invertible layers from the data to
211
+ N(0, I), with an exact log-likelihood by the change of variables. `RealNVP`
212
+ builds the usual ones from affine couplings (`Flows`):
213
+
214
+ ```ruby
215
+ flow = Maurograd::DGM::RealNVP.for_vectors(2, couplings: 8)
216
+ loss = flow.call(x) # the negative log-likelihood
217
+ flow.log_prob(x) # exact, one value per sample
218
+ flow.sample(500)
219
+
220
+ images = Maurograd::DGM::RealNVP.for_images([1, 28, 28], levels: 256)
221
+ images.bits_per_dim(x) # x in [0, 1], dequantized
222
+ images.sample(64, temperature: 0.7)
223
+ ```
224
+
225
+ `FlowMatching` learns a velocity field whose ODE carries noise (t = 0) to
226
+ data (t = 1), by regression on straight lines between the two. It takes
227
+ the same networks as `DDPM`, with times in [0, 1]:
228
+
229
+ ```ruby
230
+ unet = Maurograd::DGM::Networks::UNet.new(in_channels: 1, channels: [32, 64, 128], time_scale: 1000)
231
+ model = Maurograd::DGM::FlowMatching.new(unet, shape: [1, 28, 28]) # data in [-1, 1]
232
+ loss = model.call(x)
233
+ model.sample(64, steps: 25) # Heun: 50 network evaluations
234
+ model.sample(64, steps: 10, method: :euler) # 10
235
+ noise = model.encode(x) # the ODE backward
236
+ model.log_prob(x, hutchinson: true) # exact likelihood, through the divergence
237
+ ```
238
+
239
+ The couplings are tested against Jacobians computed by autograd, and a
240
+ flow's density against a numerical integral; the ODE against the exact
241
+ velocity field of Gaussian data, whose flow is known in closed form (Heun
242
+ far ahead of Euler at equal evaluations), and its likelihood against the
243
+ Gaussian's density.
244
+
245
+ `examples/flows_2d.rb` trains both on three 2D sets, on the CPU in about
246
+ half a minute each. Test negative log-likelihoods, in nats:
247
+
248
+ | | RealNVP | flow matching | the data's own entropy |
249
+ |---|---|---|---|
250
+ | moons | 1.71 | 1.73 | |
251
+ | 8 Gaussians | 1.89 | 1.74 | 1.70 |
252
+ | checkerboard | 3.66 | 3.86 | 3.47 |
253
+
254
+ RealNVP keeps the checkerboard's edges sharper, with thin artifacts where
255
+ its couplings fold the plane; flow matching is smoother, and spreads its
256
+ mass more evenly over the eight Gaussians.
257
+
258
+ `examples/realnvp_mnist.rb` trains a RealNVP of 15 couplings (1.3M
259
+ parameters) on dequantized MNIST: 20 epochs, about 3 minutes each with
260
+ MLX, reach 1.33 bits per dimension on the test set. Its samples are
261
+ digit-like strokes, more legible at temperature 0.7, as is usual for
262
+ RealNVP.
263
+
264
+ `examples/flow_matching_mnist.rb` trains flow matching with the diffusion
265
+ example's UNet and recipe (115 s per epoch, 20 epochs). Its samples are as
266
+ clean as DDPM's, and the paths are nearly straight: Euler with 10 network
267
+ evaluations gives the same digits as Heun with 50. Its likelihood, by the
268
+ ODE with Hutchinson's estimator, is 1.78 bits per dimension on 500 test images: worse than
269
+ RealNVP's, since flow matching is not trained for likelihood, nor on
270
+ dequantized data. The ODE is stiff near the data, where the steps must
271
+ crowd (`log_prob`'s `power:`): with uniform steps, 50 Heun steps
272
+ misjudge it by a whole bit.
273
+
274
+ ## Generative adversarial networks
275
+
276
+ A `GAN` holds a generator and a discriminator, which you build or take
277
+ from `GAN.for_vectors` (MLPs) and `GAN.for_images` (a DCGAN). It computes
278
+ the two losses, in one of four forms (`:non_saturating`, the default,
279
+ `:minimax`, `:hinge` or `:least_squares`). `GANTrainer` alternates their
280
+ steps, each network with its own optimizer:
281
+
282
+ ```ruby
283
+ gan = Maurograd::DGM::GAN.for_images([1, 28, 28], latent_dim: 64) # data in [-1, 1]
284
+ adam = ->(params) { Maurograd::Optim::Adam.new(params, lr: 2e-4, betas: [0.5, 0.999]) }
285
+ ema = Maurograd::Optim::EMA.new(gan.generator_parameters, decay: 0.999)
286
+ Maurograd::DGM::GANTrainer.new(gan, adam.call(gan.generator_parameters),
287
+ adam.call(gan.discriminator_parameters), max_epochs: 20, ema: ema).fit(loader)
288
+ ema.swap { gan.sample(64) } # from the averaged generator
289
+ ```
290
+
291
+ The losses are tested against their formulas, and a small GAN against a
292
+ Gaussian it must learn: its mean and spread, and the discriminator's loss
293
+ at the equilibrium, 2 log 2.
294
+
295
+ A GAN has no likelihood. `examples/gan_2d.rb` compares the four losses on
296
+ three 2D sets by the energy distance between 5000 samples and 5000 test
297
+ points. Two samples of the data itself are 0.0007 to 0.0013 apart, which
298
+ is as low as the measure can go. Each GAN trains in about 20 seconds on
299
+ the CPU:
300
+
301
+ | energy distance | non-saturating | minimax | hinge | least squares |
302
+ |---|---|---|---|---|
303
+ | 8 Gaussians | 0.030 | 0.003 | 0.004 | 0.034 |
304
+ | moons | 0.002 | 0.0009 | 0.0009 | 0.0013 |
305
+ | checkerboard | 0.005 | 0.003 | 0.004 | 0.006 |
306
+
307
+ These numbers come from an exponential moving average of the generator's
308
+ weights. The last generator is between 1.2 and 23 times further from the
309
+ data (non-saturating on the 8 Gaussians: 0.036; on the checkerboard:
310
+ 0.069), because a GAN's iterates keep circling the equilibrium instead of
311
+ settling on it. Every GAN reaches all 8 Gaussians, with 93% to 96% of its
312
+ samples within 3 standard deviations of one. On the checkerboard, 84% to
313
+ 90% of the samples land on the dark squares. With a 2-dimensional latent,
314
+ the last non-saturating generator puts only 60% there: the generator, a continuous map, folds a
315
+ plane onto the 8 squares and leaves filaments of samples between them.
316
+ The minimax loss trains well here, because the discriminator never
317
+ becomes confident enough to make its gradient vanish.
318
+
319
+ `examples/dcgan_mnist.rb` trains a DCGAN (540k parameters in the
320
+ generator, 139k in the discriminator) on MNIST, 13 seconds an epoch with
321
+ MLX. Its digits are sharp after a few epochs.
322
+
323
+ ### Comparing the MNIST models by their samples
324
+
325
+ `examples/sample_quality.rb` scores the MNIST models of the other examples
326
+ in the same way. It trains a small classifier on MNIST (98.4% test
327
+ accuracy) and computes the Fréchet distance between its features on 5000
328
+ samples and on the 10,000 test images. This is FID's method, with an
329
+ MNIST classifier in place of the Inception network. It also reports how
330
+ evenly the classifier spreads the samples over the 10 digits:
331
+
332
+ | model | Fréchet distance | digit classes |
333
+ |---|---|---|
334
+ | 5000 training images (the floor) | 1.6 | 8.6% to 11.2% |
335
+ | VAE, MLP, standard normal prior | 123.2 | 6.1% to 13.9% |
336
+ | VAE, conv, standard normal prior | 103.9 | 5.0% to 15.7% |
337
+ | VAE, MLP, mixture of 16 Gaussians | 52.7 | 8.2% to 12.2% |
338
+ | VAE, MLP, VampPrior | 36.9 | 7.9% to 12.3% |
339
+ | flow matching, 25 Heun steps | 13.0 | 7.1% to 14.9% |
340
+ | DDPM, DDIM in 50 steps | 32.0 | 5.8% to 18.1% |
341
+ | RealNVP, temperature 1 | 47.0 | 5.2% to 21.5% |
342
+ | RealNVP, temperature 0.7 | 60.3 | 3.4% to 22.4% |
343
+ | DCGAN | 57.9 | 3.1% to 19.8% |
344
+ | EBM, 120 Langevin steps from noise | 117.9 | 0.8% to 34.9% |
345
+ | EBM, 600 Langevin steps from noise | 52.2 | 2.5% to 29.0% |
346
+
347
+ Flow matching comes closest to the data. For the VAEs, which model
348
+ binarized digits, the samples are the decoder's means, pixel
349
+ probabilities. Their prior matters more than their architecture: a
350
+ standard normal prior covers regions no digit's posterior reaches, and
351
+ the decoder turns them into blurred shapes. The learned priors follow
352
+ the posteriors and do far better: the VampPrior's samples come nearly as
353
+ close to the data as DDPM's. Both spread their samples over the digits
354
+ more evenly than any other model.
355
+
356
+ The DCGAN's digits look as sharp as any, but it scores near RealNVP's. It draws some digits six times as
357
+ often as others: a partial collapse onto some modes, which its samples
358
+ hide and the distance exposes. The hinge loss does no better (58.8), and
359
+ neither does sampling with batch statistics in place of the running ones.
360
+ Lowering RealNVP's temperature makes its digits cleaner but less varied,
361
+ and the distance grows. The EBM's chains keep improving past the 60
362
+ steps they were trained with. After 600 steps from noise, the EBM scores
363
+ better than the DCGAN, but its digits are the most uneven of all the
364
+ models.
365
+
366
+ ## Energy-based models
367
+
368
+ An `EBM` turns any network with one output per sample into a density,
369
+ p(x) ∝ exp(−E(x)). It is trained by contrastive divergence: the energy is
370
+ pushed down on the data and up on the model's own samples. The samples
371
+ come from a few dozen steps of Langevin dynamics, started from a replay
372
+ buffer of earlier chains, with 5% of chains restarted from noise each
373
+ step (Du and Mordatch, 2019):
374
+
375
+ ```ruby
376
+ ebm = Maurograd::DGM::EBM.new(energy_net, shape: [2], steps: 20, step_size: 0.01, bounds: [-4.0, 4.0])
377
+ loss = ebm.call(x) # E(data) - E(samples) + 0.1 (E^2 terms)
378
+ ebm.sample(500, steps: 100) # Langevin dynamics from uniform noise
379
+ ebm.unnormalized_log_prob(x) # -E(x)
380
+
381
+ images = Maurograd::DGM::EBM.new(conv_energy, shape: [1, 28, 28], steps: 60, step_size: 10.0,
382
+ noise: 0.005, gradient_clip: 0.03, data_noise: 0.005) # the usual settings for images
383
+ ```
384
+
385
+ The sampler is tested against a Gaussian energy, whose samples must have
386
+ the Gaussian's mean and spread. Training is tested on a Gaussian energy
387
+ with learnable mean and scale, which must recover the data's.
388
+
389
+ In 2D, the normalizing constant can be summed over a grid, so
390
+ `examples/ebm_2d.rb` reports exact test log-likelihoods. Each EBM trains
391
+ in about 2 minutes on the CPU. Test NLL, in nats, next to the flows':
392
+
393
+ | | EBM | RealNVP | flow matching | the data's own entropy |
394
+ |---|---|---|---|---|
395
+ | moons | 1.81 | 1.71 | 1.73 | |
396
+ | 8 Gaussians | 1.83 | 1.89 | 1.74 | 1.70 |
397
+ | checkerboard | 3.69 | 3.66 | 3.86 | 3.47 |
398
+
399
+ Chains of 20 steps from noise, as in training, leave samples strewn
400
+ between the modes. By 100 steps they match the data. The EBM's
401
+ checkerboard density is blurred at the squares' edges.
402
+
403
+ On MNIST (`examples/ebm_mnist.rb`, 77k parameters, about a minute an
404
+ epoch with MLX), the step size and noise of image EBMs are far from
405
+ Langevin dynamics proper. The energy learns to make short chains end on
406
+ digits. Training is unstable. After about 9 epochs, chains from noise
407
+ start stalling on gray, textured images, and the loss runs away. Gradient
408
+ clipping and a decaying learning rate did not prevent this. With 40
409
+ steps instead of 60 it happened sooner. The example therefore keeps the
410
+ last weights from before the loss leaves 0 (epoch 8) and stops training
411
+ once it runs away. Those weights give recognizable digits from 120 steps
412
+ of noise, and cleaner ones from 600 (see the comparison above).
413
+
414
+ ## Development
415
+
416
+ The Gemfile takes Maurograd from a checkout next to this one (or from
417
+ `MAUROGRAD_PATH`), so that work on both can go together; without one, it
418
+ takes the released `maurograd` and `maurograd-mlx` gems (leave the latter
419
+ out with `BUNDLE_WITHOUT=mlx` where mlx-c isn't installed).
420
+
421
+ ```sh
422
+ git clone https://github.com/mtortonesi/maurograd ../maurograd # optional
423
+ bundle install
424
+ bundle exec bake build_ext # builds a Maurograd checkout's extensions
425
+ bundle exec bake test
426
+ bundle exec bake lint
427
+ bundle exec yard # API documentation, in doc/
428
+ ```
429
+
430
+ The public methods carry YARD tags (`@param`, `@return`, `@raise`) with
431
+ the types and shapes of their arguments and results;
432
+ `bundle exec yard stats --list-undoc` lists what has none. Methods whose
433
+ comment already says all there is (one-line accessors, the layers' shared
434
+ `forward`/`inverse`) go without.
435
+
436
+ The MLX tests run when the MLX backend is available (`brew install mlx-c`
437
+ before `bundle install`, or before `bake build_ext` with a checkout), and
438
+ skip otherwise.
439
+
440
+ ## License
441
+
442
+ MIT; see [LICENSE](LICENSE).
@@ -0,0 +1,53 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "fileutils"
4
+ require "digest"
5
+
6
+ module Maurograd
7
+ module DGM
8
+ module Datasets
9
+ # Downloads a file once, checking its MD5, from the first of several
10
+ # mirrors that works.
11
+ module Download
12
+ # Returns `path`, downloading it first unless it is already there
13
+ # with the expected checksum.
14
+ def self.fetch(path, urls:, md5:, timeout: 60)
15
+ return path if File.exist?(path) && Digest::MD5.file(path).hexdigest == md5
16
+
17
+ FileUtils.mkdir_p(File.dirname(path))
18
+ tmp = "#{path}.part"
19
+ errors = Array(urls).filter_map do |url|
20
+ get(URI(url), tmp, timeout)
21
+ got = Digest::MD5.file(tmp).hexdigest
22
+ raise "MD5 mismatch: got #{got}, expected #{md5}" unless got == md5
23
+
24
+ FileUtils.mv(tmp, path)
25
+ return path
26
+ rescue => e
27
+ FileUtils.rm_f(tmp)
28
+ "#{url}: #{e.message}"
29
+ end
30
+ raise Error, "could not download #{File.basename(path)}:\n #{errors.join("\n ")}"
31
+ end
32
+
33
+ def self.get(uri, dest, timeout, redirects = 3)
34
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: timeout, read_timeout: timeout) do |http|
35
+ http.request(Net::HTTP::Get.new(uri)) do |res|
36
+ case res
37
+ when Net::HTTPSuccess
38
+ File.open(dest, "wb") { |f| res.read_body { |chunk| f.write(chunk) } }
39
+ when Net::HTTPRedirection
40
+ raise "too many redirects" if redirects.zero?
41
+
42
+ return get(URI.join(uri, res["location"]), dest, timeout, redirects - 1)
43
+ else
44
+ raise "HTTP #{res.code} #{res.message}"
45
+ end
46
+ end
47
+ end
48
+ end
49
+ private_class_method :get
50
+ end
51
+ end
52
+ end
53
+ end