This example was automatically generated from a Jupyter notebook in the RxInferExamples.jl repository.
We welcome and encourage contributions! You can help by:
- Improving this example
- Creating new examples
- Reporting issues or bugs
- Suggesting enhancements
Visit our GitHub repository to get started. Together we can make RxInfer.jl even better! 💪
A Hierarchical Model
This example is part of the Universal Inference section, which runs inference in a broad class of models by approximating what has no closed form. In the other examples of the section, fallback = LocalLaplace() handles nodes that have no rules. Here every node has its rules, but one posterior is a product of messages with no closed form, and the fallback approximates it.
The model is the pump failure model of Gaver and O'Muircheartaigh (1987), a standard example for Gibbs sampling (Gelfand and Smith, 1990) and the Pumps example of the BUGS manual. Ten pumps of a nuclear power plant have failed $y_i$ times in $t_i$ thousand hours of operation. Each pump has its own failure rate $\lambda_i$, and the rates share a Gamma distribution whose shape $\alpha$ and rate $\beta$ are learned:
\[\begin{aligned} \alpha &\sim \mathrm{Exponential}(1),\\ \beta &\sim \mathrm{Gamma}(0.1, 1),\\ \lambda_i &\sim \mathrm{Gamma}(\alpha, \beta),\\ y_i &\sim \mathrm{Poisson}(\lambda_i t_i). \end{aligned}\]
Under the mean-field factorisation $q(\lambda, \alpha, \beta) = q(\lambda)\,q(\alpha)\,q(\beta)$, the rates and $\beta$ are conjugate: their posteriors are Gamma distributions, which RxInfer computes with exact rules. The shape $\alpha$ is not conjugate. Its message from each $\lambda_i$ is $\exp(\alpha\,\mathbb{E}[\log \beta \lambda_i] - \log\Gamma(\alpha))$, and the product of ten of these messages with the prior does not belong to a known family. Without the fallback, RxInfer requires a form constraint on $\alpha$, chosen by hand. With the fallback, LocalLaplace() projects the product onto a Gaussian in $\log \alpha$ by the Laplace method. NaturalGradientPropagation() instead gives each of the ten messages a site in the family of the prior of $\alpha$. That prior is an Exponential, which is a Gamma with shape 1, so the posterior of $\alpha$ stays a Gamma distribution.
using RxInfer, BayesBase, Distributions, SpecialFunctions
using Plots, PrettyTables, Printf
Data
t = [94.3, 15.7, 62.9, 126.0, 5.24, 31.4, 1.05, 1.05, 2.1, 10.5] # thousands of hours
y = [5, 1, 5, 14, 3, 19, 1, 1, 4, 22] # failures
bar(y ./ t; xlabel = "pump", ylabel = "failures per thousand hours", label = "yᵢ / tᵢ", color = :gray)

