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,211 @@
1
+ module Maurograd
2
+ module DGM
3
+ # An energy-based model: a network E(x) gives each sample an energy,
4
+ # and the model's density is
5
+ #
6
+ # p(x) = exp(-E(x)) / Z, Z = integral of exp(-E(x)) dx
7
+ #
8
+ # Any network with a scalar output will do, which makes EBMs the most
9
+ # flexible of the models here; the price is Z, which can't be
10
+ # computed. The gradient of the log-likelihood doesn't need it:
11
+ #
12
+ # d/dtheta E_data[-log p(x)] = E_data[dE/dtheta] - E_p[dE/dtheta]
13
+ #
14
+ # the energy pushed down on the data and up on the model's own samples.
15
+ # The samples come from Langevin dynamics, gradient descent on the
16
+ # energy with noise:
17
+ #
18
+ # x <- x - step_size * dE/dx + noise * z, z ~ N(0, I)
19
+ #
20
+ # which samples p for noise = sqrt(2 step_size) and many steps. Run for
21
+ # a few dozen steps only ("short-run" MCMC, Nijkamp et al., 2019),
22
+ # starting from a replay buffer of past samples, 5% of them from fresh
23
+ # noise every time (Du and Mordatch, 2019), so that the chains go on
24
+ # across training steps. The loss is
25
+ #
26
+ # mean E(x_data) - mean E(x_samples) + alpha (E(x_data)^2 + E(x_samples)^2)
27
+ #
28
+ # where the last term keeps the energies near 0 (they are otherwise
29
+ # free to drift together).
30
+ #
31
+ # energy = Layers::Sequential.new(...) # [N, ...] -> [N, 1]
32
+ # ebm = EBM.new(energy, shape: [1, 28, 28], steps: 40, step_size: 10.0, noise: 0.005)
33
+ # loss = ebm.call(x) # x in [-1, 1]
34
+ # images = ebm.sample(16) # 16 chains from noise, more steps
35
+ #
36
+ # With image settings like these, noise far below sqrt(2 step_size),
37
+ # the sampler is no longer Langevin dynamics for p, and the energy
38
+ # learns whatever makes those short chains end on the data: a good
39
+ # sampler, a poor density (Nijkamp et al.).
40
+ class EBM < Layers::Module
41
+ attr_reader :network, :shape, :steps, :step_size, :noise, :bounds, :buffer
42
+
43
+ # @param network [Layers::Module] samples -> energies, [N] or [N, 1]
44
+ # @param shape [Array<Integer>] one sample's shape
45
+ # @param steps [Integer] Langevin steps per training batch
46
+ # @param step_size [Float] Langevin's step size
47
+ # @param noise [Float, nil] Langevin's noise; sqrt(2 step_size) if nil
48
+ # @param bounds [Array(Float, Float), nil] [low, high]: samples are clipped to the box, and
49
+ # new chains start uniformly in it; nil for chains from N(0, I), unclipped
50
+ # @param buffer_size [Integer] the most samples the replay buffer keeps
51
+ # @param reinit [Float] the share of chains started from noise at each training step
52
+ # @param alpha [Float] the weight of the energies' squares in the loss
53
+ # @param gradient_clip [Float, nil] clamp each element of dE/dx to [-c, c] before a Langevin
54
+ # step, so that no step moves a value by more than step_size * c; image EBMs
55
+ # need it, as their energies' gradients are large and uneven early in training
56
+ # @param data_noise [Float] the standard deviation of Gaussian noise added to the data in
57
+ # the loss, which smooths the energy around it
58
+ def initialize(network, shape:, steps: 60, step_size: 10.0, noise: nil, bounds: [-1.0, 1.0],
59
+ buffer_size: 10_000, reinit: 0.05, alpha: 0.1, gradient_clip: nil, data_noise: 0.0)
60
+ @network = network
61
+ @shape = shape
62
+ @steps = steps
63
+ @step_size = step_size
64
+ @noise = noise || Math.sqrt(2 * step_size)
65
+ @bounds = bounds
66
+ @buffer_size = buffer_size
67
+ @reinit = reinit
68
+ @alpha = alpha
69
+ @gradient_clip = gradient_clip
70
+ @data_noise = data_noise
71
+ @buffer = nil
72
+ end
73
+
74
+ # The energies of x, [N].
75
+ #
76
+ # @param x [Tensor, Numo::NArray] [N, *shape]
77
+ # @return [Tensor] [N]
78
+ def energy(x)
79
+ x = as_tensor(x)
80
+ @network.call(x).reshape(x.shape[0])
81
+ end
82
+
83
+ # log p(x) + log Z = -E(x): the log-density up to a constant.
84
+ #
85
+ # @param x [Tensor, Numo::NArray] [N, *shape]
86
+ # @return [Tensor] -E(x), [N]
87
+ def unnormalized_log_prob(x) = -energy(x)
88
+
89
+ # The training loss on data x, after drawing as many samples from the
90
+ # replay buffer by Langevin dynamics (see the class comment).
91
+ #
92
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape]
93
+ # @return [Tensor] a scalar
94
+ def forward(x)
95
+ x = as_tensor(x)
96
+ # optionally blur the data a little with Gaussian noise
97
+ x += Maurograd.randn_like(x) * @data_noise if @data_noise.positive?
98
+ # the model's own samples, as many as the data, by Langevin dynamics
99
+ negatives = buffer_samples(x.shape[0], x.backend)
100
+ # the energies of both (the negatives are constants: no gradient flows into the sampler)
101
+ real = energy(x)
102
+ fake = energy(negatives)
103
+ # lower the data's energy, raise the samples', and keep both near 0
104
+ (real.mean - fake.mean) + ((real**2).mean + (fake**2).mean) * @alpha
105
+ end
106
+
107
+ # n samples from chains started from noise (or from x), by `steps`
108
+ # steps of Langevin dynamics (by default twice the training's), with
109
+ # the parameters' gradients left as they were. every: also return
110
+ # every that many steps' states, as [x, states].
111
+ #
112
+ # @param n [Integer, nil] the chains (without x)
113
+ # @param steps [Integer]
114
+ # @param step_size [Float]
115
+ # @param noise [Float]
116
+ # @param x [Tensor, Numo::NArray, nil] the chains' starting points, [N, *shape]
117
+ # @param every [Integer, nil] also return the states every that many steps
118
+ # @return [Tensor, Array(Tensor, Array<Tensor>)] [n, *shape]; with every:, [samples, states]
119
+ def sample(n = nil, steps: 2 * @steps, step_size: @step_size, noise: @noise, x: nil, every: nil)
120
+ x = x ? as_tensor(x) : initial(n, parameter_backend)
121
+ langevin(x, steps: steps, step_size: step_size, noise: noise, every: every)
122
+ end
123
+
124
+ # Runs Langevin dynamics from x and returns the last state, detached
125
+ # (and with `every:`, the states every that many steps).
126
+ #
127
+ # @param x [Tensor, Numo::NArray] the starting points, [N, *shape]
128
+ # @param steps [Integer]
129
+ # @param step_size [Float]
130
+ # @param noise [Float]
131
+ # @param every [Integer, nil] also return the states every that many steps
132
+ # @return [Tensor, Array(Tensor, Array<Tensor>)] [N, *shape]; with every:, [samples, states]
133
+ def langevin(x, steps: @steps, step_size: @step_size, noise: @noise, every: nil)
134
+ # backward passes also fill the parameters' gradients: save them
135
+ saved = parameters.map(&:grad)
136
+ x = as_tensor(x).detach
137
+ states = [x] if every
138
+ steps.times do |i|
139
+ # a copy of x that records the graph, so we can differentiate in x
140
+ input = Tensor.new(x.data, requires_grad: true, backend: x.backend)
141
+ # the samples' energies are independent: the gradient of their sum
142
+ # gives each sample its own dE/dx
143
+ energy(input).sum.backward
144
+ gradient = Tensor.new(input.grad, backend: x.backend)
145
+ # optionally bound each element of the gradient
146
+ gradient = gradient.clamp(min: -@gradient_clip, max: @gradient_clip) if @gradient_clip
147
+ x = Maurograd.no_grad do
148
+ # a step downhill on the energy
149
+ moved = x - gradient * step_size
150
+ # plus Gaussian noise, which makes it sampling rather than descent
151
+ moved += Maurograd.randn_like(x) * noise if noise.positive?
152
+ # kept inside the bounds, if any
153
+ @bounds ? moved.clamp(min: @bounds[0], max: @bounds[1]) : moved
154
+ end
155
+ # evaluate now on a lazy backend (MLX)
156
+ x.backend.eval([x.data])
157
+ states << x if every && ((i + 1) % every).zero?
158
+ end
159
+ # put the parameters' gradients back as they were
160
+ parameters.zip(saved).each { |p, g| p.grad = g }
161
+ every ? [x, states] : x
162
+ end
163
+
164
+ # n starting points: uniform in the bounds, or N(0, I) without.
165
+ #
166
+ # @param n [Integer]
167
+ # @param backend [Module, Symbol] the model's by default
168
+ # @return [Tensor] [n, *shape]
169
+ def initial(n, backend = parameter_backend)
170
+ if @bounds
171
+ low, high = @bounds
172
+ Maurograd.rand(n, *@shape, backend: backend) * (high - low) + low
173
+ else
174
+ Maurograd.randn(n, *@shape, backend: backend)
175
+ end
176
+ end
177
+
178
+ private
179
+
180
+ # n chains: a share reinit of them (and any the buffer can't supply)
181
+ # from noise, the rest drawn from the replay buffer, advanced by
182
+ # Langevin dynamics. The results are added to the buffer, whose
183
+ # oldest samples are dropped past buffer_size: it starts with one
184
+ # batch, so early on the same few chains are refined over and over,
185
+ # and later it holds the latest ones.
186
+ def buffer_samples(n, backend)
187
+ # the buffer starts as one batch of noise, kept on the CPU
188
+ @buffer ||= ::Numo::SFloat.cast(initial(n, :cpu).to_numo)
189
+ # how many chains start from fresh noise: each with probability reinit
190
+ fresh = ::Numo::DFloat.new(n).rand.lt(@reinit).count_true
191
+ # the rest continue chains from the buffer, as many as it holds
192
+ old = [n - fresh, @buffer.shape[0]].min
193
+ index = ::Numo::Int32.cast((::Numo::DFloat.new(old).rand * @buffer.shape[0]).floor)
194
+ # the starting points: buffered chains first, then fresh noise
195
+ start = ::Numo::SFloat.zeros(n, *@shape)
196
+ start[0...old, false] = @buffer[index, false] if old.positive?
197
+ start[old...n, false] = ::Numo::SFloat.cast(initial(n - old, :cpu).to_numo) if old < n
198
+ # advance all of them by Langevin dynamics
199
+ x = langevin(Tensor.new(start, backend: backend))
200
+ # put the results in front of the buffer, and drop its oldest past the limit
201
+ @buffer = ::Numo::SFloat.cast(x.to_numo).concatenate(@buffer)
202
+ @buffer = @buffer[0...@buffer_size, false].copy if @buffer.shape[0] > @buffer_size
203
+ x
204
+ end
205
+
206
+ def parameter_backend = parameters.first&.backend || Maurograd.backend
207
+
208
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
209
+ end
210
+ end
211
+ end
@@ -0,0 +1,303 @@
1
+ module Maurograd
2
+ module DGM
3
+ # Flow matching (Lipman et al., 2023; Liu et al., 2023, as rectified
4
+ # flow): a continuous-time flow, an ODE dx/dt = v(x, t) that carries
5
+ # noise at t = 0 to data at t = 1, with the velocity field v a network
6
+ # trained by regression, without simulating the ODE.
7
+ #
8
+ # Draw noise x0 and data x1, and the point at a uniform time t on the
9
+ # straight line between them; the line's velocity is x1 - x0:
10
+ #
11
+ # x_t = (1 - t) x0 + t x1
12
+ # loss = || v(x_t, t) - (x1 - x0) ||^2
13
+ #
14
+ # Many lines cross any one x_t, and the regression learns their mean
15
+ # velocity, E[x1 - x0 | x_t]: a field whose flow has the same marginals
16
+ # as the lines, so that it carries the noise to the data (Lipman et
17
+ # al.'s conditional flow matching). Sampling integrates it from t = 0
18
+ # to 1, with Euler or Heun steps.
19
+ #
20
+ # unet = Networks::UNet.new(in_channels: 1, channels: [32, 64, 128], time_scale: 1000)
21
+ # model = FlowMatching.new(unet, shape: [1, 28, 28])
22
+ # loss = model.call(x) # x in [-1, 1]
23
+ # images = model.sample(16, steps: 25) # Heun: 50 network evaluations
24
+ #
25
+ # The network takes times in [0, 1]: time_scale: 1000 spreads them for
26
+ # the embeddings, as diffusion steps are spread. Like DDIM, the ODE runs
27
+ # backward too (#encode), and it gives an exact log-likelihood as any
28
+ # flow does, here through the divergence of v (#log_prob).
29
+ class FlowMatching < Layers::Module
30
+ METHODS = %i[euler heun].freeze
31
+
32
+ attr_reader :network, :shape
33
+
34
+ # @param network [Layers::Module] (x, t) -> the velocity, shaped like x; e.g. Networks::UNet
35
+ # @param shape [Array<Integer>] one sample's shape
36
+ def initialize(network, shape:)
37
+ @network = network
38
+ @shape = shape
39
+ end
40
+
41
+ # The point at time t (one per sample, or one for all) on the line
42
+ # from x0 to x1.
43
+ #
44
+ # @param x0 [Tensor, Numo::NArray] noises, [N, *shape]
45
+ # @param x1 [Tensor, Numo::NArray] data, [N, *shape]
46
+ # @param t [Float, Array<Float>, Numo::NArray] a time in [0, 1] for all, or one per sample
47
+ # @return [Tensor] [N, *shape]
48
+ def path(x0, x1, t)
49
+ x0 = as_tensor(x0)
50
+ # one time per sample, shaped to broadcast against x
51
+ t = per_sample(times(t, x0.shape[0]), x0)
52
+ # the point a fraction t of the way along the line: (1 - t) x0 + t x1
53
+ (x0 * (t * -1.0 + 1.0)) + (as_tensor(x1) * t)
54
+ end
55
+
56
+ # The network's velocity at x and time t.
57
+ #
58
+ # @param x [Tensor] [N, *shape]
59
+ # @param t [Float, Array<Float>, Numo::NArray] a time in [0, 1] for all, or one per sample
60
+ # @return [Tensor] shaped like x
61
+ def velocity(x, t) = @network.call(x, times(t, x.shape[0]))
62
+
63
+ # The training loss: the mean squared error between the network's
64
+ # velocity and the line's, at a uniform time per sample.
65
+ #
66
+ # @param x1 [Tensor, Numo::NArray] the data, [N, *shape]
67
+ # @return [Tensor] the mean squared error, a scalar
68
+ def forward(x1)
69
+ x1 = as_tensor(x1)
70
+ # pair each data point x1 with a noise x0 ~ N(0, I)
71
+ x0 = Maurograd.randn_like(x1)
72
+ # a random time on each pair's line, t uniform in [0, 1)
73
+ t = ::Numo::SFloat.new(x1.shape[0]).rand
74
+ # the line's velocity is constant, x1 - x0: regress the network on it
75
+ error = velocity(path(x0, x1, t), t) - (x1 - x0)
76
+ # the mean squared error
77
+ (error * error).mean
78
+ end
79
+
80
+ # The training loss at time t (a Float), for every sample.
81
+ #
82
+ # @param x1 [Tensor, Numo::NArray] the data, [N, *shape]
83
+ # @param t [Float] in [0, 1]
84
+ # @return [Tensor] each sample's mean squared error, [N]
85
+ def loss_at(x1, t)
86
+ x1 = as_tensor(x1)
87
+ Maurograd.no_grad do
88
+ x0 = Maurograd.randn_like(x1)
89
+ error = velocity(path(x0, x1, t), t) - (x1 - x0)
90
+ (error * error).reshape(x1.shape[0], -1).mean(axis: 1)
91
+ end
92
+ end
93
+
94
+ # The number of network evaluations of `steps` steps of `method`.
95
+ #
96
+ # @param steps [Integer]
97
+ # @param method [Symbol] :euler or :heun
98
+ # @return [Integer]
99
+ def evaluations(steps, method: :heun) = (method == :heun) ? 2 * steps : steps
100
+
101
+ # n samples from fresh noise (or from the given noise), under no_grad.
102
+ # With every: k, also returns the states every k steps (the noise and
103
+ # the samples included).
104
+ #
105
+ # @param n [Integer]
106
+ # @param steps [Integer]
107
+ # @param method [Symbol] :euler or :heun
108
+ # @param noise [Tensor, Numo::NArray, nil] [n, *shape]; drawn if nil
109
+ # @param every [Integer, nil] also return the states every that many steps
110
+ # @return [Tensor, Array(Tensor, Array<Tensor>)] [n, *shape]; with every:, [samples, states]
111
+ # @raise [ArgumentError] for an unknown method, or steps not positive
112
+ def sample(n, steps: 50, method: :heun, noise: nil, every: nil)
113
+ noise ||= Maurograd.randn(n, *@shape, backend: parameter_backend)
114
+ decode(noise, steps: steps, method: method, every: every)
115
+ end
116
+
117
+ # The ODE from t = 0 (the noise) to t = 1 (the data).
118
+ #
119
+ # @param noise [Tensor, Numo::NArray] [N, *shape]
120
+ # @param steps [Integer]
121
+ # @param method [Symbol] :euler or :heun
122
+ # @param every [Integer, nil] also return the states every that many steps
123
+ # @return [Tensor, Array(Tensor, Array<Tensor>)] [N, *shape]; with every:, [samples, states]
124
+ # @raise [ArgumentError] for an unknown method, or steps not positive
125
+ def decode(noise, steps: 50, method: :heun, every: nil)
126
+ integrate(as_tensor(noise), 0.0, 1.0, steps, method, every)
127
+ end
128
+
129
+ # The ODE backward, from t = 1 (the data) to t = 0: the noise that
130
+ # #decode turns back into x1, up to the solver's error.
131
+ #
132
+ # @param x1 [Tensor, Numo::NArray] the data, [N, *shape]
133
+ # @param steps [Integer]
134
+ # @param method [Symbol] :euler or :heun
135
+ # @return [Tensor] the noises, [N, *shape]
136
+ # @raise [ArgumentError] for an unknown method, or steps not positive
137
+ def encode(x1, steps: 50, method: :heun)
138
+ integrate(as_tensor(x1), 1.0, 0.0, steps, method, nil)
139
+ end
140
+
141
+ # `count` samples between a and b (each [1, ...]), interpolated
142
+ # spherically through their noises (see DGM.slerp).
143
+ #
144
+ # @param a [Tensor, Numo::NArray] a sample, [1, *shape]
145
+ # @param b [Tensor, Numo::NArray] another, [1, *shape]
146
+ # @param count [Integer] the samples, endpoints included
147
+ # @param steps [Integer] the ODE's steps, both ways
148
+ # @param method [Symbol] :euler or :heun
149
+ # @return [Tensor] [count, *shape]
150
+ def interpolate(a, b, count: 8, steps: 50, method: :heun)
151
+ # the noises the ODE carries to a and b
152
+ za = encode(a, steps: steps, method: method).to_numo
153
+ zb = encode(b, steps: steps, method: method).to_numo
154
+ # points on the great circle between them, carried to the data
155
+ decode(DGM.slerp(za, zb, count), steps: steps, method: method)
156
+ end
157
+
158
+ # log p(x) for each sample, [N], by the instantaneous change of
159
+ # variables (Chen et al., 2018): along the ODE,
160
+ #
161
+ # d log p(x_t) / dt = -div v(x_t, t)
162
+ #
163
+ # so running it backward from x to its noise x0 gives
164
+ # log p(x) = log N(x0 | 0, I) - integral of div v from 0 to 1.
165
+ #
166
+ # The divergence is exact by default: one backward pass per
167
+ # dimension, at every step, which suits low-dimensional data. With
168
+ # hutchinson: true it is estimated as e^T (dv/dx) e, for one Gaussian
169
+ # e per sample (Grathwohl et al., 2019): one backward pass a step,
170
+ # and an unbiased estimate of log p(x) for images.
171
+ #
172
+ # Near t = 1 the field turns stiff on data with exact, repeated
173
+ # values (MNIST's black background): the lines bunch up onto them,
174
+ # and the divergence grows large. The steps are therefore crowded
175
+ # there, at times t_i = 1 - (i / steps)^power: with the default
176
+ # power 3, 100 Heun steps on MNIST agree with 800 uniform ones
177
+ # (power: 1) within 0.01 bits per dimension, where 50 uniform steps
178
+ # are off by a whole bit.
179
+ #
180
+ # @param x [Tensor, Numo::NArray] the data, [N, *shape]
181
+ # @param steps [Integer]
182
+ # @param method [Symbol] :euler or :heun
183
+ # @param hutchinson [Boolean] estimate the divergence instead of computing it
184
+ # @param power [Numeric] how much the steps crowd near the data (1: uniform)
185
+ # @return [Tensor] [N]
186
+ def log_prob(x, steps: 100, method: :heun, hutchinson: false, power: 3)
187
+ x = as_tensor(x).detach
188
+ n = x.shape[0]
189
+ # Hutchinson's probe vectors, one per sample, kept for the whole ODE
190
+ probe = Maurograd.randn_like(x) if hutchinson
191
+ # the time grid, from 1 down to 0, crowded near 1
192
+ times = Array.new(steps + 1) { |i| 1.0 - (i.to_f / steps)**power }
193
+ # the running integral of the divergence, one per sample
194
+ total = Tensor.new(x.backend.zeros([n]), backend: x.backend)
195
+ steps.times do |i|
196
+ t = times[i]
197
+ # a negative step: we go backward in time
198
+ h = times[i + 1] - t
199
+ # the velocity and its divergence at the current point
200
+ v1, div1 = field_and_divergence(x, t, probe)
201
+ if method == :euler
202
+ # one Euler step, for x and for the integral alike
203
+ x += v1 * h
204
+ total += div1 * h
205
+ else
206
+ # Heun: also evaluate at the Euler step's end, and average the two
207
+ v2, div2 = field_and_divergence(x + v1 * h, t + h, probe)
208
+ x += (v1 + v2) * (h / 2)
209
+ total += (div1 + div2) * (h / 2)
210
+ end
211
+ x.backend.eval([x.data, total.data])
212
+ end
213
+ # total is the integral from 1 down to 0, the negative of the one
214
+ # from 0 to 1.
215
+ Distributions::StandardNormal.new(*@shape).log_prob(x) + total
216
+ end
217
+
218
+ private
219
+
220
+ def integrate(x, from, to, steps, method, every)
221
+ raise ArgumentError, "method must be one of #{METHODS.inspect}, got #{method.inspect}" unless METHODS.include?(method)
222
+ raise ArgumentError, "steps must be positive, got #{steps.inspect}" unless steps.is_a?(Integer) && steps.positive?
223
+
224
+ Maurograd.no_grad do
225
+ # equal steps from `from` to `to` (negative when going backward)
226
+ h = (to - from) / steps
227
+ states = [x]
228
+ steps.times do |i|
229
+ t = from + h * i
230
+ # the velocity at the current point
231
+ v = velocity(x, t)
232
+ x = if method == :euler
233
+ # Euler: follow it for one step
234
+ x + v * h
235
+ else
236
+ # Heun: average it with the velocity at the Euler step's end
237
+ (x + (v + velocity(x + v * h, t + h)) * (h / 2))
238
+ end
239
+ x.backend.eval([x.data])
240
+ states << x if every && ((i + 1) % every).zero?
241
+ end
242
+ every ? [x, states] : x
243
+ end
244
+ end
245
+
246
+ # v(x, t) and its divergence for each sample, both detached, with the
247
+ # parameters' gradients left as they were.
248
+ def field_and_divergence(x, t, probe)
249
+ # backward passes also fill the parameters' gradients: save them
250
+ saved = parameters.map(&:grad)
251
+ n = x.shape[0]
252
+ # the number of dimensions of one sample
253
+ flat = x.size / n
254
+ divergence =
255
+ if probe
256
+ # a copy of x that records the graph, so we can differentiate in x
257
+ input = Tensor.new(x.data, requires_grad: true, backend: x.backend)
258
+ v = velocity(input, t)
259
+ # backward with the probe e gives e^T (dv/dx) in input.grad
260
+ v.backward(probe.data)
261
+ # times e again, summed: e^T (dv/dx) e, whose mean is the trace
262
+ Distributions.sum_per_sample(Tensor.new(input.grad, backend: x.backend) * probe)
263
+ else
264
+ # the exact trace, one diagonal entry dv_i/dx_i per backward pass
265
+ columns = Array.new(flat) do |i|
266
+ input = Tensor.new(x.data, requires_grad: true, backend: x.backend)
267
+ out = velocity(input, t)
268
+ # a one-hot vector picks output i for every sample
269
+ basis = ::Numo::SFloat.zeros(n, flat)
270
+ basis[true, i] = 1
271
+ out.backward(x.backend.from(basis.reshape(*x.shape)))
272
+ # row i of the Jacobian; keep its entry i, dv_i/dx_i
273
+ Tensor.new(input.grad, backend: x.backend).reshape(n, flat).slice(1, i...(i + 1))
274
+ end
275
+ # the trace: the sum of the diagonal entries
276
+ Maurograd.concat(columns, axis: 1).sum(axis: 1)
277
+ end
278
+ # the velocity itself, without a graph
279
+ v = Maurograd.no_grad { velocity(x, t) }
280
+ # put the parameters' gradients back as they were
281
+ parameters.zip(saved).each { |p, g| p.grad = g }
282
+ [v, divergence.detach]
283
+ end
284
+
285
+ # t as an SFloat vector of n times.
286
+ def times(t, n)
287
+ t = t.to_numo if t.is_a?(Tensor)
288
+ t = t.is_a?(Numeric) ? ::Numo::SFloat.new(n).fill(t) : ::Numo::SFloat.cast(t)
289
+ raise ArgumentError, "expected #{n} times, got #{t.size}" unless t.size == n
290
+
291
+ t
292
+ end
293
+
294
+ def per_sample(values, x)
295
+ Tensor.new(::Numo::SFloat.cast(values).reshape(x.shape[0], *([1] * (x.ndim - 1))), backend: x.backend)
296
+ end
297
+
298
+ def parameter_backend = parameters.first&.backend || Maurograd.backend
299
+
300
+ def as_tensor(x) = x.is_a?(Tensor) ? x : Tensor.new(::Numo::SFloat.cast(x), backend: parameter_backend)
301
+ end
302
+ end
303
+ end