Contributing

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! 💪


Reading the Inference Report

This example is part of the Universal Inference section. With fallback = LocalLaplace(), RxInfer uses exact rules where a model has them and approximates the other messages and posteriors. The posteriors themselves do not show which parts were approximated, or how. To record this, pass report = true to infer; it works with all of the fallback schemes. The result then has a report, result.report, with two sections:

  • result.report.approximations lists the approximated posteriors and how each was projected. For each posterior it lists the node instances that sent messages to it, counts how many of those messages came from an exact rule and how many from the rule fallback, and names the backends that computed the fallback's expectations. It also warns about the parts of the inference that are most likely to be inaccurate.
  • result.report.timings shows how the inference time was spent.

This notebook reads the report of one model under two inference schemes, and then uses the report as data.

using RxInfer, StatsFuns, StableRNGs, PrettyTables

The model

A logistic regression with one coefficient $\beta$, whose prior precision $\tau$ is itself unknown:

\[\begin{aligned} \tau &\sim \mathrm{Gamma}(2, 1),\\ \beta &\sim \mathcal{N}(0, \tau^{-1}),\\ y_i &\sim \mathrm{Bernoulli}\left(\sigma(\beta x_i)\right). \end{aligned}\]

The Gamma prior on the precision of a Gaussian is conjugate under mean field, so RxInfer has exact variational rules for $\tau$. The likelihood has no rules. We define it as a custom node that has a log-density and nothing else.

rng = StableRNG(3)
n = 60
x = randn(rng, n)
β_true = 1.5
y = [rand(rng) < logistic(β_true * xi) ? 1.0 : 0.0 for xi in x]

struct LogisticBernoulli{B, X} <: DiscreteUnivariateDistribution
    β::B
    x::X
end

BayesBase.logpdf(d::LogisticBernoulli, y) = y * log(logistic(d.β * d.x)) + (1 - y) * log1p(-logistic(d.β * d.x))
BayesBase.insupport(::LogisticBernoulli, y) = true

@define_factor_node(node = LogisticBernoulli, type = Stochastic, interfaces = [:out, :β, :x])

@model function shrinkage(y, x)
    τ ~ Gamma(shape = 2.0, rate = 1.0)
    β ~ NormalMeanPrecision(0.0, τ)
    for i in eachindex(y)
        y[i] ~ LogisticBernoulli(β, x[i])
    end
end

Under mean field

We factorise the posterior as $q(\beta)\,q(\tau)$ and ask for the report.

mean_field = @constraints begin
    q(β, τ) = q(β)q(τ)
end

result = infer(
    model = shrinkage(x = x),
    data = (y = y,),
    constraints = mean_field,
    iterations = 10,
    fallback = LocalLaplace(),
    free_energy = true,
    report = true,
)

q_β, q_τ = result.posteriors[:β][end], result.posteriors[:τ][end]

With PrettyTables.jl loaded, the report prints as tables.

result.report.approximations
  Approximations: 1 of 2 posteriors approximated (exact rules on approximated inputs: τ), no warnings
                             Approximated posteriors
╭───────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                     │ towards │ exact │ fallback │ expectations │
├───────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ β: Laplace, converged in 2 iterations, log Z = -31.08                         │
├───────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ β ~ NormalMeanPrecision(0.0, τ)   │ out     │ 10    │ 0        │              │
│ y[1:60] ~ LogisticBernoulli(β, …) │ β       │ 0     │ 600      │ exact        │
╰───────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                    Joints and energies by the fallback
╭───────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                              │ computed       │ times │ how         │
├───────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:60] ~ LogisticBernoulli(β, …) │ average energy │ 600   │ expectation │
╰───────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

The first line is a summary. One of the two posteriors was approximated. The posterior of $\tau$ comes from the conjugate rules, but they take the approximated marginal of $\beta$, so the summary lists $\tau$ under "exact rules on approximated inputs" rather than as exact. There are no warnings.