The model
Exponential is not a factor node in RxInfer, so the prior on $\alpha$ is written as the equivalent Gamma distribution, with shape 1 and rate 1. The rate of a Poisson count is λ[i] * t[i], the product of a variable and a constant, for which RxInfer has rules.
@model function pumps(y, t)
α ~ Gamma(shape = 1.0, rate = 1.0)
β ~ Gamma(shape = 0.1, rate = 1.0)
for i in eachindex(y)
λ[i] ~ Gamma(shape = α, rate = β)
y[i] ~ Poisson(λ[i] * t[i])
end
end
mean_field = @constraints begin
q(λ, α, β) = q(λ)q(α)q(β)
end
initial = @initialization begin
q(α) = GammaShapeRate(1.0, 1.0)
q(β) = GammaShapeRate(1.0, 1.0)
q(λ) = GammaShapeRate(1.0, 1.0)
end
Initial state:
q(α) = GammaShapeRate(1.0, 1.0)
q(β) = GammaShapeRate(1.0, 1.0)
q(λ) = GammaShapeRate(1.0, 1.0)Inference
We run both schemes for 100 iterations of variational message passing and compute the free energy.
Under NaturalGradientPropagation(), the message from each rate towards $\alpha$ is a log-density $\ell_i(\alpha) = \alpha\,\mathbb{E}[\log \beta\lambda_i] - \log\Gamma(\alpha)$, and it has a Gamma site on its edge. $q(\alpha)$ is the prior times the ten sites. At each iteration, a site moves towards its target $\eta^\star = G(q)^{-1}\,\mathrm{Cov}_q[T(\alpha), \ell_i(\alpha)]$, the natural gradient of $\mathbb{E}_q[\ell_i]$, where $T(\alpha) = (\log\alpha, \alpha)$ is the sufficient statistic of the Gamma and $G$ its Fisher information. The covariance is computed by quadrature in $\log\alpha$. The move is a damped heavy-ball step in the natural parameters of the Gamma, $v \leftarrow b\,v + a(\eta^\star - \eta)$ and $\eta \leftarrow \eta + v$, with the step size $a$ = alpha = 0.5 and the momentum $b$ = beta = 0.2 by default. These are keywords of the scheme and are unrelated to the $\alpha$ and $\beta$ of the model. At the fixed point each site equals its target, and $q(\alpha)$ is the best Gamma under mean field: the stationary point of the free energy over Gamma distributions, which conjugate-computation variational inference would also reach in that family.
fit(fallback) = infer(
model = pumps(t = t), data = (y = y,),
constraints = mean_field, initialization = initial, iterations = 100,
fallback = fallback, free_energy = true, report = true,
)
laplace = fit(LocalLaplace())
ngmp = fit(NaturalGradientPropagation())
qα_laplace, qα_ngmp = laplace.posteriors[:α][end], ngmp.posteriors[:α][end]
qβ_laplace, qβ_ngmp = laplace.posteriors[:β][end], ngmp.posteriors[:β][end]
(GammaShapeRate(7.324703215269697, 7.867330147411184), GammaShapeRate(6.624643520945116, 7.906207935256098))What was approximated
The report of the Laplace run shows what the fallback did. Only the posterior of $\alpha$ was approximated; the rates and $\beta$ have exact Gamma posteriors. No message needed the fallback, because every node has its rules.
The free energy needs two more computations. The product node λ[i] * t[i] has message rules but no rule for the joint distribution of its inputs, which the free energy needs. The fallback computes it: with $t_i$ known, that joint is the marginal of $\lambda_i$, the product of its message and the message of the node towards it, in closed form. And the posterior of $\alpha$ is now a log-normal, under which the Gamma node of the rates has no rule for its average energy, which needs $\mathrm{E}[\log \Gamma(\alpha)]$: the fallback computes it by quadrature, and the report lists it too.
records = laplace.report.approximations
records
Approximations: 1 of 13 posteriors approximated (exact rules on approximated inputs: · (anonymous), β, λ[1:10]), no warnings
Approximated posteriors
╭────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from │ towards │ exact │ fallback │ expectations │
├────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ α: Laplace, converged in 1 iteration, log Z = -12.97 │
├────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ α ~ GammaShapeRate(1.0, 1.0) │ out │ 1 │ 0 │ │
│ λ[1:10] ~ GammaShapeRate(α, β) │ α │ 1009 │ 0 │ │
╰────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯
Joints and energies by the fallback
╭────────────────────────────────┬──────────────────┬───────┬─────────────╮
│ Node │ computed │ times │ how │
├────────────────────────────────┼──────────────────┼───────┼─────────────┤
│ · := *(λ[1:10], …) │ joint of (A, in) │ 1000 │ closed form │
│ λ[1:10] ~ GammaShapeRate(α, β) │ average energy │ 1000 │ expectation │
╰────────────────────────────────┴──────────────────┴───────┴─────────────╯
Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendreThe Laplace Gaussian on $\log \alpha$ is a log-normal distribution on $\alpha$. The posterior of $\alpha$ from natural-gradient propagation is a Gamma distribution, the prior times ten Gamma sites. Its report counts the sites and their steps, and shows that every site has settled:
qα_laplace.gaussian, qα_ngmp
(Normal(-0.35869157459652706, 0.2592783727423176), GammaShapeRate(14.324341768981462, 21.95421362560496))ngmp.report.approximations
Approximations: 1 of 13 posteriors approximated (exact rules on approximated inputs: · (anonymous), β, λ[1:10]), no warnings
Approximated posteriors
╭────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from │ towards │ exact │ fallback │ expectations │
├────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ α: natural-gradient propagation, 10 sites, 1020 steps │
├────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ α ~ GammaShapeRate(1.0, 1.0) │ out │ 1 │ 0 │ │
│ λ[1:10] ~ GammaShapeRate(α, β) │ α │ 1020 │ 0 │ │
╰────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯
Joints and energies by the fallback
╭────────────────────┬──────────────────┬───────┬─────────────╮
│ Node │ computed │ times │ how │
├────────────────────┼──────────────────┼───────┼─────────────┤
│ · := *(λ[1:10], …) │ joint of (A, in) │ 1000 │ closed form │
╰────────────────────┴──────────────────┴───────┴─────────────╯
Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendreThe exact posterior
The rates can be integrated out in closed form: a Poisson count whose rate has a Gamma distribution is negative binomial,
\[p(y_i \mid \alpha, \beta) = \frac{\Gamma(y_i + \alpha)}{\Gamma(\alpha)\, y_i!} \left(\frac{\beta}{\beta + t_i}\right)^{\alpha} \left(\frac{t_i}{\beta + t_i}\right)^{y_i}.\]
The posterior of $(\alpha, \beta)$ is then two-dimensional, and a grid in log coordinates gives it, together with the evidence $p(y)$.
lognegbin(α, β) = sum(loggamma(y[i] + α) - loggamma(α) - loggamma(y[i] + 1) + α * log(β / (β + t[i])) + y[i] * log(t[i] / (β + t[i])) for i in eachindex(y))
logjoint(α, β) = logpdf(Gamma(1.0, 1.0), α) + logpdf(Gamma(0.1, 1.0), β) + lognegbin(α, β)
us, vs = range(log(0.02), log(10), length = 1200), range(log(0.01), log(20), length = 1200)
grid = [logjoint(exp(u), exp(v)) + u + v for u in us, v in vs] # the Jacobian of the log coordinates
top = maximum(grid)
weights = exp.(grid .- top)
logevidence = top + log(sum(weights) * step(us) * step(vs))
weights ./= sum(weights)
αgrid, βgrid = exp.(us), exp.(vs)
Eα = sum(weights .* αgrid)
Eβ = sum(weights .* βgrid')
sdα = sqrt(sum(weights .* (αgrid .- Eα) .^ 2))
sdβ = sqrt(sum(weights .* (βgrid' .- Eβ) .^ 2))
@printf("exact: E[α] = %.3f (sd %.3f), E[β] = %.3f (sd %.3f), -log p(y) = %.3f\n", Eα, sdα, Eβ, sdβ, -logevidence)
exact: E[α] = 0.697 (sd 0.271), E[β] = 0.927 (sd 0.543), -log p(y) = 36.578The means agree with the Gibbs sampler of the BUGS manual, which reports about 0.70 and 0.92.
The best mean-field posterior
Both schemes make two approximations: the mean-field factorisation, and a fixed family for $q(\alpha)$. To separate the two, we compute the best mean-field posterior, with $q(\alpha)$ of any shape, on a fine grid. Coordinate ascent alternates the three exact updates, and only the update of $\alpha$ needs the grid:
\[q(\alpha) \propto p(\alpha) \exp\Big(\sum_i \alpha\,\mathbb{E}[\log\beta] - \log\Gamma(\alpha) + (\alpha - 1)\,\mathbb{E}[\log\lambda_i]\Big).\]
function best_mean_field(; iterations = 500)
as = range(1.0e-4, 4.0, length = 40_000)
Eα, Elogβ, Eβ = 1.0, 0.0, 1.0
qλ, qβ, w = nothing, nothing, nothing
for _ in 1:iterations
qλ = [Gamma(Eα + y[i], 1 / (Eβ + t[i])) for i in eachindex(y)]
Elogλ = [digamma(shape(q)) + log(scale(q)) for q in qλ]
qβ = Gamma(0.1 + length(y) * Eα, 1 / (1 + sum(mean, qλ)))
Elogβ, Eβ = digamma(shape(qβ)) + log(scale(qβ)), mean(qβ)
logw = [-a + sum(a * Elogβ - loggamma(a) + (a - 1) * Elogλ[i] for i in eachindex(y)) for a in as]
w = exp.(logw .- maximum(logw))
w ./= sum(w)
Eα = sum(w .* as)
end
# its free energy: the expected negative log joint, minus the entropies
Elogλ = [digamma(shape(q)) + log(scale(q)) for q in qλ]
U = Eα - (-0.9 * Elogβ - Eβ - loggamma(0.1))
for i in eachindex(y)
U -= Eα * Elogβ - sum(w .* loggamma.(as)) + (Eα - 1) * Elogλ[i] - Eβ * mean(qλ[i])
U -= y[i] * (log(t[i]) + Elogλ[i]) - t[i] * mean(qλ[i]) - loggamma(y[i] + 1)
end
H = -sum(p * log(p / step(as)) for p in w if p > 0) + entropy(qβ) + sum(entropy, qλ)
return (; α = as, density = w ./ step(as), mean = Eα, sd = sqrt(sum(w .* (as .- Eα) .^ 2)), β = qβ, free_energy = U - H)
end
best = best_mean_field()
(α = 0.0001:0.0001:4.0, density = [9.520908328574421e-35, 9.740530364754914e-32, 5.6117638614623304e-30, 9.956137263797332e-29, 9.263925539764953e-28, 5.7307504193412224e-27, 2.6747506299413124e-26, 1.0157962476174487e-25, 3.295608340263382e-25, 9.443091375263245e-25 … 2.2692490907267607e-28, 2.263030669759971e-28, 2.2568292250573327e-28, 2.2506447104518335e-28, 2.244477079901326e-28, 2.2383262874885134e-28, 2.232192287420516e-28, 2.22607503402847e-28, 2.219974481767101e-28, 2.213890585214705e-28], mean = 0.6525776074262523, sd = 0.17138527006652157, β = Gamma(6.6257760742625225, 0.12648391159343048), free_energy = 37.06608381264028)Results
F_ngmp = last(ngmp.free_energy)
rows = [
"exact" Eα sdα Eβ sdβ -logevidence;
"best mean field" best.mean best.sd mean(best.β) std(best.β) best.free_energy;
"NaturalGradientPropagation()" mean(qα_ngmp) std(qα_ngmp) mean(qβ_ngmp) std(qβ_ngmp) F_ngmp;
"LocalLaplace()" mean(qα_laplace) std(qα_laplace) mean(qβ_laplace) std(qβ_laplace) last(laplace.free_energy)
]
pretty_table(rows; column_labels = ["", "E[α]", "sd(α)", "E[β]", "sd(β)", "free energy"], formatters = [fmt__printf("%.3f", 2:6)], fit_table_in_display_horizontally = false)
┌──────────────────────────────┬───────┬───────┬───────┬───────┬─────────────┐
│ │ E[α] │ sd(α) │ E[β] │ sd(β) │ free energy │
├──────────────────────────────┼───────┼───────┼───────┼───────┼─────────────┤
│ exact │ 0.697 │ 0.271 │ 0.927 │ 0.543 │ 36.578 │
│ best mean field │ 0.653 │ 0.171 │ 0.838 │ 0.326 │ 37.066 │
│ NaturalGradientPropagation() │ 0.652 │ 0.172 │ 0.838 │ 0.326 │ 37.067 │
│ LocalLaplace() │ 0.722 │ 0.191 │ 0.931 │ 0.344 │ 37.112 │
└──────────────────────────────┴───────┴───────┴───────┴───────┴─────────────┘The last column is the free energy, an upper bound on $-\log p(y)$, which is given in the first row.
αs = range(0.05, 2.0, length = 400)
exact_α = vec(sum(weights; dims = 2)) ./ (αgrid .* step(us)) # the marginal of α, in α's own coordinates
lognormal(q) = LogNormal(mean(q.gaussian), std(q.gaussian))
plot(αgrid, exact_α; xlims = (0, 2), color = :black, linewidth = 2, label = "exact", xlabel = "α", ylabel = "density")
plot!(best.α, best.density; color = :gray, linestyle = :dash, linewidth = 2, label = "best mean field")
plot!(αs, pdf.(qα_ngmp, αs); color = :red, label = "NaturalGradientPropagation()")
plot!(αs, pdf.(lognormal(qα_laplace), αs); color = :blue, label = "LocalLaplace()")

NaturalGradientPropagation() finds the best mean-field posterior. Its $\alpha$ agrees with the best mean field to within 0.002 in mean and standard deviation, and its free energy is within 0.005 of the best one. The best $q(\alpha)$, with no restriction on its shape, is close to a Gamma, the family of the prior that the sites keep, so restricting $q(\alpha)$ to that family costs almost nothing here.
Mean field itself underestimates the spread. Both schemes, and the best mean field, are overconfident: the standard deviation of $\alpha$ is 0.17 to 0.19, compared with the exact 0.27, and that of $\beta$ is 0.33 to 0.34, compared with 0.54. A larger shape together with a larger rate explains the same failure rates, and mean field cannot represent this dependence between $\alpha$ and $\beta$.
The Laplace mean of $\alpha$ is closer to the exact one than the mean from natural-gradient propagation, but only by coincidence. It is 0.07 above the best mean-field mean, while the factorisation puts that mean 0.045 below the exact one, so the two errors partly cancel. The Laplace free energy, the quantity that mean field minimises, is the highest of the three.
The free energy ranks the approximations without the exact answer: lower is better, and the free energy of NaturalGradientPropagation() is lower than that of LocalLaplace(). It does not show what the factorisation costs; only a comparison with a less factorised approximation can show that.
References
- D. P. Gaver and I. G. O'Muircheartaigh (1987). Robust empirical Bayes analyses of event rates. Technometrics, 29(1), 1–15.
- A. E. Gelfand and A. F. M. Smith (1990). Sampling-based approaches to calculating marginal densities. Journal of the American Statistical Association, 85(410), 398–409.
- M. Lukashchuk, K. Yemets, A. Ledbetter and İ. Şenöz (2026). Information geometry of message passing. arXiv:2608.15922.
- D. Spiegelhalter, A. Thomas, N. Best and W. Gilks (1996). BUGS 0.5 Examples, Volume 1: Pumps. MRC Biostatistics Unit, Cambridge.
This example was automatically generated from a Jupyter notebook in the RxInferExamples.jl repository.
We welcome and encourage contributions! You can help by:
- Improving this example
- Creating new examples
- Reporting issues or bugs
- Suggesting enhancements
Visit our GitHub repository to get started. Together we can make RxInfer.jl even better! 💪
This example was executed in a clean, isolated environment. Below are the exact package versions used:
For reproducibility:
- Use the same package versions when running locally
- Report any issues with package compatibility
Status `/tmp/jl_kQqZki/Project.toml`
[b4ee3484] BayesBase v1.7.0
⌃ [31c24e10] Distributions v0.25.134
[62312e5e] ExponentialFamily v2.9.3
[91a5bcdd] Plots v1.41.10
[08abe8d2] PrettyTables v3.5.1
[86711068] RxInfer v6.2.0
[276daf66] SpecialFunctions v2.9.2
[de0858da] Printf v1.11.0
Info Packages marked with ⌃ have new versions available and may be upgradable.