Skip to main content

Inference basics

Bayesian Inference with SVGD (Stein Variational Gradient Descent)

To estimate model parameters and their confidence intervals, Phasic used uses Stein Variational Gradient Descent (SVGD), which represents the posterior with a set of particles (parameter vectors) and combines ideas from optimization, kernel methods, and functional analysis in a deterministic algorithm that updates these particles iteratively to move them toward the posterior distribution. SVGD exploits the PDF for gradient computation and moments for regularization. It begins with an initial set of particles (typically drawn from the prior or from a simple distribution) and iteratively transport these particles toward the posterior using gradient information. Each particle interacts with all other particles through a kernel function, with the interaction strength depending on the distance between particles. This interaction ensures that particles spread out to cover the posterior distribution, allowing extraction of not only the most likely parameter value (MAP estimate) but also a confidence interval of the estimate.

Such inference is not possible in the standard matrix formulation of phase-type distributions where the large number of likelihood computations required would each be \(O(n^3)\). In Phasic, the algorithm of the gaussian elimination on the graph fully exploits the sparseness of state spaces bringing the complexity closer to \(n^2\). Because Phasic records and caches the elimination trace, this computation is only done once, removing a dimension of complexity for all subsequent likelihood evaluations. For an expose of these tricks and innovations see Math and Algorithms, Architecture, Caching and Sharing.

from phasic import (
    Graph, with_ipv,
    GaussPrior, HalfCauchyPrior, DataPrior,
    ConstantStepSize, ExpStepSize, AdaptiveStepSize, WarmupExpStepSize,
    ConstantRegularization, ExpRegularization, ExponentialCDFRegularization,
    Adam, Adamelia,
    set_log_level, clear_caches,
)
import sys
import numpy as np
import jax.numpy as jnp
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(42)
import vscodenb
import svgd_tests
sns.set_palette('tab10')
set_log_level('INFO')
clear_caches()
[INFO] phasic.graph_cache: Cleared 0 cached graphs
  Removed 20 file(s), preserved directory structure

Lets make a coalescent moddel with one parameter, the coalescent rate:

nr_samples = 4

@with_ipv([nr_samples]+[0]*(nr_samples-1))
def coalescent_1param(state):
    transitions = []
    for i in range(state.size):
        for j in range(i, state.size):            
            same = int(i == j)
            if same and state[i] < 2:
                continue
            if not same and (state[i] < 1 or state[j] < 1):
                continue 
            new = state.copy()
            new[i] -= 1
            new[j] -= 1
            new[i+j+1] += 1
            transitions.append([new, [state[i]*(state[j]-same)/(1+same)]])
    return transitions

Construct the graph and set some value of the model parameter:

graph = Graph(coalescent_1param)
true_theta = [7]
graph.update_weights(true_theta)
graph.plot()
[INFO] phasic.graph_cache: Saved graph to cache: 4e7d3baaa4030c3c... (6 vertices)
[INFO] phasic: Saved graph to cache: 6 vertices

With a large set of observed times to the most recent common ancestor (TMRCA), we can fit our model to find the most likely value of the model parameter. For this turorial we will just set the model parameter to 7 and then sample from the model to get such a data set. This has the advantage that we know what the model parameter is supposed to be.

nr_observations = 10000
observed_data = graph.sample(nr_observations)
observed_data.shape
(10000,)

We can plot a histogram of the observed data along with the theoretical density to see that they match up:

fig, ax = plt.subplots()
ax.hist(observed_data, density=True, bins=30, label='Sample distribution')
x = np.linspace(0, 1, 100)
ax.plot(x, graph.pdf(x), color='C1', label='True PDF')
ax.legend() ;

The svgd method provide sensible defaults to the optimization parameters. So in the simplest version, all you have to do to fit parameter values is:

svgd = graph.svgd(observed_data)
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             6.967      6.969      0.08098    6.782        7.066       

Particles: 20, Iterations: 1000
svgd.get_results()["theta_mean"].item()
6.96945891158499
svgd.hpd_intervals(0.95) 
(array([6.78238568]), array([7.06551295]))
svgd.hpd_intervals(0.5) 
(array([6.92088075]), array([6.96889361]))
estimates, loglike = svgd.map_estimate_from_particles()
estimates, loglike
([6.967437907072457], 6802.097858549072)

