Expectations
Inference algorithms often need the expectation $\mathbb{E}_q[f]$ of a function f under a distribution q. BayesBase defines a protocol for computing it, BayesBase.expectation(backend, f, q), where the backend argument selects the method: a closed form, a quadrature rule or a sampler, for example. Backends are defined in other packages, such as ExpectationApproximations.jl. An algorithm written against the protocol works with every backend that supports its distributions, and the user of the algorithm chooses the method.
The design is similar to DifferentiationInterface.jl, which has a backend argument that selects the differentiation package and prepare_* functions whose result is reused by later calls. Here, BayesBase.prepare_expectation(backend, q) does the work that depends only on q, such as computing quadrature nodes and weights, and its result is reused for many integrands.
The names of the protocol are public but not exported. Call them qualified, as BayesBase.expectation.
using BayesBase, Distributions
backend = SomeBackend() # from a backend package
BayesBase.expectation(backend, x -> x^2, Normal(0.0, 1.0))
prepared = BayesBase.prepare_expectation(backend, Normal(0.0, 1.0))
BayesBase.expectation(prepared, x -> x^2) # many integrands, nodes computed onceComputing expectations
expectation(backend, f, q) returns the expectation, or throws a BayesBase.UnsupportedExpectationError when backend cannot compute it. For several integrands under the same q, call prepare_expectation(backend, q) once and then expectation(prepared, f) for each integrand.
A backend implements one of two things for the distributions it supports. A closed form is a method of expectation for specific types of f and q, such as expectation(::MyBackend, ::typeof(log), q::Gamma). A preparation is a method of prepare_expectation for specific types of q. It returns an object with its own method expectation(prepared, f), which works for any integrand, including integrands whose values are dual numbers. Most numerical backends return a BayesBase.ExpectationPointSet, a weighted sum over points.
Backends define these methods for specific families of distributions, not for all q. Products of distributions and routers rely on this.
BayesBase.expectation — Function
expectation(backend, f, q)The expectation E_q[f] of the integrand f under the distribution q, computed by backend.
A backend with a closed form adds a method for the specific types of f and q it covers. A numerical backend adds a method of prepare_expectation for the types of q it supports instead, and the fallback method computes expectation(prepare_expectation(backend, q), f). When the backend has neither, the fallback throws an UnsupportedExpectationError.
expectation(prepared, f)The expectation of f from an object returned by prepare_expectation.
BayesBase.prepare_expectation — Function
prepare_expectation(backend, q)Do the work for expectations under q that does not depend on the integrand, such as computing nodes and weights, and return an object prepared. Then expectation(prepared, f) computes the expectation of any f, including integrands whose values are dual numbers.
The default returns a PreparedExpectation, which forwards every call to the backend.
BayesBase.PreparedExpectation — Type
PreparedExpectation(backend, q)The default result of prepare_expectation: no work is done in advance, and expectation(prepared, f) calls expectation(backend, f, q).
BayesBase.UnsupportedExpectationError — Type
UnsupportedExpectationError(backend, f, q)Thrown when backend cannot compute the expectation of f under q.
What a backend supports
A backend declares the pairs it supports with methods of BayesBase.supports_expectation. These methods take the types of f and q, so the compiler knows the answer. The integrand type Any means every integrand, which is what a numerical method declares:
BayesBase.supports_expectation(::MyQuadrature, ::Type, ::Type{<:Normal}) = true # any f
BayesBase.supports_expectation(::MyClosedForms, ::Type{typeof(log)}, ::Type{<:Gamma}) = trueFor the expectation of a log-density, E_q[log p(x)], the integrand is Base.Fix1(logpdf, p), which is Julia's callable for x -> logpdf(p, x). A backend with a closed form declares and implements it by dispatch on that type:
BayesBase.supports_expectation(::MyClosedForms, ::Type{<:Base.Fix1{typeof(logpdf), <:Normal}}, ::Type{<:Normal}) = true
BayesBase.expectation(::MyClosedForms, f::Base.Fix1{typeof(logpdf), <:Normal}, q::Normal) = …A backend with many closed forms writes each one together with its declaration through BayesBase.@supports_expectation. The macro defines the method and the method of supports_expectation for the same argument types, so a closed form cannot be added without being declared. The method always extends BayesBase.expectation, also when it is written expectation in a module that has not imported that name:
import BayesBase: @supports_expectation
@supports_expectation function BayesBase.expectation(::MyClosedForms, ::typeof(log), q::Gamma)
α, θ = params(q)
return digamma(α) + log(θ)
endSupport that depends on more than the types of one method is still declared with a method of supports_expectation, written out.
BayesBase.supports_expectation — Function
supports_expectation(backend, F::Type, Q::Type)
supports_expectation(backend, f, q)Whether backend computes expectations of integrands of type F under distributions of type Q. Backends add methods to the type form, which is false by default. F = Any asks whether every integrand is supported. A numerical method supports every integrand and declares it with supports_expectation(::MyBackend, ::Type, ::Type{<:MyFamily}) = true.
BayesBase.which_expectation_backend — Function
which_expectation_backend(backend, F::Type, Q::Type)
which_expectation_backend(backend, f, q)The backend that computes the expectation, or nothing if there is none. A router returns the backend it chooses, or itself for a product of distributions. Any other backend returns itself if it supports the pair.
BayesBase.@supports_expectation — Macro
@supports_expectation function BayesBase.expectation(backend::B, f::F, q::Q) where {…}
…
endDefine a closed form of BayesBase.expectation and declare that the backend supports it. Besides the method itself, the macro defines
BayesBase.supports_expectation(::B, ::Type{<:F}, ::Type{<:Q}) where {…} = truewith the types and the where parameters of the definition. An argument without a type means Any. An integrand without a type therefore declares every integrand, as a numerical backend does, see BayesBase.supports_expectation. The definition can be in long or short form, and a docstring placed before the macro documents the method. Only methods of expectation with three positional arguments are accepted. Keyword arguments and default values are not. The method always extends BayesBase's function: a bare expectation is read as BayesBase.expectation, even where the name is not imported, and a function of another module is rejected.
Support that depends on more than the types of one method, such as "wherever another backend has a closed form", is declared with a method of supports_expectation written out instead.
The macro is public but not exported: write BayesBase.@supports_expectation, or import it with import BayesBase: @supports_expectation.
julia> using Distributions
julia> struct Moments end
julia> BayesBase.@supports_expectation function BayesBase.expectation(::Moments, ::typeof(identity), q::Gamma)
α, θ = params(q)
return α * θ
end
julia> BayesBase.supports_expectation(Moments(), identity, Gamma(2.0, 1.0))
true
julia> BayesBase.supports_expectation(Moments(), identity, Normal(0.0, 1.0))
false
julia> BayesBase.expectation(Moments(), identity, Gamma(2.0, 3.0))
6.0Gradients of expectations
BayesBase.expectation_gradient(backend, f, q) is the gradient of $\mathbb{E}_{q_\theta}[f]$ with respect to the parameters $\theta$ of q. Natural-gradient and score-function methods, for example, need it. The parametrization is the one the type of q defines: params(q) for a distribution of Distributions.jl, so (μ, σ) for a Normal, and the natural parameters for an ExponentialFamilyDistribution of ExponentialFamily.jl.
The gradient is itself an expectation. When f and the support of q do not depend on $\theta$,
\[\nabla_\theta \mathbb{E}_{q_\theta}[f] = \mathbb{E}_{q}\left[f \, \nabla_\theta \log q\right],\]
so expectation_gradient(backend, f, q) computes the expectation of the integrand BayesBase.ExpectationScoreProduct(f, q), which is x -> f(x) * expectation_score(q, x). Everything above therefore applies to gradients unchanged:
- A backend with a closed form for a gradient defines a method of
expectationfor the type of that integrand, most simply withBayesBase.@supports_expectation_gradient, and declares its support the same way. - A numerical backend that supports every integrand under
qcomputes the gradient as the sum off(x) * expectation_score(q, x)over its points. It needsBayesBase.expectation_scorefor the type ofq, so it supports gradients only whereBayesBase.has_expectation_scoreholds. BayesBase has the score of the common univariate families and of products of them. A package that adds a score adds a method ofhas_expectation_scoretoo. - A router chooses a closed form for the gradient when one of its backends has it, and a numerical backend otherwise, wherever they are in its list. It passes over a numerical backend for a family without a score. Labels, preparations and products work as for expectations, and with a preparation for
qthe gradient isexpectation(prepared, ExpectationScoreProduct(f, q)). - The integrand
fmust return a scalar, which multiplies the score.
import BayesBase: @supports_expectation_gradient
@supports_expectation_gradient function BayesBase.expectation_gradient(::MyClosedForms, ::typeof(log), q::Gamma)
α, θ = params(q)
return [trigamma(α), 1 / θ] # with respect to the shape α and the scale θ
end
router = BayesBase.ExpectationFirstOf(MyClosedForms(), MyQuadrature())
BayesBase.expectation_gradient(router, log, Gamma(2.0, 1.0)) # the closed form
BayesBase.expectation_gradient(router, x -> x^2, Gamma(2.0, 1.0)) # quadrature of x² times the scoreBayesBase.expectation_gradient — Function
expectation_gradient(backend, f, q)The gradient of the expectation of f under q with respect to the parameters of q, $\nabla_\theta \mathbb{E}_{q_\theta}[f]$, computed by backend. The parametrization is that of BayesBase.expectation_score: params(q) for a distribution of Distributions.jl, and the natural parameters for an ExponentialFamilyDistribution.
The gradient equals $\mathbb{E}_q[f \, \nabla_\theta \log q]$, and it is computed as expectation(backend, ExpectationScoreProduct(f, q), q). Routers, labels and products therefore work for gradients as they do for expectations: a router chooses a backend with a closed form for the gradient when there is one, and otherwise a numerical backend that sums f(x) * expectation_score(q, x) over its points. Backends with closed forms define them with BayesBase.@supports_expectation_gradient.
The identity holds when f does not depend on θ and the support of q does not depend on θ, so it does not apply to the bounds of a Uniform, for example. The integrand f must return a scalar, which multiplies the score.
BayesBase.supports_expectation_gradient — Function
supports_expectation_gradient(backend, F::Type, Q::Type)
supports_expectation_gradient(backend, f, q)Whether backend computes the gradient of the expectation of integrands of type F under distributions of type Q, see BayesBase.expectation_gradient. Backends declare support with methods of BayesBase.supports_expectation for the integrand ExpectationScoreProduct{F, Q}, not with methods of this function.
A backend that supports every integrand under Q, such as a quadrature rule, computes gradients by summing f times the score, so it supports gradients only where BayesBase.has_expectation_score holds for Q. Routers apply the same rule, so they pass over such a backend for a family without a score and choose a backend with a closed form for the gradient instead.
BayesBase.ExpectationScoreProduct — Type
ExpectationScoreProduct(f, q)The integrand x -> f(x) * expectation_score(q, x), whose expectation under q is the gradient of the expectation of f with respect to the parameters of q, see BayesBase.expectation_gradient. A backend with a closed form for the gradient adds a method of expectation for this type, for example with BayesBase.@supports_expectation_gradient. A numerical backend evaluates it at its points like any other integrand, which needs BayesBase.expectation_score for q.
With a preparation for q, the gradient is expectation(prepared, ExpectationScoreProduct(f, q)).
BayesBase.expectation_score — Function
expectation_score(q, x)The score of q at x: the gradient of log q(x; θ) with respect to the parameters θ of q. The parametrization is the one the type of q defines: params(q) for a distribution of Distributions.jl, and the natural parameters for an ExponentialFamilyDistribution of ExponentialFamily.jl. BayesBase has methods for Normal, LogNormal, Gamma, Exponential, Beta and a FactorizedJoint of those, whose score concatenates the scores of its components at the tuple x. Packages add methods for the types they define.
The default throws an ArgumentError. A backend with a closed form for the gradient does not need the score.
julia> using Distributions
julia> BayesBase.expectation_score(Normal(1.0, 2.0), 4.0) # with respect to μ and σ
2-element StaticArraysCore.SVector{2, Float64} with indices SOneTo(2):
0.75
0.625BayesBase.has_expectation_score — Function
has_expectation_score(Q::Type)
has_expectation_score(q)Whether BayesBase.expectation_score has a method for distributions of type Q. It is false by default, true for the families with a score in BayesBase, and for a FactorizedJoint whose components all have one. A package that adds a method of expectation_score also adds a method of this function, which makes numerical backends compute gradients under its type, see BayesBase.supports_expectation_gradient.
julia> using Distributions
julia> BayesBase.has_expectation_score(Normal(0.0, 1.0))
true
julia> BayesBase.has_expectation_score(Categorical([0.5, 0.5]))
falseBayesBase.@supports_expectation_gradient — Macro
@supports_expectation_gradient function BayesBase.expectation_gradient(backend::B, f::F, q::Q) where {…}
…
endDefine a closed form of BayesBase.expectation_gradient and declare that the backend supports it. Besides the method itself, the macro defines the method that routers reach, which passes the integrand on to the closed form,
BayesBase.expectation(backend::B, product::ExpectationScoreProduct{<:F, <:Q}, q::Q) where {…} =
BayesBase.expectation_gradient(backend, product.f, q)and the declaration
BayesBase.supports_expectation(::B, ::Type{<:ExpectationScoreProduct{<:F, <:Q}}, ::Type{<:Q}) where {…} = truesee BayesBase.ExpectationScoreProduct. The result must be in the parametrization of BayesBase.expectation_score. Otherwise the macro works as BayesBase.@supports_expectation.
julia> using Distributions
julia> struct Moments end
julia> BayesBase.@supports_expectation_gradient function BayesBase.expectation_gradient(::Moments, ::typeof(identity), q::Gamma)
α, θ = params(q)
return [θ, α] # the gradient of α θ with respect to the shape α and the scale θ
end
julia> BayesBase.supports_expectation_gradient(Moments(), identity, Gamma(2.0, 1.0))
true
julia> router = BayesBase.ExpectationFirstOf(Moments());
julia> BayesBase.expectation_gradient(router, identity, Gamma(2.0, 3.0))
2-element Vector{Float64}:
3.0
2.0Labels
A label is a property of a computation that a caller can rely on, such as BayesBase.ExpectationExact for a result that is exact up to rounding. A backend declares a label for all the pairs it supports or for some of them, and only where the property is guaranteed. Below, every closed form is exact, and the quadrature rule is exact for categorical distributions:
BayesBase.has_expectation_label(::MyClosedForms, ::BayesBase.ExpectationExact) = true
BayesBase.has_expectation_label(::MyQuadrature, ::Type, ::Type{<:Categorical}, ::BayesBase.ExpectationExact) = trueBayesBase.ExpectationLabel — Type
ExpectationLabelA property of the computation of an expectation that a caller can rely on. Labels are conservative: a backend declares a label only where it is guaranteed.
BayesBase.ExpectationExact — Type
ExpectationExact()The result equals the expectation up to rounding.
BayesBase.ExpectationStochastic — Type
ExpectationStochastic()The result depends on a random number generator.
BayesBase.has_expectation_label — Function
has_expectation_label(backend, label)
has_expectation_label(backend, F::Type, Q::Type, label)
has_expectation_label(backend, f, q, label)Whether backend has label. The first form asks about every pair the backend supports and is false by default. The other two forms ask about one pair. The type form falls back to the first form, and the instance form is also false when the backend does not support the pair.
BayesBase.is_expectation_exact — Function
Whether backend computes the expectation of f under q exactly.
BayesBase.is_expectation_stochastic — Function
Whether backend uses random numbers, for every pair or for the pair (f, q).
BayesBase.combine_expectation_label — Function
combine_expectation_label(label, a::Bool, b::Bool)Whether a computation made of two parts has label, given whether each part has it. The computation is exact if both parts are exact, and stochastic if either part is stochastic. A label defined in another package is combined like ExpectationExact, which is the conservative choice, unless that package adds a method.
Random number generators
A stochastic backend stores its own random number generator, and expectation does not take one. The code that sets up the computation, such as an inference engine, gives the backend a generator with BayesBase.with_expectation_rng. A generator that the user has already set is never replaced.
BayesBase.with_expectation_rng — Function
with_expectation_rng(backend, rng)backend with rng as its random number generator if it has none yet. A backend that already has a generator keeps it, so a generator set by the user is never replaced. Composite backends, such as routers, pass rng on to their parts. The default returns backend unchanged.
BayesBase.get_expectation_rng — Function
get_expectation_rng(backend)The random number generator of backend, or nothing.
Products of distributions
An expectation over several independent variables, which can be of different kinds (for example a categorical, a multivariate Gaussian and a point mass), is an expectation under a FactorizedJoint. The integrand receives a tuple with one value per component. A backend supports a product when it supports every component for any integrand, and a router when it supports every component, possibly each with a different backend. The expectation is computed as nested expectations over the preparations of the components, $\mathbb{E}_{q_1}[x_1 \mapsto \mathbb{E}_{q_2}[x_2 \mapsto f((x_1, x_2))]]$, so any preparation works, such as sigma points or a sampler. When every preparation is an BayesBase.ExpectationPointSet, the nesting is the product rule over the point sets, an BayesBase.ExpectationProductPointSet. An unsupported product throws an BayesBase.UnsupportedExpectationError. Labels are combined with BayesBase.combine_expectation_label: the product is exact only if every component is exact, and stochastic if any component is stochastic.
BayesBase.ExpectationPointSet — Type
ExpectationPointSet(points, weights)A prepared expectation that is a weighted sum, Σᵢ wᵢ f(xᵢ). Quadrature and cubature rules, sigma points, exact sums over a finite support and samples with equal weights all have this form. points and weights can be any collections indexed from one, including tuples. Product rules over a FactorizedJoint are built from the point sets of the components, see BayesBase.ExpectationProductPointSet.
The sum starts from its first term, so its type follows the values of the integrand. For example, an integrand that returns dual numbers needs no special handling.
BayesBase.ExpectationProductPointSet — Type
ExpectationProductPointSet(sets)The product rule over a tuple of ExpectationPointSets: every combination of points, weighted by the product of their weights. The integrand receives a tuple of points. It is the preparation of a FactorizedJoint whose components all have a point set. Otherwise the preparation computes nested expectations over the components' preparations.
Routers
A router is a backend that passes each expectation on to one of several other backends. BayesBase.ExpectationFirstOf chooses from the types of f and q alone, so the choice is made at compile time. BayesBase.ExpectationDynamicRouter chooses at run time among the backends that packages have registered, and is meant for interactive use. ExpectationFirstOf(ExpectationDynamicRouter()) turns the current choice of the dynamic router into an ExpectationFirstOf.
BayesBase.ExpectationFirstOf — Type
ExpectationFirstOf(backends...; prefer = (), exclude = ())A router: a backend that passes each expectation to the first of backends that supports the pair (f, q) and has none of the labels in exclude. If prefer is given, the first such backend that also has all the labels in prefer is chosen, and if there is none, the first such backend. prefer and exclude are a label or a tuple of labels. The choice depends only on the types of f and q, so type inference makes it and nothing is decided at run time.
A product of distributions (FactorizedJoint) is routed component by component.
BayesBase.ExpectationDynamicRouter — Type
ExpectationDynamicRouter(registry = the global registry)A router that chooses among the registered backends at run time. Among the backends that support the pair, it prefers one that is exact for the pair, then one that is not stochastic, then one with a higher priority, and finally orders by the name of the backend's type. Backends with different names therefore do not depend on the order in which packages were loaded. Only backends that tie on all of these, such as two backends of the same type, keep the order in which they were registered.
The router is type-unstable. ExpectationFirstOf(ExpectationDynamicRouter()) freezes the current choice into a type-stable router, which is what an inference engine should use, as RxInfer's fallback schemes do by default. with_expectation_rng freezes it too, so that the generator reaches the backends.
BayesBase.ExpectationBackendRegistry — Type
ExpectationBackendRegistry()The backends, each with a priority, among which an ExpectationDynamicRouter chooses.
BayesBase.register_expectation_backend! — Function
register_expectation_backend!(backend; priority = 0, registry = the global registry)Make backend available to ExpectationDynamicRouters. Registering a backend again changes its priority. Packages call this in __init__. A dynamic router cannot be registered, because it would choose among the backends that include itself.
BayesBase.expectation_backend_priority — Function
expectation_backend_priority(backend; registry = the global registry) -> Union{Int, Nothing}The priority backend was registered with, or nothing if it is not registered. A negative priority marks a last resort: a backend meant for the cases where no other applies. An inference report can use it to say where such a backend was used. An ExpectationFirstOf frozen from a dynamic router keeps the order that the priorities gave but not the priorities themselves, so this function looks them up in the registry.