Skip to content

SVI

Stochastic variational inference (SVI) fits a guide by gradient steps on a sampled estimate of a variational objective, such as the evidence lower bound (ELBO), IWAE, Rényi, or VR-IWAE bound (Hoffman et al., 2013; Blei et al., 2017; Pyro Developers, n.d.-g). For a model of a coin's bias, for instance, the guide may be a Beta distribution whose two shape parameters the optimization adjusts. Posterior predictive draws then show which observations the fitted approximation predicts.

svi

Stochastic Variational Inference (SVI) training loop.

SVI optimizes a quivers.inference.objectives.Objective (the ELBO, IWAE, Rényi, or VR-IWAE bound) by taking gradient steps on the guide and model parameters. The objective parameter accepts any Objective subclass.

INITIAL_ATTEMPTS module-attribute

INITIAL_ATTEMPTS = 100

How many times SVI.run draws the objective of its first step before it reports a non-finite start, the budget MCMC gives an initial position.

SVI

SVI(model: MonadicProgram, guide: Guide, optim: Optimizer | None, objective: Objective)

Stochastic Variational Inference optimizer.

PARAMETER DESCRIPTION
model

Generative model.

TYPE: MonadicProgram

guide

Variational guide.

TYPE: Guide

optim

Optimizer for model and guide parameters. None is valid only when neither has trainable parameters; steps then evaluate the objective without constructing phantom parameters or taking a gradient step.

TYPE: Optimizer or None

objective

Variational objective (ELBO, IWAEBound, RenyiBound, VRIWAEBound, …).

TYPE: Objective

Source code in src/quivers/inference/svi.py
def __init__(
    self,
    model: MonadicProgram,
    guide: Guide,
    optim: torch.optim.Optimizer | None,
    objective: Objective,
) -> None:
    if optim is None and _unique_parameters(model.parameters(), guide.parameters()):
        raise ValueError(
            "an optimizer is required for trainable model or guide parameters"
        )
    self.model = model
    self.guide = guide
    self.optim = optim
    self.objective = objective

step

step(x: Tensor, observations: dict[str, Tensor]) -> float

One SVI step.

PARAMETER DESCRIPTION
x

Program input. Shape (batch, ...).

TYPE: Tensor

observations

Observed variable values + host data (the non-site keys are exposed to the trace via the condition machinery).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
float

Scalar loss for this step.

Source code in src/quivers/inference/svi.py
def step(
    self,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> float:
    """One SVI step.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.
    observations : dict[str, torch.Tensor]
        Observed variable values + host data (the
        non-site keys are exposed to the trace via the
        ``condition`` machinery).

    Returns
    -------
    float
        Scalar loss for this step.
    """
    if self.optim is not None:
        self.optim.zero_grad()
    loss_val = self.objective(self.model, self.guide, x, observations)
    if not bool(torch.isfinite(loss_val).all()):
        raise _NonFiniteObjective("nonfinite variational objective")
    if self.optim is not None:
        loss_val.backward()
        self.optim.step()
    return loss_val.item()

run

run(x: Tensor, observations: Mapping[str, Tensor] | Callable[[int], Mapping[str, Tensor]], *, num_steps: int, callback: Callable[[int, float], None] | None = None) -> tuple[float, ...]

Optimize one posterior and retain its finite loss history.

PARAMETER DESCRIPTION
x

Model execution input.

TYPE: Tensor

observations

Fixed bindings, or a step-indexed supplier that recomputes differentiable predictors for the current parameter values.

TYPE: Mapping[str, Tensor] or Callable

num_steps

Nonnegative optimization budget. Zero retains initialization without evaluating the objective or updating parameters.

TYPE: int

callback

Receives each zero-based step index and its scalar loss.

TYPE: Callable[[int, float], None] or None DEFAULT: None

RETURNS DESCRIPTION
tuple[float, ...]

Losses in optimization order.

RAISES DESCRIPTION
ValueError

If the budget is invalid or an objective is nonfinite. The first step's objective is drawn up to INITIAL_ATTEMPTS times, without a parameter update, before a nonfinite start is reported.

Source code in src/quivers/inference/svi.py
def run(
    self,
    x: torch.Tensor,
    observations: Mapping[str, torch.Tensor]
    | Callable[[int], Mapping[str, torch.Tensor]],
    *,
    num_steps: int,
    callback: Callable[[int, float], None] | None = None,
) -> tuple[float, ...]:
    """Optimize one posterior and retain its finite loss history.

    Parameters
    ----------
    x : torch.Tensor
        Model execution input.
    observations : Mapping[str, torch.Tensor] or Callable
        Fixed bindings, or a step-indexed supplier that recomputes
        differentiable predictors for the current parameter values.
    num_steps : int
        Nonnegative optimization budget. Zero retains initialization
        without evaluating the objective or updating parameters.
    callback : Callable[[int, float], None] or None
        Receives each zero-based step index and its scalar loss.

    Returns
    -------
    tuple[float, ...]
        Losses in optimization order.

    Raises
    ------
    ValueError
        If the budget is invalid or an objective is nonfinite. The first
        step's objective is drawn up to `INITIAL_ATTEMPTS` times, without
        a parameter update, before a nonfinite start is reported.
    """
    if (
        isinstance(num_steps, bool)
        or not isinstance(num_steps, int)
        or num_steps < 0
    ):
        raise ValueError("num_steps must be a nonnegative integer")
    losses: list[float] = []
    for index in range(num_steps):
        bindings = observations(index) if callable(observations) else observations
        # The objective is a Monte Carlo estimate. At the start a draw of
        # the untrained guide may fall outside the model's support, so a
        # non-finite first objective is drawn again, as a sampler redraws
        # a non-finite initial position.
        attempts = INITIAL_ATTEMPTS if index == 0 else 1
        attempt = 1
        while True:
            try:
                loss = self.step(x, dict(bindings))
            except _NonFiniteObjective as exc:
                if attempt < attempts:
                    attempt += 1
                    continue
                tried = f" after {attempt} draws" if attempts > 1 else ""
                raise ValueError(
                    f"variational optimization at step {index}: {exc}{tried}"
                ) from exc
            except ValueError as exc:
                raise ValueError(
                    f"variational optimization at step {index}: {exc}"
                ) from exc
            break
        losses.append(loss)
        if callback is not None:
            callback(index, loss)
    return tuple(losses)

A parameter-free model and guide may use optim=None. SVI still evaluates the requested finite objectives and invokes callbacks, but has no gradient update to perform. The source and formula fitting adapters select this policy when their combined trainable parameter set is empty; frozen parameters do not create an optimizer. Omitting the optimizer while trainable parameters exist is an error.

Cited sources

Matthew D. Hoffman, David M. Blei, Chong Wang, and John Paisley. Stochastic Variational Inference. Journal of Machine Learning Research, 14(40):1303–1347, 2013. URL: https://www.jmlr.org/papers/v14/hoffman13a.html.

David M. Blei, Alp Kucukelbir, and Jon D. McAuliffe. Variational Inference: A Review for Statisticians. Journal of the American Statistical Association, 112(518):859–877, 2017. URL: https://doi.org/10.1080/01621459.2017.1285773, doi:10.1080/01621459.2017.1285773.

Pyro Developers. SVI part I: an introduction to stochastic variational inference in Pyro. Pyro Tutorials, version 1.9.1, n.d.-g. URL: https://pyro.ai/examples/svi_part_i.html (visited on 2026-11-06).