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,225 @@
1
+ module Maurograd
2
+ module DGM
3
+ # A normalizing flow: an invertible map f, a stack of layers (see
4
+ # Flows), from the data x to a latent z = f(x) with a simple density,
5
+ # N(0, I). The change of variables gives the data's density exactly,
6
+ #
7
+ # log p(x) = log N(f(x) | 0, I) + log |det df/dx|
8
+ #
9
+ # with the log-determinant the sum of the layers' own. Training
10
+ # maximizes it; sampling draws z and runs the layers backward,
11
+ # x = f^-1(z).
12
+ #
13
+ # flow = RealNVP.for_vectors(2, couplings: 8)
14
+ # loss = flow.call(x) # the negative log-likelihood, averaged
15
+ # flow.log_prob(x) # [N], exact
16
+ # flow.sample(500) # [500, 2]
17
+ #
18
+ # On discrete data, such as images of 256 intensities, a density can
19
+ # grow without bound on the few values the data takes. With levels: L,
20
+ # the flow models such data as Dinh et al. do: each x in [0, 1] (the
21
+ # intensity k / (L - 1)) is dequantized, replaced by (k + u) / L with u
22
+ # uniform in [0, 1), a fresh u at every call, and the loss and
23
+ # #bits_per_dim measure the discrete data, -log p(y) + D log L, an
24
+ # upper bound on its negative log-likelihood (Theis et al., 2016).
25
+ #
26
+ # A flow on vectors is also a prior for a VAE: it has the log_prob and
27
+ # sample(n, backend:) that VAE needs, and is trained with the rest.
28
+ class NormalizingFlow < Layers::Module
29
+ attr_reader :layers, :shape, :latent_shape, :levels
30
+
31
+ # @param layers [Array<Layers::Module>] Flows layers, from the data's side to the noise's
32
+ # @param shape [Array<Integer>] one sample's shape, e.g. [2] or [1, 28, 28]
33
+ # @param latent_shape [Array<Integer>] its latent's shape, if the layers change it
34
+ # (Squeeze does); as many values
35
+ # @param levels [Integer, nil] the intensities of discrete data (256 for images), which
36
+ # the loss then dequantizes; nil for continuous data
37
+ # @raise [ArgumentError] if latent_shape and shape differ in size
38
+ def initialize(layers, shape:, latent_shape: shape, levels: nil)
39
+ unless latent_shape.reduce(1, :*) == shape.reduce(1, :*)
40
+ raise ArgumentError, "the latent #{latent_shape.inspect} must have as many values as a sample #{shape.inspect}"
41
+ end
42
+
43
+ @layers = layers
44
+ @shape = shape
45
+ @latent_shape = latent_shape
46
+ @levels = levels
47
+ @base = Distributions::StandardNormal.new(*latent_shape)
48
+ end
49
+
50
+ def dims = @shape.reduce(1, :*)
51
+
52
+ # [z, log |det df/dx|]: the latent of each sample, and the log of the
53
+ # volume change, [N].
54
+ #
55
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape] (in [0, 1] with levels)
56
+ # @return [Array(Tensor, Tensor)] z [N, *latent_shape], and log |det| [N]
57
+ def transform(x)
58
+ log_det = nil
59
+ z = as_tensor(x)
60
+ # through the layers from the data toward the noise
61
+ @layers.each do |layer|
62
+ # each layer returns its output and the log of its volume change
63
+ z, term = layer.call(z)
64
+ # the volume changes multiply, so their logs add up
65
+ log_det = log_det ? log_det + term : term
66
+ end
67
+ [z, log_det]
68
+ end
69
+
70
+ # f^-1(z): the data that z encodes.
71
+ #
72
+ # @param z [Tensor, Numo::NArray] latents, [N, *latent_shape]
73
+ # @return [Tensor] [N, *shape]
74
+ def inverse(z)
75
+ x = as_tensor(z)
76
+ # undo the layers in reverse order, from the noise back to the data
77
+ @layers.reverse_each { |layer| x = layer.inverse(x) }
78
+ x
79
+ end
80
+
81
+ # The density of x, exactly: log p(x) for each sample, [N].
82
+ #
83
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape] (in [0, 1] with levels)
84
+ # @return [Tensor] [N]
85
+ def log_prob(x)
86
+ # map x to its latent z, tracking the volume change
87
+ z, log_det = transform(x)
88
+ # change of variables: log p(x) = log N(z; 0, I) + log |det dz/dx|
89
+ @base.log_prob(z) + log_det
90
+ end
91
+
92
+ # The training loss: the negative log-likelihood, averaged over the
93
+ # batch (of the discrete data, dequantized, with levels).
94
+ #
95
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape] (in [0, 1] with levels)
96
+ # @return [Tensor] the mean negative log-likelihood, in nats: a scalar
97
+ def forward(x)
98
+ (discrete_log_prob(x) * -1.0).mean
99
+ end
100
+
101
+ # The negative log-likelihood of each sample in bits per dimension,
102
+ # [N]: the measure flows on images are compared by. With levels, of
103
+ # the dequantized discrete data.
104
+ #
105
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape] (in [0, 1] with levels)
106
+ # @return [Tensor] [N]
107
+ def bits_per_dim(x)
108
+ Maurograd.no_grad { discrete_log_prob(x) * (-1.0 / (dims * Math.log(2))) }
109
+ end
110
+
111
+ # n samples, under no_grad: f^-1(z) for z from N(0, I), scaled by the
112
+ # temperature (below 1 trades variety for cleaner samples, as in
113
+ # Kingma and Dhariwal, 2018).
114
+ #
115
+ # @param n [Integer]
116
+ # @param temperature [Float] the latents' scale
117
+ # @param backend [Module, Symbol, nil] the model's if nil
118
+ # @return [Tensor] [n, *shape]
119
+ def sample(n, temperature: 1.0, backend: nil)
120
+ Maurograd.no_grad { inverse(@base.sample(n, backend: backend || parameter_backend) * temperature) }
121
+ end
122
+
123
+ # The latents of x, under no_grad.
124
+ #
125
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape] (in [0, 1] with levels)
126
+ # @return [Tensor] [N, *latent_shape]
127
+ def encode(x) = Maurograd.no_grad { transform(x).first }
128
+
129
+ # The data of latents z, under no_grad.
130
+ #
131
+ # @param z [Tensor, Numo::NArray] [N, *latent_shape]
132
+ # @return [Tensor] [N, *shape]
133
+ def decode(z) = Maurograd.no_grad { inverse(z) }
134
+
135
+ # x [N, ...] in [0, 1], as (k + u) / L with k the level of each value
136
+ # and u uniform in [0, 1).
137
+ #
138
+ # @param x [Tensor, Numo::NArray] [N, ...] in [0, 1], multiples of 1 / (levels - 1)
139
+ # @return [Tensor] shaped like x, in [0, 1)
140
+ def dequantize(x)
141
+ x = as_tensor(x)
142
+ # recover each value's level k, an integer in 0...levels
143
+ level = Tensor.new(::Numo::SFloat.cast((::Numo::SFloat.cast(x.to_numo) * (@levels - 1)).round), backend: x.backend)
144
+ # spread it uniformly over its bin [k, k + 1), scaled back to [0, 1]
145
+ (level + Maurograd.rand_like(x)) * (1.0 / @levels)
146
+ end
147
+
148
+ private
149
+
150
+ def discrete_log_prob(x)
151
+ return log_prob(x) unless @levels
152
+
153
+ # the density of the dequantized data, times each bin's width 1/levels
154
+ # per dimension: a lower bound on the discrete data's log-probability
155
+ log_prob(dequantize(x)) - dims * Math.log(@levels)
156
+ end
157
+
158
+ def parameter_backend = parameters.first&.backend || Maurograd.backend
159
+
160
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
161
+ end
162
+
163
+ # RealNVP (Dinh et al., 2017): a flow of affine coupling layers with
164
+ # alternating masks. Two builders give the usual architectures.
165
+ module RealNVP
166
+ module_function
167
+
168
+ # For vectors [N, dim]: `couplings` layers, each with an MLP, masking
169
+ # the even and the odd features in turn.
170
+ #
171
+ # @param dim [Integer]
172
+ # @param couplings [Integer]
173
+ # @param hidden [Integer] units per hidden layer of each coupling's MLP
174
+ # @param depth [Integer] hidden layers per MLP
175
+ # @return [NormalizingFlow]
176
+ def for_vectors(dim, couplings: 8, hidden: 128, depth: 2)
177
+ layers = Array.new(couplings) do |i|
178
+ Flows::AffineCoupling.new(Flows.alternating_mask(dim, parity: i % 2), Flows.mlp(dim, hidden: hidden, depth: depth))
179
+ end
180
+ NormalizingFlow.new(layers, shape: [dim])
181
+ end
182
+
183
+ # For images [N, C, H, W] in [0, 1] of `levels` intensities: a Logit,
184
+ # then, at each of `scales` resolutions, 3 couplings with
185
+ # checkerboard masks, a Squeeze and 3 couplings with channel masks;
186
+ # 3 more checkerboard couplings at the last resolution. Each coupling
187
+ # has a Flows.cnn. (Dinh et al. also set half of the variables aside
188
+ # at each scale; here all of them go through every layer.)
189
+ #
190
+ # @param shape [Array<Integer>] [C, H, W], H and W divisible by 2^scales
191
+ # @param scales [Integer]
192
+ # @param hidden [Integer] channels of each coupling's CNN
193
+ # @param blocks [Integer] residual blocks per CNN
194
+ # @param levels [Integer] the data's intensities
195
+ # @param alpha [Float] the Logit layer's margin
196
+ # @return [NormalizingFlow]
197
+ # @raise [ArgumentError] if H or W isn't divisible by 2^scales
198
+ def for_images(shape, scales: 2, hidden: 64, blocks: 2, levels: 256, alpha: 0.05)
199
+ c, h, w = shape
200
+ unless (h % (2**scales)).zero? && (w % (2**scales)).zero?
201
+ raise ArgumentError, "height and width must be divisible by 2^scales, got #{shape.inspect} for #{scales} scales"
202
+ end
203
+
204
+ layers = [Flows::Logit.new(alpha: alpha)]
205
+ checkerboard = ->(count) do
206
+ count.times do |i|
207
+ layers << Flows::AffineCoupling.new(Flows.checkerboard_mask(c, h, w, parity: i % 2), Flows.cnn(c, hidden: hidden, blocks: blocks))
208
+ end
209
+ end
210
+ scales.times do
211
+ checkerboard.call(3)
212
+ layers << Flows::Squeeze.new
213
+ c *= 4
214
+ h /= 2
215
+ w /= 2
216
+ 3.times do |i|
217
+ layers << Flows::AffineCoupling.new(Flows.channel_mask(c, parity: i % 2), Flows.cnn(c, hidden: hidden, blocks: blocks))
218
+ end
219
+ end
220
+ checkerboard.call(3)
221
+ NormalizingFlow.new(layers, shape: shape, latent_shape: [c, h, w], levels: levels)
222
+ end
223
+ end
224
+ end
225
+ end
@@ -0,0 +1,337 @@
1
+ require "numo/linalg"
2
+
3
+ module Maurograd
4
+ module DGM
5
+ # Probabilistic PCA (Tipping and Bishop, 1999): the linear-Gaussian
6
+ # latent variable model
7
+ #
8
+ # z ~ N(0, I_M) a low-dimensional latent code
9
+ # x = W z + mu + eps, eps ~ N(0, sigma^2 I_D)
10
+ #
11
+ # with W [D, M], mu [D] and the noise variance sigma^2. Integrating z
12
+ # out leaves a Gaussian with a low-rank-plus-diagonal covariance,
13
+ #
14
+ # p(x) = N(x | mu, C), C = W W^T + sigma^2 I_D,
15
+ #
16
+ # so, unlike the deep models, its log-likelihood is exact, and so is
17
+ # the posterior over z:
18
+ #
19
+ # p(z | x) = N(z | M^-1 W^T (x - mu), sigma^2 M^-1), M = W^T W + sigma^2 I_M.
20
+ #
21
+ # Three ways to fit it, which reach the same maximum likelihood:
22
+ #
23
+ # PPCA.closed_form(x, 2) # from the eigendecomposition of the covariance
24
+ # PPCA.em(x, 2) # expectation-maximization
25
+ # model = PPCA.new(d, 2) # gradient ascent: model.call(x) is the
26
+ # Trainer.new(model, Optim::Adam.new(model.parameters, lr: 1e-2)).fit(loader)
27
+ #
28
+ # W is identifiable only up to a rotation (W R gives the same C for any
29
+ # orthogonal R), so fits are compared through C, or the log-likelihood.
30
+ class PPCA < Layers::Module
31
+ attr_reader :weight, :mean, :log_noise_var
32
+
33
+ # Starts from small random W, mu = 0 and sigma^2 = 1, for a gradient fit.
34
+ #
35
+ # @param data_dim [Integer] D, the data's dimensions
36
+ # @param latent_dim [Integer] M, the latent code's dimensions
37
+ # @param seed [Integer, nil] seeds W's random start
38
+ def initialize(data_dim, latent_dim, seed: nil)
39
+ @weight = Tensor.new(Maurograd::Utils.rand_norm(data_dim, latent_dim, std: 0.1, seed: seed), requires_grad: true)
40
+ @mean = Tensor.new(::Numo::SFloat.zeros(data_dim), requires_grad: true)
41
+ @log_noise_var = Tensor.new(::Numo::SFloat.zeros(1), requires_grad: true)
42
+ end
43
+
44
+ def data_dim = @weight.shape[0]
45
+
46
+ def latent_dim = @weight.shape[1]
47
+
48
+ def noise_var = @log_noise_var.exp.item
49
+
50
+ # The maximum-likelihood fit in closed form. With S the data's
51
+ # covariance and l_1 >= ... >= l_D its eigenvalues, u_i the
52
+ # eigenvectors:
53
+ #
54
+ # mu = the data's mean
55
+ # sigma^2 = mean of the D - M discarded eigenvalues, l_{M+1} .. l_D
56
+ # W = U_M (L_M - sigma^2 I)^1/2
57
+ #
58
+ # The noise absorbs the variance PCA throws away, and each principal
59
+ # direction keeps what exceeds it.
60
+ #
61
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
62
+ # @param latent_dim [Integer] M, in 1...D
63
+ # @return [PPCA]
64
+ # @raise [ArgumentError] if latent_dim isn't in 1...D
65
+ def self.closed_form(x, latent_dim)
66
+ # host(x) ensures x is a Numo::DFloat array, not a Tensor, and copies it to the host if needed
67
+ x = host(x)
68
+ # d is the data dimension (number of features)
69
+ d = x.shape[1]
70
+ # make sure latent_dim is valid
71
+ check_dims(d, latent_dim)
72
+ # the maximum-likelihood mu is the data's mean
73
+ mu = x.mean(axis: 0)
74
+ # calculate the covariance matrix of the data
75
+ s = data_covariance(x, mu)
76
+ # get the eigenvalues and eigenvectors of the covariance matrix
77
+ values, vectors = ::Numo::Linalg.eigh(s)
78
+ # reorder the eigenvalues and eigenvectors in descending order
79
+ order = values.sort_index.reverse
80
+ values = values[order]
81
+ vectors = vectors[true, order]
82
+
83
+ # calculate the noise variance as the mean of the discarded eigenvalues
84
+ noise_var = values[latent_dim..].mean
85
+ # calculate the scales for the retained eigenvalues, ensuring they are non-negative
86
+ scales = Numo::NMath.sqrt((values[0...latent_dim] - noise_var).clip(0, nil))
87
+ # obtain the weight matrix by scaling the retained eigenvectors
88
+ weight = vectors[true, 0...latent_dim] * scales
89
+ # create a new PPCA model from the calculated parameters
90
+ from_parameters(weight, mu, noise_var)
91
+ end
92
+
93
+ # The maximum-likelihood fit by EM, from a random start. With S the
94
+ # data's covariance and mu its mean (already the maximum), each
95
+ # iteration computes the posterior moments of z (E step) and the W
96
+ # and sigma^2 that maximize the expected log-likelihood (M step),
97
+ # which in terms of S read:
98
+ #
99
+ # M = W^T W + sigma^2 I
100
+ # W' = S W (sigma^2 I + M^-1 W^T S W)^-1
101
+ # sigma'^2 = tr(S - S W M^-1 W'^T) / D
102
+ #
103
+ # Each iteration never lowers the likelihood. Stops when it improves
104
+ # by less than `tolerance` per sample, or after max_iterations (the
105
+ # likelihood flattens long before W stops moving, hence the small
106
+ # default tolerance). The block, if given, sees every iteration.
107
+ #
108
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
109
+ # @param latent_dim [Integer] M, in 1...D
110
+ # @param max_iterations [Integer]
111
+ # @param tolerance [Float] the least improvement of the mean log-likelihood to go on
112
+ # @param seed [Integer, nil] seeds W's random start
113
+ # @yieldparam iteration [Integer] from 1
114
+ # @yieldparam log_likelihood [Float] the mean log-likelihood after it
115
+ # @return [PPCA]
116
+ # @raise [ArgumentError] if latent_dim isn't in 1...D
117
+ def self.em(x, latent_dim, max_iterations: 1000, tolerance: 1e-9, seed: nil)
118
+ # host(x) ensures x is a Numo::DFloat array, not a Tensor, and copies it to the host if needed
119
+ x = host(x)
120
+ # d is the data dimension (number of features)
121
+ d = x.shape[1]
122
+ # make sure latent_dim is valid
123
+ check_dims(d, latent_dim)
124
+ # mu has a closed form, the data's mean: EM only fits W and sigma^2
125
+ mu = x.mean(axis: 0)
126
+ # the data enter EM only through their covariance S
127
+ s = data_covariance(x, mu)
128
+ # start W from small random values, uniform in [-0.5, 0.5)
129
+ rng = Random.new(seed || Random.new_seed)
130
+ w = ::Numo::DFloat.cast(Array.new(d * latent_dim) { rng.rand - 0.5 }).reshape(d, latent_dim)
131
+ # start sigma^2 from the average variance of the data
132
+ noise_var = s.diagonal.mean
133
+ eye = ::Numo::DFloat.eye(latent_dim)
134
+
135
+ previous = -Float::INFINITY
136
+ 1.upto(max_iterations) do |iteration|
137
+ # E step, folded into the M step (Tipping and Bishop's form):
138
+ # M^-1 = (W^T W + sigma^2 I)^-1 gives the posterior of z given x
139
+ m_inv = ::Numo::Linalg.inv(w.transpose.dot(w) + eye * noise_var)
140
+ # S W appears in both updates
141
+ sw = s.dot(w)
142
+ # M step for W: W_new = S W (sigma^2 I + M^-1 W^T S W)^-1
143
+ w_new = sw.dot(::Numo::Linalg.inv(eye * noise_var + m_inv.dot(w.transpose).dot(sw)))
144
+ # M step for sigma^2: the variance W_new leaves unexplained, per dimension
145
+ noise_var = (s.diagonal.sum - (sw.dot(m_inv) * w_new).sum) / d
146
+ w = w_new
147
+
148
+ # EM never decreases the log-likelihood: stop when it no longer grows
149
+ current = gaussian_log_likelihood(s, w, noise_var)
150
+ yield iteration, current if block_given?
151
+ break if current - previous < tolerance
152
+
153
+ previous = current
154
+ end
155
+ # create a new PPCA model from the fitted parameters
156
+ from_parameters(w, mu, noise_var)
157
+ end
158
+
159
+ # The marginal covariance C = W W^T + sigma^2 I, a Tensor [D, D].
160
+ #
161
+ # @return [Tensor] C, [D, D]
162
+ def covariance
163
+ @weight.matmul(@weight.transpose) + identity(data_dim) * @log_noise_var.exp
164
+ end
165
+
166
+ # log p(x) for each row of x [N, D], shape [N]:
167
+ #
168
+ # -1/2 (D log(2 pi) + log det C + (x - mu)^T C^-1 (x - mu))
169
+ #
170
+ # computed without the D x D matrix C. With M = W^T W + sigma^2 I,
171
+ # only M x M, the Woodbury identity and the matrix determinant lemma
172
+ # give
173
+ #
174
+ # C^-1 = (I - W M^-1 W^T) / sigma^2
175
+ # log det C = (D - M) log sigma^2 + log det M
176
+ #
177
+ # so, with p = W^T (x - mu), the quadratic form is
178
+ # (||x - mu||^2 - p^T M^-1 p) / sigma^2. For MNIST (D = 784, M = 16)
179
+ # this replaces a 784 x 784 factorization per step by a 16 x 16 one.
180
+ #
181
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
182
+ # @return [Tensor] log p(x), [N]
183
+ def log_prob(x)
184
+ # center the data: x - mu, [N, D]
185
+ diff = as_tensor(x) - @mean
186
+ # sigma^2, kept as its log so that it stays positive while training
187
+ noise_var = @log_noise_var.exp
188
+ # the small M x M matrix that replaces C: M = W^T W + sigma^2 I
189
+ m = @weight.transpose.matmul(@weight) + identity(latent_dim) * noise_var
190
+ # p = W^T (x - mu) for every sample, as rows: [N, M]
191
+ projected = diff.matmul(@weight)
192
+ # p^T M^-1 p for every sample: the part of the distance the subspace explains
193
+ explained = (projected.transpose * m.solve(projected.transpose)).sum(axis: 0)
194
+ # the Mahalanobis distance (x - mu)^T C^-1 (x - mu), by the Woodbury identity
195
+ mahalanobis = ((diff**2).sum(axis: 1) - explained) / noise_var
196
+ # log det C, by the matrix determinant lemma
197
+ logdet = @log_noise_var * (data_dim - latent_dim) + m.logdet
198
+ # put the Gaussian's log-density together
199
+ (mahalanobis + logdet + data_dim * Distributions::LOG_2PI) * -0.5
200
+ end
201
+
202
+ # The training loss of a gradient fit: the negative mean
203
+ # log-likelihood of the batch.
204
+ #
205
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
206
+ # @return [Tensor] the negative mean log-likelihood, a scalar
207
+ def forward(x)
208
+ -log_prob(x).mean
209
+ end
210
+
211
+ # The mean log-likelihood of x, a Float.
212
+ #
213
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
214
+ # @return [Float]
215
+ def log_likelihood(x)
216
+ Maurograd.no_grad { log_prob(x).mean.item }
217
+ end
218
+
219
+ # The posterior p(z | x): its means, [N, M], and its covariance,
220
+ # [M, M], the same for every x.
221
+ #
222
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
223
+ # @return [Array(Tensor, Tensor)] the means [N, M] and the covariance [M, M]
224
+ def posterior(x)
225
+ Maurograd.no_grad do
226
+ # M = W^T W + sigma^2 I, as in #log_prob
227
+ m = @weight.transpose.matmul(@weight) + identity(latent_dim) * @log_noise_var.exp
228
+ # the posterior means, M^-1 W^T (x - mu), one row per sample
229
+ means = m.solve(@weight.transpose.matmul((as_tensor(x) - @mean).transpose)).transpose
230
+ # the posterior covariance, sigma^2 M^-1, which doesn't depend on x
231
+ [means, m.solve(identity(latent_dim)) * @log_noise_var.exp]
232
+ end
233
+ end
234
+
235
+ # x projected onto the principal subspace and back: W E[z | x] + mu.
236
+ #
237
+ # @param x [Numo::NArray, Tensor] the data, [N, D]
238
+ # @return [Tensor] [N, D]
239
+ def reconstruct(x)
240
+ # the most likely latent of each sample, E[z | x]
241
+ means, = posterior(x)
242
+ # mapped back to the data space, without the noise
243
+ Maurograd.no_grad { means.matmul(@weight.transpose) + @mean }
244
+ end
245
+
246
+ # n samples from p(x), [n, D]: W z + mu + sigma eps.
247
+ #
248
+ # @param n [Integer]
249
+ # @return [Tensor] [n, D]
250
+ def sample(n)
251
+ Maurograd.no_grad do
252
+ bk = @weight.backend
253
+ # latents from the prior, z ~ N(0, I)
254
+ z = Maurograd.randn(n, latent_dim, backend: bk)
255
+ # noise in every data dimension, eps ~ N(0, I)
256
+ eps = Maurograd.randn(n, data_dim, backend: bk)
257
+ # x = W z + mu + sigma eps (sigma = exp(log sigma^2 / 2))
258
+ z.matmul(@weight.transpose) + @mean + eps * (@log_noise_var * 0.5).exp
259
+ end
260
+ end
261
+
262
+ # A PPCA with the given W [D, M], mu [D] and sigma^2 (Numo arrays or
263
+ # Arrays, and a Float).
264
+ #
265
+ # @param weight [Numo::NArray, Array] W, [D, M]
266
+ # @param mean [Numo::NArray, Array] mu, [D]
267
+ # @param noise_var [Float] sigma^2
268
+ # @return [PPCA]
269
+ def self.from_parameters(weight, mean, noise_var)
270
+ d, m = weight.shape
271
+ model = new(d, m)
272
+ model.load_state_dict({
273
+ "weight" => ::Numo::SFloat.cast(weight),
274
+ "mean" => ::Numo::SFloat.cast(mean),
275
+ "log_noise_var" => ::Numo::SFloat[Math.log(noise_var)]
276
+ })
277
+ model
278
+ end
279
+
280
+ # The largest principal angle between the column spaces of two
281
+ # matrices [D, M], in degrees: 0 when they span the same subspace,
282
+ # whatever the basis. How fits of W, defined up to a rotation, are
283
+ # compared. (The cosines of the principal angles are the singular
284
+ # values of Qa^T Qb, with Qa and Qb orthonormal bases of the spaces.)
285
+ #
286
+ # @param a [Numo::NArray, Tensor] [D, M]
287
+ # @param b [Numo::NArray, Tensor] [D, M]
288
+ # @return [Float] the angle in degrees, in [0, 90]
289
+ def self.subspace_angle(a, b)
290
+ qa, = ::Numo::Linalg.qr(host(a), mode: "economic")
291
+ qb, = ::Numo::Linalg.qr(host(b), mode: "economic")
292
+ cosine = ::Numo::Linalg.svdvals(qa.transpose.dot(qb)).min.clamp(-1.0, 1.0)
293
+ Math.acos(cosine) * 180 / Math::PI
294
+ end
295
+
296
+ # --- helpers ---------------------------------------------------------
297
+
298
+ def self.host(x)
299
+ x = x.to_numo if x.is_a?(Tensor)
300
+ ::Numo::DFloat.cast(x)
301
+ end
302
+
303
+ def self.check_dims(d, latent_dim)
304
+ return if latent_dim.is_a?(Integer) && latent_dim.between?(1, d - 1)
305
+
306
+ raise ArgumentError, "latent_dim must be between 1 and #{d - 1}, got #{latent_dim.inspect}"
307
+ end
308
+
309
+ # The maximum-likelihood covariance (dividing by N, not N - 1).
310
+ def self.data_covariance(x, mu)
311
+ centered = x - mu
312
+ centered.transpose.dot(centered) / x.shape[0]
313
+ end
314
+
315
+ # Mean log-likelihood of data with covariance S under N(mu, C), mu
316
+ # the data's mean: -1/2 (D log(2 pi) + log det C + tr(C^-1 S)), with
317
+ # the same M x M identities as #log_prob:
318
+ # tr(C^-1 S) = (tr S - tr(M^-1 W^T S W)) / sigma^2.
319
+ def self.gaussian_log_likelihood(s, w, noise_var)
320
+ d, m = w.shape
321
+ small = w.transpose.dot(w) + ::Numo::DFloat.eye(m) * noise_var
322
+ _, logdet_small = ::Numo::Linalg.slogdet(small)
323
+ logdet = (d - m) * Math.log(noise_var) + logdet_small
324
+ trace = (s.diagonal.sum - ::Numo::Linalg.solve(small, w.transpose.dot(s).dot(w)).diagonal.sum) / noise_var
325
+ -0.5 * (d * Distributions::LOG_2PI + logdet + trace)
326
+ end
327
+
328
+ private_class_method :host, :check_dims, :data_covariance, :gaussian_log_likelihood
329
+
330
+ private
331
+
332
+ def identity(n) = Tensor.new(::Numo::SFloat.eye(n), backend: @weight.backend)
333
+
334
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: @weight.backend)
335
+ end
336
+ end
337
+ end
@@ -0,0 +1,96 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Priors p(z) over a VAE's latent space. Each is a Module (learnable
4
+ # ones have parameters the optimizer finds through the VAE) with
5
+ #
6
+ # log_prob(z) # [N], for z [N, L]
7
+ # sample(n, backend: nil) # [n, L]
8
+ #
9
+ # and, where it exists in closed form, kl_divergence(q) for a diagonal
10
+ # Gaussian posterior q, which the VAE then uses instead of a Monte Carlo
11
+ # estimate.
12
+ module Priors
13
+ # N(0, I): the standard choice, with a closed-form KL. Simple, but it
14
+ # pulls every posterior toward the same blob, and the regions between
15
+ # the data's modes that it still covers decode to blurry samples.
16
+ class StandardNormal < Layers::Module
17
+ attr_reader :latent_dim
18
+
19
+ # @param latent_dim [Integer] L
20
+ def initialize(latent_dim)
21
+ @latent_dim = latent_dim
22
+ end
23
+
24
+ def log_prob(z) = Distributions::StandardNormal.new(@latent_dim).log_prob(z)
25
+
26
+ def sample(n, backend: nil) = Distributions::StandardNormal.new(@latent_dim).sample(n, backend: backend)
27
+
28
+ def kl_divergence(q) = q.kl_divergence(Distributions::StandardNormal.new(@latent_dim))
29
+ end
30
+
31
+ # A learnable mixture of K diagonal Gaussians (Tomczak, Deep
32
+ # Generative Modeling, section 4.5): the prior moves toward where the
33
+ # aggregate posterior puts the data, with room for several modes. Its
34
+ # KL to the posterior has no closed form, so the VAE estimates it.
35
+ class MixtureOfGaussians < Layers::Module
36
+ attr_reader :logits, :means, :log_vars
37
+
38
+ # @param latent_dim [Integer] L
39
+ # @param components [Integer] K, the Gaussians
40
+ # @param seed [Integer, nil] seeds the components' initial means
41
+ def initialize(latent_dim, components: 16, seed: nil)
42
+ @logits = Tensor.new(::Numo::SFloat.zeros(components), requires_grad: true)
43
+ @means = Tensor.new(Maurograd::Utils.rand_norm(components, latent_dim, std: 1.0, seed: seed), requires_grad: true)
44
+ @log_vars = Tensor.new(::Numo::SFloat.zeros(components, latent_dim), requires_grad: true)
45
+ end
46
+
47
+ def latent_dim = @means.shape[1]
48
+
49
+ def distribution = Distributions::MixtureOfGaussians.new(@logits, @means, @log_vars)
50
+
51
+ def log_prob(z) = distribution.log_prob(z)
52
+
53
+ def sample(n, backend: nil) = distribution.sample(n)
54
+ end
55
+
56
+ # The VampPrior (Tomczak and Welling, 2018): the mixture of the
57
+ # encoder's posteriors at K learned pseudo-inputs u_k,
58
+ #
59
+ # p(z) = 1/K sum_k q(z | u_k)
60
+ #
61
+ # which approximates the aggregate posterior, the prior that would
62
+ # maximize the ELBO. It shares the VAE's encoder; the pseudo-inputs
63
+ # are parameters, shaped like the data, best started from real
64
+ # samples.
65
+ #
66
+ # encoder = Layers::Sequential.new(...)
67
+ # prior = Priors::VampPrior.new(encoder, x_train[0...500, true])
68
+ # vae = VAE.new(encoder, decoder, 16, prior: prior)
69
+ class VampPrior < Layers::Module
70
+ attr_reader :pseudo_inputs
71
+
72
+ # @param encoder [Layers::Module] the VAE's encoder
73
+ # @param pseudo_inputs [Numo::NArray] the K starting pseudo-inputs, [K, ...] shaped like the data
74
+ def initialize(encoder, pseudo_inputs)
75
+ @encoder = encoder
76
+ @pseudo_inputs = Tensor.new(::Numo::SFloat.cast(pseudo_inputs), requires_grad: true)
77
+ end
78
+
79
+ def num_components = @pseudo_inputs.shape[0]
80
+
81
+ def distribution
82
+ # encode the pseudo-inputs: one Gaussian q(z | u_k) per pseudo-input
83
+ mean, log_var = @encoder.call(@pseudo_inputs).chunk(2, axis: 1)
84
+ # equal weights 1/K: logits of 0, which aren't learned
85
+ logits = Tensor.new(::Numo::SFloat.zeros(num_components), backend: mean.backend)
86
+ # the mixture of those Gaussians
87
+ Distributions::MixtureOfGaussians.new(logits, mean, log_var)
88
+ end
89
+
90
+ def log_prob(z) = distribution.log_prob(z)
91
+
92
+ def sample(n, backend: nil) = Maurograd.no_grad { distribution.sample(n) }
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,28 @@
1
+ module Maurograd
2
+ module DGM
3
+ # `count` points on the great circle from a to b (Numo arrays, or
4
+ # Tensors, of the same shape [1, ...]), stacked into a Numo::SFloat
5
+ # [count, ...]: how noises are interpolated by models that map noise to
6
+ # data (DDIM, FlowMatching). High-dimensional Gaussian noise lies near a
7
+ # sphere, and a straight line between two noises would cut inside it,
8
+ # to noises of lower norm, which decode to blurred images.
9
+ #
10
+ # Parallel (or opposite) points have no unique great circle, and are
11
+ # interpolated on the line between them.
12
+ def self.slerp(a, b, count)
13
+ a = ::Numo::DFloat.cast(a.respond_to?(:to_numo) ? a.to_numo : a)
14
+ b = ::Numo::DFloat.cast(b.respond_to?(:to_numo) ? b.to_numo : b)
15
+ cosine = (a * b).sum / Math.sqrt((a * a).sum * (b * b).sum)
16
+ omega = Math.acos(cosine.clamp(-1.0, 1.0))
17
+ points = (0...count).map do |i|
18
+ u = (count == 1) ? 0.0 : i.to_f / (count - 1)
19
+ if omega < 1e-6 || Math::PI - omega < 1e-6
20
+ a * (1 - u) + b * u
21
+ else
22
+ a * (Math.sin((1 - u) * omega) / Math.sin(omega)) + b * (Math.sin(u * omega) / Math.sin(omega))
23
+ end
24
+ end
25
+ ::Numo::SFloat.cast(::Numo::DFloat.vstack(points.map { |z| z.reshape(1, *a.shape[1..]) }))
26
+ end
27
+ end
28
+ end