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
@@ -0,0 +1,33 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Likelihoods p(x | z) for a decoder: each turns the decoder network's
4
+ # output into a distribution over x (see Distributions), whose log_prob
5
+ # is the reconstruction term of the ELBO and whose mean is what a
6
+ # VAE shows as its reconstruction or sample.
7
+ module Likelihoods
8
+ # Independent Bernoullis, the decoder's output their logits: for
9
+ # binary (or binarized) images, where log p(x | z) is the negative
10
+ # binary cross-entropy summed over pixels.
11
+ class Bernoulli < Layers::Module
12
+ def distribution(output) = Distributions::Bernoulli.new(output)
13
+ end
14
+
15
+ # A Gaussian around the decoder's output, with one variance for every
16
+ # pixel: fixed (log_var: 0.0, a unit variance, which makes the
17
+ # reconstruction term a squared error) or
18
+ # learned (learnable: true), which lets the model weigh reconstruction
19
+ # against the KL by itself.
20
+ class Gaussian < Layers::Module
21
+ attr_reader :log_var
22
+
23
+ # @param log_var [Float] the log-variance, or its starting value
24
+ # @param learnable [Boolean] whether training adjusts it
25
+ def initialize(log_var: 0.0, learnable: false)
26
+ @log_var = Tensor.new(::Numo::SFloat[log_var], requires_grad: learnable)
27
+ end
28
+
29
+ def distribution(output) = Distributions::Normal.new(output, @log_var)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,140 @@
1
+ module Maurograd
2
+ module DGM
3
+ # A variational autoencoder with linear maps for both networks, which
4
+ # makes it probabilistic PCA fitted by its evidence lower bound (ELBO)
5
+ # instead of its exact likelihood:
6
+ #
7
+ # decoder p(x | z) = N(x | W z + mu, sigma^2 I), p(z) = N(0, I)
8
+ # encoder q(z | x) = N(z | V x + b, diag(s^2))
9
+ #
10
+ # The decoder is PPCA's model. The exact posterior p(z | x) is Gaussian
11
+ # with a mean linear in x, so a linear encoder can match it, except that
12
+ # q's covariance is diagonal and the true one, sigma^2 (W^T W + sigma^2 I)^-1,
13
+ # is not. Lucas et al. (Don't Blame the ELBO, 2019) show that this
14
+ # costs nothing at the optimum: the ELBO is maximized when W's columns
15
+ # are orthogonal, which makes the true posterior diagonal, and then the
16
+ # bound is tight and the decoder is the PPCA maximum-likelihood fit.
17
+ # Training this model therefore finds PPCA's subspace, the check that
18
+ # the ELBO machinery (reparameterization aside) does what it should.
19
+ #
20
+ # With a linear decoder, the expected reconstruction term has a closed
21
+ # form, so #elbo is exact, with no sampling noise:
22
+ #
23
+ # E_q ||x - W z - mu||^2 = ||x - W m - mu||^2 + sum_j s_j^2 ||W_j||^2
24
+ #
25
+ # (m and s^2 the encoder's mean and variances, W_j W's columns). The
26
+ # general VAE estimates that expectation by sampling z; #monte_carlo_elbo
27
+ # does the same here, to check one against the other.
28
+ class LinearVAE < Layers::Module
29
+ attr_reader :encoder, :decoder, :log_var, :log_noise_var
30
+
31
+ # @param data_dim [Integer] D, the data's dimensions
32
+ # @param latent_dim [Integer] M, the latent code's dimensions
33
+ # @param seed [Integer, nil] seeds the encoder's and decoder's weights
34
+ def initialize(data_dim, latent_dim, seed: nil)
35
+ @encoder = Layers::Linear.new(data_dim, latent_dim, seed: seed)
36
+ @decoder = Layers::Linear.new(latent_dim, data_dim, seed: seed && seed + 1)
37
+ # The best q has the same variances for every x, so they are
38
+ # parameters, not an output of the encoder.
39
+ @log_var = Tensor.new(::Numo::SFloat.zeros(latent_dim), requires_grad: true)
40
+ @log_noise_var = Tensor.new(::Numo::SFloat.zeros(1), requires_grad: true)
41
+ end
42
+
43
+ def data_dim = @decoder.weights.shape[0]
44
+
45
+ def latent_dim = @decoder.weights.shape[1]
46
+
47
+ def noise_var = @log_noise_var.exp.item
48
+
49
+ # q(z | x), a Distributions::Normal over [N, M].
50
+ #
51
+ # @param x [Tensor, Numo::NArray] the data, [N, D]
52
+ # @return [Distributions::Normal] over [N, M]
53
+ def posterior(x)
54
+ # the mean is linear in x; the log-variances are the same for every x
55
+ Distributions::Normal.new(@encoder.call(as_tensor(x)), @log_var)
56
+ end
57
+
58
+ # The ELBO of each row of x [N, D], shape [N]: the expected
59
+ # log-likelihood of x under the decoder, in closed form, minus
60
+ # KL(q(z | x) || p(z)).
61
+ #
62
+ # @param x [Tensor, Numo::NArray] the data, [N, D]
63
+ # @return [Tensor] [N]
64
+ def elbo(x)
65
+ x = as_tensor(x)
66
+ # the encoder's Gaussian over z for each x
67
+ q = posterior(x)
68
+ # ||x - W m - mu||^2: the error of decoding the posterior mean m
69
+ squared_error = ((x - @decoder.call(q.mean))**2).sum(axis: 1)
70
+ # sum_j s_j^2 ||W_j||^2: the extra error from z's spread around m
71
+ spread = ((@decoder.weights**2).sum(axis: 0) * q.variance).sum
72
+ # E_q[log N(x | W z + mu, sigma^2 I)], in closed form from the two terms
73
+ expected_log_likelihood = ((squared_error + spread) / @log_noise_var.exp +
74
+ (@log_noise_var + Distributions::LOG_2PI) * data_dim) * -0.5
75
+ # ELBO = expected log-likelihood - KL(q(z | x) || N(0, I))
76
+ expected_log_likelihood - q.kl_divergence(Distributions::StandardNormal.new(latent_dim))
77
+ end
78
+
79
+ # The ELBO estimated by sampling `samples` latent codes per row, as a
80
+ # VAE with a nonlinear decoder must.
81
+ #
82
+ # @param x [Tensor, Numo::NArray] the data, [N, D]
83
+ # @param samples [Integer] latent codes drawn per row
84
+ # @return [Tensor] [N]
85
+ def monte_carlo_elbo(x, samples: 1)
86
+ x = as_tensor(x)
87
+ q = posterior(x)
88
+ # log p(x | z): the decoder's Gaussian around W z + mu, evaluated at x
89
+ likelihood = ->(z) { Distributions::Normal.new(@decoder.call(z), @log_noise_var).log_prob(x) }
90
+ # average it over z drawn from q by the reparameterization trick
91
+ expected = (1..samples).map { likelihood.call(q.rsample) }.reduce(:+) * (1.0 / samples)
92
+ # minus the KL divergence, which is exact for two Gaussians
93
+ expected - q.kl_divergence(Distributions::StandardNormal.new(latent_dim))
94
+ end
95
+
96
+ # The training loss: the negative mean ELBO of the batch.
97
+ #
98
+ # @param x [Tensor, Numo::NArray] the data, [N, D]
99
+ # @return [Tensor] the negative mean ELBO, a scalar
100
+ def forward(x)
101
+ -elbo(x).mean
102
+ end
103
+
104
+ # The decoder's marginal covariance, W W^T + sigma^2 I: what PPCA's
105
+ # fit computes as its own #covariance.
106
+ #
107
+ # @return [Tensor] [D, D]
108
+ def covariance
109
+ w = @decoder.weights
110
+ w.matmul(w.transpose) + Tensor.new(::Numo::SFloat.eye(data_dim), backend: w.backend) * @log_noise_var.exp
111
+ end
112
+
113
+ # The decoder as a PPCA: its W, mu and sigma^2, whose exact
114
+ # log-likelihood the ELBO bounds from below.
115
+ #
116
+ # @return [PPCA]
117
+ def to_ppca
118
+ PPCA.from_parameters(@decoder.weights.to_numo, @decoder.bias.to_numo, noise_var)
119
+ end
120
+
121
+ # n samples from the decoder's model, [n, D].
122
+ #
123
+ # @param n [Integer]
124
+ # @return [Tensor] [n, D]
125
+ def sample(n)
126
+ Maurograd.no_grad do
127
+ bk = @decoder.weights.backend
128
+ # decode latents from the prior, z ~ N(0, I): W z + mu
129
+ mean = @decoder.call(Maurograd.randn(n, latent_dim, backend: bk))
130
+ # add the decoder's noise, sigma eps
131
+ mean + Maurograd.randn(n, data_dim, backend: bk) * (@log_noise_var * 0.5).exp
132
+ end
133
+ end
134
+
135
+ private
136
+
137
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: @decoder.weights.backend)
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,85 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Measures of sample quality, for models without a likelihood to
4
+ # compare them by (GANs), or across families of models.
5
+ module Metrics
6
+ module_function
7
+
8
+ # The Fréchet distance between Gaussians fitted to two sets of
9
+ # features, a [N, D] and b [M, D] (Numo arrays or Tensors):
10
+ #
11
+ # |mu_a - mu_b|^2 + tr(S_a + S_b - 2 (S_a^1/2 S_b S_a^1/2)^1/2)
12
+ #
13
+ # the 2-Wasserstein distance between the two Gaussians. On the
14
+ # features of an Inception network it is the FID (Heusel et al.,
15
+ # 2017); on those of a classifier trained on the data, the same idea
16
+ # for a dataset like MNIST. Lower is better; it is biased upward for
17
+ # small samples, so compare it only across equal sample sizes.
18
+ #
19
+ # @param a [Numo::NArray, Tensor] [N, D]
20
+ # @param b [Numo::NArray, Tensor] [M, D]
21
+ # @return [Float]
22
+ # @raise [ArgumentError] if either isn't [N, D] with N > 1
23
+ def frechet_distance(a, b)
24
+ # fit a Gaussian to each set: its mean and covariance
25
+ mu_a, cov_a = gaussian(a)
26
+ mu_b, cov_b = gaussian(b)
27
+ # (S_a^1/2 S_b S_a^1/2)^1/2: symmetric, unlike the equivalent (S_a S_b)^1/2
28
+ root_a = sqrt_psd(cov_a)
29
+ cross = sqrt_psd(root_a.dot(cov_b).dot(root_a))
30
+ # the distance between the means, plus the one between the covariances
31
+ diff = mu_a - mu_b
32
+ (diff * diff).sum + trace(cov_a) + trace(cov_b) - 2 * trace(cross)
33
+ end
34
+
35
+ # The mean [D] and covariance [D, D] (with N - 1) of features [N, D],
36
+ # in double precision.
37
+ #
38
+ # @param features [Numo::NArray, Tensor] [N, D]
39
+ # @return [Array(Numo::DFloat, Numo::DFloat)] the mean [D] and covariance [D, D]
40
+ # @raise [ArgumentError] unless features are [N, D] with N > 1
41
+ def gaussian(features)
42
+ x = ::Numo::DFloat.cast(features.respond_to?(:to_numo) ? features.to_numo : features)
43
+ raise ArgumentError, "features must be [N, D] with N > 1, got #{x.shape.inspect}" unless x.ndim == 2 && x.shape[0] > 1
44
+
45
+ mean = x.mean(axis: 0)
46
+ centered = x - mean
47
+ [mean, centered.transpose.dot(centered) / (x.shape[0] - 1)]
48
+ end
49
+
50
+ # The square root of a symmetric positive semidefinite matrix, by the
51
+ # Newton-Schulz iteration (Higham, Functions of Matrices, 6.3), which
52
+ # needs only matrix products: scaled by its Frobenius norm, the
53
+ # matrix's eigenvalues lie in [0, 1], where the iteration converges.
54
+ # Covariances of features are often singular, and rounding then
55
+ # leaves eigenvalues slightly below 0, where it diverges: they are
56
+ # shifted up by 1e-12 of the norm, which moves the root by at most
57
+ # 1e-6 of the norm's square root.
58
+ #
59
+ # @param matrix [Numo::NArray] symmetric positive semidefinite, [D, D]
60
+ # @param iterations [Integer]
61
+ # @return [Numo::DFloat] [D, D]
62
+ def sqrt_psd(matrix, iterations: 100)
63
+ matrix = ::Numo::DFloat.cast(matrix)
64
+ matrix = (matrix + matrix.transpose) / 2
65
+ norm = Math.sqrt((matrix * matrix).sum)
66
+ return matrix.new_zeros if norm.zero?
67
+
68
+ identity = ::Numo::DFloat.eye(matrix.shape[0])
69
+ # scaled to eigenvalues in [0, 1], and shifted off 0
70
+ y = matrix / norm + identity * 1e-12
71
+ z = identity
72
+ # y converges to the square root, z to its inverse
73
+ iterations.times do
74
+ t = (identity * 3 - z.dot(y)) / 2
75
+ y = y.dot(t)
76
+ z = t.dot(z)
77
+ end
78
+ # undo the scaling: sqrt(norm * A) = sqrt(norm) * sqrt(A)
79
+ y * Math.sqrt(norm)
80
+ end
81
+
82
+ def trace(matrix) = matrix.diagonal.sum
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,151 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Networks for the models whose network takes a time (or noise level)
4
+ # along with the data, network.call(x, t): diffusion models' noise
5
+ # predictors, and the velocity fields of flow matching. t is a vector
6
+ # with one time per sample: integer steps for diffusion, or values in
7
+ # [0, 1] for flow matching (scaled up before embedding; see
8
+ # SinusoidalEmbedding).
9
+ #
10
+ # Any Module with that call works with the models; these are good
11
+ # defaults: TimeMLP for vectors (2D toy data), UNet for images.
12
+ module Networks
13
+ # The sinusoidal embedding of Vaswani et al. (2017), applied to time:
14
+ # t becomes [sin(t w_1), ..., sin(t w_k), cos(t w_1), ..., cos(t w_k)],
15
+ # with frequencies w_i spaced geometrically from 1 down to 1 / 10000,
16
+ # so that nearby times get similar vectors and the network can tell
17
+ # apart both distant and adjacent steps. It is computed on the host,
18
+ # and has no parameters.
19
+ class SinusoidalEmbedding < Layers::Module
20
+ attr_reader :dim, :scale
21
+
22
+ # scale multiplies t first: with times in [0, 1], a scale of 1000
23
+ # spreads them like diffusion steps.
24
+ def initialize(dim, scale: 1.0)
25
+ raise ArgumentError, "the embedding's dimension must be even, got #{dim}" unless dim.even?
26
+
27
+ @dim = dim
28
+ @scale = scale
29
+ end
30
+
31
+ # t: a Numo array, a Ruby Array or a Tensor of n times. Returns a
32
+ # Tensor [n, dim] on `backend`.
33
+ def forward(t, backend: nil)
34
+ t = t.to_numo if t.is_a?(Tensor)
35
+ t = ::Numo::DFloat.cast(t).flatten.reshape(true, 1) * @scale
36
+ half = @dim / 2
37
+ freqs = ::Numo::NMath.exp(::Numo::DFloat.new(1, half).seq * (-Math.log(10_000.0) / [half - 1, 1].max))
38
+ angles = t * freqs
39
+ Tensor.new(::Numo::SFloat.cast(::Numo::DFloat.hstack([::Numo::NMath.sin(angles), ::Numo::NMath.cos(angles)])),
40
+ backend: backend || Maurograd.backend)
41
+ end
42
+ end
43
+
44
+ # An MLP over [x, embedding(t)], for vector data: the noise predictor
45
+ # of a diffusion model on 2D toy data.
46
+ #
47
+ # net = TimeMLP.new(2, hidden: 128, depth: 3)
48
+ # net.call(x, t) # x [N, 2], t [N] -> [N, 2]
49
+ class TimeMLP < Layers::Module
50
+ def initialize(dim, hidden: 128, depth: 3, time_dim: 32, time_scale: 1.0)
51
+ @embedding = SinusoidalEmbedding.new(time_dim, scale: time_scale)
52
+ layers = [Layers::Linear.new(dim + time_dim, hidden), Layers::SiLU.new]
53
+ (depth - 1).times { layers.push(Layers::Linear.new(hidden, hidden), Layers::SiLU.new) }
54
+ @net = Layers::Sequential.new(*layers, Layers::Linear.new(hidden, dim))
55
+ end
56
+
57
+ def forward(x, t)
58
+ @net.call(Maurograd.concat([x, @embedding.call(t, backend: x.backend)], axis: 1))
59
+ end
60
+ end
61
+
62
+ # A residual block of a UNet, conditioned on time: two 3x3
63
+ # convolutions, each after GroupNorm and SiLU, with the time embedding,
64
+ # projected to one value per channel, added in between. A 1x1
65
+ # convolution matches the channels of the skip path when they change.
66
+ class ResidualBlock < Layers::Module
67
+ def initialize(in_channels, out_channels, time_dim, groups: 8)
68
+ @norm1 = Layers::GroupNorm.new(groups, in_channels)
69
+ @conv1 = Layers::Conv2D.new(in_channels, out_channels, 3, padding: 1)
70
+ @time = Layers::Linear.new(time_dim, out_channels)
71
+ @norm2 = Layers::GroupNorm.new(groups, out_channels)
72
+ @conv2 = Layers::Conv2D.new(out_channels, out_channels, 3, padding: 1)
73
+ @skip = Layers::Conv2D.new(in_channels, out_channels, 1) unless in_channels == out_channels
74
+ end
75
+
76
+ def forward(x, time)
77
+ h = @conv1.call(@norm1.call(x).silu)
78
+ h += @time.call(time).reshape(h.shape[0], h.shape[1], 1, 1)
79
+ h = @conv2.call(@norm2.call(h).silu)
80
+ (@skip ? @skip.call(x) : x) + h
81
+ end
82
+ end
83
+
84
+ # A small UNet (Ronneberger et al., 2015, as adapted to diffusion by
85
+ # Ho et al., 2020), the noise predictor for images: a contracting
86
+ # path of residual blocks, each level halving the resolution, a
87
+ # middle at the lowest one, and an expanding path that doubles it
88
+ # back, each level concatenating the features saved at the same
89
+ # resolution on the way down. Every block gets the time embedding.
90
+ #
91
+ # unet = UNet.new(in_channels: 1, channels: [32, 64, 128])
92
+ # unet.call(x, t) # x [N, 1, 28, 28], t [N] -> [N, 1, 28, 28]
93
+ #
94
+ # One level per entry of `channels`; the image's side must be
95
+ # divisible by 2^(levels - 1) (28 is, for three levels). Downsampling
96
+ # is a strided 3x3 convolution, upsampling nearest-neighbor followed
97
+ # by a 3x3 convolution. There is no attention: at MNIST's size,
98
+ # convolutions see enough. The last convolution starts at zero, so the
99
+ # untrained network predicts no noise, a stable start.
100
+ class UNet < Layers::Module
101
+ attr_reader :channels
102
+
103
+ def initialize(in_channels: 1, channels: [32, 64, 128], time_dim: nil, groups: 8, time_scale: 1.0)
104
+ @channels = channels
105
+ time_dim ||= 4 * channels.first
106
+ @embedding = SinusoidalEmbedding.new(channels.first, scale: time_scale)
107
+ @time_mlp = Layers::Sequential.new(Layers::Linear.new(channels.first, time_dim), Layers::SiLU.new,
108
+ Layers::Linear.new(time_dim, time_dim), Layers::SiLU.new)
109
+ @conv_in = Layers::Conv2D.new(in_channels, channels.first, 3, padding: 1)
110
+
111
+ last = channels.size - 1
112
+ previous = channels.first
113
+ @down = channels.map do |c|
114
+ block = ResidualBlock.new(previous, c, time_dim, groups: groups)
115
+ previous = c
116
+ block
117
+ end
118
+ @downsample = channels[0...last].map { |c| Layers::Conv2D.new(c, c, 3, stride: 2, padding: 1) }
119
+ @middle = [ResidualBlock.new(channels.last, channels.last, time_dim, groups: groups),
120
+ ResidualBlock.new(channels.last, channels.last, time_dim, groups: groups)]
121
+ @up = channels.each_with_index.map do |c, i|
122
+ below = (i == last) ? channels.last : channels[i + 1]
123
+ ResidualBlock.new(below + c, c, time_dim, groups: groups)
124
+ end
125
+ @upsample = channels[1..].map { |c| Layers::Sequential.new(Layers::Upsample2D.new, Layers::Conv2D.new(c, c, 3, padding: 1)) }
126
+
127
+ @norm_out = Layers::GroupNorm.new(groups, channels.first)
128
+ @conv_out = Layers::Conv2D.new(channels.first, in_channels, 3, padding: 1)
129
+ [@conv_out.weights, @conv_out.bias].each { |p| p.data = p.backend.zeros(p.shape) }
130
+ end
131
+
132
+ def forward(x, t)
133
+ time = @time_mlp.call(@embedding.call(t, backend: x.backend))
134
+ h = @conv_in.call(x)
135
+ skips = []
136
+ @down.each_with_index do |block, i|
137
+ h = block.call(h, time)
138
+ skips << h
139
+ h = @downsample[i].call(h) if i < @downsample.size
140
+ end
141
+ @middle.each { |block| h = block.call(h, time) }
142
+ (@up.size - 1).downto(0) do |i|
143
+ h = @up[i].call(Maurograd.concat([h, skips[i]], axis: 1), time)
144
+ h = @upsample[i - 1].call(h) if i.positive?
145
+ end
146
+ @conv_out.call(@norm_out.call(h).silu)
147
+ end
148
+ end
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,97 @@
1
+ module Maurograd
2
+ module DGM
3
+ # The noise schedule of a diffusion model: the variances beta_1..beta_T
4
+ # of the forward process, which adds a little Gaussian noise at each of
5
+ # T steps,
6
+ #
7
+ # q(x_t | x_{t-1}) = N(sqrt(1 - beta_t) x_{t-1}, beta_t I)
8
+ #
9
+ # so that, with alpha_t = 1 - beta_t and alpha_bar_t their running
10
+ # product, any step can be reached from the data in one jump:
11
+ #
12
+ # q(x_t | x_0) = N(sqrt(alpha_bar_t) x_0, (1 - alpha_bar_t) I)
13
+ #
14
+ # alpha_bar falls from about 1 (clean data) to about 0 (pure noise).
15
+ # Steps are indexed from 0 to T - 1 here, as arrays are; step t of the
16
+ # papers is index t - 1.
17
+ #
18
+ # The values are Numo::DFloat arrays on the host: the models pick the
19
+ # entries a batch needs and send them to the backend.
20
+ class NoiseSchedule
21
+ attr_reader :betas, :alphas, :alpha_bars
22
+
23
+ # Ho et al. (2020): betas rising linearly from 1e-4 to 0.02 over
24
+ # 1000 steps.
25
+ #
26
+ # @param steps [Integer] T
27
+ # @param beta_start [Float] beta_1
28
+ # @param beta_end [Float] beta_T
29
+ # @return [NoiseSchedule]
30
+ def self.linear(steps = 1000, beta_start: 1e-4, beta_end: 0.02)
31
+ new(::Numo::DFloat.linspace(beta_start, beta_end, steps))
32
+ end
33
+
34
+ # Nichol and Dhariwal (2021): alpha_bar follows a squared cosine,
35
+ #
36
+ # alpha_bar(t) = f(t) / f(0), f(t) = cos^2((t / T + s) / (1 + s) * pi / 2)
37
+ #
38
+ # which destroys information more evenly over the steps than the
39
+ # linear schedule, whose last steps are almost pure noise already.
40
+ # Betas are capped at max_beta, to avoid a singularity at t = T.
41
+ #
42
+ # @param steps [Integer] T
43
+ # @param s [Float] a small offset, so that beta_1 isn't 0
44
+ # @param max_beta [Float]
45
+ # @return [NoiseSchedule]
46
+ def self.cosine(steps = 1000, s: 0.008, max_beta: 0.999)
47
+ # f(t) is alpha_bar_t, up to a constant: a squared cosine from 1 down to about 0
48
+ f = ->(t) { Math.cos((t.to_f / steps + s) / (1 + s) * Math::PI / 2)**2 }
49
+ # beta_t = 1 - alpha_bar_t / alpha_bar_{t-1}, capped so the last steps aren't all noise
50
+ betas = (1..steps).map { |t| [1 - f.call(t) / f.call(t - 1), max_beta].min }
51
+ new(::Numo::DFloat.cast(betas))
52
+ end
53
+
54
+ # @param betas [Numo::NArray, Array<Float>] beta_1..beta_T, each in (0, 1)
55
+ # @raise [ArgumentError] if betas isn't a vector of values in (0, 1)
56
+ def initialize(betas)
57
+ @betas = ::Numo::DFloat.cast(betas)
58
+ unless @betas.ndim == 1 && (@betas.gt(0) & @betas.lt(1)).all?
59
+ raise ArgumentError, "betas must be a vector of values in (0, 1)"
60
+ end
61
+
62
+ # alpha_t = 1 - beta_t: the share of the signal's variance a step keeps
63
+ @alphas = 1 - @betas
64
+ # alpha_bar_t = alpha_1 ... alpha_t: what is left after t steps
65
+ @alpha_bars = @alphas.cumprod
66
+ end
67
+
68
+ # T, the number of steps.
69
+ def steps = @betas.size
70
+
71
+ # alpha_bar at step t, with alpha_bar at t = -1 (before the first
72
+ # step: the data itself) equal to 1.
73
+ #
74
+ # @param t [Integer] a step in -1...T
75
+ # @return [Float]
76
+ def alpha_bar(t) = t.negative? ? 1.0 : @alpha_bars[t]
77
+
78
+ # The variance of the forward process's posterior q(x_{t-1} | x_t, x_0),
79
+ #
80
+ # beta_tilde_t = (1 - alpha_bar_{t-1}) / (1 - alpha_bar_t) beta_t
81
+ #
82
+ # the lower of the two variances Ho et al. found to work for the
83
+ # reverse process (beta_t is the upper one). It is 0 at the first step.
84
+ #
85
+ # @return [Numo::DFloat] beta_tilde_t for each step, [T]
86
+ def posterior_variances
87
+ # alpha_bar_{t-1} for every t, with alpha_bar_{-1} = 1
88
+ previous = ::Numo::DFloat.hstack([::Numo::DFloat[1.0], @alpha_bars[0...-1]])
89
+ # beta_tilde_t = (1 - alpha_bar_{t-1}) / (1 - alpha_bar_t) beta_t
90
+ (1 - previous) / (1 - @alpha_bars) * @betas
91
+ end
92
+
93
+ # The signal-to-noise ratio alpha_bar / (1 - alpha_bar) at each step.
94
+ def signal_to_noise = @alpha_bars / (1 - @alpha_bars)
95
+ end
96
+ end
97
+ end