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,245 @@
1
+ module Maurograd
2
+ module DGM
3
+ # The invertible layers that NormalizingFlow composes, with the
4
+ # networks and masks RealNVP builds them from.
5
+ #
6
+ # Every layer is a bijection f from its input x to its output y, run in
7
+ # the direction from the data to the noise, and reports the log of the
8
+ # absolute determinant of its Jacobian along with y:
9
+ #
10
+ # y, log_det = layer.call(x) # log_det: [N], one per sample
11
+ # x = layer.inverse(y)
12
+ #
13
+ # A layer of your own works in a flow if it does the same.
14
+ module Flows
15
+ # An affine coupling layer (Dinh et al., 2017): a binary mask splits
16
+ # the input in two; the part the mask keeps (mask 1) passes through
17
+ # unchanged, and conditions a scale and a shift of the rest,
18
+ #
19
+ # y = x * exp(s(x * mask)) + t(x * mask) where mask is 0
20
+ # y = x where mask is 1
21
+ #
22
+ # The Jacobian is triangular, so its log-determinant is just the sum
23
+ # of s, and the inverse needs no inverse of the network:
24
+ # x = (y - t) * exp(-s), with s and t computed from y * mask, which
25
+ # is x * mask. The network can be anything.
26
+ #
27
+ # net = Flows.mlp(2, hidden: 64) # [N, 2] -> [N, 4]: s and t
28
+ # layer = AffineCoupling.new(Flows.alternating_mask(2, parity: 0), net)
29
+ #
30
+ # The network maps the masked input [N, C, ...] to [N, 2C, ...]: s,
31
+ # then t, along axis 1. s goes through a tanh and a learned scale,
32
+ # which bounds it, so that an exp never overflows early in training.
33
+ # Stacked couplings alternate their masks, so that every part is
34
+ # transformed by some of them.
35
+ class AffineCoupling < Layers::Module
36
+ attr_reader :network, :mask
37
+
38
+ # @param mask [Numo::NArray, Array, Tensor] 0s and 1s, broadcastable against the input,
39
+ # e.g. [1, D] or [1, C, H, W]
40
+ # @param network [Layers::Module] the masked input [N, C, ...] -> [N, 2C, ...]: s, then t
41
+ def initialize(mask, network)
42
+ # 1 where the input passes through unchanged (and conditions the rest)
43
+ @mask = mask.is_a?(Tensor) ? mask : Tensor.new(::Numo::SFloat.cast(mask))
44
+ # 1 where the input gets scaled and shifted
45
+ @complement = @mask * -1.0 + 1.0
46
+ @network = network
47
+ # a learned bound on log-scales, one per position, starting at 1
48
+ @scale = Tensor.new(::Numo::SFloat.ones(*@mask.shape), requires_grad: true)
49
+ end
50
+
51
+ def forward(x)
52
+ x = Flows.tensor(x, @mask.backend)
53
+ # s and t computed from the masked part of x only
54
+ s, t = scale_and_shift(x)
55
+ # y = x exp(s) + t; where the mask keeps x, s = t = 0 and y = x.
56
+ # The Jacobian is triangular, so log |det| is the sum of s.
57
+ [x * s.exp + t, Distributions.sum_per_sample(s)]
58
+ end
59
+
60
+ def inverse(y)
61
+ y = Flows.tensor(y, @mask.backend)
62
+ # the masked part of y equals x's, so s and t come out the same
63
+ s, t = scale_and_shift(y)
64
+ # undo the affine map: x = (y - t) exp(-s)
65
+ (y - t) * (-s).exp
66
+ end
67
+
68
+ private
69
+
70
+ # s and t, zero where the mask keeps the input.
71
+ def scale_and_shift(x)
72
+ # the network sees only the part the mask keeps
73
+ out = @network.call(x * @mask)
74
+ unless out.ndim == x.ndim && out.shape[0] == x.shape[0] && out.shape[1] == 2 * x.shape[1] && out.shape[2..] == x.shape[2..]
75
+ raise ArgumentError, "a coupling network must map #{x.shape.inspect} to twice the channels along axis 1, got #{out.shape.inspect}"
76
+ end
77
+
78
+ # its output's channels: first the log-scales, then the shifts
79
+ raw_s, t = out.chunk(2, axis: 1)
80
+ # tanh bounds the log-scales, which keeps early training stable;
81
+ # the complement zeroes s and t where the input passes through
82
+ [raw_s.tanh * @scale * @complement, t * @complement]
83
+ end
84
+ end
85
+
86
+ # Trades space for channels (Dinh et al., 2017): each 2x2 block of
87
+ # pixels becomes 4 channels, [N, C, H, W] -> [N, 4C, H/2, W/2]. A
88
+ # permutation, so its log-determinant is 0. It lets couplings that
89
+ # mask channels see pixels that were neighbors.
90
+ class Squeeze < Layers::Module
91
+ def forward(x)
92
+ x = Flows.tensor(x)
93
+ n, c, h, w = x.shape
94
+ raise ArgumentError, "Squeeze needs an even height and width, got #{x.shape.inspect}" unless h.even? && w.even?
95
+
96
+ # split each axis into (blocks, 2), move the two 2s next to the
97
+ # channels, and merge them into them: 4 channels per 2x2 block
98
+ y = x.reshape(n, c, h / 2, 2, w / 2, 2).permute(0, 1, 3, 5, 2, 4).reshape(n, c * 4, h / 2, w / 2)
99
+ # a permutation doesn't change volumes: log |det| = 0
100
+ [y, zeros(x)]
101
+ end
102
+
103
+ def inverse(y)
104
+ y = Flows.tensor(y)
105
+ n, c, h, w = y.shape
106
+ # the same moves in reverse
107
+ y.reshape(n, c / 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3).reshape(n, c / 4, h * 2, w * 2)
108
+ end
109
+
110
+ private
111
+
112
+ def zeros(x) = Tensor.new(x.backend.zeros([x.shape[0]]), backend: x.backend)
113
+ end
114
+
115
+ # Maps [0, 1] to the real line (Dinh et al., 2017): the first layer
116
+ # of a flow on images, whose pixels are bounded while the base
117
+ # distribution is not,
118
+ #
119
+ # y = logit(alpha + (1 - 2 alpha) x)
120
+ #
121
+ # alpha keeps 0 and 1 away from the logit's infinities. Being part of
122
+ # the flow, its log-determinant makes the density one over [0, 1],
123
+ # the data's own space.
124
+ class Logit < Layers::Module
125
+ attr_reader :alpha
126
+
127
+ # @param alpha [Float] in [0, 0.5): how far 0 and 1 are kept from the logit's infinities
128
+ def initialize(alpha: 0.05)
129
+ @alpha = alpha
130
+ end
131
+
132
+ def forward(x)
133
+ # squeeze [0, 1] into [alpha, 1 - alpha]
134
+ p = Flows.tensor(x) * (1 - 2 * @alpha) + @alpha
135
+ log_p = p.log
136
+ log_q = (p * -1.0 + 1.0).log
137
+ # logit(p) = log p - log(1 - p); its derivative in x is
138
+ # (1 - 2 alpha) / (p (1 - p)), whose log is summed per sample
139
+ [log_p - log_q, Distributions.sum_per_sample(log_p * -1.0 - log_q + Math.log(1 - 2 * @alpha))]
140
+ end
141
+
142
+ def inverse(y) = (Flows.tensor(y).sigmoid - @alpha) * (1 / (1 - 2 * @alpha))
143
+ end
144
+
145
+ module_function
146
+
147
+ # x as a Tensor: Tensors as they are, Numo arrays and Arrays on
148
+ # `backend` (by default the current one).
149
+ #
150
+ # @param x [Tensor, Numo::NArray, Array]
151
+ # @param backend [Module, Symbol, nil] a backend (Backends::CPU, Backends::MLX) or its name; the current one if nil
152
+ # @return [Tensor]
153
+ def tensor(x, backend = nil)
154
+ x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: backend || Maurograd.backend)
155
+ end
156
+
157
+ # The mask that keeps every other feature of [N, dim]: the features
158
+ # of even index for parity 0, the odd ones for parity 1. [1, dim].
159
+ #
160
+ # @param dim [Integer]
161
+ # @param parity [Integer] 0 or 1: which half the mask keeps
162
+ # @return [Numo::SFloat] [1, dim]
163
+ def alternating_mask(dim, parity: 0)
164
+ ::Numo::SFloat.cast(Array.new(dim) { |i| (i + parity).even? ? 1 : 0 }).reshape(1, dim)
165
+ end
166
+
167
+ # The checkerboard mask over [C, H, W]: pixels where row + column +
168
+ # parity is even. [1, C, H, W].
169
+ #
170
+ # @param channels [Integer]
171
+ # @param height [Integer]
172
+ # @param width [Integer]
173
+ # @param parity [Integer] 0 or 1: which half the mask keeps
174
+ # @return [Numo::SFloat] [1, C, H, W]
175
+ def checkerboard_mask(channels, height, width, parity: 0)
176
+ board = ::Numo::SFloat.zeros(height, width)
177
+ height.times { |i| width.times { |j| board[i, j] = ((i + j + parity).even? ? 1 : 0) } }
178
+ ::Numo::SFloat.zeros(1, channels, height, width) + board.reshape(1, 1, height, width)
179
+ end
180
+
181
+ # The mask that keeps the first half of the channels (parity 0) or
182
+ # the second (parity 1). [1, C, 1, 1].
183
+ #
184
+ # @param channels [Integer] C, even
185
+ # @param parity [Integer] 0 or 1: which half the mask keeps
186
+ # @return [Numo::SFloat] [1, C, 1, 1]
187
+ def channel_mask(channels, parity: 0)
188
+ half = channels / 2
189
+ ::Numo::SFloat.cast(Array.new(channels) { |i| ((i < half) == parity.zero?) ? 1 : 0 }).reshape(1, channels, 1, 1)
190
+ end
191
+
192
+ # A coupling network for vectors: an MLP from [N, dim] to [N, 2 dim].
193
+ # Its last layer starts at zero, so the coupling starts as the
194
+ # identity.
195
+ #
196
+ # @param dim [Integer]
197
+ # @param hidden [Integer] units per hidden layer
198
+ # @param depth [Integer] hidden layers
199
+ # @return [Layers::Sequential] [N, dim] -> [N, 2 dim]
200
+ def mlp(dim, hidden: 128, depth: 2)
201
+ layers = [Layers::Linear.new(dim, hidden), Layers::ReLU.new]
202
+ (depth - 1).times { layers.push(Layers::Linear.new(hidden, hidden), Layers::ReLU.new) }
203
+ last = Layers::Linear.new(hidden, 2 * dim)
204
+ zero!(last)
205
+ Layers::Sequential.new(*layers, last)
206
+ end
207
+
208
+ # A coupling network for images: [N, C, H, W] to [N, 2C, H, W], 3x3
209
+ # convolutions with `blocks` residual blocks in between. Its last
210
+ # convolution starts at zero, so the coupling starts as the identity.
211
+ #
212
+ # @param channels [Integer] C
213
+ # @param hidden [Integer] the hidden channels
214
+ # @param blocks [Integer] residual blocks
215
+ # @param groups [Integer] group normalization's groups
216
+ # @return [Layers::Module] [N, C, H, W] -> [N, 2C, H, W]
217
+ def cnn(channels, hidden: 64, blocks: 2, groups: 8)
218
+ last = Layers::Conv2D.new(hidden, 2 * channels, 3, padding: 1)
219
+ zero!(last)
220
+ Layers::Sequential.new(Layers::Conv2D.new(channels, hidden, 3, padding: 1),
221
+ *Array.new(blocks) { ConvBlock.new(hidden, groups: groups) },
222
+ Layers::GroupNorm.new(groups, hidden), Layers::ReLU.new, last)
223
+ end
224
+
225
+ def zero!(layer)
226
+ [layer.weights, layer.bias].each { |p| p.data = p.backend.zeros(p.shape) }
227
+ layer
228
+ end
229
+
230
+ # x + conv(relu(norm(x))) twice: the residual block of Flows.cnn.
231
+ class ConvBlock < Layers::Module
232
+ def initialize(channels, groups: 8)
233
+ @norm1 = Layers::GroupNorm.new(groups, channels)
234
+ @conv1 = Layers::Conv2D.new(channels, channels, 3, padding: 1)
235
+ @norm2 = Layers::GroupNorm.new(groups, channels)
236
+ @conv2 = Layers::Conv2D.new(channels, channels, 3, padding: 1)
237
+ end
238
+
239
+ def forward(x)
240
+ x + @conv2.call(@norm2.call(@conv1.call(@norm1.call(x).relu)).relu)
241
+ end
242
+ end
243
+ end
244
+ end
245
+ end
@@ -0,0 +1,366 @@
1
+ module Maurograd
2
+ module DGM
3
+ # A generative adversarial network (Goodfellow et al., 2014): a
4
+ # generator G maps noise z ~ N(0, I) to samples, and a discriminator D
5
+ # scores samples, a logit of how likely they are to be real. The two
6
+ # are trained against each other: D to tell the data from G's samples,
7
+ # G to fool D. There is no likelihood, and no encoder: what G learns
8
+ # shows only in its samples.
9
+ #
10
+ # gan = GAN.for_images([1, 28, 28], latent_dim: 64) # a DCGAN
11
+ # gan.discriminator_loss(x) # x in [-1, 1], [N, 1, 28, 28]
12
+ # gan.generator_loss(128) # on 128 fresh samples
13
+ # images = gan.sample(16) # [16, 1, 28, 28], in [-1, 1]
14
+ #
15
+ # GANTrainer alternates the two losses' steps, with an optimizer each.
16
+ #
17
+ # The losses, for logits d of D (sigma the sigmoid, so log D = log
18
+ # sigma(d) = -softplus(-d)):
19
+ #
20
+ # - :non_saturating (the default; Goodfellow et al.'s practical form):
21
+ # D minimizes softplus(-d_real) + softplus(d_fake), the cross-entropy
22
+ # of telling real from fake; G minimizes softplus(-d_fake), that is
23
+ # maximizes log D(G(z)).
24
+ # - :minimax: the same D, but G minimizes log(1 - D(G(z))) =
25
+ # -softplus(d_fake), the game as written. Its gradient vanishes when
26
+ # D confidently rejects G's samples, as early in training, which is
27
+ # why the non-saturating form is used instead.
28
+ # - :hinge (Lim and Ye, 2017; Miyato et al., 2018): D minimizes
29
+ # relu(1 - d_real) + relu(1 + d_fake), G minimizes -d_fake.
30
+ # - :least_squares (LSGAN; Mao et al., 2017): D minimizes
31
+ # (d_real - 1)^2 / 2 + d_fake^2 / 2, G minimizes (d_fake - 1)^2 / 2.
32
+ #
33
+ # Each is averaged over the batch.
34
+ class GAN < Layers::Module
35
+ LOSSES = %i[non_saturating minimax hinge least_squares].freeze
36
+
37
+ attr_reader :generator, :discriminator, :latent_shape, :loss
38
+
39
+ # @param generator [Layers::Module] noises [N, *latent_shape] -> samples
40
+ # @param discriminator [Layers::Module] samples -> logits, [N] or [N, 1]
41
+ # @param latent_shape [Array<Integer>, Integer] one noise's shape, e.g. [64]
42
+ # @param loss [Symbol] one of LOSSES
43
+ # @raise [ArgumentError] for a loss not in LOSSES
44
+ def initialize(generator, discriminator, latent_shape:, loss: :non_saturating)
45
+ raise ArgumentError, "loss must be one of #{LOSSES.map(&:inspect).join(", ")}, got #{loss.inspect}" unless LOSSES.include?(loss)
46
+
47
+ @generator = generator
48
+ @discriminator = discriminator
49
+ @latent_shape = Array(latent_shape)
50
+ @loss = loss
51
+ end
52
+
53
+ def generator_parameters = @generator.parameters
54
+
55
+ def discriminator_parameters = @discriminator.parameters
56
+
57
+ # n noises, on the generator's backend.
58
+ #
59
+ # @param n [Integer]
60
+ # @return [Tensor] [n, *latent_shape]
61
+ def noise(n) = Maurograd.randn(n, *@latent_shape, backend: parameter_backend)
62
+
63
+ # The generator's samples for the noises z, recording the graph.
64
+ #
65
+ # @param z [Tensor, Numo::NArray] noises, [N, *latent_shape]
66
+ # @return [Tensor] the samples
67
+ def forward(z) = @generator.call(as_tensor(z))
68
+
69
+ # The discriminator's logits, one per sample, [N].
70
+ #
71
+ # @param x [Tensor, Numo::NArray] data, [N, ...] as the discriminator takes it
72
+ # @return [Tensor] the logits, [N]
73
+ def score(x)
74
+ x = as_tensor(x)
75
+ @discriminator.call(x).reshape(x.shape[0])
76
+ end
77
+
78
+ # The discriminator's loss on the data x and as many of the
79
+ # generator's samples, from fresh noises (or from z). The samples are
80
+ # generated under no_grad: only the discriminator learns from it.
81
+ #
82
+ # @param x [Tensor, Numo::NArray] data, [N, ...] as the discriminator takes it
83
+ # @param z [Tensor, Numo::NArray, nil] the noises of the generated samples; drawn if nil
84
+ # @return [Tensor] a scalar
85
+ def discriminator_loss(x, z = nil)
86
+ x = as_tensor(x)
87
+ # as many generated samples as real ones, without a graph through the generator
88
+ fake = Maurograd.no_grad { forward(z || noise(x.shape[0])) }
89
+ # score both, and compare the scores with what they should be
90
+ discriminator_loss_on(score(x), score(fake.detach))
91
+ end
92
+
93
+ # The generator's loss on n samples from fresh noises (or on z). Its
94
+ # gradient flows back through the discriminator, whose parameters get
95
+ # gradients too: zero them before the discriminator's next step.
96
+ #
97
+ # @param n [Integer, nil] the samples to generate (without z)
98
+ # @param z [Tensor, Numo::NArray, nil] their noises instead
99
+ # @return [Tensor] a scalar
100
+ def generator_loss(n = nil, z: nil)
101
+ z ||= noise(n)
102
+ # generate (recording the graph), let the discriminator score the
103
+ # samples, and measure how far it is from taking them for real
104
+ generator_loss_on(score(forward(z)))
105
+ end
106
+
107
+ # The discriminator's loss for given logits on real and fake samples.
108
+ #
109
+ # @param real [Tensor] the logits on real samples, [N]
110
+ # @param fake [Tensor] the logits on generated ones, [M]
111
+ # @return [Tensor] a scalar
112
+ def discriminator_loss_on(real, fake)
113
+ case @loss
114
+ # binary cross-entropy: -log D(x) = softplus(-d) on real, -log(1 - D) = softplus(d) on fake
115
+ when :non_saturating, :minimax then ((-real).softplus + fake.softplus).mean
116
+ # a margin: real logits pushed above 1, fake ones below -1, no further
117
+ when :hinge then (-real + 1.0).relu.mean + (fake + 1.0).relu.mean
118
+ # regression of the logits on targets: 1 for real, 0 for fake
119
+ when :least_squares then ((real - 1.0)**2).mean * 0.5 + (fake**2).mean * 0.5
120
+ end
121
+ end
122
+
123
+ # The generator's loss for given logits on its samples.
124
+ #
125
+ # @param fake [Tensor] the logits on generated samples, [M]
126
+ # @return [Tensor] a scalar
127
+ def generator_loss_on(fake)
128
+ case @loss
129
+ # -log D(G(z)): large gradients while the discriminator rejects the samples
130
+ when :non_saturating then (-fake).softplus.mean
131
+ # log(1 - D(G(z))): the game as written, flat while D rejects the samples
132
+ when :minimax then -fake.softplus.mean
133
+ # raise the fake logits
134
+ when :hinge then -fake.mean
135
+ # push the fake logits toward the real target, 1
136
+ when :least_squares then ((fake - 1.0)**2).mean * 0.5
137
+ end
138
+ end
139
+
140
+ # n samples from fresh noises, under no_grad and with the generator in
141
+ # eval mode (batch normalization then uses its running statistics).
142
+ #
143
+ # @param n [Integer]
144
+ # @return [Tensor] [n, ...]
145
+ def sample(n) = decode(noise(n))
146
+
147
+ # The generator's samples for the noises z, under no_grad and in eval
148
+ # mode.
149
+ #
150
+ # @param z [Tensor, Numo::NArray] noises, [N, *latent_shape]
151
+ # @return [Tensor] [N, ...]
152
+ def decode(z)
153
+ was_training = @generator.training?
154
+ # eval mode: batch normalization uses its running statistics
155
+ @generator.eval
156
+ Maurograd.no_grad { forward(z) }
157
+ ensure
158
+ @generator.train if was_training
159
+ end
160
+
161
+ # `count` samples along the great circle from noise a to noise b
162
+ # (each [1, *latent_shape]), as DDIM and FlowMatching interpolate.
163
+ #
164
+ # @param a [Tensor, Numo::NArray] a noise, [1, *latent_shape]
165
+ # @param b [Tensor, Numo::NArray] another, [1, *latent_shape]
166
+ # @param count [Integer] the samples, endpoints included
167
+ # @return [Tensor] [count, ...]
168
+ def interpolate(a, b, count: 8) = decode(DGM.slerp(a, b, count))
169
+
170
+ # A GAN of MLPs for vectors of `dim` dimensions: a generator from
171
+ # latent_dim noises, and a discriminator, each with `depth` hidden
172
+ # layers of `hidden` units (ReLUs in the generator, LeakyReLUs of
173
+ # slope 0.2 in the discriminator, as Radford et al. advise).
174
+ #
175
+ # @param dim [Integer] the data's dimensions
176
+ # @param latent_dim [Integer]
177
+ # @param hidden [Integer] units per hidden layer
178
+ # @param depth [Integer] hidden layers per network
179
+ # @param loss [Symbol] one of LOSSES
180
+ # @return [GAN]
181
+ def self.for_vectors(dim, latent_dim: 2, hidden: 128, depth: 3, loss: :non_saturating)
182
+ generator = Layers::Sequential.new(*mlp(latent_dim, dim, hidden, depth) { Layers::ReLU.new })
183
+ discriminator = Layers::Sequential.new(*mlp(dim, 1, hidden, depth) { Layers::LeakyReLU.new(negative_slope: 0.2) })
184
+ new(generator, discriminator, latent_shape: [latent_dim], loss: loss)
185
+ end
186
+
187
+ # A DCGAN (Radford et al., 2016) for images of shape [C, H, W], H and
188
+ # W divisible by 4, in [-1, 1]. The generator maps a latent_dim noise
189
+ # by a dense layer to 2 * channels feature maps of a quarter of the
190
+ # size, then doubles their size twice with transposed convolutions
191
+ # (kernel 4, stride 2), with batch normalization and ReLUs between
192
+ # and a tanh at the end. The discriminator mirrors it: two strided
193
+ # convolutions with LeakyReLUs (batch normalization after the
194
+ # second), then a dense layer to the logit.
195
+ #
196
+ # @param shape [Array<Integer>] [C, H, W], H and W divisible by 4
197
+ # @param latent_dim [Integer]
198
+ # @param channels [Integer] C', the networks' channels are C' and 2C'
199
+ # @param loss [Symbol] one of LOSSES
200
+ # @return [GAN]
201
+ # @raise [ArgumentError] if H or W isn't divisible by 4
202
+ def self.for_images(shape, latent_dim: 64, channels: 64, loss: :non_saturating)
203
+ c, h, w = shape
204
+ raise ArgumentError, "the height and width must be divisible by 4, got #{shape.inspect}" unless (h % 4).zero? && (w % 4).zero?
205
+
206
+ wide = 2 * channels
207
+ generator = Layers::Sequential.new(
208
+ Layers::Linear.new(latent_dim, wide * (h / 4) * (w / 4)),
209
+ Layers::Reshape.new(wide, h / 4, w / 4),
210
+ Layers::BatchNorm2D.new(wide), Layers::ReLU.new,
211
+ Layers::ConvTranspose2D.new(wide, channels, 4, stride: 2, padding: 1),
212
+ Layers::BatchNorm2D.new(channels), Layers::ReLU.new,
213
+ Layers::ConvTranspose2D.new(channels, c, 4, stride: 2, padding: 1),
214
+ Layers::Tanh.new
215
+ )
216
+ discriminator = Layers::Sequential.new(
217
+ Layers::Conv2D.new(c, channels, 4, stride: 2, padding: 1),
218
+ Layers::LeakyReLU.new(negative_slope: 0.2),
219
+ Layers::Conv2D.new(channels, wide, 4, stride: 2, padding: 1),
220
+ Layers::BatchNorm2D.new(wide), Layers::LeakyReLU.new(negative_slope: 0.2),
221
+ Layers::Flatten.new,
222
+ Layers::Linear.new(wide * (h / 4) * (w / 4), 1)
223
+ )
224
+ new(generator, discriminator, latent_shape: [latent_dim], loss: loss)
225
+ end
226
+
227
+ def self.mlp(input, output, hidden, depth)
228
+ sizes = [input] + [hidden] * depth
229
+ sizes.each_cons(2).flat_map { |a, b| [Layers::Linear.new(a, b), yield] } + [Layers::Linear.new(sizes.last, output)]
230
+ end
231
+ private_class_method :mlp
232
+
233
+ private
234
+
235
+ def parameter_backend = parameters.first&.backend || Maurograd.backend
236
+
237
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
238
+ end
239
+
240
+ # The training loop of a GAN: for every batch of data, a step of the
241
+ # discriminator, then (every `discriminator_steps` batches) a step of
242
+ # the generator on a batch of fresh samples as large.
243
+ #
244
+ # gan = GAN.for_vectors(2)
245
+ # trainer = GANTrainer.new(gan,
246
+ # Maurograd::Optim::Adam.new(gan.generator_parameters, lr: 2e-4, betas: [0.5, 0.999]),
247
+ # Maurograd::Optim::Adam.new(gan.discriminator_parameters, lr: 2e-4, betas: [0.5, 0.999]),
248
+ # max_epochs: 100)
249
+ # trainer.fit(loader)
250
+ #
251
+ # (Adam with beta1 = 0.5, as Radford et al. found works for GANs: a
252
+ # shorter memory of the gradient, which keeps changing as the other
253
+ # network moves.)
254
+ #
255
+ # An Optim::EMA of the generator's parameters (ema:) is updated after
256
+ # every generator step: a GAN's iterates circle around the equilibrium
257
+ # rather than settle on it, and their average is often the better
258
+ # generator (Yazici et al., 2019).
259
+ #
260
+ # There is no validation loss and no early stopping: neither loss
261
+ # measures how good the samples are. The block, if given, runs after
262
+ # every epoch with the epoch's record, to save samples.
263
+ class GANTrainer
264
+ attr_reader :gan, :generator_optimizer, :discriminator_optimizer, :history
265
+
266
+ # @param gan [GAN]
267
+ # @param generator_optimizer [Optim::Optimizer] over gan.generator_parameters
268
+ # @param discriminator_optimizer [Optim::Optimizer] over gan.discriminator_parameters
269
+ # @param max_epochs [Integer]
270
+ # @param discriminator_steps [Integer] discriminator steps per generator step
271
+ # @param ema [Optim::EMA, nil] an average of the generator's parameters, updated after its steps
272
+ # @param log [IO, nil] where to print one line per epoch; nil for silence
273
+ def initialize(gan, generator_optimizer, discriminator_optimizer, max_epochs: 10,
274
+ discriminator_steps: 1, ema: nil, log: $stdout)
275
+ @gan = gan
276
+ @generator_optimizer = generator_optimizer
277
+ @discriminator_optimizer = discriminator_optimizer
278
+ @max_epochs = max_epochs
279
+ @discriminator_steps = discriminator_steps
280
+ @ema = ema
281
+ @log = log
282
+ @history = []
283
+ end
284
+
285
+ # Trains, and returns the history: one Hash per epoch, with :epoch
286
+ # (from 1), the means over its batches of :discriminator_loss and
287
+ # :generator_loss and of the discriminator's logits on real and
288
+ # generated samples (:real_score, :fake_score), and :seconds.
289
+ #
290
+ # @param train [Enumerable] batches: Tensors, or [Tensor, labels] pairs, e.g. a Datasets::Loader
291
+ # @yieldparam record [Hash] the epoch's record
292
+ # @return [Array<Hash>] the history
293
+ # @raise [Error] if a loss or score isn't finite
294
+ def fit(train)
295
+ @history = []
296
+ @steps = 0
297
+ 1.upto(@max_epochs) do |epoch|
298
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
299
+ record = {epoch: epoch}.merge(train_epoch(train))
300
+ record[:seconds] = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
301
+ @history << record
302
+ log(record)
303
+ yield record if block_given?
304
+ end
305
+ @history
306
+ end
307
+
308
+ private
309
+
310
+ def train_epoch(loader)
311
+ @gan.train
312
+ sums = Hash.new(0.0)
313
+ counts = Hash.new(0)
314
+ loader.each do |batch|
315
+ x = batch.is_a?(Array) ? batch.first : batch
316
+ n = x.shape[0]
317
+ add = ->(key, tensor) do
318
+ value = tensor.item
319
+ raise Error, "the #{key.to_s.tr("_", " ")} is #{value} at batch #{counts[:discriminator_loss] + 1}" unless value.finite?
320
+
321
+ sums[key] += value
322
+ counts[key] += 1
323
+ end
324
+
325
+ # The discriminator.
326
+ # a batch of samples, generated without a graph: the generator stays put
327
+ fake = Maurograd.no_grad { @gan.call(@gan.noise(n)) }
328
+ # clear the gradients, including those the generator's last step left in D
329
+ @discriminator_optimizer.zero_grad
330
+ # score real and generated samples
331
+ real_score = @gan.score(x)
332
+ fake_score = @gan.score(fake)
333
+ # the discriminator's loss, and a step to lower it
334
+ loss = @gan.discriminator_loss_on(real_score, fake_score)
335
+ loss.backward
336
+ @discriminator_optimizer.step
337
+ add.call(:discriminator_loss, loss)
338
+ add.call(:real_score, Maurograd.no_grad { real_score.mean })
339
+ add.call(:fake_score, Maurograd.no_grad { fake_score.mean })
340
+ @steps += 1
341
+ next unless (@steps % @discriminator_steps).zero?
342
+
343
+ # The generator.
344
+ @generator_optimizer.zero_grad
345
+ # fresh samples, scored by the discriminator just updated
346
+ loss = @gan.generator_loss(n)
347
+ # the gradient flows through D into G; only G's optimizer steps
348
+ loss.backward
349
+ @generator_optimizer.step
350
+ # update the moving average of the generator's weights
351
+ @ema&.update
352
+ add.call(:generator_loss, loss)
353
+ end
354
+ sums.to_h { |key, total| [key, total / counts[key]] }
355
+ end
356
+
357
+ def log(record)
358
+ return unless @log
359
+
360
+ @log.puts format("epoch %3d discriminator %.4f generator %.4f D(real) %+.2f D(fake) %+.2f (%.1fs)",
361
+ record[:epoch], record[:discriminator_loss], record[:generator_loss] || Float::NAN,
362
+ record[:real_score], record[:fake_score], record[:seconds])
363
+ end
364
+ end
365
+ end
366
+ end
@@ -0,0 +1,78 @@
1
+ require "zlib"
2
+ require "numo/narray"
3
+
4
+ module Maurograd
5
+ module DGM
6
+ # Tiles a batch of images into one picture, and writes it as a PNG:
7
+ # how samples, reconstructions and interpolations are looked at.
8
+ #
9
+ # ImageGrid.save(model.sample(64), "samples.png", nrow: 8)
10
+ # ImageGrid.save(x, "x.png", range: [-1, 1]) # images scaled to [-1, 1]
11
+ #
12
+ # Images are a Tensor (on any backend) or a Numo array, of shape
13
+ # [N, C, H, W] with 1 (grayscale) or 3 (RGB) channels, or [N, H, W].
14
+ # Values are mapped from `range` (default [0, 1]) to 0..255, clamping
15
+ # whatever falls outside.
16
+ module ImageGrid
17
+ module_function
18
+
19
+ # The grid as a Numo::UInt8 [height, width] (grayscale) or
20
+ # [height, width, 3] (RGB): nrow images per row, `padding` pixels of
21
+ # `pad_value` (in 0..1) between and around them.
22
+ def make(images, nrow: 8, padding: 2, pad_value: 0.0, range: [0.0, 1.0])
23
+ images = images.to_numo if images.respond_to?(:to_numo) && !images.is_a?(::Numo::NArray)
24
+ images = ::Numo::SFloat.cast(images)
25
+ images = images.reshape(images.shape[0], 1, *images.shape[1..]) if images.ndim == 3
26
+ n, c, h, w = images.shape
27
+ unless images.ndim == 4 && [1, 3].include?(c) && n.positive?
28
+ raise ArgumentError, "expected images [N, 1 or 3, H, W] or [N, H, W], got #{images.shape.inspect}"
29
+ end
30
+
31
+ low, high = range
32
+ pixels = ((images - low) / (high - low)).clip(0.0, 1.0)
33
+
34
+ cols = [nrow, n].min
35
+ rows = (n + cols - 1) / cols
36
+ grid = ::Numo::SFloat.new(c, rows * (h + padding) + padding, cols * (w + padding) + padding).fill(pad_value)
37
+ n.times do |i|
38
+ top = padding + (i / cols) * (h + padding)
39
+ left = padding + (i % cols) * (w + padding)
40
+ grid[true, top...(top + h), left...(left + w)] = pixels[i, true, true, true]
41
+ end
42
+
43
+ grid = (c == 1) ? grid[0, true, true] : grid.transpose(1, 2, 0)
44
+ ::Numo::UInt8.cast((grid * 255).round)
45
+ end
46
+
47
+ # Makes the grid (same options as #make) and writes it to `path` as a
48
+ # PNG. Returns the path.
49
+ def save(images, path, **options)
50
+ write_png(path, make(images, **options))
51
+ path
52
+ end
53
+
54
+ # Writes a Numo::UInt8 [height, width] (grayscale) or
55
+ # [height, width, 3] (RGB) as an 8-bit PNG: the signature, then
56
+ # length-prefixed, CRC-checked chunks: IHDR (size and pixel format),
57
+ # IDAT (the rows, each prefixed by filter type 0, deflated) and IEND.
58
+ def write_png(path, pixels)
59
+ height, width = pixels.shape
60
+ color_type = (pixels.ndim == 3) ? 2 : 0 # 2: RGB, 0: grayscale
61
+ row_bytes = width * ((color_type == 2) ? 3 : 1)
62
+ raw = ::Numo::UInt8.cast(pixels).to_binary
63
+ scanlines = (0...height).map { |y| "\0".b + raw.byteslice(y * row_bytes, row_bytes) }.join
64
+
65
+ png = "\x89PNG\r\n\x1A\n".b
66
+ png << png_chunk("IHDR", [width, height, 8, color_type, 0, 0, 0].pack("NNCCCCC"))
67
+ png << png_chunk("IDAT", Zlib::Deflate.deflate(scanlines))
68
+ png << png_chunk("IEND", "")
69
+ File.binwrite(path, png)
70
+ end
71
+
72
+ def png_chunk(type, data)
73
+ body = type.b + data.b
74
+ [data.bytesize].pack("N") + body + [Zlib.crc32(body)].pack("N")
75
+ end
76
+ end
77
+ end
78
+ end