Plaice
Plaice.jl converts samples from distributions to and from vectors.
It assumes that there are three forms of samples from a distribution d that we are interested in:
The original form, which is what
rand(d)returns.A vectorised form, which is a vector that contains a flattened version of the original form.
A unconstrained vectorised form, which is a vector in which:
- each element is independent; and
- each element is unconstrained (can take any value in ℝ).
Note that because of the independence requirement, the unconstrained vectorised form may have a different dimension to the vectorised form. For example, when sampling from a Dirichlet distribution, the original form is a vector that always sums to 1. The unconstrained vectorised form will have one element less than the original form, because this constraint is eliminated.
Plaice.jl provides functionality to convert between these three forms, via subtypes of Plaice.AbstractBijector. Assuming that x = rand(d) for some distribution d:
to_vec(d)is anAbstractBijectorwhich convertsxto the vectorised formfrom_vec(d)is the inverse ofto_vec(d), also anAbstractBijectorvec_length(d)returns the length ofto_vec(d)(x)optic_vec(d)returns a vector of optics that describes how each element ofto_vec(d)(x)is accessed fromxto_unconstrained_vec(d)is anAbstractBijectorwhich convertsxto the unconstrained vectorised formfrom_unconstrained_vec(d)is the inverse ofto_unconstrained_vec(d), also anAbstractBijectorunconstrained_vec_length(d)returns the length ofto_unconstrained_vec(d)(x)unconstrained_optic_vec(d)returns a vector of optics that describes how each element ofto_unconstrained_vec(d)(x)is accessed fromx(if possible)
For example:
julia> using Plaice, Distributionsjulia> d = Beta(2, 2); x = rand(d); # x is between 0 and 10.5602086057097567julia> to_vec(d)(x)1-element Vector{Float64}: 0.5602086057097567julia> to_unconstrained_vec(d)(x)1-element Vector{Float64}: 0.24200871395677753Subtypes of AbstractBijector must minimally implement ChangesOfVariables.with_logabsdet_jacobian as well as InverseFunctions.inverse. This is tested for all of Plaice's own bijectors. By defining with_logabsdet_jacobian, you can also get default definitions for (b::AbstractBijector)(x) and logabsdet_jacobian(b, x).
Plaice.logabsdet_jacobian — Function
logabsdet_jacobian(b::AbstractBijector, x)Return the log absolute determinant of the Jacobian of the bijector b at x.
By default, this returns last(with_logabsdet_jacobian(b, x)), but subtypes of AbstractBijector may provide specialised implementations for efficiency.
Implementing your own vector bijector
The full Plaice interface consists of the following functions:
Plaice.AbstractBijector — Type
AbstractBijectorAn abstract type for bijective transforms.
Subtypes must implement two methods:
with_logabsdet_jacobian, which should return a tuple of (transformed value, log absolute determinant Jacobian) when called with a value to transform.inverse, which should return anotherAbstractBijectorthat represents the inverse transformation.
The methods
(b::AbstractBijector)(x), to return just the transformed value, andlogabsdet_jacobian(b::AbstractBijector, x), to return just the log-Jacobian,
are then automatically derived for subtypes of AbstractBijector by simply returning either component of with_logabsdet_jacobian's result. However, custom implementations of those methods may be provided for efficiency reasons if desired.
Plaice.from_vec — Function
Plaice.from_vec(dist)Returns a function that can be used to convert a vectorised sample from d back to its original form.
from_vec(d) is the inverse of to_vec(d).
Examples
julia> using Plaice: from_vec; using Distributionsjulia> d = Beta(2, 2); from_vec(d)([0.5])0.5julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); from_vec(d)([0.2, 0.5])(a = 0.2, b = 0.5)Plaice.to_vec — Function
Plaice.to_vec(dist)Returns a function that can be used to vectorise a sample from d.
to_vec(d) is the inverse of from_vec(d).
Examples
julia> using Plaice: to_vec; using Distributionsjulia> d = Beta(2, 2); to_vec(d)(0.5)1-element Vector{Float64}: 0.5julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); to_vec(d)((a = 0.2, b = 0.5))2-element Vector{Float64}: 0.2 0.5Plaice.from_unconstrained_vec — Function
Plaice.from_unconstrained_vec(dist)Returns a function that can be used to convert an unconstrained vector back to a sample from d.
from_unconstrained_vec(d) is the inverse of to_unconstrained_vec(d).
Examples
julia> using Plaice: from_unconstrained_vec; using Distributions, Plaicejulia> d = Beta(2, 2); from_unconstrained_vec(d)([1.0])0.7310585786300049julia> f = from_unconstrained_vec(d); with_logabsdet_jacobian(f, [1.0])(0.7310585786300049, -1.6265233750364456)julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); from_unconstrained_vec(d)([0.2, 1.0])(a = 0.2, b = 0.7310585786300049)julia> f = from_unconstrained_vec(d); with_logabsdet_jacobian(f, [0.2, 1.0])((a = 0.2, b = 0.7310585786300049), -1.6265233750364456)Plaice.to_unconstrained_vec — Function
Plaice.to_unconstrained_vec(dist)Returns a function that can be used to convert a sample from d to an unconstrained vector.
to_unconstrained_vec(d) is the inverse of from_unconstrained_vec(d).
Examples
julia> using Plaice: to_unconstrained_vec; using Distributions, Plaicejulia> d = Beta(2, 2); to_unconstrained_vec(d)(0.5)1-element Vector{Float64}: 0.0julia> f = to_unconstrained_vec(d); with_logabsdet_jacobian(f, 0.5)([0.0], 1.3862943611198906)julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); to_unconstrained_vec(d)((a = 0.2, b = 0.5))2-element Vector{Float64}: 0.2 0.0julia> f = to_unconstrained_vec(d); with_logabsdet_jacobian(f, (a = 0.2, b = 0.5))([0.2, 0.0], 1.3862943611198906)Plaice.vec_length — Function
Plaice.vec_length(dist)Returns the length of the vector representation of a sample from d, i.e., length(to_vec(d)(rand(d))). However, it does this without actually drawing a sample.
Examples
julia> using Plaice: vec_length; using Distributionsjulia> d = Beta(2, 2); vec_length(d)1julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); vec_length(d)2Plaice.unconstrained_vec_length — Function
Plaice.unconstrained_vec_length(dist)Returns the length of the unconstrained vector representation of a sample from d, i.e., length(to_unconstrained_vec(d)(rand(d))). However, it does this without actually drawing a sample.
Examples
julia> using Plaice: unconstrained_vec_length; using Distributionsjulia> d = Beta(2, 2); unconstrained_vec_length(d)1julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); unconstrained_vec_length(d)2Plaice.optic_vec — Function
Plaice.optic_vec(dist)Returns a vector of optics (from VarNames.jl), which describe how each element in the vectorised sample from d can be accessed from the original sample.
For example, if d = MvNormal(zeros(3), I), then optic_vec(d) would return a vector of [@opticof(_[1]), @opticof(_[2]), @opticof(_[3])]. The length of this vector would be equal to vec_length(d).
If optics = optic_vec(d), then for any sample x ~ d and its vectorised form v = to_vec(d)(x), it should hold that v[i] == optics[i](x) for all i.
Examples
For the Beta case, the return value of an empty optic indicates that 'the first element of the vector is the sample itself'.
For the product_distribution case, the return value of Optic(.a) indicates that 'the first element of the vector is the .a component of the sample', and similarly for Optic(.b).
julia> using Plaice: optic_vec; using Distributionsjulia> d = Beta(2, 2); optic_vec(d)1-element Vector{VarNames.Iden}: Optic()julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); optic_vec(d)2-element Vector{VarNames.Property{_A, VarNames.Iden} where _A}: Optic(.a) Optic(.b)Plaice.unconstrained_optic_vec — Function
Plaice.unconstrained_optic_vec(dist)Returns a vector of optics (from VarNames.jl), which describe how each element in the unconstrained vector representation of a sample from d is related to the original sample.
This is not always well-defined. For example, consider a Dirichlet distribution, with three components. The unconstrained vector representation would have two elements. However, these two elements do not correspond to specific components of the original sample, since all three components are interdependent (they must sum to one). In such cases, this function should return a vector of two nothings.
However, for a distribution like MvNormal, this function would return a vector of [@opticof(_[1]), @opticof(_[2]), @opticof(_[3])], similar to optic_vec. That is because the first element of the unconstrained vector is solely determined by the first component of the original sample, the second element by the second component, and so on.
Note that, unlike optic_vec, the first element of the unconstrained vector does not necessarily have to be exactly equal to the first component of the original sample, as there may have been a transformation applied. It merely needs to be determined by the first component (and only the first component).
Examples
In this case since linking does not affect the 'provenance' of the sample (i.e., for the product distribution the first element of the unconstrained vector is still determined by .a and the second by .b), the return value of unconstrained_optic_vec is the same as that of optic_vec.
julia> using Plaice: unconstrained_optic_vec; using Distributionsjulia> d = Beta(2, 2); unconstrained_optic_vec(d)1-element Vector{VarNames.Iden}: Optic()julia> d = product_distribution((a = Normal(), b = Beta(2, 2))); unconstrained_optic_vec(d)2-element Vector{VarNames.Property{_A, VarNames.Iden} where _A}: Optic(.a) Optic(.b)In practice, if your distribution is a univariate distribution, you will probably only need to implement scalar_to_scalar_bijector (see below).
For multivariate and matrix distributions, there are default implementations of the non-unconstrained versions (i.e., from_vec, to_vec, vec_length, and optic_vec) which should already be optimal. However you will have to define the unconstrained versions (see the examples page for more info).
If you have a very customised distribution, you will likely have to implement all the functions yourself.
Known constant bijectors
Additionally, if your distribution is likely to be used in part of a product distribution, it can lead to substantial performance improvements to overload has_constant_vec_bijector to return true (but make sure to only do this if the bijector is genuinely constant!):
Plaice.has_constant_vec_bijector — Function
Plaice.has_constant_vec_bijector(::Type{T}) where {T}Return true if the vector bijector for each element of a collection of distributions is determined solely by the type of the distribution, and not by any runtime parameter values.
This is slightly confusing, so is best explained by example. Consider
d = product_distribution(array_of_dists)If it can be inferred from typeof(array_of_dists) that each distribution inside array_of_dists has the same vector bijector, then has_constant_vec_bijector(typeof(array_of_dists)) should return true.
For example, if array_of_dists is a FillArrays.Fill of some distribution type, then we know that each distribution inside is necessarily the same, and so they all have the same vector bijector. Thus, we have that
has_constant_vec_bijector(::Type{<:FillArrays.Fill}) == trueFor generic AbstractArrays or Tuples, this function will recursively call itself on the element type of the array. That means that if a dist::D (where D<:Distribution) has a constant vector bijector, we can simply mark has_constant_vec_bijector(::Type{D}) == true, and that will automatically propagate to arrays of that distribution type.
For example, Beta has a constant vector bijector, because its support is always between 0 and 1, regardless of its parameters, and thus we can wite
has_constant_vec_bijector(::Type{<:Distributions.Beta}) == trueOn the other hand, Uniform does not have a constant vector bijector, because its support depends on its parameters. So, it would be inappropriate (and can lead to wrong results) if we were to write has_constant_vec_bijector(::Type{<:Distributions.Uniform}) == true.
distribution, and not the actual value. This is necessary in order to guarantee type stability.
Product bijector building blocks
Use these constructors when implementing vector bijectors for product distributions.
Plaice.ProductVecTransform — Type
ProductVecTransform(transforms, ranges, base_size)Combine component vectorisation bijectors into one bijector. transforms and ranges have matching tuple, array, or named-tuple structures. For tuple and array products, base_size is the original size of each component, and ranges selects each component's coordinates in the output vector. Ranges must partition the output vector without gaps or overlaps and match the component output lengths. For named tuples, ranges follow field order and base_size is unused.
For repeated components, pass Elementwise(bijector, dims) as transforms and nothing as ranges. Input dimensions are (base_size..., dims...), with components in column-major order. Empty multivariate products are not supported. For scalar components (base_size == ()), the repeated bijector must map scalars to scalars, as provided by scalar_to_scalar_bijector.
Use inverse for the inverse bijector and with_logabsdet_jacobian to transform values and sum the component log-Jacobians.
Plaice.Elementwise — Type
Elementwise(value, size::Dims)Similar in principle to a FillArrays.Fill: this represents an array of size size where all entries are value. However, this does not subtype AbstractArray.
This is used to represent the vector bijector for homogeneous product distributions, where the same transform is applied to each component. By using a Elementwise, we can compute the transform once and reuse it, rather than computing it separately for each component.
Univariate distributions
For univariate distributions the default definition is to generate a bijector that inspects the minimum and maximum of the distribution. While this will work correctly, it might not be the most performant. You can manually define the Plaice API for univariate distributions, but it is probably faster to just overload the single function scalar_to_scalar_bijector: everything else will be automatically dervied.
Plaice.scalar_to_scalar_bijector — Function
Plaice.scalar_to_scalar_bijector(dist)The Plaice interface is intended to map samples to vectors. However, for univariate distributions, the 'vectorisation' part of this is trivial (we only need to convert a scalar to a vector of length one, and vice versa). Therefore, this function is provided to allow users to specify the 'interesting' part of the transformation, which is the function that maps values to unconstrained space.
Overloading this function for a univariate distribution is sufficient to implement the entire Plaice interface for that distribution.
There are three scalar-to-scalar bijectors that are exported, which should be enough for any univariate distribution:
If you need a different scalar-to-scalar bijector, please open an issue.
Univariate distributions tend to fall into one of the following categories:
Plaice.TypedIdentity — Type
TypedIdentity <: ScalarToScalarBijectorThe same as identity.
This is the appropriate scalar-to-scalar bijector for univariate distributions which have support over the entire real line. However, note that this can also be used in other contexts apart from univariate distributions. For example, TypedIdentity() is the correct implementation of to_vec and from_vec for MvNormal distributions.
The problem with using identity as a bijector is that ChangesOfVariables.jl defines with_logabsdet_jacobian(identity, x) = (x, zero(eltype(x))), which can fail if eltype(x) is not a number type! Implementing this allows us to shortcircuit that definition and return a sensible result (i.e. a Bool) even if x is not a numeric vector. Note that we intentionally do not return 0.0::Float64 in such cases as that can cause unwanted promotion.
Plaice.Log — Type
Log(bound, sign) <: ScalarToScalarBijector
Callable struct, defined such that (l::Log)(x) = log(l.sign * (x - l.bound)). The sign is determined by the sign field.
This is the appropriate scalar-to-scalar bijector for univariate distributions which have a support of [l.bound, ∞) (if l.sign == 1), or (-∞, l.bound] (if l.sign == -1).
Plaice.Untruncate — Type
Untruncate(a, b) <: ScalarToScalarBijector
Callable struct, defined such that (::Untruncate(a, b))(x) maps a scalar x from (a, b) to (-Inf, Inf).
This is the appropriate scalar-to-scalar bijector for distributions which have support over (a, b).
Testing
Because the scope of a vector bijector is very well-defined, there is a well-established testing framework to verify correctness of an implementation (Plaice.test_all()), which you can use in the test suite. This function contains additional keyword arguments to control the exact testing procedure. For example, you can test that the transformations do not cause extra allocations, should you know this to be the case for your bijector (note that this is not always possible).
For more information about generally testing bijectors (and in particular how to test Jacobians for transformations that modify the number of dimensions), see the examples page.
One of the most tricky parts of testing Plaice is ensuring that the transforms are compatible with automatic differentiation. This is important for DynamicPPL: we need to be able to compute the gradient of the log-density with respect to (possibly transformed) parameters, which may include the log-abs-det-Jacobian of the transformation. The default AD backends tested are ForwardDiff, ReverseDiff, Mooncake, and Enzyme. It is acceptable to skip tests for a particular backend if there are genuine upstream bugs, especially with ReverseDiff, which is not actively maintained. However where possible it is best to ensure that all backends are supported, and to use @test_broken to mark any known issues with specific backends.