A nice property of SVGD is that you can easily evaluate if the optimization converges. We would like to see both the mean and standard deviation across particles to plateau towards the end.

svgd.plot_convergence()

In this case they clearly do not. Fortunately there are several easy remedies for this as shown below.

Learning rate

We can change the learning rate the number of iterations from their default values:

svgd = graph.svgd(observed_data, 
                  learning_rate=0.001,
                  n_iterations=500,
                  )
svgd.plot_convergence()

If the curves are not nice and smooth, you should inspect the parameter values of each particle across iterations:

svgd.plot_trace();

You can also plot the acceleration (the relative rate of change of each particle estimate) for an alternative way to diagnose this behavior:

svgd.plot_trace_accel()

You an see the values jumping abruptly. That happens when the learning rate step is too large compared to the gradient. Since the gradient flattens during the fit, we need to make the learning rate start our large and decay exponentially during training. We can do that by passing “step size schedule” like ExpStepSize to svgd. Its lets you control the sizes of the first as last steps and the exponential transition between them (the tau argument).

step_schedule = ExpStepSize(first_step=0.001, last_step=0.0001, tau=80.0)
step_schedule.plot(nr_iter=200);

svgd = graph.svgd(observed_data, 
                  learning_rate=step_schedule,
                  n_iterations=200,                  
                  )
svgd.plot_convergence()

svgd.plot_trace()

The distribution of particle values describe the posterior distribution from which MAP estimate, mean and CI can be plotted:

svgd.plot_ci(true_theta=true_theta)

You can even make an animation of the fit with svgd.animate().

Moment regularization

If you control learning rate using the learning_rate keyword argument, you can help optimization by applying moment regularization across iterations:

reg_schedule = ExpRegularization(first_reg=10.0, last_reg=0.1, tau=20.0)
reg_schedule.plot(200) ;

svgd = graph.svgd(observed_data, 
                  prior=GaussPrior(ci=[5, 15]),
                  learning_rate=ExpStepSize(first_step=0.005, last_step=0.005, tau=50.0),
                  n_iterations=200,
                  n_particles=100,
                  regularization=reg_schedule,
                  nr_moments=2
                  )
svgd.plot_ci(true_theta=true_theta)

It does not contribute much in this case that already converges, but for more complex models using regularization can help stabilize the optimization.

Adaptive optimizers

Instead of specifying learning_rate, you can use the optimizer keyword argument to pass one of the adaptive optimizers that come with Phasic. Phasic also supports/wraps the optimizers distributed in the optax package.

Prior

The prior distribution used in Bayesian inference represents our prior belief, I.e. our knowledge about what range of values the parameter can reasonably take. Phasic comes with two types of priors that are easily defined from basic knowledge about the parameter. The default behaviour of Phasic is to use a Gaussian prior centered on a rough estimate of each parameter using method-of-moments. To see the prior used, you can can plot it like this:

svgd.prior.plot() ;

You can define your own Gaussian prior (GaussPrior) or a Half-Cauchy prior (HalfCauchy) (see also ?@sec-priors-and-schedules). Lets add a prior (defined by its confidence interval) to SVGD inference and rerun it with more particles. If we pick a prior that only barely includes the true value, SVGD will can still find the right MAP estimate but the estimated posterior distribution (and thus the CI) will be skewed in the direction of the prior:

svgd = graph.svgd(observed_data, 
                  prior=GaussPrior(ci=[5, 20]),
                  learning_rate=ExpStepSize(first_step=0.005, last_step=0.005, tau=50.0),
                  n_iterations=200, 
                  n_particles=100,               
                  )
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             6.963      7.985      2.624      5.452        14.11       

Particles: 100, Iterations: 200
svgd.plot_convergence()

svgd.plot_ci(true_theta=true_theta)

This is mostly an issue for the “fringes” of the interval. To better see how the probability mass it distributed, you can pass a ci keyword argument to plot_ci to make it plot a narrower HDR. Here you can see that the densest 50% of the probability nicely homes in around the true value:

