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,39 @@
1
+ require "zlib"
2
+ require "numo/narray"
3
+
4
+ module Maurograd
5
+ module DGM
6
+ module Datasets
7
+ # The IDX format of MNIST and Fashion-MNIST: a big-endian header
8
+ # (two zero bytes, a type code, the number of dimensions, then each
9
+ # dimension as a 32-bit integer) followed by the raw values. Both
10
+ # datasets store unsigned bytes (type code 0x08): pixels and labels.
11
+ module IDX
12
+ UNSIGNED_BYTE = 0x08
13
+
14
+ # Reads an IDX file, gzipped (.gz) or not, as a Numo::UInt8 array of
15
+ # the shape its header gives.
16
+ def self.read(path)
17
+ bytes = path.end_with?(".gz") ? Zlib::GzipReader.open(path, &:read) : File.binread(path)
18
+ zero, type, ndim = bytes.unpack("nCC")
19
+ unless zero == 0 && type == UNSIGNED_BYTE
20
+ raise Error, "#{path} is not an IDX file of unsigned bytes"
21
+ end
22
+
23
+ shape = bytes.byteslice(4, 4 * ndim).unpack("N#{ndim}")
24
+ size = shape.reduce(1, :*)
25
+ data = bytes.byteslice(4 + 4 * ndim, size)
26
+ raise Error, "#{path} is truncated" unless data && data.bytesize == size
27
+
28
+ ::Numo::UInt8.from_binary(data, shape)
29
+ end
30
+
31
+ # Writes a Numo::UInt8 array in the IDX format (used by the tests).
32
+ def self.write(path, array)
33
+ header = [0, UNSIGNED_BYTE, array.ndim].pack("nCC") + array.shape.pack("N*")
34
+ File.binwrite(path, header + ::Numo::UInt8.cast(array).to_binary)
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,62 @@
1
+ require "numo/narray"
2
+
3
+ module Maurograd
4
+ module DGM
5
+ module Datasets
6
+ # Splits a dataset into batches of Tensors on a backend, in a new
7
+ # random order on every pass.
8
+ #
9
+ # loader = Datasets::Loader.new(x_train, batch_size: 128, seed: 1)
10
+ # loader.each { |x| loss = model.call(x) ... } # x: Tensor [128, ...]
11
+ #
12
+ # loader = Datasets::Loader.new(x, y, batch_size: 128)
13
+ # loader.each { |x, y| ... } # y: Numo slice, on the host
14
+ #
15
+ # `data` is a Numo array whose first axis is the samples; `labels`, if
16
+ # given, is split the same way and stays on the host (models that use
17
+ # labels, such as class-conditional ones, choose what to do with
18
+ # them). The order is reproducible: pass after pass, the shuffles
19
+ # follow from `seed`.
20
+ class Loader
21
+ include Enumerable
22
+
23
+ attr_reader :batch_size, :size
24
+
25
+ def initialize(data, labels = nil, batch_size: 64, shuffle: true, drop_last: false, seed: nil, backend: nil)
26
+ @data = data
27
+ @labels = labels
28
+ @size = data.shape[0]
29
+ if labels && labels.shape[0] != @size
30
+ raise ArgumentError, "data has #{@size} samples, labels #{labels.shape[0]}"
31
+ end
32
+
33
+ @batch_size = batch_size
34
+ @shuffle = shuffle
35
+ @drop_last = drop_last
36
+ @rng = Random.new(seed || Random.new_seed)
37
+ @backend = backend
38
+ end
39
+
40
+ # Number of batches in one pass.
41
+ def length
42
+ @drop_last ? @size / @batch_size : (@size + @batch_size - 1) / @batch_size
43
+ end
44
+
45
+ # Yields each batch: a Tensor, or [Tensor, labels] with labels.
46
+ def each
47
+ return enum_for(:each) unless block_given?
48
+
49
+ order = @shuffle ? (0...@size).to_a.shuffle(random: @rng) : (0...@size).to_a
50
+ rest = [true] * (@data.ndim - 1)
51
+ order.each_slice(@batch_size) do |idx|
52
+ break if @drop_last && idx.length < @batch_size
53
+
54
+ idx = ::Numo::Int32.cast(idx)
55
+ x = Tensor.new(::Numo::SFloat.cast(@data[idx, *rest]), backend: @backend)
56
+ yield(@labels ? [x, @labels[idx]] : x)
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,96 @@
1
+ require_relative "download"
2
+ require_relative "idx"
3
+
4
+ module Maurograd
5
+ module DGM
6
+ module Datasets
7
+ # 28x28 grayscale image datasets in the IDX format, downloaded on first
8
+ # use into root/<name>/ (default ./data, which .gitignore leaves out).
9
+ #
10
+ # x, y = Datasets::MNIST.load(split: :train) # x [60000, 1, 28, 28] in [0, 1], y [60000]
11
+ # x = Datasets.binarize(x, seed: 1) # binarized MNIST
12
+ #
13
+ # Images come as Numo::SFloat in [0, 1], NCHW; labels as Numo::Int32.
14
+ class IDXImages
15
+ SPLITS = {train: "train", test: "t10k"}.freeze
16
+
17
+ class << self
18
+ attr_reader :name, :mirrors, :md5
19
+
20
+ # Returns [images, labels] for split :train or :test.
21
+ def load(split: :train, root: "data", download: true)
22
+ prefix = SPLITS.fetch(split) { raise ArgumentError, "split must be :train or :test, got #{split.inspect}" }
23
+ images, labels = ["#{prefix}-images-idx3-ubyte.gz", "#{prefix}-labels-idx1-ubyte.gz"].map do |file|
24
+ path = File.join(root, name, file)
25
+ if download
26
+ Download.fetch(path, urls: mirrors.map { |m| m + file }, md5: md5.fetch(file))
27
+ elsif !File.exist?(path)
28
+ raise Error, "#{path} not found (pass download: true to fetch it)"
29
+ end
30
+ IDX.read(path)
31
+ end
32
+
33
+ n, h, w = images.shape
34
+ [::Numo::SFloat.cast(images).reshape(n, 1, h, w) / 255.0, ::Numo::Int32.cast(labels)]
35
+ end
36
+
37
+ private
38
+
39
+ def dataset(name, mirrors:, md5:)
40
+ @name = name
41
+ @mirrors = mirrors.freeze
42
+ @md5 = md5.freeze
43
+ end
44
+ end
45
+ end
46
+
47
+ # Handwritten digits, 60000 for training and 10000 for testing.
48
+ class MNIST < IDXImages
49
+ dataset "mnist",
50
+ mirrors: [
51
+ "https://ossci-datasets.s3.amazonaws.com/mnist/",
52
+ "https://yann.lecun.com/exdb/mnist/"
53
+ ],
54
+ md5: {
55
+ "train-images-idx3-ubyte.gz" => "f68b3c2dcbeaaa9fbdd348bbdeb94873",
56
+ "train-labels-idx1-ubyte.gz" => "d53e105ee54ea40749a09fcbcd1e9432",
57
+ "t10k-images-idx3-ubyte.gz" => "9fb629c4189551a2d022fa330f9573f3",
58
+ "t10k-labels-idx1-ubyte.gz" => "ec29112dd5afa0611ce80d1b7f02629c"
59
+ }
60
+ end
61
+
62
+ # Zalando's clothing images, a drop-in replacement for MNIST that is
63
+ # harder to model: 10 classes, from T-shirts to ankle boots.
64
+ class FashionMNIST < IDXImages
65
+ CLASSES = %w[T-shirt/top Trouser Pullover Dress Coat Sandal Shirt Sneaker Bag Ankle\ boot].freeze
66
+
67
+ dataset "fashion_mnist",
68
+ mirrors: ["http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/"],
69
+ md5: {
70
+ "train-images-idx3-ubyte.gz" => "8d4fb7e6c68d591d4c3dfef9ec88bf0d",
71
+ "train-labels-idx1-ubyte.gz" => "25c81989df183df01b3e8a0aad5dffbe",
72
+ "t10k-images-idx3-ubyte.gz" => "bef4ecab320f06d8554ea6380940ec79",
73
+ "t10k-labels-idx1-ubyte.gz" => "bb300cfdad3c16e7a12a480ee83cd310"
74
+ }
75
+ end
76
+
77
+ # Binarizes images in [0, 1]. By default each pixel becomes 1 with
78
+ # probability equal to its intensity (stochastic binarization, the
79
+ # usual way to make binarized MNIST for VAEs, Salakhutdinov and Murray
80
+ # 2008); with threshold:, pixels above the threshold become 1.
81
+ # Returns a Numo::SFloat of 0s and 1s.
82
+ def self.binarize(images, threshold: nil, seed: nil)
83
+ images = ::Numo::SFloat.cast(images)
84
+ return ::Numo::SFloat.cast(images.gt(threshold)) if threshold
85
+
86
+ # Uniform draws from Ruby's own seeded generator (leaving Numo's
87
+ # global one alone), as 16-bit integers: random bytes read as
88
+ # UInt16 are fast even for all of MNIST's 47 million pixels, and a
89
+ # resolution of 1/65536 is far finer than the pixels' 1/255.
90
+ rng = Random.new(seed || Random.new_seed)
91
+ u = ::Numo::UInt16.from_binary(rng.bytes(2 * images.size), images.shape)
92
+ ::Numo::SFloat.cast(::Numo::SFloat.cast(u).lt(images * 65536.0))
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,96 @@
1
+ require "numo/narray"
2
+
3
+ module Maurograd
4
+ module DGM
5
+ module Datasets
6
+ # Two-dimensional test sets, where what a model learned can be seen in
7
+ # a scatter plot: whether it covers every mode, or follows a thin
8
+ # curved manifold. Each returns n points as a Numo::SFloat [n, 2],
9
+ # roughly within [-4, 4], drawn from its own generator: the same seed
10
+ # gives the same points, and Numo's global generator is left alone.
11
+ module Toy2D
12
+ module_function
13
+
14
+ # The swiss roll: a spiral, x = t cos t, y = t sin t, for t in
15
+ # [1.5 pi, 4.5 pi] (as in Marsland, Machine Learning: An Algorithmic
16
+ # Perspective, chapter 6), scaled down by 5 and with Gaussian noise.
17
+ def swiss_roll(n, noise: 0.5, seed: nil)
18
+ rng = rng(seed)
19
+ t = uniform(rng, n) * (3 * Math::PI) + 1.5 * Math::PI
20
+ points = stack(t * Numo::NMath.cos(t), t * Numo::NMath.sin(t))
21
+ ::Numo::SFloat.cast((points + normal(rng, n, 2) * noise) / 5.0)
22
+ end
23
+
24
+ # Two interleaved half circles, as in scikit-learn's make_moons,
25
+ # centered on the origin and scaled by 2.
26
+ def moons(n, noise: 0.05, seed: nil)
27
+ rng = rng(seed)
28
+ outer = n / 2
29
+ theta = uniform(rng, n) * Math::PI
30
+ x = Numo::NMath.cos(theta)
31
+ y = Numo::NMath.sin(theta)
32
+ x[outer..] = 1 - x[outer..]
33
+ y[outer..] = 0.5 - y[outer..]
34
+ points = stack(x - 0.5, y - 0.25) + normal(rng, n, 2) * noise
35
+ ::Numo::SFloat.cast(points * 2.0)
36
+ end
37
+
38
+ # `modes` Gaussians of standard deviation `std`, evenly spaced on a
39
+ # circle of the given radius, with equal weights: the classic test of
40
+ # mode collapse for GANs (8 modes by default).
41
+ def gaussians(n, modes: 8, radius: 2.0, std: 0.2, seed: nil)
42
+ rng = rng(seed)
43
+ k = ::Numo::DFloat.cast(Array.new(n) { rng.rand(modes) })
44
+ angle = k * (2 * Math::PI / modes)
45
+ centers = stack(Numo::NMath.cos(angle), Numo::NMath.sin(angle)) * radius
46
+ ::Numo::SFloat.cast(centers + normal(rng, n, 2) * std)
47
+ end
48
+
49
+ # The true density of #gaussians, to score a model's samples against
50
+ # or to draw its contours.
51
+ def gaussians_density(modes: 8, radius: 2.0, std: 0.2)
52
+ angle = ::Numo::DFloat.new(modes).seq * (2 * Math::PI / modes)
53
+ means = stack(Numo::NMath.cos(angle), Numo::NMath.sin(angle)) * radius
54
+ Distributions::MixtureOfGaussians.new(
55
+ ::Numo::SFloat.zeros(modes), ::Numo::SFloat.cast(means),
56
+ ::Numo::SFloat.new(modes, 2).fill(2 * Math.log(std))
57
+ )
58
+ end
59
+
60
+ # A 4x4 checkerboard of uniform squares, the 8 dark ones holding all
61
+ # the probability: sharp edges that smooth models blur.
62
+ def checkerboard(n, seed: nil)
63
+ rng = rng(seed)
64
+ x = uniform(rng, n) * 4 - 2
65
+ row = ::Numo::DFloat.cast(Array.new(n) { rng.rand(2) })
66
+ parity = ((x.floor % 2) + 2) % 2 # 0 or 1; Numo's % keeps the sign of x
67
+ y = uniform(rng, n) - row * 2 + parity
68
+ ::Numo::SFloat.cast(stack(x, y) * 2.0)
69
+ end
70
+
71
+ # --- helpers ------------------------------------------------------
72
+
73
+ def rng(seed) = Random.new(seed || Random.new_seed)
74
+
75
+ # n uniform draws in [0, 1), as a Numo::DFloat.
76
+ def uniform(rng, n)
77
+ ::Numo::DFloat.cast(::Numo::UInt32.from_binary(rng.bytes(4 * n), [n])) / 4_294_967_296.0
78
+ end
79
+
80
+ # Standard normal draws of the given shape, by the Box-Muller
81
+ # transform: sqrt(-2 log u1) cos(2 pi u2) is N(0, 1) for uniform u1, u2.
82
+ def normal(rng, *shape)
83
+ size = shape.reduce(1, :*)
84
+ u1 = 1.0 - uniform(rng, size) # in (0, 1], so the log is finite
85
+ u2 = uniform(rng, size)
86
+ (Numo::NMath.sqrt(Numo::NMath.log(u1) * -2) * Numo::NMath.cos(u2 * (2 * Math::PI))).reshape(*shape)
87
+ end
88
+
89
+ # Columns x and y side by side: [n, 2].
90
+ def stack(x, y)
91
+ ::Numo::DFloat.vstack([x, y]).transpose
92
+ end
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,19 @@
1
+ require_relative "datasets/download"
2
+ require_relative "datasets/idx"
3
+ require_relative "datasets/mnist"
4
+ require_relative "datasets/toy_2d"
5
+ require_relative "datasets/loader"
6
+
7
+ module Maurograd
8
+ module DGM
9
+ # Datasets, as Numo arrays on the host, and Datasets::Loader to feed them to
10
+ # a model in batches of Tensors:
11
+ #
12
+ # - Datasets::MNIST and Datasets::FashionMNIST, downloaded on first use;
13
+ # Datasets.binarize for binarized MNIST.
14
+ # - Datasets::Toy2D: the swiss roll, two moons, a ring of Gaussians and a
15
+ # checkerboard, for models whose samples can be seen in a scatter plot.
16
+ module Datasets
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,194 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Denoising diffusion implicit models (Song et al., 2021): a faster
4
+ # sampler for a trained DDPM, with no retraining.
5
+ #
6
+ # DDPM's loss only depends on the marginals q(x_t | x_0), and many
7
+ # forward processes, not all Markovian, share them. DDIM picks a family
8
+ # whose reverse steps can skip: from x_t it predicts x_0 (through the
9
+ # network's noise estimate eps) and jumps to any earlier step s,
10
+ #
11
+ # x_s = sqrt(alpha_bar_s) x0 + sqrt(1 - alpha_bar_s - sigma^2) eps + sigma z
12
+ # sigma = eta sqrt((1 - alpha_bar_s) / (1 - alpha_bar_t)) sqrt(1 - alpha_bar_t / alpha_bar_s)
13
+ #
14
+ # so sampling can run on a subsequence of, say, 50 of the 1000 steps.
15
+ # eta = 0 makes it deterministic: the noise x_T alone decides the
16
+ # image. eta = 1 on the full sequence is DDPM with the posterior
17
+ # variance.
18
+ #
19
+ # Being deterministic, the sampler is an ODE solver, and running it the
20
+ # other way maps an image to the noise that produces it (#encode):
21
+ # images can then be interpolated through their noises (#interpolate).
22
+ #
23
+ # ddim = DDIM.new(ddpm)
24
+ # images = ddim.sample(64, steps: 50)
25
+ # noise = ddim.encode(images, iterations: 2) # ddim.decode(noise) gives them back
26
+ class DDIM
27
+ attr_reader :model
28
+
29
+ # @param model [DDPM] a trained DDPM, whose network and schedule the sampler uses
30
+ def initialize(model)
31
+ @model = model
32
+ end
33
+
34
+ def schedule = @model.schedule
35
+
36
+ # `count` steps spread evenly over 0...T, in decreasing order: the
37
+ # subsequence the sampler visits.
38
+ #
39
+ # @param count [Integer] in 1..T
40
+ # @return [Array<Integer>] count steps, decreasing
41
+ # @raise [ArgumentError] if count isn't in 1..T
42
+ def timesteps(count)
43
+ total = schedule.steps
44
+ raise ArgumentError, "steps must be in 1..#{total}, got #{count}" unless count.between?(1, total)
45
+
46
+ (0...count).map { |i| i * total / count }.reverse
47
+ end
48
+
49
+ # n samples from fresh noise (or from the given noise), under no_grad.
50
+ #
51
+ # @param n [Integer]
52
+ # @param steps [Integer] network evaluations, in 1..T
53
+ # @param eta [Float] the fresh noise per step: 0 deterministic, 1 as DDPM
54
+ # @param noise [Tensor, Numo::NArray, nil] x_T, [n, *shape]; drawn if nil
55
+ # @param clip [Boolean] clip each predicted x_0 to [-1, 1]
56
+ # @return [Tensor] [n, *shape]
57
+ def sample(n, steps: 50, eta: 0.0, noise: nil, clip: true)
58
+ noise ||= Maurograd.randn(n, *@model.shape, backend: backend)
59
+ decode(noise, steps: steps, eta: eta, clip: clip)
60
+ end
61
+
62
+ # Runs the sampler from x_T = noise to x_0.
63
+ #
64
+ # @param noise [Tensor, Numo::NArray] x_T, [N, *shape]
65
+ # @param steps [Integer] network evaluations, in 1..T
66
+ # @param eta [Float] the fresh noise per step: 0 deterministic, 1 as DDPM
67
+ # @param clip [Boolean] clip each predicted x_0 to [-1, 1]
68
+ # @return [Tensor] x_0, [N, *shape]
69
+ def decode(noise, steps: 50, eta: 0.0, clip: false)
70
+ Maurograd.no_grad do
71
+ x = as_tensor(noise)
72
+ # the steps visited, e.g. 980, 960, ..., 0 for 50 of 1000
73
+ sequence = timesteps(steps)
74
+ sequence.each_with_index do |t, i|
75
+ # jump from t straight to the next visited step (-1: the data)
76
+ s = sequence[i + 1] || -1
77
+ x = step(x, t, s, eta: eta, clip: clip)
78
+ # evaluate now on a lazy backend (MLX)
79
+ x.backend.eval([x.data])
80
+ end
81
+ x
82
+ end
83
+ end
84
+
85
+ # The deterministic sampler run backward, from x_0 to x_T: the noise
86
+ # that decode turns back into x0.
87
+ #
88
+ # Each step inverts one step of decode, x_t -> x_s, which needs the
89
+ # noise estimate at x_t, the point being solved for. Song et al.
90
+ # use the estimate at x_s instead, which makes decode(encode(x)) only
91
+ # approximately x. With iterations: k, each step refines x_t k times
92
+ # by fixed-point iteration, re-estimating the noise at the latest
93
+ # x_t: one network evaluation per iteration, and a round trip that
94
+ # comes back to x as k grows.
95
+ #
96
+ # @param x0 [Tensor, Numo::NArray] images, [N, *shape], in [-1, 1]
97
+ # @param steps [Integer] in 1..T
98
+ # @param iterations [Integer] fixed-point refinements per step
99
+ # @return [Tensor] x_T, [N, *shape]
100
+ def encode(x0, steps: 50, iterations: 0)
101
+ Maurograd.no_grad do
102
+ x = as_tensor(x0)
103
+ # the step x is at; -1 is the data itself
104
+ from = -1
105
+ # visit the steps in increasing order, adding noise
106
+ timesteps(steps).reverse_each do |t|
107
+ source = x
108
+ # the noise estimate, taken at the known point (Song et al.'s approximation)
109
+ eps = @model.predict_noise(source, from.negative? ? t : from)
110
+ # the x_0 that source and eps imply, moved forward to step t
111
+ x = jump(predicted_x0(source, eps, from), eps, t, 0.0)
112
+ # optionally, refine: re-estimate the noise at the new x_t and redo the jump
113
+ iterations.times do
114
+ eps = @model.predict_noise(x, t)
115
+ x = jump(predicted_x0(source, eps, from), eps, t, 0.0)
116
+ end
117
+ x.backend.eval([x.data])
118
+ from = t
119
+ end
120
+ x
121
+ end
122
+ end
123
+
124
+ # `count` images between a and b (each [1, ...]), interpolated
125
+ # spherically through their noises (see DGM.slerp).
126
+ #
127
+ # @param a [Tensor, Numo::NArray] an image, [1, *shape]
128
+ # @param b [Tensor, Numo::NArray] another, [1, *shape]
129
+ # @param count [Integer] the images, endpoints included
130
+ # @param steps [Integer] the sampler's steps, both ways
131
+ # @param iterations [Integer] fixed-point refinements per encoding step
132
+ # @return [Tensor] [count, *shape]
133
+ def interpolate(a, b, count: 8, steps: 50, iterations: 0)
134
+ # the noises that decode to a and b
135
+ za = encode(a, steps: steps, iterations: iterations)
136
+ zb = encode(b, steps: steps, iterations: iterations)
137
+ # points on the great circle between them, decoded
138
+ decode(DGM.slerp(za, zb, count), steps: steps)
139
+ end
140
+
141
+ # One step of the sampler, from step t to an earlier step s (-1 for
142
+ # the data).
143
+ #
144
+ # @param x [Tensor] x_t, [N, *shape]
145
+ # @param t [Integer] the current step
146
+ # @param s [Integer] the step to jump to, below t; -1 for the data
147
+ # @param eta [Float]
148
+ # @param clip [Boolean]
149
+ # @return [Tensor] x_s, shaped like x
150
+ def step(x, t, s, eta: 0.0, clip: false)
151
+ # the network's guess of the noise in x_t, and the x_0 it implies
152
+ eps = @model.predict_noise(x, t)
153
+ x0 = predicted_x0(x, eps, t)
154
+ if clip
155
+ x0 = x0.clamp(min: -1.0, max: 1.0)
156
+ # The noise consistent with the clipped x0.
157
+ eps = (x - x0 * Math.sqrt(schedule.alpha_bar(t))) * (1 / Math.sqrt(1 - schedule.alpha_bar(t)))
158
+ end
159
+ a_t = schedule.alpha_bar(t)
160
+ a_s = schedule.alpha_bar(s)
161
+ # the fresh noise of the step: 0 for eta = 0 (deterministic), DDPM's for eta = 1
162
+ sigma = eta * Math.sqrt((1 - a_s) / (1 - a_t)) * Math.sqrt(1 - a_t / a_s)
163
+ # put x_0 back at noise level s, along the same noise direction
164
+ jump(x0, eps, s, sigma)
165
+ end
166
+
167
+ private
168
+
169
+ # x0 from x_t and the noise in it.
170
+ def predicted_x0(x, eps, t)
171
+ a = schedule.alpha_bar(t)
172
+ (x - eps * Math.sqrt(1 - a)) * (1 / Math.sqrt(a))
173
+ end
174
+
175
+ # x_s from x0, a noise direction and a fresh noise of size sigma.
176
+ def jump(x0, eps, s, sigma)
177
+ a = schedule.alpha_bar(s)
178
+ # the signal's part at step s
179
+ x = x0 * Math.sqrt(a)
180
+ # at the data, nothing else
181
+ return x if s.negative?
182
+
183
+ # the old noise direction, with the variance the fresh noise leaves it
184
+ x += eps * Math.sqrt([1 - a - sigma**2, 0.0].max)
185
+ # and the fresh noise, if any
186
+ sigma.positive? ? x + Maurograd.randn_like(x0) * sigma : x
187
+ end
188
+
189
+ def backend = @model.parameters.first&.backend || Maurograd.backend
190
+
191
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: backend)
192
+ end
193
+ end
194
+ end