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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +135 -0
- data/LICENSE +21 -0
- data/README.md +442 -0
- data/lib/maurograd/dgm/datasets/download.rb +53 -0
- data/lib/maurograd/dgm/datasets/idx.rb +39 -0
- data/lib/maurograd/dgm/datasets/loader.rb +62 -0
- data/lib/maurograd/dgm/datasets/mnist.rb +96 -0
- data/lib/maurograd/dgm/datasets/toy_2d.rb +96 -0
- data/lib/maurograd/dgm/datasets.rb +19 -0
- data/lib/maurograd/dgm/ddim.rb +194 -0
- data/lib/maurograd/dgm/ddpm.rb +188 -0
- data/lib/maurograd/dgm/distributions/bernoulli.rb +54 -0
- data/lib/maurograd/dgm/distributions/categorical.rb +62 -0
- data/lib/maurograd/dgm/distributions/mixture_of_gaussians.rb +79 -0
- data/lib/maurograd/dgm/distributions/normal.rb +88 -0
- data/lib/maurograd/dgm/distributions/standard_normal.rb +42 -0
- data/lib/maurograd/dgm/distributions.rb +49 -0
- data/lib/maurograd/dgm/ebm.rb +211 -0
- data/lib/maurograd/dgm/flow_matching.rb +303 -0
- data/lib/maurograd/dgm/flows.rb +245 -0
- data/lib/maurograd/dgm/gan.rb +366 -0
- data/lib/maurograd/dgm/image_grid.rb +78 -0
- data/lib/maurograd/dgm/likelihoods.rb +33 -0
- data/lib/maurograd/dgm/linear_vae.rb +140 -0
- data/lib/maurograd/dgm/metrics.rb +85 -0
- data/lib/maurograd/dgm/networks.rb +151 -0
- data/lib/maurograd/dgm/noise_schedule.rb +97 -0
- data/lib/maurograd/dgm/normalizing_flow.rb +225 -0
- data/lib/maurograd/dgm/ppca.rb +337 -0
- data/lib/maurograd/dgm/priors.rb +96 -0
- data/lib/maurograd/dgm/slerp.rb +28 -0
- data/lib/maurograd/dgm/trainer.rb +158 -0
- data/lib/maurograd/dgm/vae.rb +208 -0
- data/lib/maurograd/dgm/version.rb +5 -0
- data/lib/maurograd/dgm.rb +64 -0
- data/lib/maurograd-dgm.rb +3 -0
- metadata +143 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
# A denoising diffusion probabilistic model (Ho et al., 2020).
|
|
4
|
+
#
|
|
5
|
+
# The forward process adds Gaussian noise to the data over T steps
|
|
6
|
+
# (see NoiseSchedule) until nothing but noise is left; the model learns
|
|
7
|
+
# to undo one step at a time. A network eps(x_t, t) is trained to
|
|
8
|
+
# predict the noise that took x_0 to x_t:
|
|
9
|
+
#
|
|
10
|
+
# x_t = sqrt(alpha_bar_t) x_0 + sqrt(1 - alpha_bar_t) eps, eps ~ N(0, I)
|
|
11
|
+
# loss = || eps - eps(x_t, t) ||^2, t uniform over the steps
|
|
12
|
+
#
|
|
13
|
+
# which is a reweighted form of the variational bound (Ho et al.'s
|
|
14
|
+
# "simple" loss). Sampling starts from pure noise and runs the learned
|
|
15
|
+
# reverse process, all T steps:
|
|
16
|
+
#
|
|
17
|
+
# x_{t-1} = mu(x_t, t) + sigma_t z, z ~ N(0, I)
|
|
18
|
+
#
|
|
19
|
+
# with mu the mean of q(x_{t-1} | x_t, x_0) at the x_0 the predicted
|
|
20
|
+
# noise implies.
|
|
21
|
+
#
|
|
22
|
+
# unet = Networks::UNet.new(in_channels: 1, channels: [32, 64, 128])
|
|
23
|
+
# model = DDPM.new(unet, shape: [1, 28, 28])
|
|
24
|
+
# loss = model.call(x) # x in [-1, 1], [N, 1, 28, 28]
|
|
25
|
+
# images = model.sample(16) # [16, 1, 28, 28], in [-1, 1]
|
|
26
|
+
#
|
|
27
|
+
# The data should be scaled to [-1, 1], the range the noise is
|
|
28
|
+
# matched to. DDIM samples from the same trained model in fewer steps.
|
|
29
|
+
class DDPM < Layers::Module
|
|
30
|
+
attr_reader :network, :schedule, :shape, :variance
|
|
31
|
+
|
|
32
|
+
# @param network [Layers::Module] (x_t, t) -> the predicted noise, shaped like x_t; e.g. Networks::UNet
|
|
33
|
+
# @param shape [Array<Integer>] one sample's shape, e.g. [1, 28, 28] or [2]
|
|
34
|
+
# @param schedule [NoiseSchedule]
|
|
35
|
+
# @param variance [Symbol] the reverse process's sigma_t^2: :beta (beta_t) or :posterior
|
|
36
|
+
# (beta_tilde_t); Ho et al. found both work, beta a bit better with their schedule
|
|
37
|
+
# @param clip [Boolean] clip the predicted x_0 to [-1, 1] while sampling, as Ho et al.'s
|
|
38
|
+
# code does: it keeps samples in range early on, when the prediction is poor
|
|
39
|
+
# @raise [ArgumentError] if variance is neither :beta nor :posterior
|
|
40
|
+
def initialize(network, shape:, schedule: NoiseSchedule.linear, variance: :beta, clip: true)
|
|
41
|
+
raise ArgumentError, "variance must be :beta or :posterior, got #{variance.inspect}" unless %i[beta posterior].include?(variance)
|
|
42
|
+
|
|
43
|
+
@network = network
|
|
44
|
+
@shape = shape
|
|
45
|
+
@schedule = schedule
|
|
46
|
+
@variance = variance
|
|
47
|
+
@clip = clip
|
|
48
|
+
@sigmas = ::Numo::NMath.sqrt((variance == :beta) ? schedule.betas : schedule.posterior_variances)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def steps = @schedule.steps
|
|
52
|
+
|
|
53
|
+
# A sample of q(x_t | x_0) in one jump, for x_0 [N, ...] and t one
|
|
54
|
+
# step for all (an Integer) or one per sample. The noise is drawn if
|
|
55
|
+
# not given.
|
|
56
|
+
#
|
|
57
|
+
# @param x0 [Tensor, Numo::NArray] the data, [N, *shape], in [-1, 1]
|
|
58
|
+
# @param t [Integer, Array<Integer>, Numo::NArray] a step in 0...T for all samples, or one per sample
|
|
59
|
+
# @param noise [Tensor, Numo::NArray, nil] eps, shaped like x0; drawn if nil
|
|
60
|
+
# @return [Tensor] x_t, shaped like x0
|
|
61
|
+
# @raise [ArgumentError] if a step is outside 0...T
|
|
62
|
+
def q_sample(x0, t, noise = nil)
|
|
63
|
+
x0 = as_tensor(x0)
|
|
64
|
+
# the Gaussian noise to mix in, eps ~ N(0, I)
|
|
65
|
+
noise = noise ? as_tensor(noise) : Maurograd.randn_like(x0)
|
|
66
|
+
# one step per sample
|
|
67
|
+
t = steps_for(t, x0.shape[0])
|
|
68
|
+
# alpha_bar_t: how much of the signal is left after t steps
|
|
69
|
+
alpha_bars = @schedule.alpha_bars[t]
|
|
70
|
+
# x_t = sqrt(alpha_bar_t) x_0 + sqrt(1 - alpha_bar_t) eps
|
|
71
|
+
(x0 * per_sample(::Numo::NMath.sqrt(alpha_bars), x0)) + (noise * per_sample(::Numo::NMath.sqrt(1 - alpha_bars), x0))
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The network's estimate of the noise in x_t.
|
|
75
|
+
#
|
|
76
|
+
# @param x [Tensor] x_t, [N, *shape]
|
|
77
|
+
# @param t [Integer, Array<Integer>, Numo::NArray] a step in 0...T for all samples, or one per sample
|
|
78
|
+
# @return [Tensor] shaped like x
|
|
79
|
+
def predict_noise(x, t) = @network.call(x, steps_for(t, x.shape[0]))
|
|
80
|
+
|
|
81
|
+
# The training loss: the mean squared error between the noise and the
|
|
82
|
+
# network's estimate of it, at a uniformly drawn step per sample.
|
|
83
|
+
#
|
|
84
|
+
# @param x0 [Tensor, Numo::NArray] the data, [N, *shape], in [-1, 1]
|
|
85
|
+
# @return [Tensor] the mean squared error, a scalar
|
|
86
|
+
def forward(x0)
|
|
87
|
+
x0 = as_tensor(x0)
|
|
88
|
+
# a random noise level for each sample, t uniform in 0...T
|
|
89
|
+
t = random_steps(x0.shape[0])
|
|
90
|
+
# the noise that will corrupt x_0
|
|
91
|
+
noise = Maurograd.randn_like(x0)
|
|
92
|
+
# corrupt x_0 to x_t, and ask the network which noise it added
|
|
93
|
+
error = predict_noise(q_sample(x0, t, noise), t) - noise
|
|
94
|
+
# the mean squared error of its answer
|
|
95
|
+
(error * error).mean
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# The training loss at a given step (an Integer), for every sample:
|
|
99
|
+
# how hard denoising is at each noise level.
|
|
100
|
+
#
|
|
101
|
+
# @param x0 [Tensor, Numo::NArray] the data, [N, *shape], in [-1, 1]
|
|
102
|
+
# @param t [Integer] a step in 0...T
|
|
103
|
+
# @return [Tensor] the mean squared error of each sample, [N]
|
|
104
|
+
def loss_at(x0, t)
|
|
105
|
+
x0 = as_tensor(x0)
|
|
106
|
+
Maurograd.no_grad do
|
|
107
|
+
noise = Maurograd.randn_like(x0)
|
|
108
|
+
error = predict_noise(q_sample(x0, t, noise), t) - noise
|
|
109
|
+
(error * error).reshape(x0.shape[0], -1).mean(axis: 1)
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# n samples, from noise through all T reverse steps, under no_grad.
|
|
114
|
+
# With every: k, also returns the states every k steps (the first,
|
|
115
|
+
# x_T, and the last, x_0, included), to show the denoising.
|
|
116
|
+
#
|
|
117
|
+
# @param n [Integer]
|
|
118
|
+
# @param every [Integer, nil] also return the states every that many steps
|
|
119
|
+
# @param noise [Tensor, Numo::NArray, nil] x_T, [n, *shape]; drawn if nil
|
|
120
|
+
# @return [Tensor, Array(Tensor, Array<Tensor>)] the samples [n, *shape], in about
|
|
121
|
+
# [-1, 1]; with every:, [samples, states]
|
|
122
|
+
def sample(n, every: nil, noise: nil)
|
|
123
|
+
Maurograd.no_grad do
|
|
124
|
+
# start from pure noise, x_T ~ N(0, I)
|
|
125
|
+
x = noise ? as_tensor(noise) : Maurograd.randn(n, *@shape, backend: parameter_backend)
|
|
126
|
+
states = [x]
|
|
127
|
+
# undo the noise one step at a time, from t = T - 1 down to 0
|
|
128
|
+
(steps - 1).downto(0) do |t|
|
|
129
|
+
x = reverse_step(x, t)
|
|
130
|
+
# evaluate now on a lazy backend (MLX), not one long graph at the end
|
|
131
|
+
x.backend.eval([x.data])
|
|
132
|
+
states << x if every && (t % every).zero?
|
|
133
|
+
end
|
|
134
|
+
every ? [x, states] : x
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# One reverse step, x_t -> x_{t-1}.
|
|
139
|
+
#
|
|
140
|
+
# @param x [Tensor] x_t, [N, *shape]
|
|
141
|
+
# @param t [Integer] the step, in 0...T
|
|
142
|
+
# @return [Tensor] x_{t-1}, shaped like x
|
|
143
|
+
def reverse_step(x, t)
|
|
144
|
+
# the network's guess of the noise in x_t
|
|
145
|
+
eps = predict_noise(x, t)
|
|
146
|
+
# the schedule's coefficients at t and t - 1
|
|
147
|
+
alpha_bar = @schedule.alpha_bar(t)
|
|
148
|
+
previous = @schedule.alpha_bar(t - 1)
|
|
149
|
+
beta = @schedule.betas[t]
|
|
150
|
+
# the x_0 that guess implies, inverting x_t = sqrt(alpha_bar) x_0 + sqrt(1 - alpha_bar) eps
|
|
151
|
+
x0 = (x - eps * Math.sqrt(1 - alpha_bar)) * (1 / Math.sqrt(alpha_bar))
|
|
152
|
+
# keep it in the data's range, [-1, 1]
|
|
153
|
+
x0 = x0.clamp(min: -1.0, max: 1.0) if @clip
|
|
154
|
+
# the mean of q(x_{t-1} | x_t, x_0): a weighted average of x_0 and x_t
|
|
155
|
+
mean = (x0 * (Math.sqrt(previous) * beta / (1 - alpha_bar))) +
|
|
156
|
+
(x * (Math.sqrt(@schedule.alphas[t]) * (1 - previous) / (1 - alpha_bar)))
|
|
157
|
+
# the last step returns the mean, without noise
|
|
158
|
+
return mean if t.zero?
|
|
159
|
+
|
|
160
|
+
# every other step adds fresh noise of standard deviation sigma_t
|
|
161
|
+
mean + Maurograd.randn_like(x) * @sigmas[t]
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
private
|
|
165
|
+
|
|
166
|
+
def random_steps(n) = ::Numo::Int32.cast((::Numo::DFloat.new(n).rand * steps).floor)
|
|
167
|
+
|
|
168
|
+
# t as an Int32 vector of n steps.
|
|
169
|
+
def steps_for(t, n)
|
|
170
|
+
t = t.to_numo if t.is_a?(Tensor)
|
|
171
|
+
t = t.is_a?(Integer) ? ::Numo::Int32.new(n).fill(t) : ::Numo::Int32.cast(t)
|
|
172
|
+
raise ArgumentError, "steps must be in 0...#{steps}" unless t.size == n && t.min >= 0 && t.max < steps
|
|
173
|
+
|
|
174
|
+
t
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# A per-sample coefficient, as a Tensor [N, 1, ...] that broadcasts
|
|
178
|
+
# against x.
|
|
179
|
+
def per_sample(values, x)
|
|
180
|
+
Tensor.new(::Numo::SFloat.cast(values).reshape(x.shape[0], *([1] * (x.ndim - 1))), backend: x.backend)
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def parameter_backend = parameters.first&.backend || Maurograd.backend
|
|
184
|
+
|
|
185
|
+
def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
module Distributions
|
|
4
|
+
# Independent Bernoulli variables, parameterized by their logits: the
|
|
5
|
+
# decoder of a VAE on (binarized) MNIST, one variable per pixel.
|
|
6
|
+
#
|
|
7
|
+
# p = Bernoulli.new(decoder.call(z)) # logits, e.g. [N, 784]
|
|
8
|
+
# p.log_prob(x) # [N], for x in [0, 1]
|
|
9
|
+
#
|
|
10
|
+
# With z the logit and sigmoid(z) the probability of a 1:
|
|
11
|
+
#
|
|
12
|
+
# log p(x) = x log sigmoid(z) + (1 - x) log(1 - sigmoid(z))
|
|
13
|
+
# = x z - softplus(z)
|
|
14
|
+
#
|
|
15
|
+
# The second form is exact for any logit, where the first takes the
|
|
16
|
+
# log of 0 once sigmoid(z) rounds to 0 or 1. It is the negative of
|
|
17
|
+
# Losses::BCEWithLogits, summed per sample instead of averaged. It
|
|
18
|
+
# also accepts x anywhere in [0, 1], as for grayscale MNIST, though
|
|
19
|
+
# then it is no longer a normalized density.
|
|
20
|
+
class Bernoulli
|
|
21
|
+
attr_reader :logits
|
|
22
|
+
|
|
23
|
+
def initialize(logits)
|
|
24
|
+
@logits = Distributions.tensor(logits, nil)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def probs = @logits.sigmoid
|
|
28
|
+
|
|
29
|
+
alias_method :mean, :probs
|
|
30
|
+
|
|
31
|
+
# Log-probability of each sample in x, shape [N].
|
|
32
|
+
def log_prob(x)
|
|
33
|
+
x = Distributions.tensor(x, @logits.backend)
|
|
34
|
+
Distributions.sum_per_sample(x * @logits - @logits.softplus)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# A sample of 0s and 1s (as floats), the shape of the logits: 1
|
|
38
|
+
# where a uniform draw falls below the probability.
|
|
39
|
+
def sample
|
|
40
|
+
bk = @logits.backend
|
|
41
|
+
Maurograd.no_grad do
|
|
42
|
+
Tensor.new(bk.greater(probs.data, bk.uniform(@logits.shape)), backend: bk)
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Entropy of each sample, shape [N]: with p = sigmoid(z),
|
|
47
|
+
# -p log p - (1 - p) log(1 - p) = softplus(z) - p z.
|
|
48
|
+
def entropy
|
|
49
|
+
Distributions.sum_per_sample(@logits.softplus - probs * @logits)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
module Distributions
|
|
4
|
+
# A categorical distribution over K classes, parameterized by logits
|
|
5
|
+
# of shape [N, K] (one distribution per row) or [K] (a single one):
|
|
6
|
+
# the mixing weights of a mixture, or a classifier's output.
|
|
7
|
+
#
|
|
8
|
+
# log p(k) = log_softmax(logits)_k = logits_k - logsumexp(logits)
|
|
9
|
+
class Categorical
|
|
10
|
+
attr_reader :logits
|
|
11
|
+
|
|
12
|
+
def initialize(logits)
|
|
13
|
+
@logits = Distributions.tensor(logits, nil)
|
|
14
|
+
raise ArgumentError, "logits must have shape [K] or [N, K], got #{@logits.shape.inspect}" unless [1, 2].include?(@logits.ndim)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def num_classes = @logits.shape.last
|
|
18
|
+
|
|
19
|
+
def log_probs = @logits.log_softmax(axis: -1)
|
|
20
|
+
|
|
21
|
+
def probs = @logits.softmax(axis: -1)
|
|
22
|
+
|
|
23
|
+
# Log-probability of each class index in `indices` (an Array, a
|
|
24
|
+
# Numo integer array, or a Tensor), one per row: shape [N]. With a
|
|
25
|
+
# single distribution, its log-probabilities are shared by all N.
|
|
26
|
+
def log_prob(indices)
|
|
27
|
+
indices = indices.to_numo if indices.is_a?(Tensor)
|
|
28
|
+
bk = @logits.backend
|
|
29
|
+
one_hot = Tensor.new(bk.one_hot(bk.from(::Numo::Int32.cast(indices)), num_classes), backend: bk)
|
|
30
|
+
lp = (@logits.ndim == 1) ? log_probs.reshape(1, num_classes) : log_probs
|
|
31
|
+
(one_hot * lp).sum(axis: 1)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Class indices, a Numo::Int32 array: one per row of the logits, or
|
|
35
|
+
# n of them for a single distribution. Drawn on the host with the
|
|
36
|
+
# Gumbel-max trick: argmax_k (logits_k + g_k), g_k = -log(-log u_k),
|
|
37
|
+
# is distributed as the softmax. Indices are small, and are what
|
|
38
|
+
# Backend#one_hot and Numo indexing take.
|
|
39
|
+
def sample(n = nil)
|
|
40
|
+
logits = ::Numo::DFloat.cast(@logits.to_numo)
|
|
41
|
+
if logits.ndim == 1
|
|
42
|
+
raise ArgumentError, "a single categorical needs a number of samples" unless n
|
|
43
|
+
|
|
44
|
+
logits = logits.reshape(1, logits.size).tile(n, 1)
|
|
45
|
+
elsif n
|
|
46
|
+
raise ArgumentError, "a batch of categoricals draws one sample per row; got n = #{n}"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
u = ::Numo::DFloat.new(*logits.shape).rand(1e-12, 1.0)
|
|
50
|
+
gumbel = -Numo::NMath.log(-Numo::NMath.log(u))
|
|
51
|
+
::Numo::Int32.cast((logits + gumbel).max_index(axis: 1) % logits.shape[1])
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Entropy of each row, shape [N] (or [1] for a single distribution).
|
|
55
|
+
def entropy
|
|
56
|
+
lp = (@logits.ndim == 1) ? log_probs.reshape(1, num_classes) : log_probs
|
|
57
|
+
-(lp.exp * lp).sum(axis: 1)
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
module Distributions
|
|
4
|
+
# A mixture of K diagonal Gaussians over D-dimensional vectors:
|
|
5
|
+
#
|
|
6
|
+
# p(x) = sum_k w_k N(x | m_k, diag(exp(log_var_k))), w = softmax(logits)
|
|
7
|
+
#
|
|
8
|
+
# A VAE prior that can be learned (its parameters as Tensors with
|
|
9
|
+
# requires_grad), and the target density of the 2D test sets.
|
|
10
|
+
#
|
|
11
|
+
# prior = MixtureOfGaussians.new(logits, means, log_vars) # [K], [K, D], [K, D]
|
|
12
|
+
# prior.log_prob(z) # z [N, D] -> [N]
|
|
13
|
+
#
|
|
14
|
+
# log p(x) is computed as logsumexp_k (log w_k + log N(x | m_k, ...)),
|
|
15
|
+
# so it stays finite when every component's density underflows.
|
|
16
|
+
class MixtureOfGaussians
|
|
17
|
+
attr_reader :logits, :means, :log_vars
|
|
18
|
+
|
|
19
|
+
def initialize(logits, means, log_vars)
|
|
20
|
+
@means = Distributions.tensor(means, nil)
|
|
21
|
+
bk = @means.backend
|
|
22
|
+
@logits = Distributions.tensor(logits, bk)
|
|
23
|
+
@log_vars = Distributions.tensor(log_vars, bk)
|
|
24
|
+
|
|
25
|
+
k, d = @means.shape
|
|
26
|
+
unless @means.ndim == 2 && @log_vars.shape == [k, d] && @logits.shape == [k]
|
|
27
|
+
raise ArgumentError, "expected logits [K], means and log_vars [K, D], got " \
|
|
28
|
+
"#{@logits.shape.inspect}, #{@means.shape.inspect}, #{@log_vars.shape.inspect}"
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def num_components = @means.shape[0]
|
|
33
|
+
|
|
34
|
+
def dim = @means.shape[1]
|
|
35
|
+
|
|
36
|
+
def weights = @logits.softmax(axis: -1)
|
|
37
|
+
|
|
38
|
+
# Log-density of each row of x [N, D], shape [N].
|
|
39
|
+
def log_prob(x)
|
|
40
|
+
joint_log_probs(x).logsumexp(axis: 1)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# n samples, shape [n, D]: a component k per sample (on the host,
|
|
44
|
+
# see Categorical#sample), then m_k + s_k * eps on the backend.
|
|
45
|
+
# The components' parameters are picked with a one-hot matrix
|
|
46
|
+
# product, so they never leave the backend.
|
|
47
|
+
def sample(n)
|
|
48
|
+
bk = @means.backend
|
|
49
|
+
Maurograd.no_grad do
|
|
50
|
+
components = Categorical.new(@logits).sample(n)
|
|
51
|
+
one_hot = Tensor.new(bk.one_hot(bk.from(components), num_components), backend: bk)
|
|
52
|
+
mean = one_hot.matmul(@means)
|
|
53
|
+
stddev = (one_hot.matmul(@log_vars) * 0.5).exp
|
|
54
|
+
mean + stddev * Maurograd.randn(n, dim, backend: bk)
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The probability of each component given each row of x, [N, K]:
|
|
59
|
+
# w_k N(x | k) / p(x). Which mode a sample belongs to.
|
|
60
|
+
def responsibilities(x)
|
|
61
|
+
joint_log_probs(x).softmax(axis: 1)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
# log w_k + log N(x_n | m_k, diag(var_k)), shape [N, K].
|
|
67
|
+
def joint_log_probs(x)
|
|
68
|
+
x = Distributions.tensor(x, @means.backend)
|
|
69
|
+
k = num_components
|
|
70
|
+
d = dim
|
|
71
|
+
diff = x.reshape(x.shape[0], 1, d) - @means.reshape(1, k, d) # [N, K, D]
|
|
72
|
+
log_vars = @log_vars.reshape(1, k, d)
|
|
73
|
+
per_component = ((log_vars + diff**2 * (-log_vars).exp + LOG_2PI) * -0.5).sum(axis: 2)
|
|
74
|
+
per_component + @logits.log_softmax(axis: -1).reshape(1, k)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
module Distributions
|
|
4
|
+
# A Gaussian with diagonal covariance, N(mean, diag(exp(log_var))): a
|
|
5
|
+
# VAE's approximate posterior q(z|x), or a Gaussian decoder p(x|z).
|
|
6
|
+
#
|
|
7
|
+
# mean, log_var = encoder.call(x).chunk(2, axis: 1)
|
|
8
|
+
# q = Normal.new(mean, log_var)
|
|
9
|
+
# z = q.rsample # differentiable in mean, log_var
|
|
10
|
+
#
|
|
11
|
+
# log N(x | m, s^2) = -1/2 * sum_i (log(2 pi) + log s_i^2 + (x_i - m_i)^2 / s_i^2)
|
|
12
|
+
#
|
|
13
|
+
# A full-covariance Gaussian needs log-determinants and linear solves,
|
|
14
|
+
# which come with probabilistic PCA (phase D1).
|
|
15
|
+
class Normal
|
|
16
|
+
attr_reader :mean, :log_var
|
|
17
|
+
|
|
18
|
+
# mean and log_var are Tensors (or Numo arrays) of shapes that
|
|
19
|
+
# broadcast together; log_var defaults to 0, unit variance.
|
|
20
|
+
def initialize(mean, log_var = nil)
|
|
21
|
+
@mean = Distributions.tensor(mean, nil)
|
|
22
|
+
@log_var = log_var ? Distributions.tensor(log_var, @mean.backend) : Tensor.new(::Numo::SFloat.zeros(*@mean.shape), backend: @mean.backend)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def variance = @log_var.exp
|
|
26
|
+
|
|
27
|
+
def stddev = (@log_var * 0.5).exp
|
|
28
|
+
|
|
29
|
+
# Log-density of each sample in x, shape [N].
|
|
30
|
+
def log_prob(x)
|
|
31
|
+
x = Distributions.tensor(x, @mean.backend)
|
|
32
|
+
per_element = (@log_var + ((x - @mean)**2) * (-@log_var).exp + LOG_2PI) * -0.5
|
|
33
|
+
Distributions.sum_per_sample(per_element)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# The reparameterization trick: mean + stddev * eps, eps ~ N(0, I).
|
|
37
|
+
# The randomness is in eps alone, so gradients reach the mean and the
|
|
38
|
+
# variance.
|
|
39
|
+
def rsample
|
|
40
|
+
@mean + stddev * Maurograd.randn(broadcast_shape, backend: @mean.backend)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# A sample with no graph recorded.
|
|
44
|
+
def sample
|
|
45
|
+
Maurograd.no_grad { rsample }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# KL(self || other), per sample, shape [N], in closed form; other is
|
|
49
|
+
# a Normal or a StandardNormal. With q = self and p = other:
|
|
50
|
+
#
|
|
51
|
+
# KL = 1/2 * sum_i (log p_var_i - log q_var_i
|
|
52
|
+
# + (q_var_i + (q_mean_i - p_mean_i)^2) / p_var_i - 1)
|
|
53
|
+
#
|
|
54
|
+
# Against N(0, I) it reduces to the familiar VAE term
|
|
55
|
+
# 1/2 * sum_i (q_var_i + q_mean_i^2 - 1 - log q_var_i).
|
|
56
|
+
def kl_divergence(other)
|
|
57
|
+
per_element =
|
|
58
|
+
case other
|
|
59
|
+
when StandardNormal
|
|
60
|
+
variance + @mean**2 - @log_var - 1.0
|
|
61
|
+
when Normal
|
|
62
|
+
other.log_var - @log_var + (variance + (@mean - other.mean)**2) * (-other.log_var).exp - 1.0
|
|
63
|
+
else
|
|
64
|
+
raise ArgumentError, "no closed-form KL from a Normal to a #{other.class}"
|
|
65
|
+
end
|
|
66
|
+
Distributions.sum_per_sample(per_element * 0.5)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Entropy of each sample, shape [N]:
|
|
70
|
+
# 1/2 * sum_i (1 + log(2 pi) + log var_i).
|
|
71
|
+
def entropy
|
|
72
|
+
Distributions.sum_per_sample((@log_var + (1 + LOG_2PI)) * 0.5)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def broadcast_shape
|
|
78
|
+
a = @mean.shape
|
|
79
|
+
b = @log_var.shape
|
|
80
|
+
n = [a.length, b.length].max
|
|
81
|
+
a = [1] * (n - a.length) + a
|
|
82
|
+
b = [1] * (n - b.length) + b
|
|
83
|
+
a.zip(b).map { |x, y| [x, y].max }
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
module Distributions
|
|
4
|
+
# The standard normal N(0, I) over vectors (or images) of a fixed
|
|
5
|
+
# shape: the usual prior of a VAE, and the noise a diffusion model or
|
|
6
|
+
# a flow starts from. It has no parameters.
|
|
7
|
+
#
|
|
8
|
+
# prior = StandardNormal.new(16) # 16-dimensional latents
|
|
9
|
+
# z = prior.sample(64) # [64, 16]
|
|
10
|
+
# prior.log_prob(z) # [64]
|
|
11
|
+
#
|
|
12
|
+
# log N(x | 0, I) = -1/2 * sum_i (log(2 pi) + x_i^2)
|
|
13
|
+
class StandardNormal
|
|
14
|
+
attr_reader :event_shape
|
|
15
|
+
|
|
16
|
+
def initialize(*event_shape)
|
|
17
|
+
@event_shape = event_shape.flatten
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Log-density of each sample in x, shape [N].
|
|
21
|
+
def log_prob(x)
|
|
22
|
+
Distributions.sum_per_sample((x**2 + LOG_2PI) * -0.5)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# n samples, shape [n, *event_shape], on `backend` (default: the
|
|
26
|
+
# current one, Maurograd.backend).
|
|
27
|
+
def sample(n, backend: nil)
|
|
28
|
+
Maurograd.randn(n, *@event_shape, backend: backend)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def mean(n, backend: nil)
|
|
32
|
+
Tensor.new(::Numo::SFloat.zeros(n, *@event_shape), backend: backend)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Entropy of one sample: D/2 * (1 + log(2 pi)), D the event size.
|
|
36
|
+
def entropy
|
|
37
|
+
@event_shape.reduce(1, :*) * 0.5 * (1 + LOG_2PI)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
require_relative "distributions/standard_normal"
|
|
2
|
+
require_relative "distributions/normal"
|
|
3
|
+
require_relative "distributions/bernoulli"
|
|
4
|
+
require_relative "distributions/categorical"
|
|
5
|
+
require_relative "distributions/mixture_of_gaussians"
|
|
6
|
+
|
|
7
|
+
module Maurograd
|
|
8
|
+
module DGM
|
|
9
|
+
# The probability distributions the models are built from: priors,
|
|
10
|
+
# posteriors and likelihoods.
|
|
11
|
+
#
|
|
12
|
+
# They share a few conventions:
|
|
13
|
+
#
|
|
14
|
+
# - Parameters are Tensors, so gradients flow through log_prob (and
|
|
15
|
+
# through Normal#rsample) into whatever produced them: an encoder's
|
|
16
|
+
# output, or a learnable prior's parameters.
|
|
17
|
+
# - The first axis is the batch. log_prob(x) returns one log-density per
|
|
18
|
+
# sample, a Tensor of shape [N], summing over every other axis: the
|
|
19
|
+
# pixels of an image, the dimensions of a latent vector.
|
|
20
|
+
# - Parameters broadcast against x, so a Normal with a mean of shape
|
|
21
|
+
# [1, D] scores a batch x of shape [N, D].
|
|
22
|
+
# - sample draws without recording a graph. Normal#rsample is the
|
|
23
|
+
# exception: the reparameterization trick, differentiable in the mean
|
|
24
|
+
# and the variance.
|
|
25
|
+
# - Variances are given as log-variances, as networks output them.
|
|
26
|
+
#
|
|
27
|
+
# q = Distributions::Normal.new(mean, log_var) # the encoder's output
|
|
28
|
+
# z = q.rsample
|
|
29
|
+
# kl = q.kl_divergence(Distributions::StandardNormal.new(latent_dim))
|
|
30
|
+
# rec = Distributions::Bernoulli.new(decoder.call(z)).log_prob(x)
|
|
31
|
+
# loss = (kl - rec).mean # the negative ELBO
|
|
32
|
+
module Distributions
|
|
33
|
+
LOG_2PI = Math.log(2 * Math::PI)
|
|
34
|
+
|
|
35
|
+
# Sums `t` over every axis but the first: per-sample totals, shape [N].
|
|
36
|
+
def self.sum_per_sample(t)
|
|
37
|
+
(t.ndim > 1) ? t.sum(axis: (1...t.ndim).to_a) : t
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# A Tensor from x (a Tensor, a Numo array or an Array) on `backend`,
|
|
41
|
+
# not tracked by autograd unless it already is a tracked Tensor.
|
|
42
|
+
def self.tensor(x, backend)
|
|
43
|
+
return x if x.is_a?(Tensor)
|
|
44
|
+
|
|
45
|
+
Tensor.new(x.is_a?(Array) ? ::Numo::SFloat.cast(x) : x, backend: backend)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|