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,158 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
# The training loop shared by the models whose training is "minimize
|
|
4
|
+
# model.call(x)": VAEs, diffusion models, flows, flow matching. (GANs,
|
|
5
|
+
# with two networks and two optimizers, have their own.)
|
|
6
|
+
#
|
|
7
|
+
# trainer = Trainer.new(model, Maurograd::Optim::Adam.new(model.parameters, lr: 1e-3),
|
|
8
|
+
# max_epochs: 100, patience: 10)
|
|
9
|
+
# history = trainer.fit(train_loader, validation: validation_loader)
|
|
10
|
+
#
|
|
11
|
+
# Each epoch trains on every batch (model.train), then, given validation
|
|
12
|
+
# data, computes the mean validation loss with model.eval and under
|
|
13
|
+
# Maurograd.no_grad. Early stopping: when the validation loss has not
|
|
14
|
+
# improved by more than min_delta for `patience` epochs in a row,
|
|
15
|
+
# training stops, and the weights of the best epoch are restored.
|
|
16
|
+
#
|
|
17
|
+
# The block, if given, runs after every epoch with the epoch's record
|
|
18
|
+
# (see #fit): to save sample grids, or a checkpoint.
|
|
19
|
+
#
|
|
20
|
+
# After every optimizer step the trainer can also clip the gradients'
|
|
21
|
+
# norm first (max_grad_norm:), update an Optim::EMA of the weights
|
|
22
|
+
# (ema:) and advance a learning-rate schedule (schedule:), as diffusion
|
|
23
|
+
# models are trained:
|
|
24
|
+
#
|
|
25
|
+
# ema = Maurograd::Optim::EMA.new(model.parameters, decay: 0.999)
|
|
26
|
+
# schedule = Maurograd::Optim::CosineAnnealingLR.new(optimizer, t_max: 20_000, warmup: 500)
|
|
27
|
+
# Trainer.new(model, optimizer, max_epochs: 50, ema: ema, schedule: schedule, max_grad_norm: 1.0)
|
|
28
|
+
class Trainer
|
|
29
|
+
attr_reader :model, :optimizer, :history, :best_epoch
|
|
30
|
+
|
|
31
|
+
# @param model [Layers::Module] whose call(x) is the loss to minimize
|
|
32
|
+
# @param optimizer [Optim::Optimizer] over model.parameters
|
|
33
|
+
# @param max_epochs [Integer]
|
|
34
|
+
# @param patience [Integer, nil] epochs without improvement before stopping; nil never stops early
|
|
35
|
+
# @param min_delta [Float] the least decrease of the validation loss that counts as one
|
|
36
|
+
# @param restore_best [Boolean] reload the best epoch's weights when training ends
|
|
37
|
+
# @param loss [Proc, nil] (model, batch) -> a scalar Tensor; model.call(x) by default (x the
|
|
38
|
+
# batch, or its first element for loaders that also yield labels)
|
|
39
|
+
# @param log [IO, nil] where to print one line per epoch; nil for silence
|
|
40
|
+
# @param ema [Optim::EMA, nil] an average of the parameters, updated after every step
|
|
41
|
+
# @param schedule [Optim::LRScheduler, nil] stepped after every step
|
|
42
|
+
# @param max_grad_norm [Float, nil] clip the gradients' total norm to it before every step
|
|
43
|
+
def initialize(model, optimizer, max_epochs: 10, patience: nil, min_delta: 0.0,
|
|
44
|
+
restore_best: true, loss: nil, log: $stdout, ema: nil, schedule: nil, max_grad_norm: nil)
|
|
45
|
+
@model = model
|
|
46
|
+
@optimizer = optimizer
|
|
47
|
+
@max_epochs = max_epochs
|
|
48
|
+
@patience = patience
|
|
49
|
+
@min_delta = min_delta
|
|
50
|
+
@restore_best = restore_best
|
|
51
|
+
@loss = loss || ->(m, batch) { m.call(batch.is_a?(Array) ? batch.first : batch) }
|
|
52
|
+
@log = log
|
|
53
|
+
@ema = ema
|
|
54
|
+
@schedule = schedule
|
|
55
|
+
@max_grad_norm = max_grad_norm
|
|
56
|
+
@history = []
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Trains, and returns the history: one Hash per epoch, with :epoch
|
|
60
|
+
# (from 1), :train_loss (the mean over the epoch's batches),
|
|
61
|
+
# :validation_loss (with validation data) and :seconds.
|
|
62
|
+
#
|
|
63
|
+
# @param train [Enumerable] batches: Tensors, or [Tensor, labels] pairs, e.g. a Datasets::Loader
|
|
64
|
+
# @param validation [Enumerable, nil] validation batches, likewise
|
|
65
|
+
# @yieldparam record [Hash] the epoch's record
|
|
66
|
+
# @return [Array<Hash>] the history
|
|
67
|
+
# @raise [Error] if a training loss isn't finite
|
|
68
|
+
def fit(train, validation: nil)
|
|
69
|
+
best = Float::INFINITY
|
|
70
|
+
best_state = nil
|
|
71
|
+
stale = 0
|
|
72
|
+
@best_epoch = nil
|
|
73
|
+
@history = []
|
|
74
|
+
|
|
75
|
+
1.upto(@max_epochs) do |epoch|
|
|
76
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
77
|
+
record = {epoch: epoch, train_loss: train_epoch(train)}
|
|
78
|
+
record[:validation_loss] = evaluate(validation) if validation
|
|
79
|
+
record[:seconds] = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
|
|
80
|
+
@history << record
|
|
81
|
+
log(record)
|
|
82
|
+
yield record if block_given?
|
|
83
|
+
|
|
84
|
+
next unless validation
|
|
85
|
+
|
|
86
|
+
if record[:validation_loss] < best - @min_delta
|
|
87
|
+
best = record[:validation_loss]
|
|
88
|
+
@best_epoch = epoch
|
|
89
|
+
best_state = @model.state_dict if @restore_best
|
|
90
|
+
stale = 0
|
|
91
|
+
else
|
|
92
|
+
stale += 1
|
|
93
|
+
if @patience && stale >= @patience
|
|
94
|
+
@log&.puts "early stopping: no improvement for #{@patience} epochs, best was epoch #{@best_epoch}"
|
|
95
|
+
break
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
@model.load_state_dict(best_state) if best_state && @best_epoch != @history.last[:epoch]
|
|
101
|
+
@history
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# The mean loss over a loader's batches, weighted by batch size, with
|
|
105
|
+
# the model in eval mode and no graph recorded.
|
|
106
|
+
#
|
|
107
|
+
# @param loader [Enumerable] batches: Tensors, or [Tensor, labels] pairs, e.g. a Datasets::Loader
|
|
108
|
+
# @return [Float] the mean loss
|
|
109
|
+
def evaluate(loader)
|
|
110
|
+
was_training = @model.training?
|
|
111
|
+
@model.eval
|
|
112
|
+
total = 0.0
|
|
113
|
+
count = 0
|
|
114
|
+
Maurograd.no_grad do
|
|
115
|
+
loader.each do |batch|
|
|
116
|
+
n = (batch.is_a?(Array) ? batch.first : batch).shape[0]
|
|
117
|
+
total += @loss.call(@model, batch).item * n
|
|
118
|
+
count += n
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
total / count
|
|
122
|
+
ensure
|
|
123
|
+
@model.train if was_training
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
private
|
|
127
|
+
|
|
128
|
+
def train_epoch(loader)
|
|
129
|
+
@model.train
|
|
130
|
+
total = 0.0
|
|
131
|
+
batches = 0
|
|
132
|
+
loader.each do |batch|
|
|
133
|
+
@optimizer.zero_grad
|
|
134
|
+
loss = @loss.call(@model, batch)
|
|
135
|
+
loss.backward
|
|
136
|
+
Maurograd::Utils.clip_grad_norm_(@optimizer.params, @max_grad_norm) if @max_grad_norm
|
|
137
|
+
@optimizer.step
|
|
138
|
+
@ema&.update
|
|
139
|
+
@schedule&.step
|
|
140
|
+
value = loss.item
|
|
141
|
+
raise Error, "the loss is #{value} at batch #{batches + 1}" unless value.finite?
|
|
142
|
+
|
|
143
|
+
total += value
|
|
144
|
+
batches += 1
|
|
145
|
+
end
|
|
146
|
+
total / batches
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def log(record)
|
|
150
|
+
return unless @log
|
|
151
|
+
|
|
152
|
+
line = format("epoch %3d train %.4f", record[:epoch], record[:train_loss])
|
|
153
|
+
line += format(" validation %.4f", record[:validation_loss]) if record.key?(:validation_loss)
|
|
154
|
+
@log.puts line + format(" (%.1fs)", record[:seconds])
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
end
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module DGM
|
|
3
|
+
# A variational autoencoder (Kingma and Welling, 2014): a latent
|
|
4
|
+
# variable model p(x, z) = p(x | z) p(z) whose decoder p(x | z) is a
|
|
5
|
+
# network, trained with an encoder network q(z | x) that approximates
|
|
6
|
+
# the posterior, by maximizing the evidence lower bound
|
|
7
|
+
#
|
|
8
|
+
# log p(x) >= ELBO(x) = E_q[log p(x | z)] - KL(q(z | x) || p(z))
|
|
9
|
+
#
|
|
10
|
+
# The library supplies the method; the networks are yours:
|
|
11
|
+
#
|
|
12
|
+
# encoder = Layers::Sequential.new(Layers::Linear.new(784, 256), Layers::ReLU.new,
|
|
13
|
+
# Layers::Linear.new(256, 2 * 16)) # mean and log-variance
|
|
14
|
+
# decoder = Layers::Sequential.new(Layers::Linear.new(16, 256), Layers::ReLU.new,
|
|
15
|
+
# Layers::Linear.new(256, 784)) # logits
|
|
16
|
+
# vae = VAE.new(encoder, decoder, 16)
|
|
17
|
+
# loss = vae.call(x) # -ELBO, averaged over the batch
|
|
18
|
+
#
|
|
19
|
+
# The encoder maps x to [N, 2L]: the posterior's mean and log-variance,
|
|
20
|
+
# side by side. The decoder maps z [N, L] to the parameters of
|
|
21
|
+
# p(x | z), shaped like x, which the likelihood interprets (see
|
|
22
|
+
# Likelihoods: Bernoulli logits by default, or a Gaussian's mean). The
|
|
23
|
+
# prior (see Priors) is N(0, I) by default.
|
|
24
|
+
#
|
|
25
|
+
# E_q[log p(x | z)] is estimated with one z = mean + std * eps drawn by
|
|
26
|
+
# the reparameterization trick, so its gradient reaches the encoder.
|
|
27
|
+
# The KL term is exact when the prior has a closed form for it (the
|
|
28
|
+
# standard normal does), and otherwise estimated with the same z as
|
|
29
|
+
# log q(z | x) - log p(z).
|
|
30
|
+
#
|
|
31
|
+
# beta weights the KL term (Higgins et al., 2017): beta > 1 trades
|
|
32
|
+
# reconstruction for a latent space closer to the prior, beta < 1 the
|
|
33
|
+
# other way. It changes the training loss only; #elbo is always the
|
|
34
|
+
# true bound.
|
|
35
|
+
class VAE < Layers::Module
|
|
36
|
+
attr_reader :encoder, :decoder, :latent_dim, :prior, :likelihood
|
|
37
|
+
attr_accessor :beta
|
|
38
|
+
|
|
39
|
+
# @param encoder [Layers::Module] x -> [N, 2L], the posterior's means and log-variances
|
|
40
|
+
# @param decoder [Layers::Module] z [N, L] -> the likelihood's parameters, shaped like x
|
|
41
|
+
# @param latent_dim [Integer] L
|
|
42
|
+
# @param prior [Layers::Module, nil] one of Priors; N(0, I) if nil
|
|
43
|
+
# @param likelihood [Layers::Module, nil] one of Likelihoods; Bernoulli if nil
|
|
44
|
+
# @param beta [Float] the KL term's weight in the training loss
|
|
45
|
+
def initialize(encoder, decoder, latent_dim, prior: nil, likelihood: nil, beta: 1.0)
|
|
46
|
+
@encoder = encoder
|
|
47
|
+
@decoder = decoder
|
|
48
|
+
@latent_dim = latent_dim
|
|
49
|
+
@prior = prior || Priors::StandardNormal.new(latent_dim)
|
|
50
|
+
@likelihood = likelihood || Likelihoods::Bernoulli.new
|
|
51
|
+
@beta = beta
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# q(z | x), a Distributions::Normal over [N, L].
|
|
55
|
+
#
|
|
56
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
57
|
+
# @return [Distributions::Normal] q(z | x), over [N, L]
|
|
58
|
+
# @raise [ArgumentError] if the encoder's output isn't [N, 2L]
|
|
59
|
+
def posterior(x)
|
|
60
|
+
# the encoder's output, [N, 2L]
|
|
61
|
+
out = @encoder.call(as_tensor(x))
|
|
62
|
+
unless out.ndim == 2 && out.shape[1] == 2 * @latent_dim
|
|
63
|
+
raise ArgumentError, "the encoder must output [N, #{2 * @latent_dim}] (mean and log-variance), got #{out.shape.inspect}"
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# its first L columns are the mean, the other L the log-variance
|
|
67
|
+
Distributions::Normal.new(*out.chunk(2, axis: 1))
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# p(x | z), a distribution over x.
|
|
71
|
+
#
|
|
72
|
+
# @param z [Tensor] [N, L]
|
|
73
|
+
# @return [Distributions::Bernoulli, Distributions::Normal] p(x | z)
|
|
74
|
+
def conditional(z) = @likelihood.distribution(@decoder.call(z))
|
|
75
|
+
|
|
76
|
+
# The two terms of the ELBO for each sample of x, as Tensors [N]:
|
|
77
|
+
# {reconstruction: E_q[log p(x | z)], kl: KL(q(z | x) || p(z))}, each
|
|
78
|
+
# estimated with one reparameterized z (the KL exactly when possible).
|
|
79
|
+
#
|
|
80
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
81
|
+
# @return [Hash{Symbol => Tensor}] :reconstruction and :kl, each [N]
|
|
82
|
+
def elbo_terms(x)
|
|
83
|
+
x = as_tensor(x)
|
|
84
|
+
# encode: the approximate posterior q(z | x)
|
|
85
|
+
q = posterior(x)
|
|
86
|
+
# draw z = mean + std * eps, so that gradients flow back into the encoder
|
|
87
|
+
z = q.rsample
|
|
88
|
+
# the KL term: exact if the prior has a formula for it, else a
|
|
89
|
+
# one-sample estimate, log q(z | x) - log p(z) at the same z
|
|
90
|
+
kl = if @prior.respond_to?(:kl_divergence)
|
|
91
|
+
@prior.kl_divergence(q)
|
|
92
|
+
else
|
|
93
|
+
q.log_prob(z) - @prior.log_prob(z)
|
|
94
|
+
end
|
|
95
|
+
# decode z and score x under p(x | z): the reconstruction term
|
|
96
|
+
{reconstruction: conditional(z).log_prob(x), kl: kl}
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# The ELBO of each sample, [N] (whatever beta is).
|
|
100
|
+
#
|
|
101
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
102
|
+
# @return [Tensor] [N]
|
|
103
|
+
def elbo(x)
|
|
104
|
+
terms = elbo_terms(x)
|
|
105
|
+
terms[:reconstruction] - terms[:kl]
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# The training loss: the negative (beta-weighted) ELBO, averaged over
|
|
109
|
+
# the batch.
|
|
110
|
+
#
|
|
111
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
112
|
+
# @return [Tensor] the negative beta-weighted ELBO, averaged: a scalar
|
|
113
|
+
def forward(x)
|
|
114
|
+
terms = elbo_terms(x)
|
|
115
|
+
# -ELBO with the KL term weighted by beta, averaged over the batch
|
|
116
|
+
(terms[:kl] * @beta - terms[:reconstruction]).mean
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# An importance-sampled estimate of log p(x) for each sample, a Tensor
|
|
120
|
+
# [N] (Burda et al., 2016), with q(z | x) as the proposal:
|
|
121
|
+
#
|
|
122
|
+
# log p(x) ~ log 1/K sum_k p(x | z_k) p(z_k) / q(z_k | x), z_k ~ q(z | x)
|
|
123
|
+
#
|
|
124
|
+
# With K = 1 it is a one-sample ELBO; as K grows it rises to log p(x).
|
|
125
|
+
# Its negative, averaged over a test set, is the test NLL by which VAEs
|
|
126
|
+
# are compared.
|
|
127
|
+
#
|
|
128
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
129
|
+
# @param samples [Integer] K, the importance samples per x
|
|
130
|
+
# @return [Tensor] log p(x), estimated, [N]
|
|
131
|
+
def log_likelihood(x, samples: 100)
|
|
132
|
+
Maurograd.no_grad do
|
|
133
|
+
x = as_tensor(x)
|
|
134
|
+
# the encoder's posterior is the proposal distribution
|
|
135
|
+
q = posterior(x)
|
|
136
|
+
n = x.shape[0]
|
|
137
|
+
# K log importance weights per sample, log p(x | z_k) + log p(z_k) - log q(z_k | x)
|
|
138
|
+
weights = Array.new(samples) do
|
|
139
|
+
z = q.rsample
|
|
140
|
+
(conditional(z).log_prob(x) + @prior.log_prob(z) - q.log_prob(z)).reshape(1, n)
|
|
141
|
+
end
|
|
142
|
+
# the log of their average, computed stably with logsumexp
|
|
143
|
+
Maurograd.concat(weights, axis: 0).logsumexp(axis: 0) - Math.log(samples)
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# The decoder's mean of p(x | z), with no graph recorded: what z
|
|
148
|
+
# decodes to.
|
|
149
|
+
#
|
|
150
|
+
# @param z [Tensor] [N, L]
|
|
151
|
+
# @return [Tensor] the mean of p(x | z), shaped like the data
|
|
152
|
+
def decode(z) = Maurograd.no_grad { conditional(z).mean }
|
|
153
|
+
|
|
154
|
+
# n new samples: z from the prior, decoded to the mean of p(x | z), or,
|
|
155
|
+
# with mean: false, sampled from it (binary images for a Bernoulli
|
|
156
|
+
# likelihood, noisy ones for a Gaussian).
|
|
157
|
+
#
|
|
158
|
+
# @param n [Integer]
|
|
159
|
+
# @param mean [Boolean] the decoder's means if true, draws from p(x | z) if false
|
|
160
|
+
# @return [Tensor] [n, ...] shaped like the data
|
|
161
|
+
def sample(n, mean: true)
|
|
162
|
+
Maurograd.no_grad do
|
|
163
|
+
# latents from the prior
|
|
164
|
+
z = @prior.sample(n, backend: parameter_backend)
|
|
165
|
+
# the decoder's distribution over x for each latent
|
|
166
|
+
p = conditional(z)
|
|
167
|
+
# its mean (a smooth image), or a draw from it
|
|
168
|
+
mean ? p.mean : p.sample
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# x through the encoder's mean and back.
|
|
173
|
+
#
|
|
174
|
+
# @param x [Tensor, Numo::NArray] the data, [N, ...] as the encoder takes it
|
|
175
|
+
# @return [Tensor] shaped like x
|
|
176
|
+
def reconstruct(x)
|
|
177
|
+
decode(Maurograd.no_grad { posterior(x).mean })
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# `steps` points on the line between the latent means of two samples
|
|
181
|
+
# a and b (each [1, ...], or any batch whose first rows are used),
|
|
182
|
+
# decoded: a walk through the latent space, [steps, ...].
|
|
183
|
+
#
|
|
184
|
+
# @param a [Tensor, Numo::NArray] a sample [1, ...] (or a batch, whose first row is used)
|
|
185
|
+
# @param b [Tensor, Numo::NArray] likewise
|
|
186
|
+
# @param steps [Integer] the points, endpoints included
|
|
187
|
+
# @return [Tensor] [steps, ...]
|
|
188
|
+
def interpolate(a, b, steps: 8)
|
|
189
|
+
Maurograd.no_grad do
|
|
190
|
+
# the latent means of the two endpoints, [1, L] each
|
|
191
|
+
za = posterior(a).mean.slice(0, 0...1)
|
|
192
|
+
zb = posterior(b).mean.slice(0, 0...1)
|
|
193
|
+
# steps fractions from 0 to 1, as a column [steps, 1]
|
|
194
|
+
t = Tensor.new(::Numo::SFloat.new(steps, 1).seq / (steps - 1), backend: za.backend)
|
|
195
|
+
# points on the line from za to zb, decoded
|
|
196
|
+
decode(za + (zb - za) * t)
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
private
|
|
201
|
+
|
|
202
|
+
def parameter_backend = parameters.first&.backend || Maurograd.backend
|
|
203
|
+
|
|
204
|
+
# Accepts Tensors, and Numo arrays (put on the model's backend).
|
|
205
|
+
def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
end
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
require "maurograd"
|
|
2
|
+
require_relative "dgm/version"
|
|
3
|
+
require_relative "dgm/distributions"
|
|
4
|
+
require_relative "dgm/datasets"
|
|
5
|
+
require_relative "dgm/trainer"
|
|
6
|
+
require_relative "dgm/image_grid"
|
|
7
|
+
require_relative "dgm/ppca"
|
|
8
|
+
require_relative "dgm/linear_vae"
|
|
9
|
+
require_relative "dgm/priors"
|
|
10
|
+
require_relative "dgm/likelihoods"
|
|
11
|
+
require_relative "dgm/vae"
|
|
12
|
+
require_relative "dgm/noise_schedule"
|
|
13
|
+
require_relative "dgm/networks"
|
|
14
|
+
require_relative "dgm/ddpm"
|
|
15
|
+
require_relative "dgm/ddim"
|
|
16
|
+
require_relative "dgm/slerp"
|
|
17
|
+
require_relative "dgm/flows"
|
|
18
|
+
require_relative "dgm/normalizing_flow"
|
|
19
|
+
require_relative "dgm/flow_matching"
|
|
20
|
+
require_relative "dgm/gan"
|
|
21
|
+
require_relative "dgm/metrics"
|
|
22
|
+
require_relative "dgm/ebm"
|
|
23
|
+
|
|
24
|
+
module Maurograd
|
|
25
|
+
# Deep generative models built on Maurograd.
|
|
26
|
+
#
|
|
27
|
+
# Every model follows the same conventions, so that they can be swapped
|
|
28
|
+
# in a training loop:
|
|
29
|
+
#
|
|
30
|
+
# model = Maurograd::DGM::VAE.new(encoder_net, decoder_net, latent_dim)
|
|
31
|
+
# loss = model.call(x) # the training loss (e.g. the negative ELBO)
|
|
32
|
+
# loss.backward
|
|
33
|
+
# x_new = model.sample(16) # 16 new samples, drawn under no_grad
|
|
34
|
+
# model.log_prob(x) # for models with a tractable density
|
|
35
|
+
#
|
|
36
|
+
# Models wrap networks the user builds (any Layers::Module): the library
|
|
37
|
+
# supplies the method, the user chooses the architecture. Models are
|
|
38
|
+
# Modules themselves, so `parameters`, `to(:mlx)`, `train`/`eval` and
|
|
39
|
+
# `state_dict` work on them as on any layer.
|
|
40
|
+
#
|
|
41
|
+
# The building blocks the models share:
|
|
42
|
+
#
|
|
43
|
+
# - Distributions: standard and diagonal Gaussians, Bernoulli,
|
|
44
|
+
# categorical, mixtures of Gaussians; log-densities, sampling, the
|
|
45
|
+
# reparameterization trick, closed-form KL divergences.
|
|
46
|
+
# - Datasets: MNIST, Fashion-MNIST, binarization, 2D test sets, and a
|
|
47
|
+
# Loader that batches them onto a backend.
|
|
48
|
+
# - Trainer: the training loop, with validation and early stopping.
|
|
49
|
+
# - ImageGrid: samples tiled into a PNG.
|
|
50
|
+
# - Metrics: the Fréchet distance between sets of features, to compare
|
|
51
|
+
# models by their samples.
|
|
52
|
+
#
|
|
53
|
+
# - Networks: time-conditioned networks for diffusion and flow matching
|
|
54
|
+
# (TimeMLP, UNet).
|
|
55
|
+
#
|
|
56
|
+
# Models: PPCA (probabilistic PCA, with exact likelihood), LinearVAE;
|
|
57
|
+
# VAE, with its Priors and Likelihoods; DDPM, with its NoiseSchedule,
|
|
58
|
+
# and the DDIM sampler; NormalizingFlow, built by RealNVP from the
|
|
59
|
+
# layers in Flows; FlowMatching; GAN, trained by GANTrainer; EBM.
|
|
60
|
+
module DGM
|
|
61
|
+
# Raised when training goes wrong, e.g. on a loss that is not finite.
|
|
62
|
+
class Error < StandardError; end
|
|
63
|
+
end
|
|
64
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: maurograd-dgm
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Mauro Tortonesi
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: maurograd
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - "~>"
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '0.3'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '0.3'
|
|
26
|
+
- !ruby/object:Gem::Dependency
|
|
27
|
+
name: numo-narray-alt
|
|
28
|
+
requirement: !ruby/object:Gem::Requirement
|
|
29
|
+
requirements:
|
|
30
|
+
- - "~>"
|
|
31
|
+
- !ruby/object:Gem::Version
|
|
32
|
+
version: 0.9.11
|
|
33
|
+
type: :runtime
|
|
34
|
+
prerelease: false
|
|
35
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
36
|
+
requirements:
|
|
37
|
+
- - "~>"
|
|
38
|
+
- !ruby/object:Gem::Version
|
|
39
|
+
version: 0.9.11
|
|
40
|
+
- !ruby/object:Gem::Dependency
|
|
41
|
+
name: numo-linalg-alt
|
|
42
|
+
requirement: !ruby/object:Gem::Requirement
|
|
43
|
+
requirements:
|
|
44
|
+
- - "~>"
|
|
45
|
+
- !ruby/object:Gem::Version
|
|
46
|
+
version: 0.7.1
|
|
47
|
+
type: :runtime
|
|
48
|
+
prerelease: false
|
|
49
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
50
|
+
requirements:
|
|
51
|
+
- - "~>"
|
|
52
|
+
- !ruby/object:Gem::Version
|
|
53
|
+
version: 0.7.1
|
|
54
|
+
- !ruby/object:Gem::Dependency
|
|
55
|
+
name: sus
|
|
56
|
+
requirement: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - "~>"
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: 0.35.0
|
|
61
|
+
type: :development
|
|
62
|
+
prerelease: false
|
|
63
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - "~>"
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: 0.35.0
|
|
68
|
+
description: |
|
|
69
|
+
A library of deep generative models written on top of the Maurograd
|
|
70
|
+
autograd framework, to be read as well as used: probabilistic PCA,
|
|
71
|
+
variational autoencoders, DDPM and DDIM diffusion, normalizing flows and
|
|
72
|
+
flow matching, GANs and energy-based models. Models wrap networks you
|
|
73
|
+
build, so the library supplies the method and you choose the
|
|
74
|
+
architecture. Runs on every Maurograd backend, including the Apple
|
|
75
|
+
Silicon GPU through maurograd-mlx.
|
|
76
|
+
email:
|
|
77
|
+
- mauro.tortonesi@unife.it
|
|
78
|
+
executables: []
|
|
79
|
+
extensions: []
|
|
80
|
+
extra_rdoc_files: []
|
|
81
|
+
files:
|
|
82
|
+
- CHANGELOG.md
|
|
83
|
+
- LICENSE
|
|
84
|
+
- README.md
|
|
85
|
+
- lib/maurograd-dgm.rb
|
|
86
|
+
- lib/maurograd/dgm.rb
|
|
87
|
+
- lib/maurograd/dgm/datasets.rb
|
|
88
|
+
- lib/maurograd/dgm/datasets/download.rb
|
|
89
|
+
- lib/maurograd/dgm/datasets/idx.rb
|
|
90
|
+
- lib/maurograd/dgm/datasets/loader.rb
|
|
91
|
+
- lib/maurograd/dgm/datasets/mnist.rb
|
|
92
|
+
- lib/maurograd/dgm/datasets/toy_2d.rb
|
|
93
|
+
- lib/maurograd/dgm/ddim.rb
|
|
94
|
+
- lib/maurograd/dgm/ddpm.rb
|
|
95
|
+
- lib/maurograd/dgm/distributions.rb
|
|
96
|
+
- lib/maurograd/dgm/distributions/bernoulli.rb
|
|
97
|
+
- lib/maurograd/dgm/distributions/categorical.rb
|
|
98
|
+
- lib/maurograd/dgm/distributions/mixture_of_gaussians.rb
|
|
99
|
+
- lib/maurograd/dgm/distributions/normal.rb
|
|
100
|
+
- lib/maurograd/dgm/distributions/standard_normal.rb
|
|
101
|
+
- lib/maurograd/dgm/ebm.rb
|
|
102
|
+
- lib/maurograd/dgm/flow_matching.rb
|
|
103
|
+
- lib/maurograd/dgm/flows.rb
|
|
104
|
+
- lib/maurograd/dgm/gan.rb
|
|
105
|
+
- lib/maurograd/dgm/image_grid.rb
|
|
106
|
+
- lib/maurograd/dgm/likelihoods.rb
|
|
107
|
+
- lib/maurograd/dgm/linear_vae.rb
|
|
108
|
+
- lib/maurograd/dgm/metrics.rb
|
|
109
|
+
- lib/maurograd/dgm/networks.rb
|
|
110
|
+
- lib/maurograd/dgm/noise_schedule.rb
|
|
111
|
+
- lib/maurograd/dgm/normalizing_flow.rb
|
|
112
|
+
- lib/maurograd/dgm/ppca.rb
|
|
113
|
+
- lib/maurograd/dgm/priors.rb
|
|
114
|
+
- lib/maurograd/dgm/slerp.rb
|
|
115
|
+
- lib/maurograd/dgm/trainer.rb
|
|
116
|
+
- lib/maurograd/dgm/vae.rb
|
|
117
|
+
- lib/maurograd/dgm/version.rb
|
|
118
|
+
homepage: https://github.com/mtortonesi/maurograd-dgm
|
|
119
|
+
licenses:
|
|
120
|
+
- MIT
|
|
121
|
+
metadata:
|
|
122
|
+
source_code_uri: https://github.com/mtortonesi/maurograd-dgm
|
|
123
|
+
bug_tracker_uri: https://github.com/mtortonesi/maurograd-dgm/issues
|
|
124
|
+
changelog_uri: https://github.com/mtortonesi/maurograd-dgm/blob/main/CHANGELOG.md
|
|
125
|
+
rubygems_mfa_required: 'true'
|
|
126
|
+
rdoc_options: []
|
|
127
|
+
require_paths:
|
|
128
|
+
- lib
|
|
129
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
130
|
+
requirements:
|
|
131
|
+
- - ">="
|
|
132
|
+
- !ruby/object:Gem::Version
|
|
133
|
+
version: '3.3'
|
|
134
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
135
|
+
requirements:
|
|
136
|
+
- - ">="
|
|
137
|
+
- !ruby/object:Gem::Version
|
|
138
|
+
version: '0'
|
|
139
|
+
requirements: []
|
|
140
|
+
rubygems_version: 4.0.20
|
|
141
|
+
specification_version: 4
|
|
142
|
+
summary: Deep generative models for Ruby, built on Maurograd.
|
|
143
|
+
test_files: []
|