In the table of approximated posteriors, each approximated posterior has a group of rows. The header of the group says how the posterior was projected: here by Laplace's method, with the number of Newton iterations and the log-normaliser. Each row is a node instance as it is written in the model. Instances of the same form share one row, as in y[1:60] ~ LogisticBernoulli(β, …), where … stands for the inputs $x_i$, which differ between the instances.

The exact and fallback columns count the messages from a node towards the variable that came from an exact rule and from the rule fallback, over all ten iterations. The expectations column says how the fallback computed its expectations. Here they are exact, because under mean field the other inputs of the likelihood are the data and the constants $x_i$.

The table of joints and energies computed by the fallback lists the average energies of the likelihood, which the free energy needs. The last line lists the expectation backends that were available, in the order in which they are tried.

Under belief propagation, a warning

Without the factorisation, inference is belief propagation. The Gaussian node $\beta \sim \mathcal{N}(0, \tau^{-1})$ then has no exact rule, because its precision is random, so the fallback computes its messages as well. The report flags this.

result_bp = infer(
    model = shrinkage(x = x),
    data = (y = y,),
    fallback = LocalLaplace(),
    report = true,
)
found = RxInfer.diagnostics(result_bp.report)
result_bp.report.approximations
  Approximations: 2 of 2 posteriors approximated, 1 warning
                                                                      Diagnostics
╭─────────┬─────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│         │ where                           │ what                                                                                                     │
├─────────┼─────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ warning │ β ~ NormalMeanPrecision(0.0, τ) │ under BP, the messages towards out, τ average over another variable's message: variational, not exact BP │
╰─────────┴─────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────╯

                                          Approximated posteriors
╭───────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────╮
│ Messages from                     │ towards │ exact │ fallback │ expectations                           │
├───────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────┤
│ β: Laplace, converged in 6 iterations, log Z = -31.95                                                   │
├───────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────┤
│ y[1:60] ~ LogisticBernoulli(β, …) │ β       │ 0     │ 60       │ exact                                  │
│ β ~ NormalMeanPrecision(0.0, τ)   │ out     │ 0     │ 1        │ GammaShapeRate → UnconstrainedLegendre │
├───────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────┤
│ τ: Laplace, converged in 6 iterations, log Z = -3.367                                                   │
├───────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────┤
│ τ ~ GammaShapeRate(2.0, 1.0)      │ out     │ 1     │ 0        │                                        │
│ β ~ NormalMeanPrecision(0.0, τ)   │ τ       │ 0     │ 1        │ NormalMeanVariance → GaussHermite      │
╰───────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

The warning has the kind :expectation_over_messages. Under belief propagation, the fallback computes the message of the Gaussian node towards $\beta$ as an expectation over the message from $\tau$. This gives the variational message. The belief propagation message would instead integrate the node against the message from $\tau$. The result approximates belief propagation, and in this model the error of that approximation is not controlled. There are two ways to avoid it:

  • Use mean field. With the factorisation above, the expectation is taken over a marginal, which is what variational message passing prescribes, and the warning goes away.
  • Use a cavity method. Under fallback = ExpectationPropagation() or LaplacePropagation(), a node with several random inputs sends the belief propagation message, which integrates the node against the messages of the other inputs, but only when those messages are Gaussian. An input whose message is not Gaussian, such as the Gamma message of $\tau$ here, still enters through the expectation of the log-density. For this model, mean field is therefore the fix.

Each diagnostic is a value with the fields kind, level, subject and text:

found
1-element Vector{RxInfer.ReportDiagnostic}:
 warning (expectation_over_messages): β ~ NormalMeanPrecision(0.0, τ): under BP, the messages towards out, τ average over another variable's message: variational, not exact BP

A test, or a notebook such as this one, can check that an inference raised no warnings with isempty(filter(d -> d.level === :warning, RxInfer.diagnostics(result.report))).

The report as data

The tables above are a formatted view of data stored in the report, which code can read directly:

  • RxInfer.node_types(result.report.approximations) counts the computations by node type;
  • result.report.approximations.variables records, for each variable, its projections and the messages it received;
  • report_tables returns the tables.

For example, the number of times the fallback computed a message from the likelihood towards $\beta$:

RxInfer.node_types(result.report.approximations)[(LogisticBernoulli, :message, :β)].fallbacks
600