svgd.plot_ci(true_theta=true_theta, ci_level=0.5)

If you plot the plot the posterior, you can see how misleading the CI can be:

svgd.plot_posterior(true_theta=true_theta, bins=100)

… or as kde plot:

from scipy import stats

def kde_bandwidth(obj, fac=0.15):
    return np.power(obj.n, -1./(obj.d+4)) * fac

particles = svgd.get_results()['particles']
vals = particles[:, 0]
kde = stats.gaussian_kde(vals, bw_method=kde_bandwidth)
x = np.linspace(vals.min(), vals.max(), 1000)
plt.plot(x, kde(x)) ;

svgd.analyze_trace()
CONVERGED (iteration 81/201)
  Mean stabilized at iteration 81
  Std stabilized at iteration 50

Detected Issues:
  ℹ Converged at 4e+01% of iterations - could reduce n_iterations
Learning Rate: Converged efficiently
  current schedule is good
Particles: High ESS ratio (1) - could reduce particles
  n_particles=80
Iterations: Converged early
  Could reduce to n_iterations=97

Posterior predictive checks

from scipy.stats import ecdf

# ECDF for observed data
res = ecdf(observed_data)
x, ecdf = res.cdf.quantiles, res.cdf.probabilities

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,3))
sns.histplot(observed_data,
             kde=False, stat='density', label='Data', ax=ax1)
graph.update_weights(svgd.get_results()['theta_mean'])
ax1.plot(x, graph.pdf(x), lw=1.5, c='C1', label='PDF')
ax1.set_xlabel('Reward (time)')
ax1.set_title('PDF')
ax1.legend()
ax2.plot(x, ecdf, lw=1.5, c='C0', label='ECDF')
ax2.plot(x, graph.cdf(x), lw=1.5, c='C1', label='CDF')
ax2.set_xlabel('Reward (time)')
ax2.set_title('CDF')
ax2.legend() 
ax3 = ax2.twinx()
ax3.plot(x, graph.cdf(x)-ecdf, lw=0.5, c='C2', 
    alpha=0.5,label='CDF-ECDF')
ax3.grid(False)
ax3.set_ylabel('CDF - ECDF', color='C2')
ax3.tick_params(axis='y', colors='C2')
plt.tight_layout()

Weight formula for non-linear parametrization

For models where updating edge weights cannot be expressed as an inner product of parameters and edge coefficients, a callback update function can be passed to graph.update_weights(). For inference with SVGD, however, such non-linear weight updates must be expressed using a “weight formula” string that is compiled and made available to the C backend.

The weight formula string may include t0, t1, … representing the scalars of the theta parameter vector, c0, c1, … representing the coefficient vector of the edge being updated. numeric literals (3, 2.5, 1e-4, .5), arithmetic operators, elementary functions, comparisons, logic, branchless selection. The weight formula producing the default inner product would be 'c0*t0 + c1*t1 + c2*t2'.

The weight formula is added as an attribute to the graph, but can also be passed as a keyword argument to graph.svgd().

graph = Graph(coalescent_1param, theta_dim=1)
graph.weight_formula = "c0*t0"
graph.svgd(observed_data)
# or
# svgd = graph.svgd(observed_data, weight_formula="c0*t0")
[INFO] phasic.graph_cache: Saved graph to cache: 88acd5348c8fc2d3... (6 vertices)
[INFO] phasic: Saved graph to cache: 6 vertices
<phasic.svgd.SVGD at 0x36672a210>
svgd.summary()
Parameter  Fixed          MAP        Mean       SD         HPD 95% lo   HPD 95% hi  
0          No             6.963      7.985      2.624      5.452        14.11       

Particles: 100, Iterations: 200

Here are some example uses:

# Basic arithmetics:
"c0*t0 + c1*t1"            # the default linear inner product (Σ cₖ·tₖ)
"c0*t0 * c1*t1"            # product form (same as weight_mode='log')
"c0*t0 / (1 + c1*t1)"      # ratio / saturating rate
"t0**2"                    # power (right-assoc: 2**3**2 == 2**(3**2) == 512)
"t0**c0"                   # power with a per-edge exponent
"c0 * t0**2 + c1*t1"       # precedence: ** > * > + (no parens needed)
"-c0*t0 + c1"              # unary minus  (note: result must stay ≥ 0)
"2*t0 - 0.5*c0"            # integer/float literals

