|
| 1 | +```@setup advi |
| 2 | +using Bijectors |
| 3 | +``` |
| 4 | + |
| 5 | +## Univariate ADVI example |
| 6 | +But the real utility of `TransformedDistribution` becomes more apparent when using `transformed(dist, b)` for any bijector `b`. To get the transformed distribution corresponding to the `Beta(2, 2)`, we called `transformed(dist)` before. This is simply an alias for `transformed(dist, bijector(dist))`. Remember `bijector(dist)` returns the constrained-to-constrained bijector for that particular `Distribution`. But we can of course construct a `TransformedDistribution` using different bijectors with the same `dist`. This is particularly useful in something called _Automatic Differentiation Variational Inference (ADVI)_.[2] An important part of ADVI is to approximate a constrained distribution, e.g. `Beta`, as follows: |
| 7 | +1. Sample `x` from a `Normal` with parameters `μ` and `σ`, i.e. `x ~ Normal(μ, σ)`. |
| 8 | +2. Transform `x` to `y` s.t. `y ∈ support(Beta)`, with the transform being a differentiable bijection with a differentiable inverse (a "bijector") |
| 9 | + |
| 10 | +This then defines a probability density with same _support_ as `Beta`! Of course, it's unlikely that it will be the same density, but it's an _approximation_. Creating such a distribution becomes trivial with `Bijector` and `TransformedDistribution`: |
| 11 | + |
| 12 | +```@repl advi |
| 13 | +using StableRNGs: StableRNG |
| 14 | +rng = StableRNG(42); |
| 15 | +dist = Beta(2, 2) |
| 16 | +b = bijector(dist) # (0, 1) → ℝ |
| 17 | +b⁻¹ = inverse(b) # ℝ → (0, 1) |
| 18 | +td = transformed(Normal(), b⁻¹) # x ∼ 𝓝(0, 1) then b(x) ∈ (0, 1) |
| 19 | + x = rand(rng, td) # ∈ (0, 1) |
| 20 | +``` |
| 21 | + |
| 22 | +It's worth noting that `support(Beta)` is the _closed_ interval `[0, 1]`, while the constrained-to-unconstrained bijection, `Logit` in this case, is only well-defined as a map `(0, 1) → ℝ` for the _open_ interval `(0, 1)`. This is of course not an implementation detail. `ℝ` is itself open, thus no continuous bijection exists from a _closed_ interval to `ℝ`. But since the boundaries of a closed interval has what's known as measure zero, this doesn't end up affecting the resulting density with support on the entire real line. In practice, this means that |
| 23 | + |
| 24 | +```@repl advi |
| 25 | +td = transformed(Beta()) |
| 26 | +inverse(td.transform)(rand(rng, td)) |
| 27 | +``` |
| 28 | + |
| 29 | +will never result in `0` or `1` though any sample arbitrarily close to either `0` or `1` is possible. _Disclaimer: numerical accuracy is limited, so you might still see `0` and `1` if you're lucky._ |
| 30 | + |
| 31 | +## Multivariate ADVI example |
| 32 | +We can also do _multivariate_ ADVI using the `Stacked` bijector. `Stacked` gives us a way to combine univariate and/or multivariate bijectors into a singe multivariate bijector. Say you have a vector `x` of length 2 and you want to transform the first entry using `Exp` and the second entry using `Log`. `Stacked` gives you an easy and efficient way of representing such a bijector. |
| 33 | + |
| 34 | +```@repl advi |
| 35 | +using Bijectors: SimplexBijector |
| 36 | +
|
| 37 | +# Original distributions |
| 38 | +dists = ( |
| 39 | + Beta(), |
| 40 | + InverseGamma(), |
| 41 | + Dirichlet(2, 3) |
| 42 | +); |
| 43 | +
|
| 44 | +# Construct the corresponding ranges |
| 45 | +ranges = []; |
| 46 | +idx = 1; |
| 47 | +
|
| 48 | +for i = 1:length(dists) |
| 49 | + d = dists[i] |
| 50 | + push!(ranges, idx:idx + length(d) - 1) |
| 51 | +
|
| 52 | + global idx |
| 53 | + idx += length(d) |
| 54 | +end; |
| 55 | +
|
| 56 | +ranges |
| 57 | +
|
| 58 | +# Base distribution; mean-field normal |
| 59 | +num_params = ranges[end][end] |
| 60 | +
|
| 61 | +d = MvNormal(zeros(num_params), ones(num_params)); |
| 62 | +
|
| 63 | +# Construct the transform |
| 64 | +bs = bijector.(dists); # constrained-to-unconstrained bijectors for dists |
| 65 | +ibs = inverse.(bs); # invert, so we get unconstrained-to-constrained |
| 66 | +sb = Stacked(ibs, ranges) # => Stacked <: Bijector |
| 67 | +
|
| 68 | +# Mean-field normal with unconstrained-to-constrained stacked bijector |
| 69 | +td = transformed(d, sb); |
| 70 | +y = rand(td) |
| 71 | +0.0 ≤ y[1] ≤ 1.0 |
| 72 | +0.0 < y[2] |
| 73 | +sum(y[3:4]) ≈ 1.0 |
| 74 | +``` |
| 75 | + |
| 76 | +## Normalizing flows |
| 77 | +A very interesting application is that of _normalizing flows_.[1] Usually this is done by sampling from a multivariate normal distribution, and then transforming this to a target distribution using invertible neural networks. Currently there are two such transforms available in Bijectors.jl: `PlanarLayer` and `RadialLayer`. Let's create a flow with a single `PlanarLayer`: |
| 78 | + |
| 79 | +```@setup normalizing-flows |
| 80 | +using Bijectors |
| 81 | +using StableRNGs: StableRNG |
| 82 | +rng = StableRNG(42); |
| 83 | +``` |
| 84 | + |
| 85 | +```@repl normalizing-flows |
| 86 | +d = MvNormal(zeros(2), ones(2)); |
| 87 | +b = PlanarLayer(2) |
| 88 | +flow = transformed(d, b) |
| 89 | +flow isa MultivariateDistribution |
| 90 | +``` |
| 91 | + |
| 92 | +That's it. Now we can sample from it using `rand` and compute the `logpdf`, like any other `Distribution`. |
| 93 | + |
| 94 | +```@repl normalizing-flows |
| 95 | +y = rand(rng, flow) |
| 96 | +logpdf(flow, y) # uses inverse of `b` |
| 97 | +``` |
| 98 | + |
| 99 | +Similarily to the multivariate ADVI example, we could use `Stacked` to get a _bounded_ flow: |
| 100 | + |
| 101 | +```@repl normalizing-flows |
| 102 | +d = MvNormal(zeros(2), ones(2)); |
| 103 | +ibs = inverse.(bijector.((InverseGamma(2, 3), Beta()))); |
| 104 | +sb = stack(ibs...) # == Stacked(ibs) == Stacked(ibs, [i:i for i = 1:length(ibs)] |
| 105 | +b = sb ∘ PlanarLayer(2) |
| 106 | +td = transformed(d, b); |
| 107 | +y = rand(rng, td) |
| 108 | +0 < y[1] |
| 109 | +0 ≤ y[2] ≤ 1 |
| 110 | +``` |
| 111 | + |
| 112 | +Want to fit the flow? |
| 113 | + |
| 114 | +```@repl normalizing-flows |
| 115 | +using Zygote |
| 116 | +
|
| 117 | +# Construct the flow. |
| 118 | +b = PlanarLayer(2) |
| 119 | +
|
| 120 | +# Convenient for extracting parameters and reconstructing the flow. |
| 121 | +using Functors |
| 122 | +θs, reconstruct = Functors.functor(b); |
| 123 | +
|
| 124 | +# Make the objective a `struct` to avoid capturing global variables. |
| 125 | +struct NLLObjective{R,D,T} |
| 126 | + reconstruct::R |
| 127 | + basedist::D |
| 128 | + data::T |
| 129 | +end |
| 130 | +
|
| 131 | +function (obj::NLLObjective)(θs...) |
| 132 | + transformed_dist = transformed(obj.basedist, obj.reconstruct(θs)) |
| 133 | + return -sum(Base.Fix1(logpdf, transformed_dist), eachcol(obj.data)) |
| 134 | +end |
| 135 | +
|
| 136 | +# Some random data to estimate the density of. |
| 137 | +xs = randn(2, 1000); |
| 138 | +
|
| 139 | +# Construct the objective. |
| 140 | +f = NLLObjective(reconstruct, MvNormal(2, 1), xs); |
| 141 | +
|
| 142 | +# Initial loss. |
| 143 | +@info "Initial loss: $(f(θs...))" |
| 144 | +
|
| 145 | +# Train using gradient descent. |
| 146 | +ε = 1e-3; |
| 147 | +for i = 1:100 |
| 148 | + ∇s = Zygote.gradient(f, θs...) |
| 149 | + θs = map(θs, ∇s) do θ, ∇ |
| 150 | + θ - ε .* ∇ |
| 151 | + end |
| 152 | +end |
| 153 | +
|
| 154 | +# Final loss |
| 155 | +@info "Finall loss: $(f(θs...))" |
| 156 | +
|
| 157 | +# Very simple check to see if we learned something useful. |
| 158 | +samples = rand(transformed(f.basedist, f.reconstruct(θs)), 1000); |
| 159 | +mean(eachcol(samples)) # ≈ [0, 0] |
| 160 | +cov(samples; dims=2) # ≈ I |
| 161 | +``` |
| 162 | + |
| 163 | +We can easily create more complex flows by simply doing `PlanarLayer(10) ∘ PlanarLayer(10) ∘ RadialLayer(10)` and so on. |
0 commit comments