The last Laplace projection of $\beta$, as reported by LaplaceForm:

result.report.approximations.variables[(:β, nothing)].marginal.outcome
(method = :laplace, logZ = -31.07874096861657, converged = true, iterations = 2)

The rows of the table of approximated posteriors:

first(report_tables(result.report.approximations)).rows
2-element Vector{Vector{String}}:
 ["β ~ NormalMeanPrecision(0.0, τ)", "out", "10", "0", ""]
 ["y[1:60] ~ LogisticBernoulli(β, …)", "β", "0", "600", "exact"]

Timings

The second section of the report shows how the time was spent. Julia compiles a model the first time it runs, so we look at a second run.

timed = infer(
    model = shrinkage(x = x),
    data = (y = y,),
    constraints = mean_field,
    iterations = 10,
    fallback = LocalLaplace(),
    free_energy = true,
    report = (:timings,),
)
timed.report
Inference report
  Timings: model 5.16 s, inference 1.33 s (10 iterations)
                              Time by kind
╭──────────────────────────────────┬─────────┬──────────────────┬───────╮
│                                  │ time    │ of the inference │ calls │
├──────────────────────────────────┼─────────┼──────────────────┼───────┤
│ exact rules                      │ 11.2 μs │ 0.0%             │ 22    │
│ rule fallback                    │ 73.4 ms │ 5.5%             │ 600   │
│ projections                      │ 74.1 ms │ 5.6%             │ 21    │
│ free energy terms                │ 22.3 ms │ 1.7%             │ 620   │
│ the engine, products and streams │ 1.16 s  │ 87.3%            │       │
╰──────────────────────────────────┴─────────┴──────────────────┴───────╯

                           Time by node and variable
╭─────────────────────┬───────────────────┬─────────┬──────────────────┬───────╮
│                     │ kind              │ time    │ of the inference │ calls │
├─────────────────────┼───────────────────┼─────────┼──────────────────┼───────┤
│ β                   │ projections       │ 74.1 ms │ 5.6%             │ 10    │
│ LogisticBernoulli   │ rule fallback     │ 73.4 ms │ 5.5%             │ 600   │
│ LogisticBernoulli   │ free energy terms │ 22.2 ms │ 1.7%             │ 600   │
│ GammaShapeRate      │ free energy terms │ 13.5 μs │ 0.0%             │ 10    │
│ NormalMeanPrecision │ free energy terms │ 9.88 μs │ 0.0%             │ 10    │
│ τ                   │ projections       │ 9.68 μs │ 0.0%             │ 11    │
│ NormalMeanPrecision │ exact rules       │ 9.41 μs │ 0.0%             │ 21    │
│ GammaShapeRate      │ exact rules       │ 1.75 μs │ 0.0%             │ 1     │
╰─────────────────────┴───────────────────┴─────────┴──────────────────┴───────╯

The time of a call does not include the time of the calls it makes, which is counted under their own kind, so the times of the kinds add up. The time not spent in rules, the fallback or projections is spent by the engine itself: on products of messages, on the streams between the nodes and on the entropies of the free energy. In this small model, the engine takes most of the time. The Laplace projections of $\beta$ and the quadrature of the fallback over the 60 observations take a few percent each, and the exact rules take almost no time. For timing statistics over many runs, use RxInfer's benchmark callbacks.

Summary

  • report = true records which posteriors an inference approximated, and for each one the node instances and rules that contributed. The report is off by default and costs nothing when off.
  • RxInfer.diagnostics lists the parts of the inference most likely to be inaccurate. Here it flagged a fallback that averages over a message under belief propagation, which mean field avoids.
  • The counts, projections and tables of the report are data that code can read and check.

Contributing

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! 💪


Environment

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`
  [08abe8d2] PrettyTables v3.5.1
  [86711068] RxInfer v6.2.0
  [860ef19b] StableRNGs v1.1.0
⌅ [4c63d2b9] StatsFuns v1.5.3
Info Packages marked with ⌅ have new versions available but compatibility constraints restrict them from upgrading. To see why use `status --outdated`