# Elementary functions: exp log sqrt logistic pow
"exp(c0*t0 + c1*t1)"       # log-link (always positive) — classic GLM rate
"exp(-c0*t0)"              # decaying rate (resistance-style)
"log(c0*t0)"              # requires c0*t0 > 0, else NaN → raises
"sqrt(c0*t0)"             # requires argument ≥ 0
"logistic(c0*t0)"         # numerically-stable 1/(1+exp(-·)) ∈ (0,1)
"pow(t0, c0)"             # same as t0**c0 (2-arg form)
"c2 * logistic(c0*t0) + 1e-3"   # bounded rate with a small floor

# Comparisons: ==  !=  <  >  <=  >= delta (Kronecker)
"delta(c0, c1)"           # 1.0 if c0 == c1 else 0.0  (sugar for c0 == c1)
"delta(c0, 3) * c1*t0"    # this term active only on edges where c0 == 3
"(c0 < c1) * t0"          # gate a term by an edge-structural comparison
"(c0 >= 2) * c1*t1"

# Logic (nonzero = true): and or not
"and(c0 == 3, c1 < 2)"            # 1.0 iff both hold
"or(c0 == 0, c1 == 0) * t0"       # term active if either coeff is zero
"not(c0) * t1"                    # active only where c0 == 0

# Branchless selection: select(cond, a, b) corresponds to cond ? a : b
"select(c0 == 3, c1*t0, c2*t1)"               # pick a branch by edge type
"delta(c0,c1)*t0 + (1 - delta(c0,c1))*t1"     # partition-of-unity (same idea)
"select(and(c0 == 3, c1 < 2), c2*t0, t1)"     # compound condition
"select(c0 > c1, exp(c2*t0), c2*t0)"          # different functional forms per edge 
'select(c0 > c1, exp(c2*t0), c2*t0)'

As with the the callback argument to update_weights, the (theta) vector can be shorter than the coefficient vectors. Just pass the param_length keyword argument to the Graph constructor. Allowing for more coefficients is handy if you need to pass more information to the callback function in order to update edge weights.

WarningTwo invariants to keep in mind
  1. Conditions cannot depend on the values of theta: The operands of == != < > <= >=, of delta, of and/or/not, and the first argument of select can use constants and c0, c1, … but not t0, t1, … . The value branches of select may use theta freely. For smooth gating on theta, use logistic(...).
"select(t0 > c0, t1, t2)"   # will raise exception because condition depends on theta
"select(c0 > 1, t1, t2)"    # ok, because condition depends only coefficients and constants
"logistic((t0 - c0)*10)*t1 + (1 - logistic((t0 - c0)*10))*t2"  # smooth θ-gate
  1. Weights must be finite and non-negative. The following will raise an exception: log/sqrt of <= 0, pow of a negative base, division by zero, or a negative result.

Examples:

# Coalescent-with-exposure-style: log-link rate with a per-edge offset
"exp(c0*t0 + c1*t1) + c2"

# Migration on/off per edge (c2 is a 0/1 edge flag), with a log-link base rate
"select(c2 == 1, exp(c0*t0), 0.0) + c1*t1"

# Piecewise: one rate law for coalescent edges (c0>0), another for mutation edges
"select(c0 > 0, c0*t0, c1*t1)"
'select(c0 > 0, c0*t0, c1*t1)'
Tip

The weight_formula argument can also be passed to graph.update_weights(). This is useful for testing formulas before running SVGD:

graph.update_weights(theta, weight_formula="c0*t0 + c1*t1")
graph.expectation()

If you need to debug your formula, you can create the a corresponding Python callback returning the formula expressed using the c and t variables:

def weight_update(theta, edge_coefficients):
    t0, t1 = theta
    c0, c1 = edge_coefficients
    return c0*t0 + c1*t1